Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–8why, one step back
1/**
2 * @module3 * css Helper for Hono.4 */56import { raw } from '../../helper/html'7import { DOM_RENDERER } from '../../jsx/constants'8import { createCssJsxDomObjects } from '../../jsx/dom/css'

Merge commit from forkTaku Amanobefore adoptioncd3f6f7

line 9why, one step back
9import { escapeToBuffer } from '../../utils/html'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 10–148why, one step back
10import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'
11import type {12 ClassNameSlug,13 CssClassName as CssClassNameCommon,14 CssVariableType,15 OnInvalidSlug,16} from './common'17import {18 CLASS_NAME,19 DEFAULT_STYLE_ID,20 PSEUDO_GLOBAL_SELECTOR,21 SELECTOR,22 SELECTORS,23 STYLE_STRING,24 cssCommon,25 cxCommon,26 keyframesCommon,27 viewTransitionCommon,28} from './common'29export { rawCssString } from './common'30export type { ClassNameSlug, OnInvalidSlug } from './common'3132type CssClassName = HtmlEscapedString & CssClassNameCommon3334type usedClassNameData = [35 Record<string, string>, // class name to add36 Record<string, true>, // class name already added37]3839interface CssType {40 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>41}4243interface CxType {44 (45 ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]46 ): Promise<string>47}4849interface KeyframesType {50 (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon51}5253interface ViewTransitionType {54 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>55 (content: Promise<string>): Promise<string>56 (): Promise<string>57}5859interface StyleType {60 (args?: { children?: Promise<string>; nonce?: string }): HtmlEscapedString61}6263/**64 * @experimental65 * `createCssContext` is an experimental feature.66 * The API might be changed.67 *68 * @param options.id - The ID for the style element69 * @param options.classNameSlug - Optional function to customize generated CSS class names70 * @param options.onInvalidSlug - Optional callback function called when an invalid slug is returned from ClassNameSlug71 */72export const createCssContext = ({73 id,74 classNameSlug,75 onInvalidSlug,76}: {77 id: Readonly<string>78 classNameSlug?: ClassNameSlug79 onInvalidSlug?: OnInvalidSlug80}): DefaultContextType => {81 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })8283 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()84 const nonceMap: WeakMap<object, string | undefined> = new WeakMap()8586 const replaceStyleRe = new RegExp(`(<style id="${id}"(?: nonce="[^"]*")?>.*?)(</style>)`)8788 const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => {89 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {90 const [toAdd, added] = contextMap.get(context) as usedClassNameData91 const names = Object.keys(toAdd)9293 if (!names.length) {94 return95 }9697 let stylesStr = ''98 names.forEach((className) => {99 added[className] = true100 stylesStr += className.startsWith(PSEUDO_GLOBAL_SELECTOR)101 ? toAdd[className]102 : `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`103 })104 contextMap.set(context, [{}, added])105106 if (buffer && replaceStyleRe.test(buffer[0])) {107 buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)108 return109 }110111 const nonce = nonceMap.get(context)112 const appendStyleScript = `<script${113 nonce ? ` nonce="${nonce}"` : ''114 }>document.querySelector('#${id}').textContent+=${JSON.stringify(stylesStr)}</script>`115116 if (buffer) {117 buffer[0] = `${appendStyleScript}${buffer[0]}`118 return119 }120121 return Promise.resolve(appendStyleScript)122 }123124 const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {125 if (!contextMap.has(context)) {126 contextMap.set(context, [{}, {}])127 }128 const [toAdd, added] = contextMap.get(context) as usedClassNameData129 let allAdded = true130 if (!added[cssClassName[SELECTOR]]) {131 allAdded = false132 toAdd[cssClassName[SELECTOR]] = cssClassName[STYLE_STRING]133 }134 cssClassName[SELECTORS].forEach(135 ({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {136 if (!added[className]) {137 allAdded = false138 toAdd[className] = styleString139 }140 }141 )142 if (allAdded) {143 return144 }145146 return Promise.resolve(raw('', [appendStyle]))147 }148

Merge commit from forkTaku Amanobefore adoptioncd3f6f7

lines 149–158why, one step back
149 // external class names from cx() are untrusted but the result is marked isEscaped,
150 // so escape it here. skip the buffer when there is nothing to escape.151 const rawClassName = cssClassName[CLASS_NAME]152 let escapedClassName = rawClassName153 if (/[&<>'"]/.test(rawClassName)) {154 const escapedBuffer: [string] = ['']155 escapeToBuffer(rawClassName, escapedBuffer)156 escapedClassName = escapedBuffer[0]157 }158 const className = new String(escapedClassName) as CssClassName

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 159–262why, one step back
159 Object.assign(className, cssClassName)
160 ;(className as HtmlEscapedString).isEscaped = true161 ;(className as HtmlEscapedString).callbacks = [addClassNameToContext]162 const promise = Promise.resolve(className)163 Object.assign(promise, cssClassName)164165 promise.toString = cssJsxDomObject.toString166 return promise167 }168169 const css: CssType = (strings, ...values) => {170 return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug))171 }172173 const cx: CxType = (...args) => {174 // eslint-disable-next-line @typescript-eslint/no-explicit-any175 args = cxCommon(args as any) as any176 // eslint-disable-next-line @typescript-eslint/no-explicit-any177 return css(Array(args.length).fill('') as any, ...args)178 }179180 const keyframes: KeyframesType = (strings, ...values) =>181 keyframesCommon(strings, values, classNameSlug, onInvalidSlug)182183 const viewTransition: ViewTransitionType = ((184 strings: TemplateStringsArray | Promise<string> | undefined,185 ...values: CssVariableType[]186 ) => {187 return newCssClassNameObject(188 viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any189 )190 }) as ViewTransitionType191192 const Style: StyleType = ({ children, nonce } = {}) =>193 raw(194 `<style id="${id}"${nonce ? ` nonce="${nonce}"` : ''}>${195 children ? (children as unknown as CssClassName)[STYLE_STRING] : ''196 }</style>`,197 [198 ({ context }) => {199 nonceMap.set(context, nonce)200 return undefined201 },202 ]203 )204205 // eslint-disable-next-line @typescript-eslint/no-explicit-any206 ;(Style as any)[DOM_RENDERER] = StyleRenderToDom207208 return {209 css,210 cx,211 keyframes,212 viewTransition: viewTransition as ViewTransitionType,213 Style,214 }215}216217interface DefaultContextType {218 css: CssType219 cx: CxType220 keyframes: KeyframesType221 viewTransition: ViewTransitionType222 Style: StyleType223}224225const defaultContext: DefaultContextType = createCssContext({226 id: DEFAULT_STYLE_ID,227})228229/**230 * @experimental231 * `css` is an experimental feature.232 * The API might be changed.233 */234export const css = defaultContext.css235236/**237 * @experimental238 * `cx` is an experimental feature.239 * The API might be changed.240 */241export const cx = defaultContext.cx242243/**244 * @experimental245 * `keyframes` is an experimental feature.246 * The API might be changed.247 */248export const keyframes = defaultContext.keyframes249250/**251 * @experimental252 * `viewTransition` is an experimental feature.253 * The API might be changed.254 */255export const viewTransition = defaultContext.viewTransition256257/**258 * @experimental259 * `Style` is an experimental feature.260 * The API might be changed.261 */262export const Style = defaultContext.Style