refactor(html): make `html` as middleware (#319)
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 d433211 · Browse files · 8 files·+280 added−67 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+280 added−67 removed
- tests:+42 added−37 removed
- other:+238 added−30 removed
Provenance
- Commit
5976a60- Tree
bd54f31- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
d433211
8 files changed+280 added−67 removed
added:src/middleware/html/index.test.ts+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041import { html, raw } from '.'
describe('Tagged Template Literals', () => { it('Should escape special characters', () => { const name = 'John "Johnny" Smith' // eslint-disable-next-line quotes expect(html`<p>I'm ${name}.</p>`.toString()).toBe("<p>I'm John "Johnny" Smith.</p>") })
describe('Booleans, Null, and Undefined Are Ignored', () => { it.each([true, false, undefined, null])('%s', (item) => { expect(html`${item}`.toString()).toBe('') })
it('falsy value', () => { expect(html`${0}`.toString()).toBe('0') }) })
it('Should call $array.flat(Infinity)', () => { const values = [ 'Name:', ['John "Johnny" Smith', undefined, null], ' Contact:', [html`<a href="http://example.com/">My Website</a>`], ] expect(html`<p>${values}</p>`.toString()).toBe( '<p>Name:John "Johnny" Smith Contact:<a href="http://example.com/">My Website</a></p>' ) })})
describe('raw', () => { it('Should be marked as escaped.', () => { const name = 'John "Johnny" Smith' expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe( // eslint-disable-next-line quotes "<p>I'm John "Johnny" Smith.</p>" ) })})added:src/middleware/html/index.ts+33 added
123456789101112131415161718192021222324252627282930313233import { escape } from '../../utils/html'
export type HtmlEscapedString = string & { isEscaped: true }
export const raw = (value: any): HtmlEscapedString => { const escapedString = new String(value) as HtmlEscapedString escapedString.isEscaped = true
return escapedString}
export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => { let result = ''
for (let i = 0, len = strings.length - 1; i < len; i++) { result += strings[i]
const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]] for (let i = 0, len = children.length; i < len; i++) { const child = children[i] if (typeof child === 'boolean' || child === null || child === undefined) { continue } else if (typeof child === 'object' && (child as any).isEscaped) { result += child } else { result += escape(child.toString()) } } } result += strings[strings.length - 1]
return raw(result)}added:src/middleware/html/README.md+153 added
1+# html Middleware2+3+html Middleware provides `html` method for building HTML.4+5+## Usage6+7+index.ts:8+9+```ts10+import { Hono } from 'hono'11+import { html } from 'hono/html'12+13+const app = new Hono()14+15+app.get('/:username', (c) => {16+ const { username } = c.req.param()17+ return c.html(18+ html`<!DOCTYPE html>19+ <h1>Hello! ${username}!</h1>`20+ )21+})22+23+app.fire()24+```25+26+### Insert snippet into JSX27+28+```typescript29+const snippet = html`30+ <script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>31+ <script>32+ window.dataLayer = window.dataLayer || []33+ function gtag() {34+ dataLayer.push(arguments)35+ }36+ gtag('js', new Date())37+38+ gtag('config', 'MEASUREMENT_ID')39+ </script>40+`41+42+app.get('/', (c) => {43+ return c.render(44+ <html>45+ <head>46+ <title>Test Site</title>47+ {snippet}48+ </head>49+ <body>Hello!</body>50+ </html>51+ )52+})53+```54+55+### Insert inline script into JSX56+57+```typescript58+app.get('/', (c) => {59+ return c.render(60+ <html>61+ <head>62+ <title>Test Site</title>63+ {html`64+ <script>65+ // No need to use dangerouslySetInnerHTML. If you write it here, it will not be escaped.66+ </script>67+ `}68+ </head>69+ <body>Hello!</body>70+ </html>71+ )72+})73+```74+75+### Act as functional component76+77+Since `html` returns an HtmlEscapedString, it can act as a fully functional component without using JSX.78+79+#### Use `html` to speed up the process instead of `memo`80+81+```typescript82+const Footer = () => html`83+ <footer>84+ <address>My Address...</address>85+ </footer>86+`87+```88+89+### Receives props and embeds values90+91+```typescript92+interface SiteData {93+ title: string94+ description: string95+ image: string96+ children?: any97+}98+const Layout = (props: SiteData) => html`99+<html>100+<head>101+ <meta charset="UTF-8">102+ <title>${props.title}</title>103+ <meta name="description" content="${props.description}">104+ <head prefix="og: http://ogp.me/ns#">105+ <meta property="og:type" content="article">106+ <!-- More elements slow down JSX, but not template literals. -->107+ <meta property="og:title" content="${props.title}">108+ <meta property="og:image" content="${props.image}">109+</head>110+<body>111+ ${props.children}112+</body>113+</html>114+`115+116+const Content = (props: { siteData: SiteData; name: string }) => (117+ <Layout {...props.siteData}>118+ <h1>Hello {props.name}</h1>119+ </Layout>120+)121+122+app.get('/', (c) => {123+ const props = {124+ name: 'World',125+ siteData: {126+ title: 'Hello <> World',127+ description: 'This is a description',128+ image: 'https://example.com/image.png',129+ },130+ }131+ return c.render(<Content {...props} />)132+})133+```134+135+## raw136+137+Using `raw`, the content will be rendered as is. You have to escape these strings by yourself.138+139+```ts140+import { html, raw } from 'hono/html'141+142+app.get('/', (c) => {143+ const name = 'John "Johnny" Smith'144+ return c.html(html`<p>I'm ${raw(name)}.</p>`)145+})146+```147+148+## Tips149+150+Thanks to these libraries, Visual Studio Code and vim also interprets template literals as HTML, allowing syntax highlighting and formatting to be applied.151+152+- <https://marketplace.visualstudio.com/items?itemName=bierner.lit-html>153+- <https://github.com/MaxMEllon/vim-jsx-pretty>modified:src/middleware/jsx/README.md+47 added
98 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215316 unmodified lines98 unmodified lines </Fragment>)```
## With html Middleware
It's powerful to use JSX middleware with html middleware.For more information, see [html middleware docs](https://github.com/honojs/hono/tree/master/src/middleware/html).
```tsximport { Hono } from 'hono'import { html } from 'hono/html'import { jsx } from 'hono/jsx'
const app = new Hono()
interface SiteData { title: string children?: any}
const Layout = (props: SiteData) => html`<!DOCTYPE html> <html> <head> <title>${props.title}</title> </head> <body> ${props.children} </body> </html>`
const Content = (props: { siteData: SiteData; name: string }) => ( <Layout {...props.siteData}> <h1>Hello {props.name}</h1> </Layout>)
app.get('/:name', (c) => { const { name } = c.req.param() const props = { name: name, siteData: { title: 'JSX with html sample', }, } return c.html(<Content {...props} />)})
app.fire()```
## Tips for Cloudflare Workers
It's useful to use Miniflare's`live-reload` option for developing.
16 unmodified linesmodified:src/utils/html.test.ts+1 added-37 removed
1-import { escape, html, raw } from './html'1+import { escape } from './html'2 3 describe('HTML escape', () => {4 it('Should escape special characters', () => {5 expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.')6 expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith')7 })8 })9-10-describe('Tagged Template Literals', () => {11- it('Should escape special characters', () => {12- const name = 'John "Johnny" Smith'13- expect(html`<p>I'm ${name}.</p>`.toString()).toBe('<p>I\'m John "Johnny" Smith.</p>')14- })15-16- describe('Booleans, Null, and Undefined Are Ignored', () => {17- it.each([true, false, undefined, null])('%s', (item) => {18- expect(html`${item}`.toString()).toBe('')19- })20-21- it('falsy value', () => {22- expect(html`${0}`.toString()).toBe('0')23- })24- })25-26- it('Should call $array.flat(Infinity)', () => {27- const values = [28- 'Name:',29- ['John "Johnny" Smith', undefined, null],30- ' Contact:',31- [html`<a href="http://example.com/">My Website</a>`],32- ]33- expect(html`<p>${values}</p>`.toString()).toBe(34- '<p>Name:John "Johnny" Smith Contact:<a href=\"http://example.com/\">My Website</a></p>'35- )36- })37-})38-39-describe('raw', () => {40- it('Should be marked as escaped.', () => {41- const name = 'John "Johnny" Smith'42- expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe('<p>I\'m John "Johnny" Smith.</p>')43- })44-})modified:src/utils/html.ts-30 removed
9 unmodified lines10 const replaceFn = (m: string) => entityMap[m]11 export const escape = (str: string): string => {12 return str.replace(escapeRe, replaceFn)13 }14-15-export const raw = (value: any): HtmlEscapedString => {16- const escapedString = new String(value) as HtmlEscapedString17- escapedString.isEscaped = true18-19- return escapedString20-}21-22-export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => {23- let result = ''24-25- for (let i = 0, len = strings.length - 1; i < len; i++) {26- result += strings[i]27-28- const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]]29- for (let i = 0, len = children.length; i < len; i++) {30- const child = children[i]31- if (typeof child === 'boolean' || child === null || child === undefined) {32- continue33- } else if (typeof child === 'object' && (child as any).isEscaped) {34- result += child35- } else {36- result += escape(child.toString())37- }38- }39- }40- result += strings[strings.length - 1]41-42- return raw(result)43-}modified:package.json+4 added
22 unmodified lines23 "./cookie": "./dist/middleware/cookie/index.js",24 "./cors": "./dist/middleware/cors/index.js",25 "./etag": "./dist/middleware/etag/index.js",26 "./graphql-server": "./dist/middleware/graphql-server/index.js",27+ "./html": "./dist/middleware/html/index.js",28 "./jsx": "./dist/middleware/jsx/index.js",29 "./jwt": "./dist/middleware/jwt/index.js",30 "./logger": "./dist/middleware/logger/index.js",31 "./mustache": "./dist/middleware/mustache/index.js",29 unmodified lines61 ],62 "graphql-server": [63 "./dist/middleware/graphql-server"64 ],65+ "html": [66+ "./dist/middleware/html"67+ ],68 "jsx": [69 "./dist/middleware/jsx"70 ],71 "jwt": [88 unmodified linesmodified:README.md+1 added
71 unmodified lines72 - [Cookie parsing / serializing](https://github.com/honojs/hono/tree/master/src/middleware/cookie/)73 - [CORS](https://github.com/honojs/hono/tree/master/src/middleware/cors/)74 - [ETag](https://github.com/honojs/hono/tree/master/src/middleware/etag/)75 - [GraphQL Server](https://github.com/honojs/hono/tree/master/src/middleware/graphql-server/)76+- [html](https://github.com/honojs/hono/tree/master/src/middleware/html/)77 - [JSX](https://github.com/honojs/hono/tree/master/src/middleware/jsx/)78 - [JWT Authentication](https://github.com/honojs/hono/tree/master/src/middleware/jwt/)79 - [Logger](https://github.com/honojs/hono/tree/master/src/middleware/logger/)80 - [Mustache template engine](https://github.com/honojs/hono/tree/master/src/middleware/mustache/) (Only for Cloudflare Workers)667 unmodified lines