Skip to content
Myr

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

8 files+280 added−67 removed

added:src/middleware/html/index.test.ts+41 added
added:src/middleware/html/index.ts+33 added
added:src/middleware/html/README.md+153 added
1# html Middleware23html Middleware provides `html` method for building HTML.45## Usage67index.ts:89```ts10import { Hono } from 'hono'11import { html } from 'hono/html'1213const app = new Hono()1415app.get('/:username', (c) => {16 const { username } = c.req.param()17 return c.html(18 html`<!DOCTYPE html>19 <h1>Hello! ${username}!</h1>`20 )21})2223app.fire()24```2526### Insert snippet into JSX2728```typescript29const 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())3738 gtag('config', 'MEASUREMENT_ID')39 </script>40`4142app.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```5455### Insert inline script into JSX5657```typescript58app.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```7475### Act as functional component7677Since `html` returns an HtmlEscapedString, it can act as a fully functional component without using JSX.7879#### Use `html` to speed up the process instead of `memo`8081```typescript82const Footer = () => html`83 <footer>84 <address>My Address...</address>85 </footer>86`87```8889### Receives props and embeds values9091```typescript92interface SiteData {93 title: string94 description: string95 image: string96 children?: any97}98const 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`115116const Content = (props: { siteData: SiteData; name: string }) => (117 <Layout {...props.siteData}>118 <h1>Hello {props.name}</h1>119 </Layout>120)121122app.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```134135## raw136137Using `raw`, the content will be rendered as is. You have to escape these strings by yourself.138139```ts140import { html, raw } from 'hono/html'141142app.get('/', (c) => {143 const name = 'John &quot;Johnny&quot; Smith'144 return c.html(html`<p>I'm ${raw(name)}.</p>`)145})146```147148## Tips149150Thanks to these libraries, Visual Studio Code and vim also interprets template literals as HTML, allowing syntax highlighting and formatting to be applied.151152- <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
modified:src/utils/html.test.ts+1 added-37 removed
1import { escape, html, raw } from './html'1import { escape } from './html'23describe('HTML escape', () => {4 it('Should escape special characters', () => {5 expect(escape('I <b>think</b> this is good.')).toBe('I &lt;b&gt;think&lt;/b&gt; this is good.')6 expect(escape('John "Johnny" Smith')).toBe('John &quot;Johnny&quot; Smith')7 })8})910describe('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 &quot;Johnny&quot; Smith.</p>')14 })1516 describe('Booleans, Null, and Undefined Are Ignored', () => {17 it.each([true, false, undefined, null])('%s', (item) => {18 expect(html`${item}`.toString()).toBe('')19 })2021 it('falsy value', () => {22 expect(html`${0}`.toString()).toBe('0')23 })24 })2526 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 &quot;Johnny&quot; Smith Contact:<a href=\"http://example.com/\">My Website</a></p>'35 )36 })37})3839describe('raw', () => {40 it('Should be marked as escaped.', () => {41 const name = 'John &quot;Johnny&quot; Smith'42 expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe('<p>I\'m John &quot;Johnny&quot; Smith.</p>')43 })44})
modified:src/utils/html.ts-30 removed
9 unmodified lines
10const replaceFn = (m: string) => entityMap[m]11export const escape = (str: string): string => {12 return str.replace(escapeRe, replaceFn)13}1415export const raw = (value: any): HtmlEscapedString => {16 const escapedString = new String(value) as HtmlEscapedString17 escapedString.isEscaped = true1819 return escapedString20}2122export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => {23 let result = ''2425 for (let i = 0, len = strings.length - 1; i < len; i++) {26 result += strings[i]2728 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]4142 return raw(result)43}
modified:package.json+4 added
22 unmodified lines
23 "./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 lines
61 ],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 lines
modified:README.md+1 added
71 unmodified lines
72- [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