index.test.tsx
This file
Path
src/helper/css/index.test.tsx
634 lines 路 19.0 KiB 路 TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoptioncd3f6f7
History of this fileTake it
1/** @jsxImportSource ../../jsx */2import { Hono } from '../../'3import { html } from '../../helper/html'4import type { JSXNode } from '../../jsx'5import { isValidElement } from '../../jsx'6import { Suspense, renderToReadableStream } from '../../jsx/streaming'7import type { HtmlEscapedString } from '../../utils/html'8import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'9import { renderTest } from './common.case.test'10import { Style, createCssContext, css, cx, keyframes, rawCssString, viewTransition } from './index'1112async function toString(13 template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString14) {15 if (template instanceof Promise) {16 template = (await template) as HtmlEscapedString17 }18 if (isValidElement(template)) {19 template = template.toString() as Promise<HtmlEscapedString>20 }21 return resolveCallback(await template, HtmlEscapedCallbackPhase.Stringify, false, template)22}2324async function toCSS(25 template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString26) {27 return (await toString(template))28 .replace(/.*?=(".*")<\/script.*/, '$1')29 .replace(/\.css-\d+/g, '.css-123')30}3132describe('CSS Helper', () => {33 renderTest(() => {34 return {35 css,36 Style,37 keyframes,38 viewTransition,39 rawCssString,40 createCssContext,41 toString,42 toCSS,43 support: {44 nest: true,45 },46 }47 })4849 describe('with `html` tag function', () => {50 it('Should render CSS styles with `html` tag function', async () => {51 const headerClass = css`52 background-color: blue;53 `54 const template = html`${Style()}55 <h1 class="${headerClass}">Hello!</h1>`56 expect(await toString(template)).toBe(57 `<style id="hono-css">.css-2458908649{background-color:blue}</style>58 <h1 class="css-2458908649">Hello!</h1>`59 )60 })6162 it('Should render CSS styles with `html` tag function and CSP nonce', async () => {63 const headerClass = css`64 background-color: blue;65 `66 const template = html`${Style({ nonce: '1234' })}67 <h1 class="${headerClass}">Hello!</h1>`68 expect(await toString(template)).toBe(69 `<style id="hono-css" nonce="1234">.css-2458908649{background-color:blue}</style>70 <h1 class="css-2458908649">Hello!</h1>`71 )72 })73 })7475 describe('cx()', () => {76 it('Should render CSS with cx()', async () => {77 const btn = css`78 border-radius: 4px;79 `80 const btnPrimary = css`81 background-color: blue;82 color: white;83 `8485 const template = (86 <>87 <Style />88 <h1 class={cx(btn, btnPrimary)}>Hello!</h1>89 </>90 )91 expect(await toString(template)).toBe(92 '<style id="hono-css">.css-2395710522{border-radius:4px;background-color:blue;color:white}</style><h1 class="css-2395710522">Hello!</h1>'93 )94 })9596 it('Should render CSS with cx() includes external class name', async () => {97 const btn = css`98 border-radius: 4px;99 `100101 const template = (102 <>103 <Style />104 <h1 class={cx(btn, 'external-class')}>Hello!</h1>105 </>106 )107 expect(await toString(template)).toBe(108 '<style id="hono-css">.css-3467431616{border-radius:4px}</style><h1 class="css-3467431616 external-class">Hello!</h1>'109 )110 })111112 it('Should render CSS with cx() includes nested external class name', async () => {113 const btn = css`114 border-radius: 4px;115 `116 const btn2 = cx(btn, 'external-class')117 const btn3 = css`118 ${btn2}119 color: white;120 `121 const btn4 = cx(btn3, 'external-class2')122 const template = (123 <>124 <Style />125 <h1 class={btn4}>Hello!</h1>126 </>127 )128 expect(await toString(template)).toBe(129 '<style id="hono-css">.css-3358636561{border-radius:4px;color:white}</style><h1 class="css-3358636561 external-class external-class2">Hello!</h1>'130 )131 })132133 it('Should escape external class name to prevent XSS via attribute injection', async () => {134 const btn = css`135 border-radius: 4px;136 `137138 const template = (139 <>140 <Style />141 <h1 class={cx(btn, '" onmouseover=alert(1) x="')}>Hello!</h1>142 </>143 )144 // the injected `"` is escaped to `"`, so it cannot close the class attribute145 const result = await toString(template)146 expect(result).toContain('class="css-3467431616 " onmouseover=alert(1) x=""')147 })148149 it('Should keep special characters in external class name working in attribute context', async () => {150 const btn = css`151 border-radius: 4px;152 `153154 const template = (155 <>156 <Style />157 <h1 class={cx(btn, '[&>*]:p-1')}>Hello!</h1>158 </>159 )160 // escaped entities are decoded back to the original class name by the browser161 expect(await toString(template)).toContain('class="css-3467431616 [&>*]:p-1"')162 })163164 it('Should keep special characters in external class name working as a selector', async () => {165 const btn = css`166 border-radius: 4px;167 `168 const wrapper = css`169 ${cx(btn, '[&>*]:p-1')} {170 color: red;171 }172 `173174 const template = (175 <>176 <Style />177 <div class={wrapper}>Hello!</div>178 </>179 )180 // legitimate class names (incl. Tailwind arbitrary values) are kept verbatim in the selector181 expect(await toString(template)).toContain('.css-3467431616 [&>*]:p-1{')182 })183184 it('Should drop external class names that could break out of a style element', async () => {185 const btn = css`186 border-radius: 4px;187 `188 // `</style>` (HTML breakout) and `{}` (CSS rule injection) are dropped from the selector189 for (const payload of ['</style><script>alert(1)</script>', 'a{}body{display:none}']) {190 const wrapper = css`191 ${cx(btn, payload)} {192 color: red;193 }194 `195 const result = await toString(196 <>197 <Style />198 <div class={wrapper}>Hello!</div>199 </>200 )201 expect(result).not.toContain('</style><script>')202 expect(result).not.toContain('body{display:none}')203 }204 })205 })206207 describe('minify', () => {208 const data: [string, Promise<string>, string][] = [209 [210 'basic CSS styles',211 css`212 background-color: blue;213 color: white;214 padding: 1rem;215 `,216 '.css-123{background-color:blue;color:white;padding:1rem}',217 ],218 [219 'remove comments',220 css`221 /* background-color: blue; */222 color: white;223 padding: 1rem;224 // inline comment225 margin: 1rem;226 `,227 '.css-123{color:white;padding:1rem;margin:1rem}',228 ],229 [230 'preserve string',231 css`232 background-color: blue;233 color: white;234 padding: 1rem;235 content: "Hel \\\n \\' lo!";236 content: 'Hel \\\n \\" lo!';237 `,238 '.css-123{background-color:blue;color:white;padding:1rem;content:"Hel \\\n \\\' lo!";content:\'Hel \\\n \\" lo!\'}',239 ],240 [241 'preserve nested selectors',242 css`243 padding: 1rem;244 &:hover {245 padding: 2rem;246 }247 `,248 '.css-123{padding:1rem;&:hover{padding:2rem}}',249 ],250 ]251 data.forEach(([name, str, expected]) => {252 it(`Should be minified while preserving content accurately: ${name}`, async () => {253 expect(JSON.parse(await toCSS(str))).toBe(expected)254 })255 })256 })257258 describe('createCssContext()', () => {259 it('Should create a new CSS context', async () => {260 const { css: css1, Style: Style1 } = createCssContext({ id: 'context1' })261 const { css: css2, Style: Style2 } = createCssContext({ id: 'context2' })262 const headerClass1 = css1`263 background-color: blue;264 `265 const headerClass2 = css2`266 background-color: red;267 `268 const template = (269 <>270 <Style1 />271 <Style2 />272 <h1 class={headerClass1}>Hello!</h1>273 <h1 class={headerClass2}>Hello!</h1>274 </>275 )276 expect(await toString(template)).toBe(277 '<style id="context1">.css-2458908649{background-color:blue}</style><style id="context2">.css-960045552{background-color:red}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-960045552">Hello!</h1>'278 )279 })280 })281282 describe('classNameSlug', () => {283 it('Should use custom classNameSlug function', async () => {284 const { css: customCss, Style: customStyle } = createCssContext({285 id: 'custom-slug',286 classNameSlug: (hash, _label, _css) => `btn-${hash.split('-')[1]}`,287 })288 const btnClass = customCss`289 background-color: blue;290 `291 const template = (292 <>293 {customStyle()}294 <button class={btnClass}>Click</button>295 </>296 )297 const result = await toString(template)298 expect(result).toContain('.btn-')299 expect(result).not.toContain('.css-')300 })301302 it('Should pass label to classNameSlug', async () => {303 const { css: customCss, Style: customStyle } = createCssContext({304 id: 'label-slug',305 classNameSlug: (hash, label) => (label ? `h-${label}` : hash),306 })307 const headerClass = customCss`308 /* hero section */309 background-color: blue;310 `311 const template = (312 <>313 {customStyle()}314 <div class={headerClass}>Hero</div>315 </>316 )317 const result = await toString(template)318 expect(result).toContain('.h-hero-section')319 expect(result).toContain('background-color:blue')320 })321322 it('Should fall back to different hash values for labels with special characters', async () => {323 const { css: customCss, Style: customStyle } = createCssContext({324 id: 'label-deferent-slug',325 classNameSlug: (hash, label) => (label ? `h-${label}` : hash),326 })327 const headerClass1 = customCss`328 /* hero section! */329 background-color: blue;330 `331 const headerClass2 = customCss`332 /* hero section? */333 background-color: blue;334 `335 const template = (336 <>337 {customStyle()}338 <div class={headerClass1}>Hero</div>339 <div class={headerClass2}>Hero</div>340 </>341 )342 const result = await toString(template)343344 const classes = new Set<string>()345 result.match(/class="(.*?)"/g)?.forEach((match) => {346 classes.add(match)347 })348 expect(classes.size).toBe(2)349 })350351 it('Should fall back to hash when label is empty', async () => {352 const { css: customCss, Style: customStyle } = createCssContext({353 id: 'fallback-slug',354 classNameSlug: (hash, label) => (label ? `h-${label}` : hash),355 })356 const noLabelClass = customCss`357 color: red;358 `359 const template = (360 <>361 {customStyle()}362 <div class={noLabelClass}>No label</div>363 </>364 )365 const result = await toString(template)366 expect(result).toContain('.css-')367 expect(result).toContain('color:red')368 })369370 it('Should not affect default context when classNameSlug is not set', async () => {371 const headerClass = css`372 background-color: blue;373 `374 const template = (375 <>376 <Style />377 <h1 class={headerClass}>Default</h1>378 </>379 )380 const result = await toString(template)381 expect(result).toContain('.css-2458908649')382 expect(result).toContain('background-color:blue')383 })384385 it('Should apply classNameSlug to keyframes', async () => {386 const {387 css: customCss,388 keyframes: customKeyframes,389 Style: customStyle,390 } = createCssContext({391 id: 'kf-slug',392 classNameSlug: (hash, label) => (label ? `h-${label}` : hash),393 })394 const animation = customKeyframes`395 /* fade-in */396 from { opacity: 0; }397 to { opacity: 1; }398 `399 const headerClass = customCss`400 animation: ${animation} 1s ease-in-out;401 `402 const template = (403 <>404 {customStyle()}405 <h1 class={headerClass}>Hello!</h1>406 </>407 )408 const result = await toString(template)409 expect(result).toContain('@keyframes h-fade-in')410 expect(result).toContain('animation:h-fade-in 1s ease-in-out')411 })412413 it('Should apply classNameSlug to viewTransition', async () => {414 const {415 css: customCss,416 viewTransition: customViewTransition,417 Style: customStyle,418 } = createCssContext({419 id: 'vt-slug',420 classNameSlug: (hash, label) => (label ? `h-${label}` : hash),421 })422 const transition = customViewTransition(customCss`423 /* hero */424 display: flex;425 `)426 const template = (427 <>428 {customStyle()}429 <h1 class={transition}>Hello!</h1>430 </>431 )432 const result = await toString(template)433 expect(result).toContain('view-transition-name:h-hero')434 })435436 it('Should fall back to hash when classNameSlug returns invalid characters', async () => {437 const { css: customCss, Style: customStyle } = createCssContext({438 id: 'empty-slug',439 classNameSlug: () => 'name!',440 })441 const headerClass = customCss`442 display: flex;443 `444 const template = (445 <>446 {customStyle()}447 <h1 class={headerClass}>Hello!</h1>448 </>449 )450 const result = await toString(template)451 expect(result).toContain('.css-')452 expect(result).toContain('display:flex')453 })454455 it('Should fall back to hash when classNameSlug starts with a number', async () => {456 const { css: customCss, Style: customStyle } = createCssContext({457 id: 'numeric-slug',458 classNameSlug: () => '1hero',459 })460 const headerClass = customCss`461 display: flex;462 `463 const template = (464 <>465 {customStyle()}466 <h1 class={headerClass}>Hello!</h1>467 </>468 )469 const result = await toString(template)470 expect(result).toContain('.css-')471 expect(result).toContain('display:flex')472 expect(result).not.toContain('.1hero')473 })474475 it('Should fall back to hash when label is empty and classNameSlug returns label', async () => {476 const { css: customCss, Style: customStyle } = createCssContext({477 id: 'empty-label-slug',478 classNameSlug: (_, label) => label,479 })480 const headerClass = customCss`481 display: flex;482 `483 const template = (484 <>485 {customStyle()}486 <h1 class={headerClass}>Hello!</h1>487 </>488 )489 const result = await toString(template)490 expect(result).toContain('.css-')491 expect(result).toContain('display:flex')492 })493494 it('Should fall back to hash when keyframes name is a reserved keyword', async () => {495 const {496 css: customCss,497 keyframes: customKeyframes,498 Style: customStyle,499 } = createCssContext({500 id: 'reserved-kf-slug',501 classNameSlug: () => 'none',502 })503 const animation = customKeyframes`504 from { opacity: 0; }505 to { opacity: 1; }506 `507 const headerClass = customCss`508 animation: ${animation} 1s ease-in-out;509 `510 const template = (511 <>512 {customStyle()}513 <h1 class={headerClass}>Hello!</h1>514 </>515 )516 const result = await toString(template)517 expect(result).toContain('@keyframes css-')518 expect(result).toContain('animation:css-')519 expect(result).not.toContain('@keyframes none')520 expect(result).not.toContain('animation:none 1s ease-in-out')521 })522523 it('Should call onInvalidSlug when an invalid slug is returned', async () => {524 const onInvalidSlug = vi.fn()525 const { css: customCss, Style: customStyle } = createCssContext({526 id: 'on-invalid-slug',527 classNameSlug: () => '123',528 onInvalidSlug,529 })530 const headerClass = customCss`531 display: flex;532 `533 const template = (534 <>535 {customStyle()}536 <h1 class={headerClass}>Hello!</h1>537 </>538 )539 await toString(template)540 expect(onInvalidSlug).toHaveBeenCalledWith('123')541 })542 })543544 describe('with application', () => {545 const app = new Hono()546547 const headerClass = css`548 background-color: blue;549 `550551 app.get('/sync', (c) =>552 c.html(553 <>554 <Style />555 <h1 class={headerClass}>Hello!</h1>556 </>557 )558 )559560 app.get('/stream', (c) => {561 const stream = renderToReadableStream(562 <>563 <Style />564 <Suspense fallback={<p>Loading...</p>}>565 <h1 class={headerClass}>Hello!</h1>566 </Suspense>567 </>568 )569 return c.body(stream, {570 headers: {571 'Content-Type': 'text/html; charset=UTF-8',572 'Transfer-Encoding': 'chunked',573 },574 })575 })576577 app.get('/stream-with-nonce', (c) => {578 const stream = renderToReadableStream(579 <>580 <Style nonce='1234' />581 <Suspense fallback={<p>Loading...</p>}>582 <h1 class={headerClass}>Hello!</h1>583 </Suspense>584 </>585 )586 return c.body(stream, {587 headers: {588 'Content-Type': 'text/html; charset=UTF-8',589 'Transfer-Encoding': 'chunked',590 },591 })592 })593594 it('/sync', async () => {595 const res = await app.request('http://localhost/sync')596 expect(res).not.toBeNull()597 expect(await res.text()).toBe(598 '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'599 )600 })601602 it('/stream', async () => {603 const res = await app.request('http://localhost/stream')604 expect(res).not.toBeNull()605 expect(await res.text()).toBe(606 `<style id="hono-css"></style><template id="H:0"></template><p>Loading...</p><!--/$--><script>document.querySelector('#hono-css').textContent+=".css-2458908649{background-color:blue}"</script><template data-hono-target="H:0"><h1 class="css-2458908649">Hello!</h1></template><script>607((d,c,n) => {608c=d.currentScript.previousSibling609d=d.getElementById('H:0')610if(!d)return611do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')612d.replaceWith(c.content)613})(document)614</script>`615 )616 })617618 it('/stream-with-nonce', async () => {619 const res = await app.request('http://localhost/stream-with-nonce')620 expect(res).not.toBeNull()621 expect(await res.text()).toBe(622 `<style id="hono-css" nonce="1234"></style><template id="H:1"></template><p>Loading...</p><!--/$--><script nonce="1234">document.querySelector('#hono-css').textContent+=".css-2458908649{background-color:blue}"</script><template data-hono-target="H:1"><h1 class="css-2458908649">Hello!</h1></template><script>623((d,c,n) => {624c=d.currentScript.previousSibling625d=d.getElementById('H:1')626if(!d)return627do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')628d.replaceWith(c.content)629})(document)630</script>`631 )632 })633 })634})