index.ts
This file
Path
src/helper/css/index.ts
262 lines 路 7.5 KiB 路 TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoptioncd3f6f7
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263/** * @module * css Helper for Hono. */
import { raw } from '../../helper/html'import { DOM_RENDERER } from '../../jsx/constants'import { createCssJsxDomObjects } from '../../jsx/dom/css'import { escapeToBuffer } from '../../utils/html'import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'import type { ClassNameSlug, CssClassName as CssClassNameCommon, CssVariableType, OnInvalidSlug,} from './common'import { CLASS_NAME, DEFAULT_STYLE_ID, PSEUDO_GLOBAL_SELECTOR, SELECTOR, SELECTORS, STYLE_STRING, cssCommon, cxCommon, keyframesCommon, viewTransitionCommon,} from './common'export { rawCssString } from './common'export type { ClassNameSlug, OnInvalidSlug } from './common'
type CssClassName = HtmlEscapedString & CssClassNameCommon
type usedClassNameData = [ Record<string, string>, // class name to add Record<string, true>, // class name already added]
interface CssType { (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>}
interface CxType { ( ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[] ): Promise<string>}
interface KeyframesType { (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon}
interface ViewTransitionType { (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> (content: Promise<string>): Promise<string> (): Promise<string>}
interface StyleType { (args?: { children?: Promise<string>; nonce?: string }): HtmlEscapedString}
/** * @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 [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })
const contextMap: WeakMap<object, usedClassNameData> = new WeakMap() const nonceMap: WeakMap<object, string | undefined> = new WeakMap()
const replaceStyleRe = new RegExp(`(<style id="${id}"(?: nonce="[^"]*")?>.*?)(</style>)`)
const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => { const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => { const [toAdd, added] = contextMap.get(context) as usedClassNameData const names = Object.keys(toAdd)
if (!names.length) { return }
let stylesStr = '' names.forEach((className) => { added[className] = true stylesStr += className.startsWith(PSEUDO_GLOBAL_SELECTOR) ? toAdd[className] : `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}` }) contextMap.set(context, [{}, added])
if (buffer && replaceStyleRe.test(buffer[0])) { buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`) return }
const nonce = nonceMap.get(context) const appendStyleScript = `<script${ nonce ? ` nonce="${nonce}"` : '' }>document.querySelector('#${id}').textContent+=${JSON.stringify(stylesStr)}</script>`
if (buffer) { buffer[0] = `${appendStyleScript}${buffer[0]}` return }
return Promise.resolve(appendStyleScript) }
const addClassNameToContext: HtmlEscapedCallback = ({ context }) => { if (!contextMap.has(context)) { contextMap.set(context, [{}, {}]) } const [toAdd, added] = contextMap.get(context) as usedClassNameData let allAdded = true if (!added[cssClassName[SELECTOR]]) { allAdded = false toAdd[cssClassName[SELECTOR]] = cssClassName[STYLE_STRING] } cssClassName[SELECTORS].forEach( ({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => { if (!added[className]) { allAdded = false toAdd[className] = styleString } } ) if (allAdded) { return }
return Promise.resolve(raw('', [appendStyle])) }
// external class names from cx() are untrusted but the result is marked isEscaped, // so escape it here. skip the buffer when there is nothing to escape. const rawClassName = cssClassName[CLASS_NAME] let escapedClassName = rawClassName if (/[&<>'"]/.test(rawClassName)) { const escapedBuffer: [string] = [''] escapeToBuffer(rawClassName, escapedBuffer) escapedClassName = escapedBuffer[0] } const className = new String(escapedClassName) as CssClassName Object.assign(className, cssClassName) ;(className as HtmlEscapedString).isEscaped = true ;(className as HtmlEscapedString).callbacks = [addClassNameToContext] const promise = Promise.resolve(className) Object.assign(promise, cssClassName)
promise.toString = cssJsxDomObject.toString return promise }
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 | Promise<string> | undefined, ...values: CssVariableType[] ) => { return newCssClassNameObject( viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any ) }) as ViewTransitionType
const Style: StyleType = ({ children, nonce } = {}) => raw( `<style id="${id}"${nonce ? ` nonce="${nonce}"` : ''}>${ children ? (children as unknown as CssClassName)[STYLE_STRING] : '' }</style>`, [ ({ context }) => { nonceMap.set(context, nonce) return undefined }, ] )
// eslint-disable-next-line @typescript-eslint/no-explicit-any ;(Style as any)[DOM_RENDERER] = StyleRenderToDom
return { css, cx, keyframes, viewTransition: viewTransition as ViewTransitionType, Style, }}
interface DefaultContextType { css: CssType cx: CxType keyframes: KeyframesType viewTransition: ViewTransitionType Style: StyleType}
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