UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

58 lines (57 loc) 2.09 kB
import { isArray } from "../../util/array.js"; import { getDictionaryItems, isDictionary } from "../../util/dictionary.js"; /** * Parse a list of possible `className` strings and join them into a single string. * - See `Classes` type for parsing rules. * * @param classes The input set of classes to merge. * @returns The merged string classname. */ export function getClass(...classes) { return Array.from(getClasses(classes)).join(" "); } /** Yield the items in a list of possible `className` strings. */ function* getClasses(classes) { if (!classes) return; if (typeof classes === "string") { yield classes; return; } if (isArray(classes)) { // Recurse. for (const value of classes) yield* getClasses(value); return; } if (isDictionary(classes)) { // If `v` is `true`, return the keyname as a classname. // Anything else is ignored or not processed. for (const [k, v] of getDictionaryItems(classes)) if (v === true) yield k; } } /** * Parse a list of possible `className` strings, match them in a `CSSModule` dictionary, and join them into a single string. * - See `Classes` type for parsing rules. * * @param module CSS module object _or_ a string. * - Allows "string" because if this environment does not process `*.module.css` files then `import styles from "./styles.module.css"` will be a string. * - This allows this situation to be handled gracefully and classes will be silently ignored in this environment. * * @param classes Class keys/values to merge. * @returns The merged string classname. */ export function getModuleClass(module, ...classes) { if (isDictionary(module)) return Array.from(getModuleClasses(module, classes)).join(" "); } /** Yield the items in a list of possible `className` strings that match a `CSSModule` dictionary. */ function* getModuleClasses(module, classes) { for (const x of getClasses(classes)) { const y = module[x]; if (y) yield y; } }