@hamur/icon 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/chunks/bun-react-fhd05zxm.js +206 -0
- package/dist/chunks/bun-react-nygte91t.js +305 -0
- package/dist/src/adapters/angular.js +104 -0
- package/dist/src/adapters/html.js +47 -0
- package/dist/src/adapters/preact.js +56 -0
- package/dist/src/adapters/react.js +66 -0
- package/dist/src/adapters/solid.js +97 -0
- package/dist/src/adapters/svelte.js +6 -0
- package/dist/src/adapters/vue.js +63 -0
- package/dist/src/index.js +897 -0
- package/dist/src/testing.js +46 -0
- package/dist/types/src/adapters/angular-icon.d.ts +32 -0
- package/dist/types/src/adapters/angular.d.ts +2 -0
- package/dist/types/src/adapters/html.d.ts +8 -0
- package/dist/types/src/adapters/preact.d.ts +6 -0
- package/dist/types/src/adapters/react.d.ts +6 -0
- package/dist/types/src/adapters/solid-icon.d.ts +6 -0
- package/dist/types/src/adapters/solid.d.ts +4 -0
- package/dist/types/src/adapters/svelte.d.ts +2 -0
- package/dist/types/src/adapters/vue.d.ts +41 -0
- package/dist/types/src/build/client.d.ts +21 -0
- package/dist/types/src/build/collections.d.ts +13 -0
- package/dist/types/src/build/css.d.ts +10 -0
- package/dist/types/src/build/custom.d.ts +10 -0
- package/dist/types/src/build/endpoint.d.ts +4 -0
- package/dist/types/src/build/runtime.d.ts +3 -0
- package/dist/types/src/build/scan.d.ts +37 -0
- package/dist/types/src/clean.d.ts +3 -0
- package/dist/types/src/index.d.ts +8 -0
- package/dist/types/src/kit.d.ts +10 -0
- package/dist/types/src/locate.d.ts +4 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/name.d.ts +13 -0
- package/dist/types/src/options.d.ts +46 -0
- package/dist/types/src/render.d.ts +68 -0
- package/dist/types/src/runtime/bundle.d.ts +2 -0
- package/dist/types/src/runtime/classes.d.ts +3 -0
- package/dist/types/src/runtime/icons.d.ts +27 -0
- package/dist/types/src/runtime/index.d.ts +2 -0
- package/dist/types/src/runtime/remote.d.ts +22 -0
- package/dist/types/src/runtime/server.d.ts +3 -0
- package/dist/types/src/server/door.d.ts +1 -0
- package/dist/types/src/server/endpoint.d.ts +28 -0
- package/dist/types/src/server/handler.d.ts +1 -0
- package/dist/types/src/testing.d.ts +2 -0
- package/dist/types/src/types.d.ts +102 -0
- package/package.json +141 -4
- package/src/adapters/Icon.svelte +60 -0
- package/src/adapters/angular-icon.ts +104 -0
- package/src/adapters/angular.ts +2 -0
- package/src/adapters/html.ts +44 -0
- package/src/adapters/preact.ts +63 -0
- package/src/adapters/react.ts +80 -0
- package/src/adapters/solid-icon.ts +99 -0
- package/src/adapters/solid.ts +8 -0
- package/src/adapters/svelte.ts +2 -0
- package/src/adapters/test/IconPage.svelte +5 -0
- package/src/adapters/test/support.ts +78 -0
- package/src/adapters/vue.ts +64 -0
- package/src/build/client.ts +113 -0
- package/src/build/collections.ts +86 -0
- package/src/build/css.ts +67 -0
- package/src/build/custom.ts +120 -0
- package/src/build/endpoint.ts +16 -0
- package/src/build/runtime.ts +24 -0
- package/src/build/scan.ts +148 -0
- package/src/clean.ts +66 -0
- package/src/env.d.ts +22 -0
- package/src/index.ts +10 -0
- package/src/kit.ts +29 -0
- package/src/locate.ts +20 -0
- package/src/module.ts +35 -0
- package/src/name.ts +38 -0
- package/src/options.ts +275 -0
- package/src/render.ts +247 -0
- package/src/runtime/bundle.ts +26 -0
- package/src/runtime/classes.ts +5 -0
- package/src/runtime/icons.ts +146 -0
- package/src/runtime/index.ts +17 -0
- package/src/runtime/remote.ts +147 -0
- package/src/runtime/server.ts +7 -0
- package/src/server/door.ts +1 -0
- package/src/server/endpoint.ts +251 -0
- package/src/server/handler.ts +30 -0
- package/src/testing.ts +23 -0
- package/src/types.ts +97 -0
package/src/render.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { sanitizeSvg, type SvgNode, type SvgStyle, type SvgValue } from "hamur/adapter"
|
|
2
|
+
import type { IconName } from "./name.ts"
|
|
3
|
+
import type { IconCustomize, IconifyAlias, IconifyIcon, IconifyJSON, IconMode, IconRuntimeOptions } from "./types.ts"
|
|
4
|
+
|
|
5
|
+
export const SVG_NAMESPACE = "http://www.w3.org/2000/svg"
|
|
6
|
+
|
|
7
|
+
/** An icon with its aliases resolved and its rotation and flips written into the body. */
|
|
8
|
+
export interface IconData {
|
|
9
|
+
body: string
|
|
10
|
+
left: number
|
|
11
|
+
top: number
|
|
12
|
+
width: number
|
|
13
|
+
height: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface Box {
|
|
17
|
+
left: number
|
|
18
|
+
top: number
|
|
19
|
+
width: number
|
|
20
|
+
height: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Iconify's alias rules: size and offsets of the nearer alias win, quarter turns add up and flips cancel in pairs. */
|
|
24
|
+
export function resolveIcon(collection: IconifyJSON, name: string): IconData | undefined {
|
|
25
|
+
const chain: IconifyAlias[] = []
|
|
26
|
+
const seen = new Set<string>()
|
|
27
|
+
let current = name
|
|
28
|
+
while (!Object.hasOwn(collection.icons, current)) {
|
|
29
|
+
const alias =
|
|
30
|
+
collection.aliases && Object.hasOwn(collection.aliases, current) ? collection.aliases[current] : undefined
|
|
31
|
+
if (!alias || seen.has(current)) return undefined
|
|
32
|
+
seen.add(current)
|
|
33
|
+
chain.push(alias)
|
|
34
|
+
current = alias.parent
|
|
35
|
+
}
|
|
36
|
+
const icon = collection.icons[current]!
|
|
37
|
+
if (typeof icon.body !== "string") return undefined
|
|
38
|
+
const box: Box = {
|
|
39
|
+
left: icon.left ?? collection.left ?? 0,
|
|
40
|
+
top: icon.top ?? collection.top ?? 0,
|
|
41
|
+
width: icon.width ?? collection.width ?? 16,
|
|
42
|
+
height: icon.height ?? collection.height ?? 16,
|
|
43
|
+
}
|
|
44
|
+
let rotate = icon.rotate ?? 0
|
|
45
|
+
let hFlip = icon.hFlip === true
|
|
46
|
+
let vFlip = icon.vFlip === true
|
|
47
|
+
for (const alias of chain.reverse()) {
|
|
48
|
+
if (alias.left !== undefined) box.left = alias.left
|
|
49
|
+
if (alias.top !== undefined) box.top = alias.top
|
|
50
|
+
if (alias.width !== undefined) box.width = alias.width
|
|
51
|
+
if (alias.height !== undefined) box.height = alias.height
|
|
52
|
+
rotate += alias.rotate ?? 0
|
|
53
|
+
if (alias.hFlip) hFlip = !hFlip
|
|
54
|
+
if (alias.vFlip) vFlip = !vFlip
|
|
55
|
+
}
|
|
56
|
+
return transform(icon.body, box, rotate, hFlip, vFlip)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The Iconify JSON entry of a resolved icon, as the payload and the client bundle hold it. */
|
|
60
|
+
export const payloadIcon = (data: IconData): IconifyIcon => ({
|
|
61
|
+
body: data.body,
|
|
62
|
+
width: data.width,
|
|
63
|
+
height: data.height,
|
|
64
|
+
...(data.left ? { left: data.left } : {}),
|
|
65
|
+
...(data.top ? { top: data.top } : {}),
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
function transform(body: string, box: Box, rotate: number, hFlip: boolean, vFlip: boolean): IconData {
|
|
69
|
+
const steps: string[] = []
|
|
70
|
+
let turns = rotate
|
|
71
|
+
if (hFlip && vFlip) turns += 2
|
|
72
|
+
else if (hFlip || vFlip) {
|
|
73
|
+
steps.push(
|
|
74
|
+
hFlip
|
|
75
|
+
? `translate(${box.width + box.left} ${-box.top || 0})`
|
|
76
|
+
: `translate(${-box.left || 0} ${box.height + box.top})`,
|
|
77
|
+
hFlip ? "scale(-1 1)" : "scale(1 -1)",
|
|
78
|
+
)
|
|
79
|
+
box.left = 0
|
|
80
|
+
box.top = 0
|
|
81
|
+
}
|
|
82
|
+
turns = ((turns % 4) + 4) % 4
|
|
83
|
+
if (turns === 1) {
|
|
84
|
+
const center = box.height / 2 + box.top
|
|
85
|
+
steps.unshift(`rotate(90 ${center} ${center})`)
|
|
86
|
+
} else if (turns === 2) {
|
|
87
|
+
steps.unshift(`rotate(180 ${box.width / 2 + box.left} ${box.height / 2 + box.top})`)
|
|
88
|
+
} else if (turns === 3) {
|
|
89
|
+
const center = box.width / 2 + box.left
|
|
90
|
+
steps.unshift(`rotate(-90 ${center} ${center})`)
|
|
91
|
+
}
|
|
92
|
+
if (turns % 2 === 1) {
|
|
93
|
+
;[box.left, box.top] = [box.top, box.left]
|
|
94
|
+
;[box.width, box.height] = [box.height, box.width]
|
|
95
|
+
}
|
|
96
|
+
return { body: steps.length ? `<g transform="${steps.join(" ")}">${body}</g>` : body, ...box }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const SANITIZED_LIMIT = 500
|
|
100
|
+
const sanitized = new Map<string, SvgNode[]>()
|
|
101
|
+
|
|
102
|
+
/** The body read once by the shared sanitiser; a body it cannot parse draws nothing. */
|
|
103
|
+
export function iconNodes(body: string): SvgNode[] {
|
|
104
|
+
let nodes = sanitized.get(body)
|
|
105
|
+
if (nodes === undefined) {
|
|
106
|
+
try {
|
|
107
|
+
nodes = sanitizeSvg(body, "icon")
|
|
108
|
+
} catch {
|
|
109
|
+
nodes = []
|
|
110
|
+
}
|
|
111
|
+
if (sanitized.size >= SANITIZED_LIMIT) sanitized.delete(sanitized.keys().next().value!)
|
|
112
|
+
} else sanitized.delete(body)
|
|
113
|
+
sanitized.set(body, nodes)
|
|
114
|
+
return nodes
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A value with each `{ id }` part written `<uid>-<id>`, so two icons on a page never share an id. */
|
|
118
|
+
export function svgValue(value: SvgValue, uid: string): string {
|
|
119
|
+
return typeof value === "string"
|
|
120
|
+
? value
|
|
121
|
+
: value.map((part) => (typeof part === "string" ? part : `${uid}-${part.id}`)).join("")
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** An element's attributes as strings, its `style` list written in as one `name:value;…` value. */
|
|
125
|
+
export function svgAttributes(
|
|
126
|
+
node: { attrs: Record<string, SvgValue>; style?: SvgStyle },
|
|
127
|
+
uid: string,
|
|
128
|
+
): Record<string, string> {
|
|
129
|
+
const attrs: Record<string, string> = {}
|
|
130
|
+
for (const [name, value] of Object.entries(node.attrs)) attrs[name] = svgValue(value, uid)
|
|
131
|
+
if (node.style)
|
|
132
|
+
attrs.style = node.style.map((declaration) => `${declaration.name}:${svgValue(declaration.value, uid)}`).join(";")
|
|
133
|
+
return attrs
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const ESCAPES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """ }
|
|
137
|
+
|
|
138
|
+
export const escapeHtml = (text: string): string => text.replace(/[&<>"]/g, (char) => ESCAPES[char]!)
|
|
139
|
+
|
|
140
|
+
const ATTRIBUTE_NAME = /^[^\s"'<>/=]+$/
|
|
141
|
+
|
|
142
|
+
/** Attributes as markup; a name HTML cannot hold as one attribute name is left out. */
|
|
143
|
+
export const attributesMarkup = (attrs: Record<string, string>): string =>
|
|
144
|
+
Object.entries(attrs)
|
|
145
|
+
.filter(([name]) => ATTRIBUTE_NAME.test(name))
|
|
146
|
+
.map(([name, value]) => ` ${name}="${escapeHtml(value)}"`)
|
|
147
|
+
.join("")
|
|
148
|
+
|
|
149
|
+
/** The nodes as markup, for html and for the data URL of a CSS rule; never a parser's input in the page. */
|
|
150
|
+
export function svgMarkup(nodes: SvgNode[], uid: string): string {
|
|
151
|
+
let out = ""
|
|
152
|
+
for (const node of nodes) {
|
|
153
|
+
if (typeof node === "string" || Array.isArray(node)) out += escapeHtml(svgValue(node, uid))
|
|
154
|
+
else
|
|
155
|
+
out += `<${node.tag}${attributesMarkup(svgAttributes(node, uid))}>${svgMarkup(node.children, uid)}</${node.tag}>`
|
|
156
|
+
}
|
|
157
|
+
return out
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const CSS_LENGTH = /^\d*\.?\d+(px|em|rem|ex|ch|vw|vh|vmin|vmax|%|pt|cm|mm|in|pc|q)?$/i
|
|
161
|
+
|
|
162
|
+
/** A `size` an icon can use: a finite number of pixels or a CSS length; anything else would write into `style`. */
|
|
163
|
+
export const validSize = (size: string | number): boolean =>
|
|
164
|
+
typeof size === "number" ? Number.isFinite(size) && size >= 0 : CSS_LENGTH.test(size)
|
|
165
|
+
|
|
166
|
+
/** `size` as an attribute and as a CSS length: a number is CSS pixels, an invalid size `1em`. */
|
|
167
|
+
export function iconSize(size: string | number | undefined): { attribute: string; css: string } {
|
|
168
|
+
if (size === undefined || !validSize(size)) return { attribute: "1em", css: "1em" }
|
|
169
|
+
return typeof size === "number" ? { attribute: String(size), css: `${size}px` } : { attribute: size, css: size }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The CSS-mode class: `<cssSelectorPrefix><prefix>:<name>`. */
|
|
173
|
+
export const iconClass = (name: IconName, selectorPrefix: string): string =>
|
|
174
|
+
`${selectorPrefix}${name.prefix}:${name.name}`
|
|
175
|
+
|
|
176
|
+
/** One rule, a mask painted in `currentColor` for a body that uses it, else the icon's own colours as a background. */
|
|
177
|
+
export function iconRule(className: string, data: IconData, nodes: SvgNode[], where: boolean): string {
|
|
178
|
+
const markup = svgMarkup(nodes, "i")
|
|
179
|
+
const svg = `<svg xmlns="${SVG_NAMESPACE}" viewBox="${data.left} ${data.top} ${data.width} ${data.height}" width="${data.width}" height="${data.height}">${markup}</svg>`
|
|
180
|
+
const selector = `.${className.replaceAll(":", "\\:")}`
|
|
181
|
+
const paint = /currentcolor/i.test(markup)
|
|
182
|
+
? "background-color: currentColor; -webkit-mask: var(--svg) no-repeat center / 100% 100%; mask: var(--svg) no-repeat center / 100% 100%;"
|
|
183
|
+
: "background: var(--svg) no-repeat center / 100% 100%;"
|
|
184
|
+
return `${where ? `:where(${selector})` : selector} { display: inline-block; width: 1em; height: 1em; ${paint} --svg: url("data:image/svg+xml,${encodeURIComponent(svg)}"); }`
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The text of `<style>` for every rule recorded, in `@layer <cssLayer>` when set. */
|
|
188
|
+
export function iconStyle(rules: Iterable<string>, layer: string | undefined): string {
|
|
189
|
+
const text = [...rules].join("\n")
|
|
190
|
+
return layer === undefined ? text : `@layer ${layer} {\n${text}\n}`
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface IconViewInput {
|
|
194
|
+
name: string
|
|
195
|
+
size?: string | number
|
|
196
|
+
mode?: IconMode
|
|
197
|
+
title?: string
|
|
198
|
+
customize?: IconCustomize
|
|
199
|
+
class?: string
|
|
200
|
+
/** The props give `aria-label` or `aria-labelledby`. */
|
|
201
|
+
labelled?: boolean
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export type IconView =
|
|
205
|
+
| { mode: "svg"; attrs: Record<string, string>; title?: string; nodes: SvgNode[] }
|
|
206
|
+
| { mode: "css"; attrs: Record<string, string>; rule?: { className: string; text: string } }
|
|
207
|
+
|
|
208
|
+
/** What one `Icon` draws, for every library alike; `found` is undefined for a name no source has. */
|
|
209
|
+
export function iconView(
|
|
210
|
+
input: IconViewInput,
|
|
211
|
+
name: IconName | undefined,
|
|
212
|
+
found: IconData | undefined,
|
|
213
|
+
options: IconRuntimeOptions,
|
|
214
|
+
): IconView {
|
|
215
|
+
const size = iconSize(input.size)
|
|
216
|
+
const extra = input.class || undefined
|
|
217
|
+
const title = input.title
|
|
218
|
+
if ((input.mode ?? "svg") === "css") {
|
|
219
|
+
const className = name ? iconClass(name, options.cssSelectorPrefix) : undefined
|
|
220
|
+
const attrs: Record<string, string> = {}
|
|
221
|
+
if (className || extra) attrs.class = [className, extra].filter(Boolean).join(" ")
|
|
222
|
+
attrs.role = "img"
|
|
223
|
+
if (title !== undefined) attrs["aria-label"] = title
|
|
224
|
+
else if (!input.labelled) attrs["aria-hidden"] = "true"
|
|
225
|
+
if (!found || !name || !className)
|
|
226
|
+
return { mode: "css", attrs: { ...attrs, style: `display:inline-block;width:${size.css};height:${size.css}` } }
|
|
227
|
+
if (size.css !== "1em") attrs.style = `width:${size.css};height:${size.css}`
|
|
228
|
+
const body = input.customize ? input.customize(found.body, name.name, name.prefix) : found.body
|
|
229
|
+
return {
|
|
230
|
+
mode: "css",
|
|
231
|
+
attrs,
|
|
232
|
+
rule: { className, text: iconRule(className, found, iconNodes(body), options.cssWherePseudo) },
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const attrs: Record<string, string> = { xmlns: SVG_NAMESPACE }
|
|
236
|
+
if (found) attrs.viewBox = `${found.left} ${found.top} ${found.width} ${found.height}`
|
|
237
|
+
attrs.width = size.attribute
|
|
238
|
+
attrs.height = size.attribute
|
|
239
|
+
if (title !== undefined || input.labelled) attrs.role = "img"
|
|
240
|
+
else attrs["aria-hidden"] = "true"
|
|
241
|
+
attrs.focusable = "false"
|
|
242
|
+
attrs["data-hamur-icon"] = name ? `${name.prefix}:${name.name}` : input.name
|
|
243
|
+
if (extra) attrs.class = extra
|
|
244
|
+
if (!found || !name) return { mode: "svg", attrs, nodes: [] }
|
|
245
|
+
const body = input.customize ? input.customize(found.body, name.name, name.prefix) : found.body
|
|
246
|
+
return { mode: "svg", attrs, ...(title === undefined ? {} : { title }), nodes: iconNodes(body) }
|
|
247
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import options from "#hamur/icon/options"
|
|
3
|
+
import { useStorage } from "hamur/server"
|
|
4
|
+
import type { IconifyJSON } from "../types.ts"
|
|
5
|
+
import { addServerCollection } from "./icons.ts"
|
|
6
|
+
|
|
7
|
+
let loading: Promise<void> | undefined
|
|
8
|
+
|
|
9
|
+
async function load(): Promise<void> {
|
|
10
|
+
const storage = useStorage("assets:icons")
|
|
11
|
+
await Promise.all(
|
|
12
|
+
options.serverBundle.map(async (prefix) => {
|
|
13
|
+
const collection = await storage.getItem<IconifyJSON>(`${prefix}.json`)
|
|
14
|
+
if (collection) addServerCollection(prefix, collection)
|
|
15
|
+
}),
|
|
16
|
+
)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Each collection of the icon server bundle is parsed once per process; the app plugin and the endpoint share the one read. */
|
|
20
|
+
export function loadServerCollections(): Promise<void> {
|
|
21
|
+
loading ??= load().catch((error: unknown) => {
|
|
22
|
+
loading = undefined
|
|
23
|
+
throw error
|
|
24
|
+
})
|
|
25
|
+
return loading
|
|
26
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { AppContext, HeadInput } from "hamur/app"
|
|
2
|
+
import { runtimeConfigOf } from "hamur/adapter"
|
|
3
|
+
import { normalizeName } from "../name.ts"
|
|
4
|
+
import {
|
|
5
|
+
iconStyle,
|
|
6
|
+
iconView,
|
|
7
|
+
payloadIcon,
|
|
8
|
+
resolveIcon,
|
|
9
|
+
validSize,
|
|
10
|
+
type IconData,
|
|
11
|
+
type IconView,
|
|
12
|
+
type IconViewInput,
|
|
13
|
+
} from "../render.ts"
|
|
14
|
+
import type { IconDefaults, IconifyJSON, IconPayload, IconRuntimeOptions } from "../types.ts"
|
|
15
|
+
import type { Remote } from "./remote.ts"
|
|
16
|
+
|
|
17
|
+
/** The icon server bundle as the server app plugin read it, by prefix; empty in the browser. */
|
|
18
|
+
const serverCollections = new Map<string, IconifyJSON>()
|
|
19
|
+
|
|
20
|
+
export function addServerCollection(prefix: string, collection: IconifyJSON): void {
|
|
21
|
+
serverCollections.set(prefix, collection)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const getServerCollection = (prefix: string): IconifyJSON | undefined => serverCollections.get(prefix)
|
|
25
|
+
|
|
26
|
+
/** `head` is the whole `<style>` text of the app's CSS-mode icons once this one is recorded. */
|
|
27
|
+
export type IconRenderView = IconView & {
|
|
28
|
+
head?: string
|
|
29
|
+
/** Set while the icon is being fetched; settles when the answer is cached. */ pending?: Promise<void>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Icons {
|
|
33
|
+
/** `config` is `runtimeConfig.public.icon`: its `aliases` rename `input.name`, its `size`, `class` and `mode` fill what `input` leaves out. */
|
|
34
|
+
view(app: AppContext, input: IconViewInput, config?: IconDefaults): IconRenderView
|
|
35
|
+
/** Calls `listener` after a fetch answered; the returned function stops it. Nothing is fetched on the server. */
|
|
36
|
+
subscribe(listener: () => void): () => void
|
|
37
|
+
/** Changes with every answer, so a subscriber that started after a render can tell it missed one. */
|
|
38
|
+
version(): number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The server render reads the icon server bundle and puts each icon it drew into `app.modulePayload.icon`, which the
|
|
43
|
+
* browser reads back, so the hydration draws the same markup with no request. An icon the client bundle holds is left out
|
|
44
|
+
* of it, since the browser has it already. CSS-mode rules are recorded per app by class.
|
|
45
|
+
*/
|
|
46
|
+
export function createIcons(
|
|
47
|
+
options: IconRuntimeOptions,
|
|
48
|
+
warn: ((message: string) => void) | undefined = import.meta.dev || import.meta.hot
|
|
49
|
+
? (message) => console.warn(message)
|
|
50
|
+
: undefined,
|
|
51
|
+
collections: Map<string, IconifyJSON> = serverCollections,
|
|
52
|
+
client: IconPayload = {},
|
|
53
|
+
remote?: Remote,
|
|
54
|
+
): Icons {
|
|
55
|
+
const warned = new Set<string>()
|
|
56
|
+
const once = (message: string) => {
|
|
57
|
+
if (!warn || warned.has(message)) return
|
|
58
|
+
warned.add(message)
|
|
59
|
+
warn(message)
|
|
60
|
+
}
|
|
61
|
+
const recorders = new WeakMap<AppContext, Map<string, string>>()
|
|
62
|
+
const sent = (app: AppContext) => app.modulePayload.icon as IconPayload | undefined
|
|
63
|
+
|
|
64
|
+
const bundled = (prefix: string, name: string) =>
|
|
65
|
+
client[prefix] !== undefined && Object.hasOwn(client[prefix].icons, name)
|
|
66
|
+
|
|
67
|
+
function find(app: AppContext, prefix: string, name: string): IconData | undefined {
|
|
68
|
+
const collection = collections.get(prefix)
|
|
69
|
+
const data = collection && resolveIcon(collection, name)
|
|
70
|
+
if (data) {
|
|
71
|
+
if (!bundled(prefix, name)) {
|
|
72
|
+
const payload = (app.modulePayload.icon ??= {}) as IconPayload
|
|
73
|
+
;(payload[prefix] ??= { icons: {} }).icons[name] = payloadIcon(data)
|
|
74
|
+
}
|
|
75
|
+
return data
|
|
76
|
+
}
|
|
77
|
+
const fetched = remote?.lookup(prefix, name)
|
|
78
|
+
for (const icons of [
|
|
79
|
+
sent(app)?.[prefix]?.icons,
|
|
80
|
+
client[prefix]?.icons,
|
|
81
|
+
fetched ? { [name]: fetched } : undefined,
|
|
82
|
+
]) {
|
|
83
|
+
const found = icons && resolveIcon({ prefix, icons }, name)
|
|
84
|
+
if (found) return found
|
|
85
|
+
}
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
view(app, given, config) {
|
|
91
|
+
const aliased =
|
|
92
|
+
config?.aliases && Object.hasOwn(config.aliases, given.name) && typeof config.aliases[given.name] === "string"
|
|
93
|
+
? config.aliases[given.name]!
|
|
94
|
+
: given.name
|
|
95
|
+
const input: IconViewInput = {
|
|
96
|
+
...given,
|
|
97
|
+
name: aliased,
|
|
98
|
+
size: given.size ?? config?.size,
|
|
99
|
+
mode: given.mode ?? config?.mode,
|
|
100
|
+
class: given.class || config?.class || undefined,
|
|
101
|
+
customize: given.customize,
|
|
102
|
+
}
|
|
103
|
+
const name = normalizeName(input.name, options.prefixes, options.cssSelectorPrefix)
|
|
104
|
+
const data = name && find(app, name.prefix, name.name)
|
|
105
|
+
const pending =
|
|
106
|
+
name && !data ? remote?.request(name.prefix, name.name, runtimeConfigOf(app).app.baseURL) : undefined
|
|
107
|
+
if (!name)
|
|
108
|
+
once(
|
|
109
|
+
`[icon] Icon name ${JSON.stringify(input.name)} is not "prefix:name" or "i-prefix-name"; import a component, or put the SVG in a custom collection`,
|
|
110
|
+
)
|
|
111
|
+
else if (!data && !pending) {
|
|
112
|
+
const known =
|
|
113
|
+
options.prefixes.includes(name.prefix) ||
|
|
114
|
+
collections.has(name.prefix) ||
|
|
115
|
+
sent(app)?.[name.prefix] !== undefined ||
|
|
116
|
+
client[name.prefix] !== undefined
|
|
117
|
+
if (options.provider === "none" && !collections.has(name.prefix))
|
|
118
|
+
once(
|
|
119
|
+
`[icon] icon.provider is "none": "${name.prefix}:${name.name}" is not in the payload or the client bundle`,
|
|
120
|
+
)
|
|
121
|
+
else if (known) once(`[icon] icon "${name.prefix}:${name.name}" not found`)
|
|
122
|
+
else if (options.provider !== "iconify")
|
|
123
|
+
once(
|
|
124
|
+
`[icon] collection "${name.prefix}" is not installed; add @iconify-json/${name.prefix}, or set icon.provider "iconify"`,
|
|
125
|
+
)
|
|
126
|
+
else if (remote) once(`[icon] icon "${name.prefix}:${name.name}" not found`)
|
|
127
|
+
}
|
|
128
|
+
if (input.size !== undefined && !validSize(input.size))
|
|
129
|
+
once(`[icon] Icon size ${JSON.stringify(input.size)} is not a number or a CSS length; 1em is used`)
|
|
130
|
+
const drawn = iconView(input, name, data || undefined, options)
|
|
131
|
+
const view: IconRenderView = pending ? { ...drawn, pending } : drawn
|
|
132
|
+
if (view.mode !== "css" || !view.rule) return view
|
|
133
|
+
let rules = recorders.get(app)
|
|
134
|
+
if (!rules) recorders.set(app, (rules = new Map()))
|
|
135
|
+
if (!rules.has(view.rule.className)) rules.set(view.rule.className, view.rule.text)
|
|
136
|
+
return { ...view, head: iconStyle(rules.values(), options.cssLayer) }
|
|
137
|
+
},
|
|
138
|
+
subscribe: (listener) => remote?.subscribe(listener) ?? (() => {}),
|
|
139
|
+
version: () => remote?.version() ?? 0,
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The app's CSS-mode rules as one `<style>`; a later push under the key holds a superset of an earlier one and replaces it. */
|
|
144
|
+
export function iconHead(view: IconRenderView): HeadInput {
|
|
145
|
+
return view.head === undefined ? {} : { style: [{ key: "hamur-icons", innerHTML: view.head }] }
|
|
146
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import client from "#hamur/icon/client"
|
|
3
|
+
import options from "#hamur/icon/options"
|
|
4
|
+
import { createIcons } from "./icons.ts"
|
|
5
|
+
import { createRemote } from "./remote.ts"
|
|
6
|
+
|
|
7
|
+
const remote =
|
|
8
|
+
import.meta.server || options.provider === "none"
|
|
9
|
+
? undefined
|
|
10
|
+
: createRemote({
|
|
11
|
+
provider: options.provider,
|
|
12
|
+
iconifyApiEndpoint: options.iconifyApiEndpoint,
|
|
13
|
+
fetchTimeout: options.fetchTimeout,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
export const icons = createIcons(options, undefined, undefined, client, remote)
|
|
17
|
+
export { iconHead, type IconRenderView } from "./icons.ts"
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { cleanCollection } from "../clean.ts"
|
|
2
|
+
import { MAX_ICONS, NAME_PATTERN } from "../name.ts"
|
|
3
|
+
import { payloadIcon, resolveIcon } from "../render.ts"
|
|
4
|
+
import type { IconifyIcon } from "../types.ts"
|
|
5
|
+
|
|
6
|
+
export interface RemoteOptions {
|
|
7
|
+
provider: "server" | "iconify"
|
|
8
|
+
iconifyApiEndpoint: string
|
|
9
|
+
fetchTimeout: number
|
|
10
|
+
fetch?: typeof fetch
|
|
11
|
+
/** Read inside a `try` on every access, since the accessor can throw; default `sessionStorage`. */
|
|
12
|
+
storage?: () => Storage | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The icons the browser asked for, by prefix and name; `null` is an icon known to be missing. */
|
|
16
|
+
export interface Remote {
|
|
17
|
+
lookup(prefix: string, name: string): IconifyIcon | null | undefined
|
|
18
|
+
/** The promise of the batch that will answer, or `undefined` when the icon is already answered. */
|
|
19
|
+
request(prefix: string, name: string, baseURL: string): Promise<void> | undefined
|
|
20
|
+
subscribe(listener: () => void): () => void
|
|
21
|
+
version(): number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const KEY = "hamur:icon:"
|
|
25
|
+
|
|
26
|
+
const sessionStore = (): Storage | undefined => globalThis.sessionStorage
|
|
27
|
+
|
|
28
|
+
interface Batch {
|
|
29
|
+
baseURL: string
|
|
30
|
+
names: Map<string, Set<string>>
|
|
31
|
+
done: Promise<void>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Names asked within one microtask are one request per prefix (at most `MAX_ICONS` names each). The answers are kept in memory
|
|
36
|
+
* and in `sessionStorage`, misses too, so a missing icon is not asked again; a failed request is remembered in memory only.
|
|
37
|
+
*/
|
|
38
|
+
export function createRemote(options: RemoteOptions): Remote {
|
|
39
|
+
const cache = new Map<string, IconifyIcon | null>()
|
|
40
|
+
const listeners = new Set<() => void>()
|
|
41
|
+
let changes = 0
|
|
42
|
+
let batch: Batch | undefined
|
|
43
|
+
const queued = new Map<string, Promise<void>>()
|
|
44
|
+
|
|
45
|
+
const keyOf = (prefix: string, name: string) => `${prefix}:${name}`
|
|
46
|
+
const storage = options.storage ?? sessionStore
|
|
47
|
+
const storageKey = (prefix: string, name: string) => `${KEY}${options.provider}:${keyOf(prefix, name)}`
|
|
48
|
+
|
|
49
|
+
function stored(prefix: string, name: string): IconifyIcon | null | undefined {
|
|
50
|
+
try {
|
|
51
|
+
const text = storage()?.getItem(storageKey(prefix, name))
|
|
52
|
+
if (text == null) return undefined
|
|
53
|
+
if (text === "0") return null
|
|
54
|
+
const collection = cleanCollection(prefix, { icons: { [name]: JSON.parse(text) } })
|
|
55
|
+
const data = resolveIcon(collection, name)
|
|
56
|
+
return data ? payloadIcon(data) : undefined
|
|
57
|
+
} catch {
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function keep(prefix: string, name: string, icon: IconifyIcon | null, persist: boolean): void {
|
|
63
|
+
cache.set(keyOf(prefix, name), icon)
|
|
64
|
+
if (!persist) return
|
|
65
|
+
try {
|
|
66
|
+
storage()?.setItem(storageKey(prefix, name), icon === null ? "0" : JSON.stringify(icon))
|
|
67
|
+
} catch {}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function ask(prefix: string, names: string[], baseURL: string): Promise<void> {
|
|
71
|
+
const origin = options.provider === "server" ? `${baseURL}_hamur/icons` : options.iconifyApiEndpoint
|
|
72
|
+
const controller = new AbortController()
|
|
73
|
+
const timer = setTimeout(() => controller.abort(), options.fetchTimeout)
|
|
74
|
+
try {
|
|
75
|
+
const response = await (options.fetch ?? fetch)(`${origin}/${prefix}.json?icons=${names.join(",")}`, {
|
|
76
|
+
signal: controller.signal,
|
|
77
|
+
headers: { accept: "application/json" },
|
|
78
|
+
})
|
|
79
|
+
if (response.status === 404) {
|
|
80
|
+
for (const name of names) keep(prefix, name, null, true)
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
if (!response.ok) throw new Error(`status ${response.status}`)
|
|
84
|
+
const body: unknown = await response.json()
|
|
85
|
+
if (
|
|
86
|
+
typeof body !== "object" ||
|
|
87
|
+
body === null ||
|
|
88
|
+
typeof (body as { icons?: unknown }).icons !== "object" ||
|
|
89
|
+
(body as { icons?: unknown }).icons === null
|
|
90
|
+
)
|
|
91
|
+
throw new Error("not an icon set")
|
|
92
|
+
const collection = cleanCollection(prefix, body as Record<string, unknown>)
|
|
93
|
+
for (const name of names) {
|
|
94
|
+
const data = resolveIcon(collection, name)
|
|
95
|
+
keep(prefix, name, data ? payloadIcon(data) : null, true)
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
for (const name of names) keep(prefix, name, null, false)
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function flush(current: Batch): Promise<void> {
|
|
105
|
+
batch = undefined
|
|
106
|
+
const requests: Promise<void>[] = []
|
|
107
|
+
for (const [prefix, set] of current.names) {
|
|
108
|
+
const rest: string[] = []
|
|
109
|
+
for (const name of set) {
|
|
110
|
+
const found = stored(prefix, name)
|
|
111
|
+
if (found === undefined) rest.push(name)
|
|
112
|
+
else cache.set(keyOf(prefix, name), found)
|
|
113
|
+
}
|
|
114
|
+
for (let at = 0; at < rest.length; at += MAX_ICONS)
|
|
115
|
+
requests.push(ask(prefix, rest.slice(at, at + MAX_ICONS), current.baseURL))
|
|
116
|
+
}
|
|
117
|
+
await Promise.all(requests)
|
|
118
|
+
for (const [prefix, set] of current.names) for (const name of set) queued.delete(keyOf(prefix, name))
|
|
119
|
+
changes++
|
|
120
|
+
for (const listener of [...listeners]) listener()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
lookup: (prefix, name) => cache.get(keyOf(prefix, name)),
|
|
125
|
+
request(prefix, name, baseURL) {
|
|
126
|
+
const key = keyOf(prefix, name)
|
|
127
|
+
if (cache.has(key) || !NAME_PATTERN.test(prefix) || !NAME_PATTERN.test(name)) return undefined
|
|
128
|
+
const waiting = queued.get(key)
|
|
129
|
+
if (waiting) return waiting
|
|
130
|
+
if (!batch) {
|
|
131
|
+
const created: Batch = { baseURL, names: new Map(), done: undefined as unknown as Promise<void> }
|
|
132
|
+
created.done = new Promise<void>((resolve) => queueMicrotask(() => void flush(created).then(resolve, resolve)))
|
|
133
|
+
batch = created
|
|
134
|
+
}
|
|
135
|
+
const set = batch.names.get(prefix) ?? new Set<string>()
|
|
136
|
+
set.add(name)
|
|
137
|
+
batch.names.set(prefix, set)
|
|
138
|
+
queued.set(key, batch.done)
|
|
139
|
+
return batch.done
|
|
140
|
+
},
|
|
141
|
+
subscribe(listener) {
|
|
142
|
+
listeners.add(listener)
|
|
143
|
+
return () => void listeners.delete(listener)
|
|
144
|
+
},
|
|
145
|
+
version: () => changes,
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { definePlugin } from "hamur/app"
|
|
2
|
+
import { loadServerCollections } from "./bundle.ts"
|
|
3
|
+
|
|
4
|
+
/** The server app plugin reads the icon server bundle once per process, before the first render needs it. */
|
|
5
|
+
export default definePlugin(async () => {
|
|
6
|
+
await loadServerCollections()
|
|
7
|
+
})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { iconEndpoint } from "./handler.ts"
|