feat: introduce css Helper (#1850)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: introduce CSS Helper * shorten * feat(css): Implement css helper with callback (#1858) * feat(css): Implement css helper with callback * feat(css): add keyframes and pseudo selectors support * fix(css): Specify missing "context" argument in resolveCallback() * feat(css): use WeakMap instead of Map, to avoid memory leak * feat(css): improve CSS helper * fix(css): fix formatting and types in css helper * chore: denoify * docs(css): add experimental flag to css helper * feat(css): Enable to embed sub `css`. * fix(css): propagate selector to parent class * feat(css): Use Record again for usedClassNameData * feat(css): escape only close tag "</...>", not all slashes. we can use url() without escaping. * fix(css): embedded `css` must have ";" * Fix format. * feat(css): add cx() helper `cx()` is a helper function to combine multiple css classes. This function is compatible with `cx()` in @emotion/css. * feat(css): ignore boolean, null, and undefined values as same as jsx * chore: denoify * feat(css): enable to use cx() with external class name * refactor(css): use symbols for keys * chore: denoify ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
18 files+1336 added−91 removed
- tests:+503 added−20 removed
- other:+833 added−71 removed
Provenance
- Commit
74287a8- Tree
4d6faf8- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
b8b0b38
18 files changed+1336 added−91 removed
added:deno_dist/helper/css/index.ts+306 added
1+import { raw } from '../../helper/html/index.ts'2+import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html.ts'3+4+const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5+const STYLE_STRING = Symbol('STYLE_STRING')6+const SELECTORS = Symbol('SELECTORS')7+const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8+type CssClassName = HtmlEscapedString & {9+ [IS_CSS_CLASS_NAME]: true10+ [STYLE_STRING]: string11+ // eslint-disable-next-line @typescript-eslint/ban-types12+ [SELECTORS]: String[]13+ [EXTERNAL_CLASS_NAMES]: string[]14+}15+16+type CssEscaped = {17+ isCssEscaped: true18+}19+type CssEscapedString = string & CssEscaped20+21+/**22+ * @experimental23+ * `rawCssString` is an experimental feature.24+ * The API might be changed.25+ */26+export const rawCssString = (value: string): CssEscapedString => {27+ const escapedString = new String(value) as CssEscapedString28+ escapedString.isCssEscaped = true29+ return escapedString30+}31+32+const DEFAULT_STYLE_ID = 'hono-css'33+34+/**35+ * Used the goober'code as a reference:36+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37+ * MIT License, Copyright (c) 2019 Cristian Bote38+ */39+const toHash = (str: string): string => {40+ let i = 0,41+ out = 1142+ while (i < str.length) {43+ out = (101 * out + str.charCodeAt(i++)) >>> 044+ }45+ return 'css-' + out46+}47+48+const cssStringReStr = [49+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50+ // eslint-disable-next-line quotes51+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52+].join('|')53+const minifyCssRe = new RegExp(54+ [55+ '(' + cssStringReStr + ')', // $1: quoted string56+57+ '(?:' +58+ [59+ '^\\s+', // head whitespace60+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment61+ '\\/\\/.*\\n\\s*', // single-line comment62+ '\\s+$', // tail whitespace63+ ].join('|') +64+ ')',65+66+ ';\\s*(}|$)\\s*', // $2: trailing semicolon67+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68+ '(\\s)\\s+', // $4: 2+ spaces69+ ].join('|'),70+ 'g'71+)72+73+const minify = (css: string): string => {74+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75+}76+77+type usedClassNameData = [78+ Record<string, string>, // class name to add79+ Record<string, true> // class name already added80+]81+// eslint-disable-next-line @typescript-eslint/ban-types82+type CssVariableBasicType = string | String | number | boolean | null | undefined83+type CssVariableAsyncType = Promise<CssVariableBasicType>84+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85+type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType86+87+const buildStyleString = async (88+ strings: TemplateStringsArray,89+ values: CssVariableType[],90+ // eslint-disable-next-line @typescript-eslint/ban-types91+ selectors: String[],92+ externalClassNames: string[]93+): Promise<string> => {94+ let styleString = ''95+ for (let i = 0; i < strings.length; i++) {96+ styleString += strings[i]97+ let vArray = values[i]98+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99+ continue100+ }101+102+ if (!Array.isArray(vArray)) {103+ vArray = [vArray] as CssVariableArrayType104+ }105+ for (let j = 0; j < vArray.length; j++) {106+ let value = (107+ vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108+ ) as CssVariableBasicType109+ if (typeof value === 'boolean' || value === null || value === undefined) {110+ continue111+ }112+ if (typeof value === 'number') {113+ styleString += value114+ } else if (value.startsWith('@keyframes ')) {115+ selectors.push(value)116+ styleString += ` ${value.substring(11)} `117+ } else {118+ if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119+ selectors.push(...(value as CssClassName)[SELECTORS])120+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121+ value = (value as CssClassName)[STYLE_STRING]122+ if (value.length > 0) {123+ const lastChar = value[value.length - 1]124+ if (lastChar !== ';' && lastChar !== '}') {125+ value += ';'126+ }127+ }128+ } else if (129+ !(value as CssEscapedString).isCssEscaped &&130+ /([\\"'\/])/.test(value as string)131+ ) {132+ value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133+ }134+ styleString += `${value || ''}`135+ }136+ }137+ }138+139+ return minify(styleString)140+}141+142+/**143+ * @experimental144+ * `createCssContext` is an experimental feature.145+ * The API might be changed.146+ */147+export const createCssContext = ({ id }: { id: Readonly<string> }) => {148+ const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149+150+ const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151+152+ const css = async (153+ strings: TemplateStringsArray,154+ ...values: CssVariableType[]155+ ): Promise<string> => {156+ // eslint-disable-next-line @typescript-eslint/ban-types157+ const selectors: String[] = []158+ const externalClassNames: string[] = []159+ const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160+ const thisSelector = toHash(thisStyleString)161+ const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162+163+ const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164+ const [toAdd, added] = contextMap.get(context) as usedClassNameData165+ const names = Object.keys(toAdd)166+167+ if (!names.length) {168+ return169+ }170+171+ let stylesStr = ''172+ names.forEach((className) => {173+ added[className] = true174+ stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175+ })176+ contextMap.set(context, [{}, added])177+178+ if (buffer && replaceStyleRe.test(buffer[0])) {179+ buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180+ return181+ }182+183+ const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184+ stylesStr185+ )}</script>`186+ if (buffer) {187+ buffer[0] = `${appendStyleScript}${buffer[0]}`188+ return189+ }190+191+ return Promise.resolve(appendStyleScript)192+ }193+194+ const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {195+ if (!contextMap.get(context)) {196+ contextMap.set(context, [{}, {}])197+ }198+ const [toAdd, added] = contextMap.get(context) as usedClassNameData199+ let allAdded = true200+ if (!added[thisSelector]) {201+ allAdded = false202+ toAdd[thisSelector] = thisStyleString203+ }204+ selectors.forEach((className) => {205+ if (!added[`${className}`]) {206+ allAdded = false207+ toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]208+ }209+ })210+ if (allAdded) {211+ return212+ }213+214+ return Promise.resolve(raw('', [appendStyle]))215+ }216+217+ Object.assign(className, {218+ isEscaped: true,219+ callbacks: [addClassNameToContext],220+ [IS_CSS_CLASS_NAME]: true,221+ [STYLE_STRING]: thisStyleString,222+ [SELECTORS]: selectors,223+ [EXTERNAL_CLASS_NAMES]: externalClassNames,224+ })225+226+ return className as string227+ }228+229+ const cx = async (230+ ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]231+ ): Promise<string> => {232+ const resolvedArgs = await Promise.all(args)233+ for (let i = 0; i < resolvedArgs.length; i++) {234+ const arg = resolvedArgs[i]235+ if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236+ const externalClassName = new String(arg) as CssClassName237+ resolvedArgs[i] = Object.assign(externalClassName, {238+ isEscaped: true,239+ [IS_CSS_CLASS_NAME]: true,240+ [STYLE_STRING]: '',241+ [SELECTORS]: [],242+ [EXTERNAL_CLASS_NAMES]: [arg],243+ })244+ }245+ }246+247+ // eslint-disable-next-line @typescript-eslint/no-explicit-any248+ return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249+ }250+251+ const keyframes = async (252+ strings: TemplateStringsArray,253+ ...values: CssVariableType[]254+ ): // eslint-disable-next-line @typescript-eslint/ban-types255+ Promise<String> => {256+ const styleString = await buildStyleString(strings, values, [], [])257+ const className = new String(`@keyframes ${toHash(styleString)}`)258+ Object.assign(className as CssClassName, {259+ isEscaped: true,260+ [IS_CSS_CLASS_NAME]: true,261+ [STYLE_STRING]: styleString,262+ [SELECTORS]: [],263+ [EXTERNAL_CLASS_NAMES]: [],264+ })265+ return className266+ }267+268+ const Style = () => raw(`<style id="${id}"></style>`)269+270+ return {271+ css,272+ cx,273+ keyframes,274+ Style,275+ }276+}277+278+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279+280+/**281+ * @experimental282+ * `css` is an experimental feature.283+ * The API might be changed.284+ */285+export const css = defaultContext.css286+287+/**288+ * @experimental289+ * `cx` is an experimental feature.290+ * The API might be changed.291+ */292+export const cx = defaultContext.cx293+294+/**295+ * @experimental296+ * `keyframes` is an experimental feature.297+ * The API might be changed.298+ */299+export const keyframes = defaultContext.keyframes300+301+/**302+ * @experimental303+ * `Style` is an experimental feature.304+ * The API might be changed.305+ */306+export const Style = defaultContext.Stylemodified:deno_dist/jsx/components.ts+29 added-9 removed
1223456789101130 unmodified lines424344454647484349505152535455565758592 unmodified lines62636465666768697017 unmodified lines88899091849293949596869798998910010110210310420 unmodified lines12512612712812913013113213313413513613713811913914012112212314114214314414514614736 unmodified linesimport { raw } from '../helper/html/index.ts'import type { HtmlEscapedString } from '../utils/html.ts'import { HtmlEscapedCallbackPhase, resolveCallback, type HtmlEscapedString, type HtmlEscapedCallback,} from '../utils/html.ts'import type { FC, Child } from './index.ts'
let errorBoundaryCounter = 0
30 unmodified lines if (!Array.isArray(children)) { children = [children] }
let fallbackStr: string | undefined const fallbackRes = (error: Error): HtmlEscapedString => { onError?.(error) return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString return (fallbackStr || fallbackRender?.(error) || '').toString() as HtmlEscapedString } let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = [] try { resArray = children.map((c) => c.toString()) as HtmlEscapedString[] } catch (e) { fallbackStr = await fallback?.toString() if (e instanceof Promise) { resArray = [ e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)), ] as Promise<HtmlEscapedString[]>[]2 unmodified lines } }
if (resArray.some((res) => (res as {}) instanceof Promise)) { fallbackStr ||= await fallback?.toString() const index = errorBoundaryCounter++ const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`) const caught = false const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {17 unmodified lines})(document)</script>` } return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [ ({ buffer }) => { ({ phase, buffer, context }) => { if (phase === HtmlEscapedCallbackPhase.BeforeStream) { return } return Promise.all(resArray) .then((htmlArray) => { .then(async (htmlArray) => { htmlArray = htmlArray.flat() const content = htmlArray.join('') const html = buffer let html = buffer ? '' : `<template>${content}</template><script>((d,c) => {c=d.currentScript.previousSibling20 unmodified lines const callbacks = htmlArray .map((html) => (html as HtmlEscapedString).callbacks || []) .flat()
if (phase === HtmlEscapedCallbackPhase.Stream) { html = await resolveCallback( html, HtmlEscapedCallbackPhase.BeforeStream, true, context ) }
let resolvedCount = 0 const promises = callbacks.map( const promises = callbacks.map<HtmlEscapedCallback>( (c) => ({ buffer }: { buffer: [string] }) => c({ buffer }) .then((content) => { (...args) => c(...args) ?.then((content) => { resolvedCount++
if (buffer) { if (resolvedCount === callbacks.length) {36 unmodified linesmodified:deno_dist/jsx/index.ts+3 added
143 unmodified lines144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146 147 children = [raw(v.__html)]148+ } else if (v instanceof Promise) {149+ buffer[0] += ` ${key}="`150+ buffer.unshift('"', v)151 } else {152 buffer[0] += ` ${key}="`153 escapeToBuffer(v.toString(), buffer)154 buffer[0] += '"'139 unmodified linesmodified:deno_dist/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines22 23 interface HTMLAttributes extends JSXAttributes, AnyAttributes {24 accesskey?: string | undefined25 autofocus?: boolean | undefined26- class?: string | undefined26+ class?: string | Promise<string> | undefined27 contenteditable?: boolean | 'inherit' | undefined28 contextmenu?: string | undefined29 dir?: string | undefined30 draggable?: boolean | undefined576 unmodified linesmodified:deno_dist/jsx/streaming.ts+40 added-16 removed
1 import { raw } from '../helper/html/index.ts'2+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'3 import type { HtmlEscapedString } from '../utils/html.ts'4 import { childrenToString } from './components.ts'5 import type { FC, Child } from './index.ts'6 27 unmodified lines34 }35 36 if (resArray.some((res) => (res as {}) instanceof Promise)) {37 const index = suspenseCounter++37- return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38- ({ buffer }) => {39- return Promise.all(resArray).then((htmlArray) => {38+ const fallbackStr = await fallback.toString()39+ return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [40+ ...(fallbackStr.callbacks || []),41+ ({ phase, buffer, context }) => {42+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {43+ return44+ }45+ return Promise.all(resArray).then(async (htmlArray) => {46 htmlArray = htmlArray.flat()47 const content = htmlArray.join('')48 if (buffer) {49 buffer[0] = buffer[0].replace(50 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),51 content52 )53 }48- const html = buffer54+ let html = buffer55 ? ''56 : `<template>${content}</template><script>57 ((d,c,n) => {58 c=d.currentScript.previousSibling2 unmodified lines61 do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62 d.replaceWith(c.content)63 })(document)64 </script>`59- if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {65+66+ const callbacks = htmlArray67+ .map((html) => (html as HtmlEscapedString).callbacks || [])68+ .flat()69+ if (!callbacks.length) {70 return html71 }72 63- return raw(64- html,65- htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66- )73+ if (phase === HtmlEscapedCallbackPhase.Stream) {74+ html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context)75+ }76+77+ return raw(html, callbacks)78 })79 },80 ])81 } else {11 unmodified lines93 str: HtmlEscapedString | Promise<HtmlEscapedString>94 ): ReadableStream<Uint8Array> => {95 const reader = new ReadableStream<Uint8Array>({96 async start(controller) {86- const resolved = str instanceof Promise ? await str : await str.toString()97+ const tmp = str instanceof Promise ? await str : await str.toString()98+ const context = typeof tmp === 'object' ? tmp : {}99+ const resolved = await resolveCallback(100+ tmp,101+ HtmlEscapedCallbackPhase.BeforeStream,102+ true,103+ context104+ )105 controller.enqueue(textEncoder.encode(resolved))106 107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []3 unmodified lines112 .catch((err) => {113 console.trace(err)114 return ''115 })98- .then((res) => {99- if ((res as HtmlEscapedString).callbacks) {100- const callbacks = (res as HtmlEscapedString).callbacks || []101- callbacks.map((c) => c({})).forEach(then)102- }116+ .then(async (res) => {117+ res = await resolveCallback(res, HtmlEscapedCallbackPhase.BeforeStream, true, context)118+ ;(res as HtmlEscapedString).callbacks119+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))120+ // eslint-disable-next-line @typescript-eslint/no-explicit-any121+ .filter<Promise<string>>(Boolean as any)122+ .forEach(then)123 resolvedCount++124 controller.enqueue(textEncoder.encode(res))125 })126 )127 }108- ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)128+ ;(resolved as HtmlEscapedString).callbacks129+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))130+ // eslint-disable-next-line @typescript-eslint/no-explicit-any131+ .filter<Promise<string>>(Boolean as any)132+ .forEach(then)133 while (resolvedCount !== callbacks.length) {134 await Promise.all(callbacks)135 }136 5 unmodified linesmodified:deno_dist/utils/html.ts+31 added-7 removed
1-type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2-export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1+export const HtmlEscapedCallbackPhase = {2+ Stringify: 1,3+ BeforeStream: 2,4+ Stream: 3,5+} as const6+type HtmlEscapedCallbackOpts = {7+ buffer?: [string]8+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]9+ context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10+}11+export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15 }93 unmodified lines109 110 buffer[0] += str.substring(lastIndex, index)111 }112 104-export const resolveStream = (113+export const resolveCallback = async (114 str: string | HtmlEscapedString,115+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],116+ preserveCallbacks: boolean,117+ context: object,118 buffer?: [string]119 ): Promise<string> => {108- if (!(str as HtmlEscapedString).callbacks?.length) {120+ const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]121+ if (!callbacks?.length) {122 return Promise.resolve(str)123 }111- const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]124 if (buffer) {125 buffer[0] += str126 } else {127 buffer = [str]128 }117- return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>118- Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])129+130+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>131+ Promise.all(132+ res133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ .filter<string>(Boolean as any)135+ .map((str) => resolveCallback(str, phase, false, context, buffer))136+ ).then(() => (buffer as [string])[0])137 )138+139+ if (preserveCallbacks) {140+ return raw(await resStr, callbacks)141+ } else {142+ return resStr143+ }144 }modified:deno_dist/context.ts+2 added-2 removed
1 unmodified line2 import type { HonoRequest } from './request.ts'3 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'4 import type { CookieOptions } from './utils/cookie.ts'5 import { serialize } from './utils/cookie.ts'6-import { resolveStream } from './utils/html.ts'6+import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'7 import type { StatusCode } from './utils/http-status.ts'8 import { StreamingApi } from './utils/stream.ts'9 import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types.ts'10 343 unmodified lines354 html = (html as string).toString() // HtmlEscapedString object to string355 }356 if ((html as string | Promise<string>) instanceof Promise) {357 return (html as unknown as Promise<string>)358- .then((html) => resolveStream(html))358+ .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))359 .then((html) => {360 return typeof arg === 'number'361 ? this.newResponse(html, arg, headers)362 : this.newResponse(html, arg)117 unmodified linesadded:src/helper/css/index.test.tsx+473 added
1+import { Hono } from '../../'2+import { html } from '../../helper/html'3+import { jsx, Fragment, JSXNode } from '../../jsx'4+import { Suspense, renderToReadableStream } from '../../jsx/streaming'5+import type { HtmlEscapedString } from '../../utils/html'6+import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'7+import { css, cx, keyframes, rawCssString, Style, createCssContext } from './index'8+9+async function toString(10+ template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString11+) {12+ if (template instanceof Promise) template = (await template) as HtmlEscapedString13+ if (template instanceof JSXNode) template = template.toString() as Promise<HtmlEscapedString>14+ return resolveCallback(await template, HtmlEscapedCallbackPhase.Stringify, false, template)15+}16+17+async function toCSS(18+ template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString19+) {20+ return (await toString(template))21+ .replace(/.*?=(".*")<\/script.*/, '$1')22+ .replace(/\.css-\d+/g, '.css-123')23+}24+25+describe('CSS Helper', () => {26+ describe('render css', () => {27+ it('Should render CSS styles with JSX', async () => {28+ const headerClass = css`29+ background-color: blue;30+ `31+ const template = (32+ <>33+ <Style />34+ <h1 class={headerClass}>Hello!</h1>35+ </>36+ )37+ expect(await toString(template)).toBe(38+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'39+ )40+ })41+42+ it('Should render CSS styles with `html` tag function', async () => {43+ const headerClass = css`44+ background-color: blue;45+ `46+ const template = html`${Style()}47+ <h1 class="${headerClass}">Hello!</h1>`48+ expect(await toString(template)).toBe(49+ `<style id="hono-css">.css-2458908649{background-color:blue}</style>50+ <h1 class="css-2458908649">Hello!</h1>`51+ )52+ })53+54+ it('Should render CSS with keyframes', async () => {55+ const animation = keyframes`56+ from {57+ opacity: 0;58+ }59+ to {60+ opacity: 1;61+ }62+ `63+ const headerClass = css`64+ background-color: blue;65+ animation: ${animation} 1s ease-in-out;66+ `67+ const template = (68+ <>69+ <Style />70+ <h1 class={headerClass}>Hello!</h1>71+ </>72+ )73+ expect(await toString(template)).toBe(74+ '<style id="hono-css">.css-1580801783{background-color:blue;animation:css-9294673 1s ease-in-out}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-1580801783">Hello!</h1>'75+ )76+ })77+78+ it('Should not output the same class name multiple times.', async () => {79+ const headerClass = css`80+ background-color: blue;81+ `82+ const headerClass2 = css`83+ background-color: blue;84+ `85+ const template = (86+ <>87+ <Style />88+ <h1 class={headerClass}>Hello!</h1>89+ <h1 class={headerClass2}>Hello2!</h1>90+ </>91+ )92+ expect(await toString(template)).toBe(93+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-2458908649">Hello2!</h1>'94+ )95+ })96+97+ it('Should render CSS with variable', async () => {98+ const headerClass = css`99+ background-color: blue;100+ content: '${'I\'m a variable!'}';101+ `102+ const template = (103+ <>104+ <Style />105+ <h1 class={headerClass}>Hello!</h1>106+ </>107+ )108+ expect(await toString(template)).toBe(109+ '<style id="hono-css">.css-4027435072{background-color:blue;content:\'I\\\'m a variable!\'}</style><h1 class="css-4027435072">Hello!</h1>'110+ )111+ })112+113+ it('Should escape </style>', async () => {114+ const headerClass = css`115+ background-color: blue;116+ content: '${'</style>'}';117+ `118+ const template = (119+ <>120+ <Style />121+ <h1 class={headerClass}>Hello!</h1>122+ </>123+ )124+ expect(await toString(template)).toBe(125+ '<style id="hono-css">.css-372954897{background-color:blue;content:\'<\\/style>\'}</style><h1 class="css-372954897">Hello!</h1>'126+ )127+ })128+129+ it('Should not escape URL', async () => {130+ const headerClass = css`131+ background-color: blue;132+ background: url('${'http://www.example.com/path/to/file.jpg'}');133+ `134+ const template = (135+ <>136+ <Style />137+ <h1 class={headerClass}>Hello!</h1>138+ </>139+ )140+ expect(await toString(template)).toBe(141+ '<style id="hono-css">.css-1321888780{background-color:blue;background:url(\'http://www.example.com/path/to/file.jpg\')}</style><h1 class="css-1321888780">Hello!</h1>'142+ )143+ })144+145+ it('Should render CSS with escaped variable', async () => {146+ const headerClass = css`147+ background-color: blue;148+ content: '${rawCssString('say "Hello!"')}';149+ `150+ const template = (151+ <>152+ <Style />153+ <h1 class={headerClass}>Hello!</h1>154+ </>155+ )156+ expect(await toString(template)).toBe(157+ '<style id="hono-css">.css-2238574885{background-color:blue;content:\'say "Hello!"\'}</style><h1 class="css-2238574885">Hello!</h1>'158+ )159+ })160+161+ it('Should render CSS with async variable', async () => {162+ const headerClass = css`163+ background-color: blue;164+ content: '${(async () => {165+ await new Promise((resolve) => setTimeout(resolve, 100))166+ return 'I\'m an async variable!'167+ })()}';168+ `169+ const template = (170+ <>171+ <Style />172+ <h1 class={headerClass}>Hello!</h1>173+ </>174+ )175+ expect(await toString(template)).toBe(176+ '<style id="hono-css">.css-1399451752{background-color:blue;content:\'I\\\'m an async variable!\'}</style><h1 class="css-1399451752">Hello!</h1>'177+ )178+ })179+180+ it('Should render CSS with number', async () => {181+ const headerClass = css`182+ background-color: blue;183+ font-size: ${1}rem;184+ `185+ const template = (186+ <>187+ <Style />188+ <h1 class={headerClass}>Hello!</h1>189+ </>190+ )191+ expect(await toString(template)).toBe(192+ '<style id="hono-css">.css-1847536026{background-color:blue;font-size:1rem}</style><h1 class="css-1847536026">Hello!</h1>'193+ )194+ })195+196+ it('Should render CSS with array', async () => {197+ const animation = keyframes`198+ from {199+ opacity: 0;200+ }201+ to {202+ opacity: 1;203+ }204+ `205+ const headerClass = css`206+ background-color: blue;207+ animation: ${animation} 1s ease-in-out;208+ `209+ const extendedHeaderClass = css`210+ ${headerClass}211+ color: red;212+ `213+ const template = (214+ <>215+ <Style />216+ <h1 class={extendedHeaderClass}>Hello!</h1>217+ </>218+ )219+ expect(await toString(template)).toBe(220+ '<style id="hono-css">.css-2558359670{background-color:blue;animation:css-9294673 1s ease-in-out;color:red}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-2558359670">Hello!</h1>'221+ )222+ })223+224+ describe('Booleans, Null, and Undefined Are Ignored', () => {225+ it.each([true, false, undefined, null])('%s', async (value) => {226+ const headerClass = css`227+ ${value}228+ background-color: blue;229+ `230+ const template = (231+ <>232+ <Style />233+ <h1 class={headerClass}>Hello!</h1>234+ </>235+ )236+ expect(await toString(template)).toBe(237+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'238+ )239+ })240+241+ it('falsy value', async () => {242+ const value = 0243+ const headerClass = css`244+ padding: ${value};245+ `246+ const template = (247+ <>248+ <Style />249+ <h1 class={headerClass}>Hello!</h1>250+ </>251+ )252+ expect(await toString(template)).toBe(253+ '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'254+ )255+ })256+ })257+ })258+259+ it('Should render sub CSS with keyframe', async () => {260+ const headerClass = css`261+ background-color: blue;262+ ${[1, 2].map(263+ (i) =>264+ css`265+ :nth-child(${i}) {266+ color: red;267+ }268+ `269+ )}270+ `271+ const template = (272+ <>273+ <Style />274+ <h1 class={headerClass}>Hello!</h1>275+ </>276+ )277+ expect(await toString(template)).toBe(278+ '<style id="hono-css">.css-1539881271{background-color:blue;:nth-child(1){color:red}:nth-child(2){color:red}}</style><h1 class="css-1539881271">Hello!</h1>'279+ )280+ })281+282+ describe('cx()', () => {283+ it('Should render CSS with cx()', async () => {284+ const btn = css`285+ border-radius: 4px;286+ `287+ const btnPrimary = css`288+ background-color: blue;289+ color: white;290+ `291+292+ const template = (293+ <>294+ <Style />295+ <h1 class={cx(btn, btnPrimary)}>Hello!</h1>296+ </>297+ )298+ expect(await toString(template)).toBe(299+ '<style id="hono-css">.css-2395710522{border-radius:4px;background-color:blue;color:white}</style><h1 class="css-2395710522">Hello!</h1>'300+ )301+ })302+303+ it('Should render CSS with cx() includes external class name', async () => {304+ const btn = css`305+ border-radius: 4px;306+ `307+308+ const template = (309+ <>310+ <Style />311+ <h1 class={cx(btn, 'external-class')}>Hello!</h1>312+ </>313+ )314+ expect(await toString(template)).toBe(315+ '<style id="hono-css">.css-3467431616{border-radius:4px}</style><h1 class="css-3467431616 external-class">Hello!</h1>'316+ )317+ })318+319+ it('Should render CSS with cx() includes nested external class name', async () => {320+ const btn = css`321+ border-radius: 4px;322+ `323+ const btn2 = cx(btn, 'external-class')324+ const btn3 = css`325+ ${btn2}326+ color: white;327+ `328+ const btn4 = cx(btn3, 'external-class2')329+ const template = (330+ <>331+ <Style />332+ <h1 class={btn4}>Hello!</h1>333+ </>334+ )335+ expect(await toString(template)).toBe(336+ '<style id="hono-css">.css-3358636561{border-radius:4px;color:white}</style><h1 class="css-3358636561 external-class external-class2">Hello!</h1>'337+ )338+ })339+ })340+341+ describe('minify', () => {342+ const data: [string, Promise<string>, string][] = [343+ [344+ 'basic CSS styles',345+ css`346+ background-color: blue;347+ color: white;348+ padding: 1rem;349+ `,350+ '.css-123{background-color:blue;color:white;padding:1rem}',351+ ],352+ [353+ 'remove comments',354+ css`355+ /* background-color: blue; */356+ color: white;357+ padding: 1rem;358+ // inline comment359+ margin: 1rem;360+ `,361+ '.css-123{color:white;padding:1rem;margin:1rem}',362+ ],363+ [364+ 'preserve string',365+ css`366+ background-color: blue;367+ color: white;368+ padding: 1rem;369+ content: "Hel \\\n \\' lo!";370+ content: 'Hel \\\n \\" lo!';371+ `,372+ '.css-123{background-color:blue;color:white;padding:1rem;content:"Hel \\\n \\\' lo!";content:\'Hel \\\n \\" lo!\'}',373+ ],374+ [375+ 'preserve nested selectors',376+ css`377+ padding: 1rem;378+ &:hover {379+ padding: 2rem;380+ }381+ `,382+ '.css-123{padding:1rem;&:hover{padding:2rem}}',383+ ],384+ ]385+ data.forEach(([name, str, expected]) => {386+ it(`Should be minified while preserving content accurately: ${name}`, async () => {387+ expect(JSON.parse(await toCSS(str))).toBe(expected)388+ })389+ })390+ })391+392+ describe('createCssContext()', () => {393+ it('Should create a new CSS context', async () => {394+ const { css: css1, Style: Style1 } = createCssContext({ id: 'context1' })395+ const { css: css2, Style: Style2 } = createCssContext({ id: 'context2' })396+ const headerClass1 = css1`397+ background-color: blue;398+ `399+ const headerClass2 = css2`400+ background-color: red;401+ `402+ const template = (403+ <>404+ <Style1 />405+ <Style2 />406+ <h1 class={headerClass1}>Hello!</h1>407+ <h1 class={headerClass2}>Hello!</h1>408+ </>409+ )410+ expect(await toString(template)).toBe(411+ '<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>'412+ )413+ })414+ })415+416+ describe('with application', () => {417+ const app = new Hono()418+419+ const headerClass = css`420+ background-color: blue;421+ `422+423+ app.get('/sync', (c) =>424+ c.html(425+ <>426+ <Style />427+ <h1 class={headerClass}>Hello!</h1>428+ </>429+ )430+ )431+432+ app.get('/stream', (c) => {433+ const stream = renderToReadableStream(434+ <>435+ <Style />436+ <Suspense fallback={<p>Loading...</p>}>437+ <h1 class={headerClass}>Hello!</h1>438+ </Suspense>439+ </>440+ )441+ return c.body(stream, {442+ headers: {443+ 'Content-Type': 'text/html; charset=UTF-8',444+ 'Transfer-Encoding': 'chunked',445+ },446+ })447+ })448+449+ it('/sync', async () => {450+ const res = await app.request('http://localhost/sync')451+ expect(res).not.toBeNull()452+ expect(await res.text()).toBe(453+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'454+ )455+ })456+457+ it('/stream', async () => {458+ const res = await app.request('http://localhost/stream')459+ expect(res).not.toBeNull()460+ expect(await res.text()).toBe(461+ `<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><h1 class="css-2458908649">Hello!</h1></template><script>462+((d,c,n) => {463+c=d.currentScript.previousSibling464+d=d.getElementById('H:0')465+if(!d)return466+do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')467+d.replaceWith(c.content)468+})(document)469+</script>`470+ )471+ })472+ })473+})added:src/helper/css/index.ts+306 added
1+import { raw } from '../../helper/html'2+import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'3+4+const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5+const STYLE_STRING = Symbol('STYLE_STRING')6+const SELECTORS = Symbol('SELECTORS')7+const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8+type CssClassName = HtmlEscapedString & {9+ [IS_CSS_CLASS_NAME]: true10+ [STYLE_STRING]: string11+ // eslint-disable-next-line @typescript-eslint/ban-types12+ [SELECTORS]: String[]13+ [EXTERNAL_CLASS_NAMES]: string[]14+}15+16+type CssEscaped = {17+ isCssEscaped: true18+}19+type CssEscapedString = string & CssEscaped20+21+/**22+ * @experimental23+ * `rawCssString` is an experimental feature.24+ * The API might be changed.25+ */26+export const rawCssString = (value: string): CssEscapedString => {27+ const escapedString = new String(value) as CssEscapedString28+ escapedString.isCssEscaped = true29+ return escapedString30+}31+32+const DEFAULT_STYLE_ID = 'hono-css'33+34+/**35+ * Used the goober'code as a reference:36+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37+ * MIT License, Copyright (c) 2019 Cristian Bote38+ */39+const toHash = (str: string): string => {40+ let i = 0,41+ out = 1142+ while (i < str.length) {43+ out = (101 * out + str.charCodeAt(i++)) >>> 044+ }45+ return 'css-' + out46+}47+48+const cssStringReStr = [49+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50+ // eslint-disable-next-line quotes51+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52+].join('|')53+const minifyCssRe = new RegExp(54+ [55+ '(' + cssStringReStr + ')', // $1: quoted string56+57+ '(?:' +58+ [59+ '^\\s+', // head whitespace60+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment61+ '\\/\\/.*\\n\\s*', // single-line comment62+ '\\s+$', // tail whitespace63+ ].join('|') +64+ ')',65+66+ ';\\s*(}|$)\\s*', // $2: trailing semicolon67+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68+ '(\\s)\\s+', // $4: 2+ spaces69+ ].join('|'),70+ 'g'71+)72+73+const minify = (css: string): string => {74+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75+}76+77+type usedClassNameData = [78+ Record<string, string>, // class name to add79+ Record<string, true> // class name already added80+]81+// eslint-disable-next-line @typescript-eslint/ban-types82+type CssVariableBasicType = string | String | number | boolean | null | undefined83+type CssVariableAsyncType = Promise<CssVariableBasicType>84+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85+type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType86+87+const buildStyleString = async (88+ strings: TemplateStringsArray,89+ values: CssVariableType[],90+ // eslint-disable-next-line @typescript-eslint/ban-types91+ selectors: String[],92+ externalClassNames: string[]93+): Promise<string> => {94+ let styleString = ''95+ for (let i = 0; i < strings.length; i++) {96+ styleString += strings[i]97+ let vArray = values[i]98+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99+ continue100+ }101+102+ if (!Array.isArray(vArray)) {103+ vArray = [vArray] as CssVariableArrayType104+ }105+ for (let j = 0; j < vArray.length; j++) {106+ let value = (107+ vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108+ ) as CssVariableBasicType109+ if (typeof value === 'boolean' || value === null || value === undefined) {110+ continue111+ }112+ if (typeof value === 'number') {113+ styleString += value114+ } else if (value.startsWith('@keyframes ')) {115+ selectors.push(value)116+ styleString += ` ${value.substring(11)} `117+ } else {118+ if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119+ selectors.push(...(value as CssClassName)[SELECTORS])120+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121+ value = (value as CssClassName)[STYLE_STRING]122+ if (value.length > 0) {123+ const lastChar = value[value.length - 1]124+ if (lastChar !== ';' && lastChar !== '}') {125+ value += ';'126+ }127+ }128+ } else if (129+ !(value as CssEscapedString).isCssEscaped &&130+ /([\\"'\/])/.test(value as string)131+ ) {132+ value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133+ }134+ styleString += `${value || ''}`135+ }136+ }137+ }138+139+ return minify(styleString)140+}141+142+/**143+ * @experimental144+ * `createCssContext` is an experimental feature.145+ * The API might be changed.146+ */147+export const createCssContext = ({ id }: { id: Readonly<string> }) => {148+ const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149+150+ const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151+152+ const css = async (153+ strings: TemplateStringsArray,154+ ...values: CssVariableType[]155+ ): Promise<string> => {156+ // eslint-disable-next-line @typescript-eslint/ban-types157+ const selectors: String[] = []158+ const externalClassNames: string[] = []159+ const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160+ const thisSelector = toHash(thisStyleString)161+ const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162+163+ const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164+ const [toAdd, added] = contextMap.get(context) as usedClassNameData165+ const names = Object.keys(toAdd)166+167+ if (!names.length) {168+ return169+ }170+171+ let stylesStr = ''172+ names.forEach((className) => {173+ added[className] = true174+ stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175+ })176+ contextMap.set(context, [{}, added])177+178+ if (buffer && replaceStyleRe.test(buffer[0])) {179+ buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180+ return181+ }182+183+ const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184+ stylesStr185+ )}</script>`186+ if (buffer) {187+ buffer[0] = `${appendStyleScript}${buffer[0]}`188+ return189+ }190+191+ return Promise.resolve(appendStyleScript)192+ }193+194+ const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {195+ if (!contextMap.get(context)) {196+ contextMap.set(context, [{}, {}])197+ }198+ const [toAdd, added] = contextMap.get(context) as usedClassNameData199+ let allAdded = true200+ if (!added[thisSelector]) {201+ allAdded = false202+ toAdd[thisSelector] = thisStyleString203+ }204+ selectors.forEach((className) => {205+ if (!added[`${className}`]) {206+ allAdded = false207+ toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]208+ }209+ })210+ if (allAdded) {211+ return212+ }213+214+ return Promise.resolve(raw('', [appendStyle]))215+ }216+217+ Object.assign(className, {218+ isEscaped: true,219+ callbacks: [addClassNameToContext],220+ [IS_CSS_CLASS_NAME]: true,221+ [STYLE_STRING]: thisStyleString,222+ [SELECTORS]: selectors,223+ [EXTERNAL_CLASS_NAMES]: externalClassNames,224+ })225+226+ return className as string227+ }228+229+ const cx = async (230+ ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]231+ ): Promise<string> => {232+ const resolvedArgs = await Promise.all(args)233+ for (let i = 0; i < resolvedArgs.length; i++) {234+ const arg = resolvedArgs[i]235+ if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236+ const externalClassName = new String(arg) as CssClassName237+ resolvedArgs[i] = Object.assign(externalClassName, {238+ isEscaped: true,239+ [IS_CSS_CLASS_NAME]: true,240+ [STYLE_STRING]: '',241+ [SELECTORS]: [],242+ [EXTERNAL_CLASS_NAMES]: [arg],243+ })244+ }245+ }246+247+ // eslint-disable-next-line @typescript-eslint/no-explicit-any248+ return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249+ }250+251+ const keyframes = async (252+ strings: TemplateStringsArray,253+ ...values: CssVariableType[]254+ ): // eslint-disable-next-line @typescript-eslint/ban-types255+ Promise<String> => {256+ const styleString = await buildStyleString(strings, values, [], [])257+ const className = new String(`@keyframes ${toHash(styleString)}`)258+ Object.assign(className as CssClassName, {259+ isEscaped: true,260+ [IS_CSS_CLASS_NAME]: true,261+ [STYLE_STRING]: styleString,262+ [SELECTORS]: [],263+ [EXTERNAL_CLASS_NAMES]: [],264+ })265+ return className266+ }267+268+ const Style = () => raw(`<style id="${id}"></style>`)269+270+ return {271+ css,272+ cx,273+ keyframes,274+ Style,275+ }276+}277+278+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279+280+/**281+ * @experimental282+ * `css` is an experimental feature.283+ * The API might be changed.284+ */285+export const css = defaultContext.css286+287+/**288+ * @experimental289+ * `cx` is an experimental feature.290+ * The API might be changed.291+ */292+export const cx = defaultContext.cx293+294+/**295+ * @experimental296+ * `keyframes` is an experimental feature.297+ * The API might be changed.298+ */299+export const keyframes = defaultContext.keyframes300+301+/**302+ * @experimental303+ * `Style` is an experimental feature.304+ * The API might be changed.305+ */306+export const Style = defaultContext.Stylemodified:src/jsx/components.test.tsx+19 added-14 removed
1 import { JSDOM } from 'jsdom'2-import { resolveStream } from '../utils/html'2+import type { HtmlEscapedString } from '../utils/html'3+import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'4 import { ErrorBoundary } from './components'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars6-import { jsx, Fragment } from './index'7+import { jsx } from './index'8 9+function resolveCallback(template: string | HtmlEscapedString) {10+ return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})11+}12+13 function replacementResult(html: string) {14 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document15 document.querySelectorAll('template, script').forEach((e) => e.remove())16 return document.body.innerHTML23 unmodified lines40 <Component />41 </ErrorBoundary>42 )43 39- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')44+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')45 46 errorBoundaryCounter--47 suspenseCounter--48 })4 unmodified lines53 <Component error={true} />54 </ErrorBoundary>55 )56 52- expect((await resolveStream(await html.toString())).toString()).toEqual(57+ expect((await resolveCallback(await html.toString())).toString()).toEqual(58 '<div>Out Of Service</div>'59 )60 61 suspenseCounter--15 unmodified lines77 <Component />78 </ErrorBoundary>79 )80 76- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')81+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')82 83 errorBoundaryCounter--84 suspenseCounter--85 })4 unmodified lines90 <Component error={true} />91 </ErrorBoundary>92 )93 89- expect((await resolveStream(await html.toString())).toString()).toEqual(94+ expect((await resolveCallback(await html.toString())).toString()).toEqual(95 '<div>Out Of Service</div>'96 )97 98 suspenseCounter--18 unmodified lines117 ).toString()118 119 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))120 116- expect((await resolveStream(await html)).toString()).toEqual('<div>1</div><div>2</div>')121+ expect((await resolveCallback(await html)).toString()).toEqual('<div>1</div><div>2</div>')122 123 errorBoundaryCounter++124 suspenseCounter--125 })10 unmodified lines136 137 handlers[2].resolve(undefined)138 handlers[1].reject()139 135- expect((await resolveStream(await html)).toString()).toEqual('<div>Out Of Service</div>')140+ expect((await resolveCallback(await html)).toString()).toEqual('<div>Out Of Service</div>')141 142 errorBoundaryCounter++143 suspenseCounter--144 })10 unmodified lines155 156 handlers[1].resolve(undefined)157 handlers[2].reject()158 154- expect((await resolveStream(await html)).toString()).toEqual(159+ expect((await resolveCallback(await html)).toString()).toEqual(160 '<div>1</div><div>Out Of Service</div>'161 )162 163 errorBoundaryCounter++65 unmodified lines229 <Component error={true} />230 </ErrorBoundary>231 )232 228- expect((await resolveStream(await html.toString())).toString()).toEqual(233+ expect((await resolveCallback(await html.toString())).toString()).toEqual(234 '<div>Out Of Service</div>'235 )236 })237 })170 unmodified lines408 <Component />409 </ErrorBoundary>410 )411 407- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')412+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')413 414 errorBoundaryCounter--415 suspenseCounter--416 7 unmodified lines424 <Component error={true} />425 </ErrorBoundary>426 )427 423- expect((await resolveStream(await html.toString())).toString()).toEqual(428+ expect((await resolveCallback(await html.toString())).toString()).toEqual(429 '<div>Out Of Service</div>'430 )431 432 suspenseCounter--18 unmodified lines451 <Component />452 </ErrorBoundary>453 )454 450- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')455+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')456 457 errorBoundaryCounter--458 suspenseCounter--459 6 unmodified lines466 <Component error={true} />467 </ErrorBoundary>468 )469 465- expect((await resolveStream(await html.toString())).toString()).toEqual(470+ expect((await resolveCallback(await html.toString())).toString()).toEqual(471 '<div data-error="true">Error</div>'472 )473 474 suspenseCounter--3 unmodified linesmodified:src/jsx/components.ts+29 added-9 removed
1 import { raw } from '../helper/html'2-import type { HtmlEscapedString } from '../utils/html'2+import {3+ HtmlEscapedCallbackPhase,4+ resolveCallback,5+ type HtmlEscapedString,6+ type HtmlEscapedCallback,7+} from '../utils/html'8 import type { FC, Child } from './index'9 10 let errorBoundaryCounter = 011 30 unmodified lines42 if (!Array.isArray(children)) {43 children = [children]44 }45 46+ let fallbackStr: string | undefined47 const fallbackRes = (error: Error): HtmlEscapedString => {48 onError?.(error)43- return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString49+ return (fallbackStr || fallbackRender?.(error) || '').toString() as HtmlEscapedString50 }51 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []52 try {53 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]54 } catch (e) {55+ fallbackStr = await fallback?.toString()56 if (e instanceof Promise) {57 resArray = [58 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),59 ] as Promise<HtmlEscapedString[]>[]2 unmodified lines62 }63 }64 65 if (resArray.some((res) => (res as {}) instanceof Promise)) {66+ fallbackStr ||= await fallback?.toString()67 const index = errorBoundaryCounter++68 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)69 const caught = false70 const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {17 unmodified lines88 })(document)89 </script>`90 }91 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [84- ({ buffer }) => {92+ ({ phase, buffer, context }) => {93+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {94+ return95+ }96 return Promise.all(resArray)86- .then((htmlArray) => {97+ .then(async (htmlArray) => {98 htmlArray = htmlArray.flat()99 const content = htmlArray.join('')89- const html = buffer100+ let html = buffer101 ? ''102 : `<template>${content}</template><script>103 ((d,c) => {104 c=d.currentScript.previousSibling20 unmodified lines125 const callbacks = htmlArray126 .map((html) => (html as HtmlEscapedString).callbacks || [])127 .flat()128 129+ if (phase === HtmlEscapedCallbackPhase.Stream) {130+ html = await resolveCallback(131+ html,132+ HtmlEscapedCallbackPhase.BeforeStream,133+ true,134+ context135+ )136+ }137+138 let resolvedCount = 0119- const promises = callbacks.map(139+ const promises = callbacks.map<HtmlEscapedCallback>(140 (c) =>121- ({ buffer }: { buffer: [string] }) =>122- c({ buffer })123- .then((content) => {141+ (...args) =>142+ c(...args)143+ ?.then((content) => {144 resolvedCount++145 146 if (buffer) {147 if (resolvedCount === callbacks.length) {36 unmodified linesmodified:src/jsx/index.ts+3 added
143 unmodified lines144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146 147 children = [raw(v.__html)]148+ } else if (v instanceof Promise) {149+ buffer[0] += ` ${key}="`150+ buffer.unshift('"', v)151 } else {152 buffer[0] += ` ${key}="`153 escapeToBuffer(v.toString(), buffer)154 buffer[0] += '"'139 unmodified linesmodified:src/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines22 23 interface HTMLAttributes extends JSXAttributes, AnyAttributes {24 accesskey?: string | undefined25 autofocus?: boolean | undefined26- class?: string | undefined26+ class?: string | Promise<string> | undefined27 contenteditable?: boolean | 'inherit' | undefined28 contextmenu?: string | undefined29 dir?: string | undefined30 draggable?: boolean | undefined576 unmodified linesmodified:src/jsx/streaming.test.tsx+11 added-6 removed
1 import { JSDOM } from 'jsdom'2 import { raw } from '../helper/html'3-import { resolveStream } from '../utils/html'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4 import type { HtmlEscapedString } from '../utils/html'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7 import { jsx, Fragment } from './index'510 unmodified lines518 )519 return content520 }521 522+ const str = await resolveCallback(522- const str = await resolveStream(await (523- <Suspense fallback={<p>Loading...</p>}>524- <Content />525- </Suspense>526- ).toString())523+ await (524+ <Suspense fallback={<p>Loading...</p>}>525+ <Content />526+ </Suspense>527+ ).toString(),528+ HtmlEscapedCallbackPhase.Stream,529+ false,530+ {}531+ )532 533 expect(str).toEqual('<h1>Hello</h1>')534 expect(contentEvaluatedCount).toEqual(1)535 })26 unmodified linesmodified:src/jsx/streaming.ts+40 added-16 removed
1 import { raw } from '../helper/html'2+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'3 import type { HtmlEscapedString } from '../utils/html'4 import { childrenToString } from './components'5 import type { FC, Child } from './index'6 27 unmodified lines34 }35 36 if (resArray.some((res) => (res as {}) instanceof Promise)) {37 const index = suspenseCounter++37- return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38- ({ buffer }) => {39- return Promise.all(resArray).then((htmlArray) => {38+ const fallbackStr = await fallback.toString()39+ return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [40+ ...(fallbackStr.callbacks || []),41+ ({ phase, buffer, context }) => {42+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {43+ return44+ }45+ return Promise.all(resArray).then(async (htmlArray) => {46 htmlArray = htmlArray.flat()47 const content = htmlArray.join('')48 if (buffer) {49 buffer[0] = buffer[0].replace(50 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),51 content52 )53 }48- const html = buffer54+ let html = buffer55 ? ''56 : `<template>${content}</template><script>57 ((d,c,n) => {58 c=d.currentScript.previousSibling2 unmodified lines61 do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62 d.replaceWith(c.content)63 })(document)64 </script>`59- if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {65+66+ const callbacks = htmlArray67+ .map((html) => (html as HtmlEscapedString).callbacks || [])68+ .flat()69+ if (!callbacks.length) {70 return html71 }72 63- return raw(64- html,65- htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66- )73+ if (phase === HtmlEscapedCallbackPhase.Stream) {74+ html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context)75+ }76+77+ return raw(html, callbacks)78 })79 },80 ])81 } else {11 unmodified lines93 str: HtmlEscapedString | Promise<HtmlEscapedString>94 ): ReadableStream<Uint8Array> => {95 const reader = new ReadableStream<Uint8Array>({96 async start(controller) {86- const resolved = str instanceof Promise ? await str : await str.toString()97+ const tmp = str instanceof Promise ? await str : await str.toString()98+ const context = typeof tmp === 'object' ? tmp : {}99+ const resolved = await resolveCallback(100+ tmp,101+ HtmlEscapedCallbackPhase.BeforeStream,102+ true,103+ context104+ )105 controller.enqueue(textEncoder.encode(resolved))106 107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []3 unmodified lines112 .catch((err) => {113 console.trace(err)114 return ''115 })98- .then((res) => {99- if ((res as HtmlEscapedString).callbacks) {100- const callbacks = (res as HtmlEscapedString).callbacks || []101- callbacks.map((c) => c({})).forEach(then)102- }116+ .then(async (res) => {117+ res = await resolveCallback(res, HtmlEscapedCallbackPhase.BeforeStream, true, context)118+ ;(res as HtmlEscapedString).callbacks119+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))120+ // eslint-disable-next-line @typescript-eslint/no-explicit-any121+ .filter<Promise<string>>(Boolean as any)122+ .forEach(then)123 resolvedCount++124 controller.enqueue(textEncoder.encode(res))125 })126 )127 }108- ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)128+ ;(resolved as HtmlEscapedString).callbacks129+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))130+ // eslint-disable-next-line @typescript-eslint/no-explicit-any131+ .filter<Promise<string>>(Boolean as any)132+ .forEach(then)133 while (resolvedCount !== callbacks.length) {134 await Promise.all(callbacks)135 }136 5 unmodified linesmodified:src/utils/html.ts+31 added-7 removed
1-type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2-export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1+export const HtmlEscapedCallbackPhase = {2+ Stringify: 1,3+ BeforeStream: 2,4+ Stream: 3,5+} as const6+type HtmlEscapedCallbackOpts = {7+ buffer?: [string]8+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]9+ context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10+}11+export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15 }93 unmodified lines109 110 buffer[0] += str.substring(lastIndex, index)111 }112 104-export const resolveStream = (113+export const resolveCallback = async (114 str: string | HtmlEscapedString,115+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],116+ preserveCallbacks: boolean,117+ context: object,118 buffer?: [string]119 ): Promise<string> => {108- if (!(str as HtmlEscapedString).callbacks?.length) {120+ const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]121+ if (!callbacks?.length) {122 return Promise.resolve(str)123 }111- const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]124 if (buffer) {125 buffer[0] += str126 } else {127 buffer = [str]128 }117- return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>118- Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])129+130+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>131+ Promise.all(132+ res133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ .filter<string>(Boolean as any)135+ .map((str) => resolveCallback(str, phase, false, context, buffer))136+ ).then(() => (buffer as [string])[0])137 )138+139+ if (preserveCallbacks) {140+ return raw(await resStr, callbacks)141+ } else {142+ return resStr143+ }144 }modified:src/context.ts+2 added-2 removed
1 unmodified line2 import type { HonoRequest } from './request'3 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'4 import type { CookieOptions } from './utils/cookie'5 import { serialize } from './utils/cookie'6-import { resolveStream } from './utils/html'6+import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'7 import type { StatusCode } from './utils/http-status'8 import { StreamingApi } from './utils/stream'9 import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types'10 343 unmodified lines354 html = (html as string).toString() // HtmlEscapedString object to string355 }356 if ((html as string | Promise<string>) instanceof Promise) {357 return (html as unknown as Promise<string>)358- .then((html) => resolveStream(html))358+ .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))359 .then((html) => {360 return typeof arg === 'number'361 ? this.newResponse(html, arg, headers)362 : this.newResponse(html, arg)117 unmodified linesmodified:package.json+9 added-1 removed
107 unmodified lines108 "types": "./dist/types/helper/html/index.d.ts",109 "import": "./dist/helper/html/index.js",110 "require": "./dist/cjs/helper/html/index.js"111 },112+ "./css": {113+ "types": "./dist/types/helper/css/index.d.ts",114+ "import": "./dist/helper/css/index.js",115+ "require": "./dist/cjs/helper/css/index.js"116+ },117 "./jsx": {118 "types": "./dist/types/jsx/index.d.ts",119 "import": "./dist/jsx/index.js",120 "require": "./dist/cjs/jsx/index.js"202 unmodified lines323 ],324 "html": [325 "./dist/types/helper/html"326 ],327+ "css": [328+ "./dist/types/helper/css"329+ ],330 "jsx": [331 "./dist/types/jsx"332 ],333 "jsx/jsx-runtime": [157 unmodified lines491 },492 "engines": {493 "node": ">=16.0.0"494 }487-}495+}