Skip to content
Myr

refactor(`utils/html`): rename `Buffer` to `StringBuffer` (#449)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent fefba4f · Browse files · 12 files+314 added−115 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+314 added−115 removed

  • tests:+72 added−8 removed
  • other:+242 added−107 removed

12 files+314 added−115 removed

modified:deno_dist/middleware/html/index.ts+15 added-11 removed
modified:deno_dist/middleware/jsx/index.test.tsx+67 added-5 removed
1import { Hono } from '../../hono.ts'2import { html } from '../html/index.ts'3import { jsx, memo, Fragment } from './index.ts'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {5 const app = new Hono()11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 it('Should render HTML strings', async () => {18 app.get('/', (c) => {19 return c.html(<h1>Hello</h1>)20 })
1 unmodified line
22 expect(res.status).toBe(200)23 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24 expect(await res.text()).toBe('<h1>Hello</h1>')25 })2627 it('Should be able to be used with html middleware', async () => {28 const Layout = (props: SiteData) => html`<!DOCTYPE html>29 <html>30 <head>31 <title>${props.title}</title>32 </head>33 <body>34 ${props.children}35 </body>36 </html>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 app.get('/', (c) => {45 const props = {46 name: 'JSX',47 siteData: {48 title: 'with html middleware',49 },50 }51 return c.html(<Content {...props} />)52 })53 const res = await app.request('http://localhost/')54 expect(res.status).toBe(200)55 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56 expect(await res.text()).toBe(`<!DOCTYPE html>57 <html>58 <head>59 <title>with html middleware</title>60 </head>61 <body>62 <h1>JSX</h1>63 </body>64 </html>`)65 })66})6768describe('render to string', () => {69 it('Nested array', () => {
28 unmodified lines
98 expect(template.toString()).toBe('<span>" is allowed here</span>')99 })100101 it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {52 expect(() => (53 <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>54 )).toThrow()102 expect(() =>103 (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104 ).toThrow()105 })106 })107108 // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored
15 unmodified lines
124 expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125 })126 })12778 describe('Special case for input boolean params', () => {128 // https://html.spec.whatwg.org/#attributes-3129 describe('Boolean attribute', () => {130 it('default prop value for checked', () => {131 const template = <input type='checkbox' checked />132 expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133 })
95 unmodified lines
229 it('should render "false" value properly for other non-defined keys', () => {230 const template = <input type='checkbox' testkey={false} />231 expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232 })233234 it('should support attributes for elements other than input', () => {235 const template = (236 <video controls autoplay>237 <source src='movie.mp4' type='video/mp4' />238 </video>239 )240 expect(template.toString()).toBe(241 '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242 )243 })244 })245246 // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247 describe('Functions as Children', () => {
109 unmodified lines
modified:deno_dist/middleware/jsx/index.ts+135 added-55 removed
1import { escape } from '../../utils/html.ts'2import type { HtmlEscapedString } from '../../utils/html.ts'1import { escapeToBuffer } from '../../utils/html.ts'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'34declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {
19 unmodified lines
26 'source',27 'track',28 'wbr',29]30const booleanAttributes = ['checked', 'selected', 'disabled', 'readonly', 'multiple']30const booleanAttributes = [31 'allowfullscreen',32 'async',33 'autofocus',34 'autoplay',35 'checked',36 'controls',37 'default',38 'defer',39 'disabled',40 'formnovalidate',41 'hidden',42 'inert',43 'ismap',44 'itemscope',45 'loop',46 'multiple',47 'muted',48 'nomodule',49 'novalidate',50 'open',51 'playsinline',52 'readonly',53 'required',54 'reversed',55 'selected',56]5732const newHtmlEscapedString = (str: string): HtmlEscapedString => {33 const escapedString = new String(str) as HtmlEscapedString34 escapedString.isEscaped = true35 return escapedString58const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {59 for (let i = 0, len = children.length; i < len; i++) {60 const child = children[i]61 if (typeof child === 'string') {62 escapeToBuffer(child, buffer)63 } else if (typeof child === 'boolean' || child === null || child === undefined) {64 continue65 } else if (child instanceof JSXNode) {66 child.toStringToBuffer(buffer)67 } else if (typeof child === 'number' || (child as any).isEscaped) {68 buffer[0] += child69 } else {70 // `child` type is `Child[]`, so stringify recursively71 childrenToStringToBuffer(child, buffer)72 }73 }74}7538export { jsxFn as jsx }39const jsxFn = (40 tag: string | Function,41 props: Record<string, any>,42 ...children: (string | HtmlEscapedString)[]43): HtmlEscapedString => {44 if (typeof tag === 'function') {45 return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })76type Child = string | number | JSXNode | Child[]77export class JSXNode implements HtmlEscaped {78 tag: string | Function79 props: Record<string, any>80 children: Child[]81 isEscaped: true = true82 constructor(tag: string | Function, props: Record<string, any>, children: Child[]) {83 this.tag = tag84 this.props = props85 this.children = children86 }8748 let result = tag !== '' ? `<${tag}` : ''88 toString(): string {89 const buffer: StringBuffer = ['']90 this.toStringToBuffer(buffer)91 return buffer[0]92 }9350 const propsKeys = Object.keys(props || {})94 toStringToBuffer(buffer: StringBuffer): void {95 const tag = this.tag as string96 const props = this.props97 let { children } = this9899 buffer[0] += `<${tag}`100101 const propsKeys = Object.keys(props || {})102103 for (let i = 0, len = propsKeys.length; i < len; i++) {104 const v = props[propsKeys[i]]52 for (let i = 0, len = propsKeys.length; i < len; i++) {53 const v = props[propsKeys[i]]54 if (typeof v === 'string') {55 result += ` ${propsKeys[i]}="${escape(v)}"`56 } else if (typeof v === 'number') {57 result += ` ${propsKeys[i]}="${v}"`58 } else if (v === null || v === undefined) {59 // Do nothing60 } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {61 if (v) {62 result += ` ${propsKeys[i]}=""`105 if (typeof v === 'string') {106 buffer[0] += ` ${propsKeys[i]}="`107 escapeToBuffer(v, buffer)108 buffer[0] += '"'109 } else if (typeof v === 'number') {110 buffer[0] += ` ${propsKeys[i]}="${v}"`111 } else if (v === null || v === undefined) {112 // Do nothing113 } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {114 if (v) {115 buffer[0] += ` ${propsKeys[i]}=""`116 }117 } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {118 if (children.length > 0) {119 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'120 }121122 const escapedString = new String(v.__html) as HtmlEscapedString123 escapedString.isEscaped = true124 children = [escapedString]125 } else {126 buffer[0] += ` ${propsKeys[i]}="`127 escapeToBuffer(v.toString(), buffer)128 buffer[0] += '"'129 }64 } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {65 if (children.length > 0) {66 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'67 }130 }13169 children = [newHtmlEscapedString(v.__html)]70 } else {71 result += ` ${propsKeys[i]}="${escape(v.toString())}"`132 if (emptyTags.includes(tag as string)) {133 buffer[0] += '/>'134 return135 }73 }13675 if (emptyTags.includes(tag)) {76 result += '/>'77 return newHtmlEscapedString(result)78 }137 buffer[0] += '>'13880 if (tag !== '') {81 result += '>'139 childrenToStringToBuffer(children, buffer)140141 buffer[0] += `</${tag}>`142 }143}14484 const flattenChildren = children.flat(Infinity)85 for (let i = 0, len = flattenChildren.length; i < len; i++) {86 const child = flattenChildren[i]87 if (typeof child === 'boolean' || child === null || child === undefined) {88 continue89 } else if (typeof child === 'object' && (child as any).isEscaped) {90 result += child145class JSXFunctionNode extends JSXNode {146 toStringToBuffer(buffer: StringBuffer): void {147 const { children } = this148149 const res = (this.tag as Function).call(null, {150 ...this.props,151 children: children.length <= 1 ? children[0] : children,152 })153154 if (res instanceof JSXNode) {155 res.toStringToBuffer(buffer)156 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {157 buffer[0] += res158 } else {92 result += escape(child.toString())159 escapeToBuffer(res, buffer)160 }161 }162}16396 if (tag !== '') {97 result += `</${tag}>`164class JSXFragmentNode extends JSXNode {165 toStringToBuffer(buffer: StringBuffer): void {166 childrenToStringToBuffer(this.children, buffer)167 }168}169100 return newHtmlEscapedString(result)170export { jsxFn as jsx }171const jsxFn = (172 tag: string | Function,173 props: Record<string, any>,174 ...children: (string | HtmlEscapedString)[]175): JSXNode => {176 if (typeof tag === 'function') {177 return new JSXFunctionNode(tag, props, children)178 } else {179 return new JSXNode(tag, props, children)180 }181}182183type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString184
31 unmodified lines
216 return (computed ||= component(props))217 }) as FC<T>218}219140export const Fragment = (props: { key?: string; children?: any }): HtmlEscapedString => {141 return jsxFn('', {}, ...(props.children || []))220export const Fragment = (props: { key?: string; children?: any }): JSXNode => {221 return new JSXFragmentNode('', {}, props.children || [])222}
modified:deno_dist/middleware/jsx/jsx-dev-runtime.ts+2 added-2 removed
modified:deno_dist/middleware/jwt/index.ts+19 added-13 removed
modified:deno_dist/utils/body.ts+3 added-3 removed
modified:deno_dist/utils/html.ts+54 added-10 removed
modified:deno_dist/request.ts+3 added-2 removed
1import { parseBody } from './utils/body.ts'2import type { Body } from './utils/body.ts'3import type { Cookie } from './utils/cookie.ts'4import { parse } from './utils/cookie.ts'56declare global {
18 unmodified lines
25 cookie: {26 (name: string): string27 (): Cookie28 }28 parsedBody?: Promise<any>29 parsedBody?: Promise<Body>30 parseBody: {30 (): Promise<any>31 (): Promise<Body>32 }33 }34}35
73 unmodified lines
modified:src/middleware/html/index.ts+2 added-2 removed
1import { escapeToBuffer } from '../../utils/html'2import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34export const raw = (value: any): HtmlEscapedString => {5 const escapedString = new String(value) as HtmlEscapedString6 escapedString.isEscaped = true
1 unmodified line
8 return escapedString9}1011export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => {12 const buffer: Buffer = ['']12 const buffer: StringBuffer = ['']1314 for (let i = 0, len = strings.length - 1; i < len; i++) {15 buffer[0] += strings[i]16
21 unmodified lines
modified:src/middleware/jsx/index.ts+6 added-6 removed
1import { escapeToBuffer } from '../../utils/html'2import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {
47 unmodified lines
54 'reversed',55 'selected',56]5758const childrenToStringToBuffer = (children: Child[], buffer: Buffer): void => {58const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {59 for (let i = 0, len = children.length; i < len; i++) {60 const child = children[i]61 if (typeof child === 'string') {62 escapeToBuffer(child, buffer)
22 unmodified lines
85 this.children = children86 }8788 toString(): string {89 const buffer: Buffer = ['']89 const buffer: StringBuffer = ['']90 this.toStringToBuffer(buffer)91 return buffer[0]92 }9394 toStringToBuffer(buffer: Buffer): void {94 toStringToBuffer(buffer: StringBuffer): void {95 const tag = this.tag as string96 const props = this.props97 let { children } = this98
43 unmodified lines
142 }143}144145class JSXFunctionNode extends JSXNode {146 toStringToBuffer(buffer: Buffer): void {146 toStringToBuffer(buffer: StringBuffer): void {147 const { children } = this148149 const res = (this.tag as Function).call(null, {150 ...this.props,
10 unmodified lines
161 }162}163164class JSXFragmentNode extends JSXNode {165 toStringToBuffer(buffer: Buffer): void {165 toStringToBuffer(buffer: StringBuffer): void {166 childrenToStringToBuffer(this.children, buffer)167 }168}169
53 unmodified lines
modified:src/utils/html.test.ts+5 added-3 removed
1import { escape, escapeToBuffer } from './html'2import type { Buffer } from './html'2import type { StringBuffer } from './html'34describe('HTML utilities', () => {5 describe('escape', () => {6 it('Should escape special characters', () => {7 expect(escape('I <b>think</b> this is good.')).toBe('I &lt;b&gt;think&lt;/b&gt; this is good.')7 expect(escape('I <b>think</b> this is good.')).toBe(8 'I &lt;b&gt;think&lt;/b&gt; this is good.'9 )10 expect(escape('John "Johnny" Smith')).toBe('John &quot;Johnny&quot; Smith')11 })12 })1314 describe('escapeToBuffer', () => {15 it('Should escape special characters', () => {14 let buffer: Buffer = ['']16 let buffer: StringBuffer = ['']17 escapeToBuffer('I <b>think</b> this is good.', buffer)18 expect(buffer[0]).toBe('I &lt;b&gt;think&lt;/b&gt; this is good.')1920 buffer = ['']
5 unmodified lines
modified:src/utils/html.ts+3 added-3 removed
1export type HtmlEscaped = { isEscaped: true }2export type HtmlEscapedString = string & HtmlEscaped3export type Buffer = [string]3export type StringBuffer = [string]45// The `escape` and `escapeToBuffer` implementations are based on code from the MIT licensed `react-dom` package.6// https://github.com/facebook/react/blob/main/packages/react-dom/src/server/escapeTextForBrowser.js7
6 unmodified lines
14 if (match === -1) {15 return str16 }1718 const buffer: Buffer = ['']18 const buffer: StringBuffer = ['']19 escapeToBuffer(str, buffer)20 return buffer[0]21}2223export const escapeToBuffer = (str: string, buffer: Buffer): void => {23export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {24 const match = str.search(escapeRe)25 if (match === -1) {26 buffer[0] += str27 return
30 unmodified lines