Skip to content
Myr

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

authored by Wambui Maina · committed by GitHub · parent 9f374a5 · Browse files · 5 files+435 added−21 removed
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

5 files+435 added−21 removed

modified:src/helper/css/common.ts+94 added-9 removed
47 unmodified lines
48 }49 return 'css-' + out50}5152const normalizeLabel = (label: string): string => {53 return label.trim().replace(/\s+/g, '-')54}5556const isValidClassName = (name: string): boolean => /^-?[_a-zA-Z][_a-zA-Z0-9-]*$/.test(name)5758// CSS-wide keywords that are invalid as @keyframes names per the spec59const RESERVED_KEYFRAME_NAMES = new Set([60 'default',61 'inherit',62 'initial',63 'none',64 'revert',65 'revert-layer',66 'unset',67])68const isValidKeyframeName = (name: string): boolean =>69 isValidClassName(name) && !RESERVED_KEYFRAME_NAMES.has(name.toLowerCase())7071const defaultOnInvalidSlug = (slug: string) => {72 console.warn(`Invalid slug: ${slug}`)73}7475const cssStringReStr: string = [76 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string7778 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string
33 unmodified lines
112type CssVariableAsyncType = Promise<CssVariableBasicType>113type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]114export type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType115116/**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 */126export type ClassNameSlug = (hash: string, label: string, styleString: string) => string127128/**129 * A callback function called when an invalid slug is returned from ClassNameSlug.130 *131 * @param slug - The invalid slug132 */133export type OnInvalidSlug = (slug: string) => void134135export const buildStyleString = (136 strings: TemplateStringsArray,137 values: CssVariableType[]138): [string, string, CssClassName[], string[]] => {
56 unmodified lines
195}196197export 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)209210 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 }221222 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 lines
253}254255export 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)263264 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 }275276 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}284285type ViewTransitionType = {212 (strings: TemplateStringsArray, values: CssVariableType[]): CssClassName286 (287 strings: TemplateStringsArray,288 values: CssVariableType[],289 classNameSlug?: ClassNameSlug,290 onInvalidSlug?: OnInvalidSlug291 ): CssClassName292 (content: CssClassName): CssClassName293 (): CssClassName294}295296let viewTransitionNameIndex = 0297export 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)310311 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 )318319 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 lines
modified:src/helper/css/index.test.tsx+262 added
204 unmodified lines
205 )206 })207 })208209 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 })228229 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 })248249 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)270271 const classes = new Set<string>()272 result.match(/class="(.*?)"/g)?.forEach((match) => {273 classes.add(match)274 })275 expect(classes.size).toBe(2)276 })277278 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 })296297 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 })311312 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 })339340 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 })362363 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 })381382 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 })401402 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 })420421 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 })449450 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 })470471 describe('with application', () => {472 const app = new Hono()473474 const headerClass = css`
87 unmodified lines
modified:src/helper/css/index.ts+26 added-6 removed
5 unmodified lines
6import { raw } from '../../helper/html'7import { DOM_RENDERER } from '../../jsx/constants'8import { createCssJsxDomObjects } from '../../jsx/dom/css'9import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'10import type { CssClassName as CssClassNameCommon, CssVariableType } from './common'10import type {11 ClassNameSlug,12 CssClassName as CssClassNameCommon,13 CssVariableType,14 OnInvalidSlug,15} from './common'16import {17 CLASS_NAME,18 DEFAULT_STYLE_ID,19 PSEUDO_GLOBAL_SELECTOR,
5 unmodified lines
25 keyframesCommon,26 viewTransitionCommon,27} from './common'28export { rawCssString } from './common'29export type { ClassNameSlug, OnInvalidSlug } from './common'3031type CssClassName = HtmlEscapedString & CssClassNameCommon3233type usedClassNameData = [
28 unmodified lines
62/**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 */61export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {71export 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 })8182 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()83 const nonceMap: WeakMap<object, string | undefined> = new WeakMap()
72 unmodified lines
156 return promise157 }158159 const css: CssType = (strings, ...values) => {142 return newCssClassNameObject(cssCommon(strings, values))160 return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug))161 }162163 const cx: CxType = (...args) => {164 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1 unmodified line
166 // eslint-disable-next-line @typescript-eslint/no-explicit-any167 return css(Array(args.length).fill('') as any, ...args)168 }169152 const keyframes = keyframesCommon170 const keyframes: KeyframesType = (strings, ...values) =>171 keyframesCommon(strings, values, classNameSlug, onInvalidSlug)172173 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 ViewTransitionType181182 const Style: StyleType = ({ children, nonce } = {}) =>183 raw(
69 unmodified lines
modified:src/jsx/dom/css.test.tsx+28 added
modified:src/jsx/dom/css.ts+25 added-6 removed
2 unmodified lines
3 * This module provides APIs that enable `hono/jsx/dom` to support.4 */56import type { FC, PropsWithChildren } from '../'7import type { CssClassName, CssVariableType } from '../../helper/css/common'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,
154 unmodified lines
171/**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 */171export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {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) => {180 return newCssClassNameObject(cssCommon(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-any
1 unmodified line
203 // eslint-disable-next-line @typescript-eslint/no-explicit-any204 return css(Array(args.length).fill('') as any, ...args)205 }206190 const keyframes: KeyframesType = keyframesCommon207 const keyframes: KeyframesType = (strings, ...values) =>208 keyframesCommon(strings, values, classNameSlug, onInvalidSlug)209210 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 ViewTransitionType218219 return {220 css,
43 unmodified lines