feat(css): add classNameSlug option to createCssContext (#4834)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(css): add classNameSlug option to createCssContext Add an optional classNameSlug function to createCssContext that lets users customize generated CSS class names instead of the default hash-based 'css-1234567890' format. The function receives (hash, label, styleString) and returns the desired class name string. This enables readable, debug-friendly class names like 'h-hero-section' while preserving hash-based uniqueness. Addresses review feedback: - Move ClassNameSlug type near CssVariableType exports - Rename third parameter from css to styleString - Propagate classNameSlug to keyframesCommon and viewTransitionCommon - Add classNameSlug support to DOM-side createCssContext - Add TSDoc documentation Closes #4577 * fix(css): sanitize and normalize classNameSlug output Normalize and sanitize the return value of classNameSlug to prevent CSS injection and improve readability: - Trim leading/trailing whitespace - Collapse whitespace sequences to hyphens (e.g. 'ultra fast' -> 'ultra-fast') - Strip characters outside [a-zA-Z0-9_-] - Fall back to hash if result is empty Addresses review feedback from yusukebe and usualoma regarding potential CSS injection through malicious classNameSlug functions. * feat(css): add onInvalidSlug and unify server/DOM contexts Add strict CSS identifier validation for classNameSlug output and onInvalidSlug callback for invalid slugs, unified across server and DOM-side createCssContext. - Replace sanitizeClassName with validateClassName/validateKeyframeName (rejects digit-leading names and reserved @keyframes keywords) - Add onInvalidSlug option (defaults to console.warn) - Normalize labels (trim + hyphenate) before passing to classNameSlug * feat(css): refine classNameSlug with strict validation and onInvalidSlug Refine classNameSlug implementation by replacing sanitization with strict validation and adding an onInvalidSlug callback. - Add isValidClassName and isValidKeyframeName for strict identifier checks (^?-?[_a-zA-Z][_a-zA-Z0-9-]*$). - Reject CSS-wide reserved keywords for @keyframes animation names. - Pre-normalize labels (trim + hyphenate) before passing to classNameSlug. - Add optional onInvalidSlug callback to createCssContext for custom error handling (defaults to console.warn). - Ensure parity between SSR and DOM-side createCssContext. - Ensure the default path remains zero-overhead when classNameSlug is unused. * test: remove .trim() usage in classNameSlug test
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+435 added−21 removed
- tests:+290 added−0 removed
- other:+145 added−21 removed
Provenance
- Commit
f82aba8- Tree
d522696- Author
Wambui Maina <startabase@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9f374a5
5 files changed+435 added−21 removed
modified:src/helper/css/common.ts+94 added-9 removed
47 unmodified lines48 }49 return 'css-' + out50 }51 52+const normalizeLabel = (label: string): string => {53+ return label.trim().replace(/\s+/g, '-')54+}55+56+const isValidClassName = (name: string): boolean => /^-?[_a-zA-Z][_a-zA-Z0-9-]*$/.test(name)57+58+// CSS-wide keywords that are invalid as @keyframes names per the spec59+const RESERVED_KEYFRAME_NAMES = new Set([60+ 'default',61+ 'inherit',62+ 'initial',63+ 'none',64+ 'revert',65+ 'revert-layer',66+ 'unset',67+])68+const isValidKeyframeName = (name: string): boolean =>69+ isValidClassName(name) && !RESERVED_KEYFRAME_NAMES.has(name.toLowerCase())70+71+const defaultOnInvalidSlug = (slug: string) => {72+ console.warn(`Invalid slug: ${slug}`)73+}74+75 const cssStringReStr: string = [76 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string77 78 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string33 unmodified lines112 type CssVariableAsyncType = Promise<CssVariableBasicType>113 type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]114 export type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType115 116+/**117+ * A function that customizes generated CSS class names.118+ *119+ * @param hash - The default hash-based class name (e.g. `css-1234567890`)120+ * @param label - The comment label extracted from the CSS template, may be empty.121+ * Whitespace is trimmed and inner spaces are replaced with hyphens.122+ * @param styleString - The minified CSS style string123+ * @returns The custom class name to use. Must be a safe CSS identifier;124+ * otherwise, the default hash is used as a fallback.125+ */126+export type ClassNameSlug = (hash: string, label: string, styleString: string) => string127+128+/**129+ * A callback function called when an invalid slug is returned from ClassNameSlug.130+ *131+ * @param slug - The invalid slug132+ */133+export type OnInvalidSlug = (slug: string) => void134+135 export const buildStyleString = (136 strings: TemplateStringsArray,137 values: CssVariableType[]138 ): [string, string, CssClassName[], string[]] => {56 unmodified lines195 }196 197 export const cssCommon = (198 strings: TemplateStringsArray,157- values: CssVariableType[]199+ values: CssVariableType[],200+ classNameSlug?: ClassNameSlug,201+ onInvalidSlug?: OnInvalidSlug202 ): CssClassName => {203 let [label, thisStyleString, selectors, externalClassNames] = buildStyleString(strings, values)204 const isPseudoGlobal = isPseudoGlobalSelectorRe.exec(thisStyleString)205 if (isPseudoGlobal) {206 thisStyleString = isPseudoGlobal[1]207 }164- const selector = (isPseudoGlobal ? PSEUDO_GLOBAL_SELECTOR : '') + toHash(label + thisStyleString)208+ const hash = toHash(label + thisStyleString)209+210+ let customSlug: string | undefined211+ if (classNameSlug) {212+ const slug = classNameSlug(hash, normalizeLabel(label), thisStyleString)213+ if (slug) {214+ if (isValidClassName(slug)) {215+ customSlug = slug216+ } else {217+ ;(onInvalidSlug || defaultOnInvalidSlug)(slug)218+ }219+ }220+ }221+222+ const selector = (isPseudoGlobal ? PSEUDO_GLOBAL_SELECTOR : '') + (customSlug || hash)223 const className = (224 isPseudoGlobal ? selectors.map((s) => s[CLASS_NAME]) : [selector, ...externalClassNames]225 ).join(' ')226 26 unmodified lines253 }254 255 export const keyframesCommon = (256 strings: TemplateStringsArray,199- ...values: CssVariableType[]257+ values: CssVariableType[],258+ classNameSlug?: ClassNameSlug,259+ onInvalidSlug?: OnInvalidSlug260 ): CssClassName => {261 const [label, styleString] = buildStyleString(strings, values)262+ const hash = toHash(label + styleString)263+264+ let customSlug: string | undefined265+ if (classNameSlug) {266+ const slug = classNameSlug(hash, normalizeLabel(label), styleString)267+ if (slug) {268+ if (isValidKeyframeName(slug)) {269+ customSlug = slug270+ } else {271+ ;(onInvalidSlug || defaultOnInvalidSlug)(slug)272+ }273+ }274+ }275+276 return {277 [SELECTOR]: '',204- [CLASS_NAME]: `@keyframes ${toHash(label + styleString)}`,278+ [CLASS_NAME]: `@keyframes ${customSlug || hash}`,279 [STYLE_STRING]: styleString,280 [SELECTORS]: [],281 [EXTERNAL_CLASS_NAMES]: [],282 }283 }284 285 type ViewTransitionType = {212- (strings: TemplateStringsArray, values: CssVariableType[]): CssClassName286+ (287+ strings: TemplateStringsArray,288+ values: CssVariableType[],289+ classNameSlug?: ClassNameSlug,290+ onInvalidSlug?: OnInvalidSlug291+ ): CssClassName292 (content: CssClassName): CssClassName293 (): CssClassName294 }295 296 let viewTransitionNameIndex = 0297 export const viewTransitionCommon: ViewTransitionType = ((298 strings: TemplateStringsArray | CssClassName | undefined,220- values: CssVariableType[]299+ values: CssVariableType[],300+ classNameSlug?: ClassNameSlug,301+ onInvalidSlug?: OnInvalidSlug302 ): CssClassName => {303 if (!strings) {304 // eslint-disable-next-line @typescript-eslint/no-explicit-any305 strings = [`/* h-v-t ${viewTransitionNameIndex++} */`] as any306 }307 const content = Array.isArray(strings)227- ? cssCommon(strings as TemplateStringsArray, values)308+ ? cssCommon(strings as TemplateStringsArray, values, classNameSlug, onInvalidSlug)309 : (strings as CssClassName)310 311 const transitionName = content[CLASS_NAME]231- // eslint-disable-next-line @typescript-eslint/no-explicit-any232- const res = cssCommon(['view-transition-name:', ''] as any, [transitionName])312+ const res = cssCommon(313+ ['view-transition-name:', ''] as any, // eslint-disable-line @typescript-eslint/no-explicit-any314+ [transitionName],315+ classNameSlug,316+ onInvalidSlug317+ )318 319 content[CLASS_NAME] = PSEUDO_GLOBAL_SELECTOR + content[CLASS_NAME]320 content[STYLE_STRING] = content[STYLE_STRING].replace(321 /(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,7 unmodified linesmodified:src/helper/css/index.test.tsx+262 added
204 unmodified lines205 )206 })207 })208 209+ describe('classNameSlug', () => {210+ it('Should use custom classNameSlug function', async () => {211+ const { css: customCss, Style: customStyle } = createCssContext({212+ id: 'custom-slug',213+ classNameSlug: (hash, _label, _css) => `btn-${hash.split('-')[1]}`,214+ })215+ const btnClass = customCss`216+ background-color: blue;217+ `218+ const template = (219+ <>220+ {customStyle()}221+ <button class={btnClass}>Click</button>222+ </>223+ )224+ const result = await toString(template)225+ expect(result).toContain('.btn-')226+ expect(result).not.toContain('.css-')227+ })228+229+ it('Should pass label to classNameSlug', async () => {230+ const { css: customCss, Style: customStyle } = createCssContext({231+ id: 'label-slug',232+ classNameSlug: (hash, label) => (label ? `h-${label}` : hash),233+ })234+ const headerClass = customCss`235+ /* hero section */236+ background-color: blue;237+ `238+ const template = (239+ <>240+ {customStyle()}241+ <div class={headerClass}>Hero</div>242+ </>243+ )244+ const result = await toString(template)245+ expect(result).toContain('.h-hero-section')246+ expect(result).toContain('background-color:blue')247+ })248+249+ it('Should fall back to different hash values for labels with special characters', async () => {250+ const { css: customCss, Style: customStyle } = createCssContext({251+ id: 'label-deferent-slug',252+ classNameSlug: (hash, label) => (label ? `h-${label}` : hash),253+ })254+ const headerClass1 = customCss`255+ /* hero section! */256+ background-color: blue;257+ `258+ const headerClass2 = customCss`259+ /* hero section? */260+ background-color: blue;261+ `262+ const template = (263+ <>264+ {customStyle()}265+ <div class={headerClass1}>Hero</div>266+ <div class={headerClass2}>Hero</div>267+ </>268+ )269+ const result = await toString(template)270+271+ const classes = new Set<string>()272+ result.match(/class="(.*?)"/g)?.forEach((match) => {273+ classes.add(match)274+ })275+ expect(classes.size).toBe(2)276+ })277+278+ it('Should fall back to hash when label is empty', async () => {279+ const { css: customCss, Style: customStyle } = createCssContext({280+ id: 'fallback-slug',281+ classNameSlug: (hash, label) => (label ? `h-${label}` : hash),282+ })283+ const noLabelClass = customCss`284+ color: red;285+ `286+ const template = (287+ <>288+ {customStyle()}289+ <div class={noLabelClass}>No label</div>290+ </>291+ )292+ const result = await toString(template)293+ expect(result).toContain('.css-')294+ expect(result).toContain('color:red')295+ })296+297+ it('Should not affect default context when classNameSlug is not set', async () => {298+ const headerClass = css`299+ background-color: blue;300+ `301+ const template = (302+ <>303+ <Style />304+ <h1 class={headerClass}>Default</h1>305+ </>306+ )307+ const result = await toString(template)308+ expect(result).toContain('.css-2458908649')309+ expect(result).toContain('background-color:blue')310+ })311+312+ it('Should apply classNameSlug to keyframes', async () => {313+ const {314+ css: customCss,315+ keyframes: customKeyframes,316+ Style: customStyle,317+ } = createCssContext({318+ id: 'kf-slug',319+ classNameSlug: (hash, label) => (label ? `h-${label}` : hash),320+ })321+ const animation = customKeyframes`322+ /* fade-in */323+ from { opacity: 0; }324+ to { opacity: 1; }325+ `326+ const headerClass = customCss`327+ animation: ${animation} 1s ease-in-out;328+ `329+ const template = (330+ <>331+ {customStyle()}332+ <h1 class={headerClass}>Hello!</h1>333+ </>334+ )335+ const result = await toString(template)336+ expect(result).toContain('@keyframes h-fade-in')337+ expect(result).toContain('animation:h-fade-in 1s ease-in-out')338+ })339+340+ it('Should apply classNameSlug to viewTransition', async () => {341+ const {342+ css: customCss,343+ viewTransition: customViewTransition,344+ Style: customStyle,345+ } = createCssContext({346+ id: 'vt-slug',347+ classNameSlug: (hash, label) => (label ? `h-${label}` : hash),348+ })349+ const transition = customViewTransition(customCss`350+ /* hero */351+ display: flex;352+ `)353+ const template = (354+ <>355+ {customStyle()}356+ <h1 class={transition}>Hello!</h1>357+ </>358+ )359+ const result = await toString(template)360+ expect(result).toContain('view-transition-name:h-hero')361+ })362+363+ it('Should fall back to hash when classNameSlug returns invalid characters', async () => {364+ const { css: customCss, Style: customStyle } = createCssContext({365+ id: 'empty-slug',366+ classNameSlug: () => 'name!',367+ })368+ const headerClass = customCss`369+ display: flex;370+ `371+ const template = (372+ <>373+ {customStyle()}374+ <h1 class={headerClass}>Hello!</h1>375+ </>376+ )377+ const result = await toString(template)378+ expect(result).toContain('.css-')379+ expect(result).toContain('display:flex')380+ })381+382+ it('Should fall back to hash when classNameSlug starts with a number', async () => {383+ const { css: customCss, Style: customStyle } = createCssContext({384+ id: 'numeric-slug',385+ classNameSlug: () => '1hero',386+ })387+ const headerClass = customCss`388+ display: flex;389+ `390+ const template = (391+ <>392+ {customStyle()}393+ <h1 class={headerClass}>Hello!</h1>394+ </>395+ )396+ const result = await toString(template)397+ expect(result).toContain('.css-')398+ expect(result).toContain('display:flex')399+ expect(result).not.toContain('.1hero')400+ })401+402+ it('Should fall back to hash when label is empty and classNameSlug returns label', async () => {403+ const { css: customCss, Style: customStyle } = createCssContext({404+ id: 'empty-label-slug',405+ classNameSlug: (_, label) => label,406+ })407+ const headerClass = customCss`408+ display: flex;409+ `410+ const template = (411+ <>412+ {customStyle()}413+ <h1 class={headerClass}>Hello!</h1>414+ </>415+ )416+ const result = await toString(template)417+ expect(result).toContain('.css-')418+ expect(result).toContain('display:flex')419+ })420+421+ it('Should fall back to hash when keyframes name is a reserved keyword', async () => {422+ const {423+ css: customCss,424+ keyframes: customKeyframes,425+ Style: customStyle,426+ } = createCssContext({427+ id: 'reserved-kf-slug',428+ classNameSlug: () => 'none',429+ })430+ const animation = customKeyframes`431+ from { opacity: 0; }432+ to { opacity: 1; }433+ `434+ const headerClass = customCss`435+ animation: ${animation} 1s ease-in-out;436+ `437+ const template = (438+ <>439+ {customStyle()}440+ <h1 class={headerClass}>Hello!</h1>441+ </>442+ )443+ const result = await toString(template)444+ expect(result).toContain('@keyframes css-')445+ expect(result).toContain('animation:css-')446+ expect(result).not.toContain('@keyframes none')447+ expect(result).not.toContain('animation:none 1s ease-in-out')448+ })449+450+ it('Should call onInvalidSlug when an invalid slug is returned', async () => {451+ const onInvalidSlug = vi.fn()452+ const { css: customCss, Style: customStyle } = createCssContext({453+ id: 'on-invalid-slug',454+ classNameSlug: () => '123',455+ onInvalidSlug,456+ })457+ const headerClass = customCss`458+ display: flex;459+ `460+ const template = (461+ <>462+ {customStyle()}463+ <h1 class={headerClass}>Hello!</h1>464+ </>465+ )466+ await toString(template)467+ expect(onInvalidSlug).toHaveBeenCalledWith('123')468+ })469+ })470+471 describe('with application', () => {472 const app = new Hono()473 474 const headerClass = css`87 unmodified linesmodified:src/helper/css/index.ts+26 added-6 removed
5 unmodified lines6 import { raw } from '../../helper/html'7 import { DOM_RENDERER } from '../../jsx/constants'8 import { createCssJsxDomObjects } from '../../jsx/dom/css'9 import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'10-import type { CssClassName as CssClassNameCommon, CssVariableType } from './common'10+import type {11+ ClassNameSlug,12+ CssClassName as CssClassNameCommon,13+ CssVariableType,14+ OnInvalidSlug,15+} from './common'16 import {17 CLASS_NAME,18 DEFAULT_STYLE_ID,19 PSEUDO_GLOBAL_SELECTOR,5 unmodified lines25 keyframesCommon,26 viewTransitionCommon,27 } from './common'28 export { rawCssString } from './common'29+export type { ClassNameSlug, OnInvalidSlug } from './common'30 31 type CssClassName = HtmlEscapedString & CssClassNameCommon32 33 type usedClassNameData = [28 unmodified lines62 /**63 * @experimental64 * `createCssContext` is an experimental feature.65 * The API might be changed.66+ *67+ * @param options.id - The ID for the style element68+ * @param options.classNameSlug - Optional function to customize generated CSS class names69+ * @param options.onInvalidSlug - Optional callback function called when an invalid slug is returned from ClassNameSlug70 */61-export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {71+export const createCssContext = ({72+ id,73+ classNameSlug,74+ onInvalidSlug,75+}: {76+ id: Readonly<string>77+ classNameSlug?: ClassNameSlug78+ onInvalidSlug?: OnInvalidSlug79+}): DefaultContextType => {80 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })81 82 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()83 const nonceMap: WeakMap<object, string | undefined> = new WeakMap()72 unmodified lines156 return promise157 }158 159 const css: CssType = (strings, ...values) => {142- return newCssClassNameObject(cssCommon(strings, values))160+ return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug))161 }162 163 const cx: CxType = (...args) => {164 // eslint-disable-next-line @typescript-eslint/no-explicit-any1 unmodified line166 // eslint-disable-next-line @typescript-eslint/no-explicit-any167 return css(Array(args.length).fill('') as any, ...args)168 }169 152- const keyframes = keyframesCommon170+ const keyframes: KeyframesType = (strings, ...values) =>171+ keyframesCommon(strings, values, classNameSlug, onInvalidSlug)172 173 const viewTransition: ViewTransitionType = ((174 strings: TemplateStringsArray | Promise<string> | undefined,175 ...values: CssVariableType[]176 ) => {158- // eslint-disable-next-line @typescript-eslint/no-explicit-any159- return newCssClassNameObject(viewTransitionCommon(strings as any, values))177+ return newCssClassNameObject(178+ viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any179+ )180 }) as ViewTransitionType181 182 const Style: StyleType = ({ children, nonce } = {}) =>183 raw(69 unmodified linesmodified:src/jsx/dom/css.test.tsx+28 added
84 unmodified lines85868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912030 unmodified lines84 unmodified lines expect(root.innerHTML).toBe( '<div><style id="hono-css">color:red</style><div class="css-3142110215">red</div></div>' ) })
it('classNameSlug with createCssContext', async () => { const { css: customCss, Style: CustomStyle } = createCssContext({ id: 'custom-dom', classNameSlug: (hash, label) => (label ? `h-${label}` : hash), }) const App = () => { return ( <div> <CustomStyle /> <div class={customCss` /* hero */ color: blue; `} > blue </div> </div> ) } render(<App />, root) expect(root.innerHTML).toBe( '<div><style id="custom-dom"></style><div class="h-hero">blue</div></div>' ) await Promise.resolve() expect(root.querySelector('style')?.sheet?.cssRules[0].cssText).toBe('.h-hero {color: blue;}') })})
describe('render', () => { renderTest(() => {30 unmodified linesmodified:src/jsx/dom/css.ts+25 added-6 removed
2 unmodified lines3 * This module provides APIs that enable `hono/jsx/dom` to support.4 */5 6 import type { FC, PropsWithChildren } from '../'7-import type { CssClassName, CssVariableType } from '../../helper/css/common'7+import type {8+ ClassNameSlug,9+ CssClassName,10+ CssVariableType,11+ OnInvalidSlug,12+} from '../../helper/css/common'13 import {14 CLASS_NAME,15 DEFAULT_STYLE_ID,16 PSEUDO_GLOBAL_SELECTOR,154 unmodified lines171 /**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 */171-export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {180+export 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 })190 191 const newCssClassNameObject = (cssClassName: CssClassName): string => {192 cssClassName.toString = cssObject.toString193 return cssClassName as unknown as string194 }195 196 const css: CssType = (strings, ...values) => {180- return newCssClassNameObject(cssCommon(strings, values))197+ return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug))198 }199 200 const cx: CxType = (...args) => {201 // eslint-disable-next-line @typescript-eslint/no-explicit-any1 unmodified line203 // eslint-disable-next-line @typescript-eslint/no-explicit-any204 return css(Array(args.length).fill('') as any, ...args)205 }206 190- const keyframes: KeyframesType = keyframesCommon207+ const keyframes: KeyframesType = (strings, ...values) =>208+ keyframesCommon(strings, values, classNameSlug, onInvalidSlug)209 210 const viewTransition: ViewTransitionType = ((211 strings: TemplateStringsArray | string | undefined,212 ...values: CssVariableType[]213 ) => {196- // eslint-disable-next-line @typescript-eslint/no-explicit-any197- return newCssClassNameObject(viewTransitionCommon(strings as any, values))214+ return newCssClassNameObject(215+ viewTransitionCommon(strings as any, values, classNameSlug, onInvalidSlug) // eslint-disable-line @typescript-eslint/no-explicit-any216+ )217 }) as ViewTransitionType218 219 return {220 css,43 unmodified lines