Package library as @moduletrace/twui npm package

- Move components/ to src/ and compile to dist/ with tsc
- Add root barrel export plus deep-import subpath exports and base.css export
- Post-compile step: copy base.css, add .js import extensions, mark client modules
- Add publish.sh and .npmrc for the Gitea npm registry
- Fix type errors, guard TinyMCE env access, drop ace-builds type dependency
- Rename clashing props type names, remove Next.js scaffolding and unused deps

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-18 10:17:54 +01:00
co-authored by Claude Opus 5.5
parent d19d412066
commit 11da9b89e7
148 changed files with 937 additions and 500 deletions
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test";
import twuiCamelToNormalCase from "./camel-to-normal-case";
describe("twuiCamelToNormalCase", () => {
test("converts simple camelCase", () => {
expect(twuiCamelToNormalCase("camelCase")).toBe("Camel Case");
});
test("converts pascalCase", () => {
expect(twuiCamelToNormalCase("PascalCase")).toBe("Pascal Case");
});
test("handles single lowercase word", () => {
expect(twuiCamelToNormalCase("word")).toBe("Word");
});
test("handles single uppercase word", () => {
expect(twuiCamelToNormalCase("Word")).toBe("Word");
});
test("handles multiple uppercase transitions", () => {
expect(twuiCamelToNormalCase("firstNameLastName")).toBe("First Name Last Name");
});
test("handles consecutive uppercase letters", () => {
expect(twuiCamelToNormalCase("XMLParser")).toBe("X M L Parser");
});
test("handles already normal text", () => {
expect(twuiCamelToNormalCase("Normal")).toBe("Normal");
});
test("handles empty string", () => {
expect(twuiCamelToNormalCase("")).toBe("");
});
test("handles string with numbers", () => {
expect(twuiCamelToNormalCase("field123")).toBe("Field123");
});
test("handles acronym at end", () => {
expect(twuiCamelToNormalCase("userID")).toBe("User I D");
});
});
+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());
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, test } from "bun:test";
import TWUIEJSON from "./ejson";
describe("TWUIEJSON.parse", () => {
test("parses valid JSON string", () => {
expect(TWUIEJSON.parse('{"key":"value"}')).toEqual({ key: "value" });
});
test("parses valid JSON array string", () => {
expect(TWUIEJSON.parse("[1,2,3]")).toEqual([1, 2, 3]);
});
test("returns undefined for null input", () => {
expect(TWUIEJSON.parse(null)).toBeUndefined();
});
test("returns undefined for undefined input (0 is falsy)", () => {
expect(TWUIEJSON.parse(0)).toBeUndefined();
});
test("returns undefined for number input", () => {
expect(TWUIEJSON.parse(42)).toBeUndefined();
});
test("returns undefined for empty string", () => {
expect(TWUIEJSON.parse("")).toBeUndefined();
});
test("returns object as-is for object input", () => {
const obj = { a: 1 };
expect(TWUIEJSON.parse(obj as any)).toBe(obj);
});
test("returns undefined for invalid JSON string", () => {
expect(TWUIEJSON.parse("not json")).toBeUndefined();
});
test("returns undefined for malformed JSON", () => {
expect(TWUIEJSON.parse("{invalid}")).toBeUndefined();
});
test("parses nested JSON", () => {
const result = TWUIEJSON.parse('{"outer":{"inner":42}}');
expect(result).toEqual({ outer: { inner: 42 } });
});
test("supports reviver function", () => {
const result = TWUIEJSON.parse('{"a":"1","b":"2"}', (_key, value) =>
typeof value === "string" && !isNaN(Number(value)) ? Number(value) : value
);
expect(result).toEqual({ a: 1, b: 2 });
});
test("parses boolean JSON values", () => {
expect(TWUIEJSON.parse("true") as unknown).toBe(true);
expect(TWUIEJSON.parse("false") as unknown).toBe(false);
});
test("parses null JSON value", () => {
expect(TWUIEJSON.parse("null") as unknown).toBeNull();
});
});
describe("TWUIEJSON.stringify", () => {
test("stringifies an object", () => {
expect(TWUIEJSON.stringify({ key: "value" })).toBe('{"key":"value"}');
});
test("stringifies an array", () => {
expect(TWUIEJSON.stringify([1, 2, 3])).toBe("[1,2,3]");
});
test("returns undefined for circular reference", () => {
const obj: any = { a: 1 };
obj.self = obj;
expect(TWUIEJSON.stringify(obj)).toBeUndefined();
});
test("supports replacer function", () => {
const result = TWUIEJSON.stringify({ a: 1, b: 2 }, (_key, value) =>
typeof value === "number" ? value * 2 : value
);
expect(result).toBe('{"a":2,"b":4}');
});
test("supports space parameter for formatting", () => {
const result = TWUIEJSON.stringify({ a: 1 }, null, 2);
expect(result).toContain('\n');
expect(result).toContain(' ');
});
test("stringifies primitive values", () => {
expect(TWUIEJSON.stringify("hello")).toBe('"hello"');
expect(TWUIEJSON.stringify(42)).toBe("42");
expect(TWUIEJSON.stringify(null)).toBe("null");
});
});
+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;
+123
View File
@@ -0,0 +1,123 @@
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 = await fetchData.json();
break;
default:
fetchData = await fetch(finalURL);
data = await fetchData.json();
break;
}
} catch (error: any) {
console.log("FetchAPI error #1:", error.message);
data = { success: false, msg: error.message };
}
} 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 = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
data = { success: false, msg: error.message };
}
} else {
try {
let fetchData = await fetch(finalURL);
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = { success: false, msg: error.message };
}
}
return data;
}
+59
View File
@@ -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,
};
}
}
+91
View File
@@ -0,0 +1,91 @@
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(/\..*/, "");
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;
const imageDataBase64 = await new Promise<string>((res, rej) => {
img.onerror = function () {
URL.revokeObjectURL(this.src);
window.alert("Cannot load image!");
rej(new Error("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);
};
}).catch(() => undefined);
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,
};
}
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";
import lowerToTitleCase from "./lower-to-title-case";
describe("lowerToTitleCase", () => {
test("converts snake_case to Title Case", () => {
expect(lowerToTitleCase("hello_world")).toBe("Hello World");
});
test("converts kebab-case to Title Case", () => {
expect(lowerToTitleCase("hello-world")).toBe("Hello World");
});
test("converts mixed snake-kebab", () => {
expect(lowerToTitleCase("hello_world-test")).toBe("Hello World Test");
});
test("handles single word", () => {
expect(lowerToTitleCase("hello")).toBe("Hello");
});
test("handles already title case", () => {
expect(lowerToTitleCase("Hello")).toBe("Hello");
});
test("handles empty string", () => {
expect(lowerToTitleCase("")).toBe("");
});
test("handles all uppercase input", () => {
expect(lowerToTitleCase("HELLO_WORLD")).toBe("Hello World");
});
test("handles mixed case input", () => {
expect(lowerToTitleCase("hello_World")).toBe("Hello World");
});
test("converts user type values correctly", () => {
expect(lowerToTitleCase("super_admin")).toBe("Super Admin");
expect(lowerToTitleCase("financial_secretary")).toBe("Financial Secretary");
expect(lowerToTitleCase("primary_resident")).toBe("Primary Resident");
});
});
+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(" ");
}
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, test } from "bun:test";
import twuiNormalizeText from "./normalize-text";
describe("twuiNormalizeText", () => {
test("collapses multiple spaces", () => {
expect(twuiNormalizeText("hello world")).toBe("hello world");
});
test("replaces newlines with spaces", () => {
expect(twuiNormalizeText("hello\nworld")).toBe("hello world");
});
test("replaces carriage returns with spaces", () => {
expect(twuiNormalizeText("hello\rworld")).toBe("hello world");
});
test("replaces CRLF with spaces", () => {
expect(twuiNormalizeText("hello\r\nworld")).toBe("hello world");
});
test("trims leading and trailing whitespace", () => {
expect(twuiNormalizeText(" hello world ")).toBe("hello world");
});
test("handles mixed whitespace", () => {
expect(twuiNormalizeText(" hello\n\n world \r\n ")).toBe("hello world");
});
test("handles empty string", () => {
expect(twuiNormalizeText("")).toBe("");
});
test("handles string with only whitespace", () => {
expect(twuiNormalizeText(" ")).toBe("");
});
test("preserves single spaces", () => {
expect(twuiNormalizeText("hello world")).toBe("hello world");
});
test("handles tabs as regular characters (not collapsed by default)", () => {
const result = twuiNormalizeText("hello\tworld");
expect(result).toContain("hello");
expect(result).toContain("world");
});
test("handles multiple consecutive newlines", () => {
expect(twuiNormalizeText("hello\n\n\nworld")).toBe("hello world");
});
});
+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();
}
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, test } from "bun:test";
import twuiNumberfy from "./numberfy";
describe("twuiNumberfy", () => {
test("converts a number to number", () => {
expect(twuiNumberfy(42)).toBe(42);
});
test("converts a numeric string to number", () => {
expect(twuiNumberfy("42")).toBe(42);
});
test("strips non-numeric characters", () => {
expect(twuiNumberfy("$1,234.56")).toBe(1234.56);
});
test("returns 0 for non-numeric string", () => {
expect(twuiNumberfy("hello")).toBe(0);
});
test("returns 0 for undefined input", () => {
expect(twuiNumberfy(undefined)).toBe(0);
});
test("returns 0 for null input", () => {
expect(twuiNumberfy(null)).toBe(0);
});
test("rounds with decimals=0", () => {
expect(twuiNumberfy(3.7, 0)).toBe(4);
});
test("rounds with decimals=0 (floor case)", () => {
expect(twuiNumberfy(3.2, 0)).toBe(3);
});
test("limits decimal places", () => {
expect(twuiNumberfy(3.14159, 2)).toBe(3.14);
});
test("preserves existing decimals when no decimals param", () => {
expect(twuiNumberfy("3.14")).toBe(3.14);
});
test("rounds integers when no decimals param and no existing decimals", () => {
expect(twuiNumberfy("42")).toBe(42);
});
test("strips minus sign (does not support negatives)", () => {
expect(twuiNumberfy("-5")).toBe(5);
});
test("handles string with currency symbol", () => {
expect(twuiNumberfy("₦50,000")).toBe(50000);
});
test("handles empty string", () => {
expect(twuiNumberfy("")).toBe(0);
});
test("handles boolean true", () => {
expect(twuiNumberfy(true)).toBe(0);
});
test("handles boolean false", () => {
expect(twuiNumberfy(false)).toBe(0);
});
test("handles string with percentage", () => {
expect(twuiNumberfy("75%")).toBe(75);
});
test("handles multiple decimal points (results in NaN -> 0)", () => {
const result = twuiNumberfy("1.2.3");
expect(result).toBe(0);
});
test("handles zero", () => {
expect(twuiNumberfy(0)).toBe(0);
});
test("handles very large numbers", () => {
expect(twuiNumberfy("9999999999")).toBe(9999999999);
});
});
+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;
}
}
+5
View File
@@ -0,0 +1,5 @@
export default function TWUIRoundToNearestMagnitude(n: number) {
if (n === 0) return 0;
const magnitude = Math.pow(10, Math.floor(Math.log10(Math.abs(n))));
return Math.round(n / magnitude) * magnitude;
}
+60
View File
@@ -0,0 +1,60 @@
import { describe, expect, test } from "bun:test";
import twuiSerializeQuery from "./serialize-query";
describe("twuiSerializeQuery", () => {
test("returns '?' for non-object input", () => {
expect(twuiSerializeQuery("string" as any)).toBe("?");
});
test("returns '?' for array input", () => {
expect(twuiSerializeQuery([1, 2] as any)).toBe("?");
});
test("returns '?' for null input", () => {
expect(twuiSerializeQuery(null as any)).toBe("?");
});
test("serializes simple object", () => {
const result = twuiSerializeQuery({ foo: "bar" });
expect(result).toBe("?foo=bar");
});
test("serializes multiple keys", () => {
const result = twuiSerializeQuery({ a: "1", b: "2" });
expect(result).toContain("a=1");
expect(result).toContain("b=2");
});
test("serializes numeric value", () => {
const result = twuiSerializeQuery({ page: 2 });
expect(result).toContain("page=2");
});
test("skips empty key", () => {
const result = twuiSerializeQuery({ "": "value", foo: "bar" });
expect(result).not.toContain("=value");
expect(result).toContain("foo=bar");
});
test("skips falsy value", () => {
const result = twuiSerializeQuery({ empty: "", foo: "bar" });
expect(result).not.toContain("empty=");
expect(result).toContain("foo=bar");
});
test("JSON-encodes object values", () => {
const result = twuiSerializeQuery({ filter: { field: "name" } });
expect(result).toContain("filter=");
expect(result).toContain("field");
});
test("URL-encodes values", () => {
const result = twuiSerializeQuery({ q: "hello world" });
expect(result).toContain("q=hello%20world");
});
test("serializes boolean value as string", () => {
const result = twuiSerializeQuery({ active: true as any });
expect(result).toContain("active=true");
});
});
+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;
}
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import twuiSlugToNormalText from "./slug-to-normal-text";
describe("twuiSlugToNormalText", () => {
test("returns empty string for undefined", () => {
expect(twuiSlugToNormalText(undefined)).toBe("");
});
test("returns empty string for empty string", () => {
expect(twuiSlugToNormalText("")).toBe("");
});
test("converts slug to normal text", () => {
expect(twuiSlugToNormalText("hello-world")).toBe("Hello World");
});
test("converts underscore slug to normal text", () => {
expect(twuiSlugToNormalText("hello_world")).toBe("Hello World");
});
test("handles single word", () => {
expect(twuiSlugToNormalText("hello")).toBe("Hello");
});
test("removes special characters", () => {
expect(twuiSlugToNormalText("hello@world")).toBe("Hello World");
});
test("handles multiple consecutive dashes", () => {
expect(twuiSlugToNormalText("hello---world")).toBe("Hello World");
});
test("converts to title case", () => {
expect(twuiSlugToNormalText("annual-dues")).toBe("Annual Dues");
});
test("handles alphanumeric slug", () => {
expect(twuiSlugToNormalText("item-123")).toBe("Item 123");
});
test("handles mixed case input", () => {
expect(twuiSlugToNormalText("Hello-World")).toBe("Hello World");
});
test("handles user type slug", () => {
expect(twuiSlugToNormalText("super_admin")).toBe("Super Admin");
});
});
+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(" ");
}
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, test } from "bun:test";
import twuiSlugify from "./slugify";
describe("twuiSlugify", () => {
test("returns empty string for undefined input", () => {
expect(twuiSlugify(undefined)).toBe("");
});
test("returns empty string for empty string input", () => {
expect(twuiSlugify("")).toBe("");
});
test("slugifies simple text", () => {
expect(twuiSlugify("Hello World")).toBe("hello-world");
});
test("removes special characters", () => {
expect(twuiSlugify("Yes!")).toBe("yes");
});
test("removes multiple special characters", () => {
expect(twuiSlugify("Hello!!! World!")).toBe("hello-world");
});
test("converts to lowercase", () => {
expect(twuiSlugify("UPPERCASE TEXT")).toBe("uppercase-text");
});
test("replaces multiple spaces with single divider", () => {
expect(twuiSlugify("Hello World")).toBe("hello-world");
});
test("removes leading dash by default", () => {
expect(twuiSlugify(" hello")).toBe("hello");
});
test("removes trailing dash by default", () => {
expect(twuiSlugify("hello ")).toBe("hello");
});
test("keeps trailing dash when allowTrailingDash is true", () => {
expect(twuiSlugify("hello-", "-", true)).toBe("hello-");
});
test("uses underscore divider when specified", () => {
expect(twuiSlugify("Hello World", "_")).toBe("hello_world");
});
test("handles numbers", () => {
expect(twuiSlugify("Item 123")).toBe("item-123");
});
test("handles mixed alphanumeric and special chars", () => {
expect(twuiSlugify("Hello @World #2024!")).toBe("hello-world-2024");
});
test("replaces consecutive dashes with single dash", () => {
expect(twuiSlugify("a---b")).toBe("a-b");
});
test("trims whitespace before processing", () => {
expect(twuiSlugify(" hello world ")).toBe("hello-world");
});
test("handles single character input", () => {
expect(twuiSlugify("a")).toBe("a");
});
test("handles number-only input", () => {
expect(twuiSlugify("123")).toBe("123");
});
});
+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 "";
}
}