This commit is contained in:
2026-03-04 17:35:14 +01:00
parent f73b56cdc4
commit db26e26495
113 changed files with 12433 additions and 169 deletions
+6
View File
@@ -0,0 +1,6 @@
export default function twuiCamelToNormalCase(str: string) {
return str
.replace(/([A-Z])/g, " $1")
.trim()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
+38
View File
@@ -0,0 +1,38 @@
/**
* # EJSON parse string
*/
function parse(
string: string | null | number,
reviver?: (this: any, key: string, value: any) => any,
): { [s: string]: any } | { [s: string]: any }[] | undefined {
if (!string) return undefined;
if (typeof string == "object") return string;
if (typeof string !== "string") return undefined;
try {
return JSON.parse(string, reviver);
} catch (error) {
return undefined;
}
}
/**
* # EJSON stringify object
*/
function stringify(
value: any,
replacer?: ((this: any, key: string, value: any) => any) | null,
space?: string | number,
): string | undefined {
try {
return JSON.stringify(value, replacer || undefined, space);
} catch (error) {
return undefined;
}
}
const TWUIEJSON = {
parse,
stringify,
};
export default TWUIEJSON;
+122
View File
@@ -0,0 +1,122 @@
import _ from "lodash";
import twuiSerializeQuery from "../serialize-query";
export const FetchAPIMethods = [
"POST",
"GET",
"DELETE",
"PUT",
"PATCH",
"post",
"get",
"delete",
"put",
"patch",
] as const;
type FetchApiOptions<T extends { [k: string]: any } = { [k: string]: any }> = {
method: (typeof FetchAPIMethods)[number];
body?: T | string;
headers?: FetchHeader;
query?: T;
csrfValue?: string;
csrfKey?: string;
fetchOptions?: RequestInit;
};
type FetchHeader = HeadersInit & {
[key: string]: string | null;
};
export type FetchApiReturn = {
success: boolean;
payload: any;
msg?: string;
[key: string]: any;
};
/**
* # Fetch API
*/
export default async function fetchApi<
T extends { [k: string]: any } = { [k: string]: any },
R extends any = any,
>(url: string, options?: FetchApiOptions<T>): Promise<R> {
let data;
let finalHeaders = {
"Content-Type": "application/json",
} as FetchHeader;
if (options?.csrfKey && options.csrfValue) {
finalHeaders[options.csrfKey] = options.csrfValue;
}
let finalURL = url;
if (options?.query) {
finalURL += twuiSerializeQuery(options.query);
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(finalURL, {
method: options,
headers: finalHeaders,
} as RequestInit);
data = fetchData.json();
break;
default:
fetchData = await fetch(finalURL);
data = fetchData.json();
break;
}
} catch (error: any) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
} else if (typeof options === "object") {
try {
let fetchData;
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
if (options.headers) {
options.headers = _.merge(options.headers, finalHeaders);
const finalOptions: any = { ...options };
fetchData = await fetch(finalURL, finalOptions);
} else {
const finalOptions = {
...options,
headers: finalHeaders,
} as RequestInit;
fetchData = await fetch(finalURL, finalOptions);
}
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
} else {
try {
let fetchData = await fetch(finalURL);
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}
@@ -0,0 +1,59 @@
export type FileInputToBase64FunctionReturn = {
fileBase64?: string;
fileBase64Full?: string;
fileName?: string;
fileSize?: number;
fileType?: string;
file?: File;
};
export type FileInputToBase64FunctioParam = {
inputFile: File;
allowedRegex?: RegExp;
};
export default async function fileInputToBase64({
inputFile,
allowedRegex,
}: FileInputToBase64FunctioParam): Promise<FileInputToBase64FunctionReturn> {
const allowedTypesRegex = allowedRegex ? allowedRegex : undefined;
if (allowedTypesRegex && !inputFile?.type?.match(allowedTypesRegex)) {
window.alert(`We currently don't support ${inputFile.type} file type.`);
return { fileName: inputFile.name };
}
let fileName = inputFile.name?.replace(/\..*/, "");
const file = inputFile;
try {
const fileData: string | undefined = await new Promise(
(resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = function () {
resolve(reader.result?.toString());
};
reader.onerror = function (/** @type {*} */ error: any) {
console.log("File Input to Base64 Error: ", error.message);
};
}
);
return {
fileBase64: fileData?.replace(/.*?base64,/, ""),
fileBase64Full: fileData,
fileName: fileName,
fileSize: inputFile.size,
fileType: inputFile.type,
file,
};
} catch (error: any) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
file,
};
}
}
@@ -0,0 +1,92 @@
export type ImageInputToBase64FunctionReturn = {
imageBase64?: string;
imageBase64Full?: string;
imageName?: string;
imageType?: string;
};
export type ImageInputToBase64FunctioParam = {
imageInput?: HTMLInputElement;
maxWidth?: number;
mimeType?: string;
file?: File;
};
export default async function imageInputToBase64({
imageInput,
maxWidth,
mimeType,
file,
}: ImageInputToBase64FunctioParam): Promise<ImageInputToBase64FunctionReturn> {
try {
const finalFile = file || imageInput?.files?.[0];
if (!finalFile) {
throw new Error("No Files found");
}
let imageName = finalFile.name.replace(/\..*/, "");
let imageDataBase64: string | undefined;
const MIME_TYPE = mimeType ? mimeType : finalFile.type;
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const blobURL = URL.createObjectURL(finalFile);
const img = new Image();
img.src = blobURL;
imageDataBase64 = await new Promise((res, rej) => {
img.onerror = function () {
URL.revokeObjectURL(this.src);
window.alert("Cannot load image!");
};
img.onload = function () {
URL.revokeObjectURL(img.src);
const canvas = document.createElement("canvas");
if (MAX_WIDTH) {
const scaleSize = MAX_WIDTH / img.naturalWidth;
canvas.width =
img.naturalWidth < MAX_WIDTH
? img.naturalWidth
: MAX_WIDTH;
canvas.height =
img.naturalWidth < MAX_WIDTH
? img.naturalHeight
: img.naturalHeight * scaleSize;
} else {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
}
const ctx = canvas.getContext("2d");
ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
res(srcEncoded);
};
});
return {
imageBase64: imageDataBase64?.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
imageType: MIME_TYPE,
};
} catch (error: any) {
console.log("Image Processing Error! =>", error.message);
return {
imageBase64: undefined,
imageBase64Full: undefined,
imageName: undefined,
};
}
}
+9
View File
@@ -0,0 +1,9 @@
export default function lowerToTitleCase(str: string) {
return str
.replace(/_|-/g, " ")
.split(" ")
.map(
(word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
)
.join(" ");
}
+6
View File
@@ -0,0 +1,6 @@
export default function twuiNormalizeText(txt: string) {
return txt
.replace(/\n|\r|\n\r/g, " ")
.replace(/ {2,}/g, " ")
.trim();
}
+30
View File
@@ -0,0 +1,30 @@
export default function twuiNumberfy(num: any, decimals?: number): number {
try {
const numberString = String(num)
.replace(/[^0-9\.]/g, "")
.replace(/\.$/, "");
if (!numberString.match(/./)) return 0;
const existingDecimals = numberString.match(/\./)
? numberString.split(".").pop()?.length
: undefined;
const numberfiedNum = Number(numberString);
if (typeof numberfiedNum !== "number") return 0;
if (isNaN(numberfiedNum)) return 0;
if (decimals == 0) {
return Math.round(Number(numberfiedNum));
} else if (decimals) {
return Number(numberfiedNum.toFixed(decimals));
}
if (existingDecimals)
return Number(numberfiedNum.toFixed(existingDecimals));
return Math.round(numberfiedNum);
} catch (error: any) {
return 0;
}
}
+42
View File
@@ -0,0 +1,42 @@
import TWUIEJSON from "./ejson";
/**
* # Serialize Query
*/
export default function twuiSerializeQuery(query: any): string {
let str = "?";
if (typeof query !== "object") {
console.log("Invalid Query type");
return str;
}
if (Array.isArray(query)) {
console.log("Query is an Array. This is invalid.");
return str;
}
if (!query) {
console.log("No Query provided.");
return str;
}
const keys = Object.keys(query);
const queryArr: string[] = [];
keys.forEach((key) => {
if (!key || !query[key]) return;
const value = query[key];
if (typeof value === "object") {
const jsonStr = TWUIEJSON.stringify(value);
queryArr.push(`${key}=${encodeURIComponent(String(jsonStr))}`);
} else if (typeof value === "string" || typeof value === "number") {
queryArr.push(`${key}=${encodeURIComponent(value)}`);
} else {
queryArr.push(`${key}=${String(value)}`);
}
});
str += queryArr.join("&");
return str;
}
+15
View File
@@ -0,0 +1,15 @@
export default function twuiSlugToNormalText(str?: string) {
if (!str) return "";
return str
.toLowerCase()
.replace(/ /g, "-")
.replace(/[^a-z0-9\-]/g, "-")
.replace(/-{2,}/g, "-")
.replace(/[-]/g, " ")
.split(" ")
.map(
(word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
)
.join(" ");
}
+36
View File
@@ -0,0 +1,36 @@
/**
* # Return the slug of a string
*
* @example
* slugify("Hello World") // "hello-world"
* slugify("Yes!") // "yes"
* slugify("Hello!!! World!") // "hello-world"
*/
export default function twuiSlugify(
str?: string,
divider?: "-" | "_" | null,
allowTrailingDash?: boolean | null
): string {
const finalSlugDivider = divider || "-";
try {
if (!str) return "";
let finalStr = String(str)
.trim()
.toLowerCase()
.replace(/ {2,}/g, " ")
.replace(/ /g, finalSlugDivider)
.replace(/[^a-z0-9]/g, finalSlugDivider)
.replace(/-{2,}|_{2,}/g, finalSlugDivider)
.replace(/^-/, "");
if (allowTrailingDash) {
return finalStr;
}
return finalStr.replace(/-$/, "");
} catch (error: any) {
return "";
}
}