Last active
December 14, 2024 04:03
-
-
Save fsubal/740fd408ed62f0599eed584a1ba9bfe1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ClassNameValue = string | number | false | undefined | null | ClassNameValue[] | { [className: string]: boolean } | |
function cx(...values: ClassNameValue[]) { | |
const classNames: string[] = [] | |
for (const value of values) { | |
if (!value) { | |
continue | |
} | |
if (Array.isArray(value)) { | |
classNames.push(cx(...value)) | |
continue | |
} | |
if (typeof value === 'string' || typeof value === 'number') { | |
classNames.push(value.toString()) | |
continue | |
} | |
for (const [key, flag] of Object.entries(value)) { | |
if (!flag) { | |
continue | |
} | |
classNames.push(key) | |
} | |
} | |
return Array.from(new Set(classNames), c => c.trim()).join(' ') | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function h<K extends keyof HTMLElementTagNameMap>( | |
tagName: K, | |
attributes: Partial<HTMLElementTagNameMap[K]>, | |
children: (Node | null | undefined | string | number | false)[] | |
): HTMLElementTagNameMap[K] { | |
const element = document.createElement(tagName) | |
for (const [key, value] of Object.entries(attributes)) { | |
element[key] = value | |
} | |
for (const node of children) { | |
if (node == null) { | |
continue | |
} | |
if (node == false) { | |
continue | |
} | |
if (node instanceof Node) { | |
element.appendChild(node) | |
} else { | |
element.innerText = node.toString() | |
} | |
} | |
return element | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment