This repository has been archived by the owner on Jun 27, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrender.ts
50 lines (44 loc) · 1.41 KB
/
render.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
import { VNode } from 'preact'
import renderToString from 'preact/render-to-string'
import { brightYellow, gray } from 'std/fmt/colors.ts'
import { defineConfig, extract, install } from 'twind'
import presetAutoPrefix from 'twind/preset-autoprefix'
import presetTailwind from 'twind/preset-tailwind'
import { Context } from './mod.ts'
export function render(c: Context, Component: VNode) {
const htmlString = renderToString(Component)
try {
const { html, css } = extract(htmlString)
c.res.body = `${css.length > 0 ? `<style>${css}</style>` : ''}${html}`
} catch (_err) {
if (c.dev) {
console.warn(
gray(
`${
brightYellow('warning')
} - twind is not installed, thus styles might not be applied`,
),
)
}
c.res.body = htmlString
}
c.res.header('content-type', 'text/html; charset=utf-8')
}
export class Renderer {
render
constructor(options?: Parameters<typeof defineConfig>[0]) {
if (options) {
options.presets = options.presets
? [presetAutoPrefix(), presetTailwind(), ...options.presets]
: [presetAutoPrefix(), presetTailwind()]
}
install(defineConfig(
options ?? {
presets: [presetAutoPrefix(), presetTailwind()],
},
))
this.render = render
}
}
export { h } from 'https://esm.sh/[email protected]?target=es2022'