css.ts
This file
Path
src/jsx/dom/css.ts
263 lines 路 6.7 KiB 路 TypeScript
Last changed by
Not known.
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264/** * @module * This module provides APIs that enable `hono/jsx/dom` to support. */
import type { FC, PropsWithChildren } from '../'import type { ClassNameSlug, CssClassName, CssVariableType, OnInvalidSlug,} from '../../helper/css/common'import { CLASS_NAME, DEFAULT_STYLE_ID, PSEUDO_GLOBAL_SELECTOR, SELECTOR, SELECTORS, STYLE_STRING, cssCommon, cxCommon, keyframesCommon, viewTransitionCommon,} from '../../helper/css/common'export { rawCssString } from '../../helper/css/common'
const splitRule = (rule: string): string[] => { const result: string[] = [] let startPos = 0 let depth = 0 for (let i = 0, len = rule.length; i < len; i++) { const char = rule[i]
// consume quote
if (char === "'" || char === '"') { const quote = char i++ for (; i < len; i++) { if (rule[i] === '\\') { i++ continue } if (rule[i] === quote) { break } } continue }
// comments are removed from the rule in advance if (char === '{') { depth++ continue } if (char === '}') { depth-- if (depth === 0) { result.push(rule.slice(startPos, i + 1)) startPos = i + 1 } continue } } return result}
interface CreateCssJsxDomObjectsType { (args: { id: Readonly<string> }): readonly [ { toString(this: CssClassName): string }, FC<PropsWithChildren<void>>, ]}
export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => { let styleSheet: CSSStyleSheet | null | undefined = undefined const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => { if (!styleSheet) { styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`) ?.sheet as CSSStyleSheet | null if (styleSheet) { // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(styleSheet as any).addedStyles = new Set<string>() } } // eslint-disable-next-line @typescript-eslint/no-explicit-any return styleSheet ? [styleSheet, (styleSheet as any).addedStyles] : [] }
const insertRule = (className: string, styleString: string) => { const [sheet, addedStyles] = findStyleSheet() if (!sheet || !addedStyles) { Promise.resolve().then(() => { if (!findStyleSheet()[0]) { throw new Error('style sheet not found') } insertRule(className, styleString) }) return }
if (!addedStyles.has(className)) { addedStyles.add(className) ;(className.startsWith(PSEUDO_GLOBAL_SELECTOR) ? splitRule(styleString) : [`${className[0] === '@' ? '' : '.'}${className}{${styleString}}`] ).forEach((rule) => { sheet.insertRule(rule, sheet.cssRules.length) }) } }
const cssObject = { toString(this: CssClassName): string { const selector = this[SELECTOR] insertRule(selector, this[STYLE_STRING]) this[SELECTORS].forEach(({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => { insertRule(className, styleString) })
return this[CLASS_NAME] }, }
const Style: FC<PropsWithChildren<{ nonce?: string }>> = ({ children, nonce }) => ({ tag: 'style', props: { id, nonce, children: children && (Array.isArray(children) ? children : [children]).map( (c) => (c as unknown as CssClassName)[STYLE_STRING] ), }, // eslint-disable-next-line @typescript-eslint/no-explicit-any }) as any
return [cssObject, Style] as const}
interface CssType { (strings: TemplateStringsArray, ...values: CssVariableType[]): string}
interface CxType { (...args: (string | boolean | null | undefined)[]): string}
interface KeyframesType { (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassName}
interface ViewTransitionType { (strings: TemplateStringsArray, ...values: CssVariableType[]): string (content: string): string (): string}
interface DefaultContextType { css: CssType cx: CxType keyframes: KeyframesType viewTransition: ViewTransitionType Style: FC<PropsWithChildren<void>>}
/** * @experimental * `createCssContext` is an experimental feature. * The API might be changed. * * @param options.id - The ID for the style element * @param options.classNameSlug - Optional function to customize generated CSS class names * @param options.onInvalidSlug - Optional callback function called when an invalid slug is returned from ClassNameSlug */export const createCssContext = ({ id, classNameSlug, onInvalidSlug,}: { id: Readonly<string> classNameSlug?: ClassNameSlug onInvalidSlug?: OnInvalidSlug}): DefaultContextType => { const [cssObject, Style] = createCssJsxDomObjects({ id })
const newCssClassNameObject = (cssClassName: CssClassName): string => { cssClassName.toString = cssObject.toString return cssClassName as unknown as string }
const css: CssType = (strings, ...values) => { return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug)) }
const cx: CxType = (...args) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any args = cxCommon(args as any) as any // eslint-disable-next-line @typescript-eslint/no-explicit-any return css(Array(args.length).fill('') as any, ...args) }
const keyframes: KeyframesType = (strings, ...values) => keyframesCommon(strings, values, classNameSlug, onInvalidSlug)
const viewTransition: ViewTransitionType = (( strings: TemplateStringsArray | string | undefined, ...values: CssVariableType[] ) => { return newCssClassNameObject( viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any ) }) as ViewTransitionType
return { css, cx, keyframes, viewTransition, Style, }}
const defaultContext: DefaultContextType = createCssContext({ id: DEFAULT_STYLE_ID })
/** * @experimental * `css` is an experimental feature. * The API might be changed. */export const css = defaultContext.css
/** * @experimental * `cx` is an experimental feature. * The API might be changed. */export const cx = defaultContext.cx
/** * @experimental * `keyframes` is an experimental feature. * The API might be changed. */export const keyframes = defaultContext.keyframes
/** * @experimental * `viewTransition` is an experimental feature. * The API might be changed. */export const viewTransition = defaultContext.viewTransition
/** * @experimental * `Style` is an experimental feature. * The API might be changed. */export const Style = defaultContext.Style