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
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–263why, one step back1/**2 * @module3 * This module provides APIs that enable `hono/jsx/dom` to support.4 */56import type { FC, PropsWithChildren } from '../'7import type {8 ClassNameSlug,9 CssClassName,10 CssVariableType,11 OnInvalidSlug,12} from '../../helper/css/common'13import {14 CLASS_NAME,15 DEFAULT_STYLE_ID,16 PSEUDO_GLOBAL_SELECTOR,17 SELECTOR,18 SELECTORS,19 STYLE_STRING,20 cssCommon,21 cxCommon,22 keyframesCommon,23 viewTransitionCommon,24} from '../../helper/css/common'25export { rawCssString } from '../../helper/css/common'2627const splitRule = (rule: string): string[] => {28 const result: string[] = []29 let startPos = 030 let depth = 031 for (let i = 0, len = rule.length; i < len; i++) {32 const char = rule[i]3334 // consume quote3536 if (char === "'" || char === '"') {37 const quote = char38 i++39 for (; i < len; i++) {40 if (rule[i] === '\\') {41 i++42 continue43 }44 if (rule[i] === quote) {45 break46 }47 }48 continue49 }5051 // comments are removed from the rule in advance52 if (char === '{') {53 depth++54 continue55 }56 if (char === '}') {57 depth--58 if (depth === 0) {59 result.push(rule.slice(startPos, i + 1))60 startPos = i + 161 }62 continue63 }64 }65 return result66}6768interface CreateCssJsxDomObjectsType {69 (args: { id: Readonly<string> }): readonly [70 {71 toString(this: CssClassName): string72 },73 FC<PropsWithChildren<void>>,74 ]75}7677export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => {78 let styleSheet: CSSStyleSheet | null | undefined = undefined79 const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {80 if (!styleSheet) {81 styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)82 ?.sheet as CSSStyleSheet | null83 if (styleSheet) {84 // eslint-disable-next-line @typescript-eslint/no-explicit-any85 ;(styleSheet as any).addedStyles = new Set<string>()86 }87 }88 // eslint-disable-next-line @typescript-eslint/no-explicit-any89 return styleSheet ? [styleSheet, (styleSheet as any).addedStyles] : []90 }9192 const insertRule = (className: string, styleString: string) => {93 const [sheet, addedStyles] = findStyleSheet()94 if (!sheet || !addedStyles) {95 Promise.resolve().then(() => {96 if (!findStyleSheet()[0]) {97 throw new Error('style sheet not found')98 }99 insertRule(className, styleString)100 })101 return102 }103104 if (!addedStyles.has(className)) {105 addedStyles.add(className)106 ;(className.startsWith(PSEUDO_GLOBAL_SELECTOR)107 ? splitRule(styleString)108 : [`${className[0] === '@' ? '' : '.'}${className}{${styleString}}`]109 ).forEach((rule) => {110 sheet.insertRule(rule, sheet.cssRules.length)111 })112 }113 }114115 const cssObject = {116 toString(this: CssClassName): string {117 const selector = this[SELECTOR]118 insertRule(selector, this[STYLE_STRING])119 this[SELECTORS].forEach(({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {120 insertRule(className, styleString)121 })122123 return this[CLASS_NAME]124 },125 }126127 const Style: FC<PropsWithChildren<{ nonce?: string }>> = ({ children, nonce }) =>128 ({129 tag: 'style',130 props: {131 id,132 nonce,133 children:134 children &&135 (Array.isArray(children) ? children : [children]).map(136 (c) => (c as unknown as CssClassName)[STYLE_STRING]137 ),138 },139 // eslint-disable-next-line @typescript-eslint/no-explicit-any140 }) as any141142 return [cssObject, Style] as const143}144145interface CssType {146 (strings: TemplateStringsArray, ...values: CssVariableType[]): string147}148149interface CxType {150 (...args: (string | boolean | null | undefined)[]): string151}152153interface KeyframesType {154 (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassName155}156157interface ViewTransitionType {158 (strings: TemplateStringsArray, ...values: CssVariableType[]): string159 (content: string): string160 (): string161}162163interface DefaultContextType {164 css: CssType165 cx: CxType166 keyframes: KeyframesType167 viewTransition: ViewTransitionType168 Style: FC<PropsWithChildren<void>>169}170171/**172 * @experimental173 * `createCssContext` is an experimental feature.174 * The API might be changed.175 *176 * @param options.id - The ID for the style element177 * @param options.classNameSlug - Optional function to customize generated CSS class names178 * @param options.onInvalidSlug - Optional callback function called when an invalid slug is returned from ClassNameSlug179 */180export const createCssContext = ({181 id,182 classNameSlug,183 onInvalidSlug,184}: {185 id: Readonly<string>186 classNameSlug?: ClassNameSlug187 onInvalidSlug?: OnInvalidSlug188}): DefaultContextType => {189 const [cssObject, Style] = createCssJsxDomObjects({ id })190191 const newCssClassNameObject = (cssClassName: CssClassName): string => {192 cssClassName.toString = cssObject.toString193 return cssClassName as unknown as string194 }195196 const css: CssType = (strings, ...values) => {197 return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug))198 }199200 const cx: CxType = (...args) => {201 // eslint-disable-next-line @typescript-eslint/no-explicit-any202 args = cxCommon(args as any) as any203 // eslint-disable-next-line @typescript-eslint/no-explicit-any204 return css(Array(args.length).fill('') as any, ...args)205 }206207 const keyframes: KeyframesType = (strings, ...values) =>208 keyframesCommon(strings, values, classNameSlug, onInvalidSlug)209210 const viewTransition: ViewTransitionType = ((211 strings: TemplateStringsArray | string | undefined,212 ...values: CssVariableType[]213 ) => {214 return newCssClassNameObject(215 viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any216 )217 }) as ViewTransitionType218219 return {220 css,221 cx,222 keyframes,223 viewTransition,224 Style,225 }226}227228const defaultContext: DefaultContextType = createCssContext({ id: DEFAULT_STYLE_ID })229230/**231 * @experimental232 * `css` is an experimental feature.233 * The API might be changed.234 */235export const css = defaultContext.css236237/**238 * @experimental239 * `cx` is an experimental feature.240 * The API might be changed.241 */242export const cx = defaultContext.cx243244/**245 * @experimental246 * `keyframes` is an experimental feature.247 * The API might be changed.248 */249export const keyframes = defaultContext.keyframes250251/**252 * @experimental253 * `viewTransition` is an experimental feature.254 * The API might be changed.255 */256export const viewTransition = defaultContext.viewTransition257258/**259 * @experimental260 * `Style` is an experimental feature.261 * The API might be changed.262 */263export const Style = defaultContext.Style