@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
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createComponent,
|
|
3
|
+
createMemo,
|
|
4
|
+
createSignal,
|
|
5
|
+
isHydrating,
|
|
6
|
+
merge,
|
|
7
|
+
omit,
|
|
8
|
+
onCleanup,
|
|
9
|
+
type Component,
|
|
10
|
+
} from "solid-js"
|
|
11
|
+
import { dynamic, isServer, spread, type JSX } from "@solidjs/web"
|
|
12
|
+
import { useApp, useRuntimeConfig, useHead, useId } from "@hamur/adapter-solid"
|
|
13
|
+
import type { SvgNode } from "hamur/adapter"
|
|
14
|
+
import { SVG_NAMESPACE, svgAttributes, svgValue } from "../render.ts"
|
|
15
|
+
import { iconHead, type Icons } from "../runtime/icons.ts"
|
|
16
|
+
import type { IconDefaults, IconProps } from "../types.ts"
|
|
17
|
+
|
|
18
|
+
export type SolidIconProps = IconProps & Omit<JSX.SvgSVGAttributes<SVGSVGElement>, keyof IconProps | "ref" | "children">
|
|
19
|
+
|
|
20
|
+
const OWN = ["name", "size", "mode", "title", "customize", "class"] as const
|
|
21
|
+
|
|
22
|
+
const tags = new Map<string, Component<Record<string, unknown>>>()
|
|
23
|
+
|
|
24
|
+
function tagged(tag: string): Component<Record<string, unknown>> {
|
|
25
|
+
let made = tags.get(tag)
|
|
26
|
+
if (!made) tags.set(tag, (made = dynamic(() => tag, { static: true }) as Component<Record<string, unknown>>))
|
|
27
|
+
return made
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Solid makes a tag outside its SVG list (`title`, `a`) as an HTML element, so a client render creates each element in the SVG namespace itself. */
|
|
31
|
+
function svgElement(tag: string, props: Record<string, unknown>): JSX.Element {
|
|
32
|
+
if (isServer || isHydrating()) return createComponent(tagged(tag), props)
|
|
33
|
+
const element = document.createElementNS(SVG_NAMESPACE, tag)
|
|
34
|
+
spread(element, props)
|
|
35
|
+
return element as unknown as JSX.Element
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Solid's client writes a style prop through cssText, which rewrites the server's text, so a ref sets it as written.
|
|
39
|
+
function withStyle(attrs: Record<string, string>): Record<string, unknown> {
|
|
40
|
+
const { style, ...rest } = attrs
|
|
41
|
+
const out: Record<string, unknown> = { ...rest }
|
|
42
|
+
if (style === undefined) return out
|
|
43
|
+
return isServer ? { ...out, style } : { ...out, ref: (element: Element) => element.setAttribute("style", style) }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function element(node: SvgNode, uid: string): JSX.Element {
|
|
47
|
+
if (typeof node === "string" || Array.isArray(node)) return svgValue(node, uid)
|
|
48
|
+
return svgElement(node.tag, {
|
|
49
|
+
...withStyle(svgAttributes(node, uid)),
|
|
50
|
+
get children() {
|
|
51
|
+
return node.children.map((child) => element(child, uid))
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** `Icon` over `icons`, so a test renders it without the build's options module. */
|
|
57
|
+
export const createIcon = (icons: Icons) =>
|
|
58
|
+
function Icon(props: SolidIconProps): JSX.Element {
|
|
59
|
+
const own = props
|
|
60
|
+
const rest = omit(props, ...OWN)
|
|
61
|
+
const app = useApp()
|
|
62
|
+
const config = useRuntimeConfig().public as { icon?: IconDefaults }
|
|
63
|
+
const uid = useId().replace(/[^\w-]/g, "_")
|
|
64
|
+
const [answers, answered] = createSignal(icons.version())
|
|
65
|
+
onCleanup(icons.subscribe(() => answered(icons.version())))
|
|
66
|
+
const view = createMemo(() => {
|
|
67
|
+
answers()
|
|
68
|
+
return icons.view(
|
|
69
|
+
app,
|
|
70
|
+
{
|
|
71
|
+
name: own.name,
|
|
72
|
+
size: own.size,
|
|
73
|
+
mode: own.mode,
|
|
74
|
+
title: own.title,
|
|
75
|
+
customize: own.customize,
|
|
76
|
+
class: typeof own.class === "string" && own.class !== "" ? own.class : undefined,
|
|
77
|
+
labelled: rest["aria-label"] != null || rest["aria-labelledby"] != null,
|
|
78
|
+
},
|
|
79
|
+
config.icon,
|
|
80
|
+
)
|
|
81
|
+
})
|
|
82
|
+
useHead(() => iconHead(view()))
|
|
83
|
+
return (() => {
|
|
84
|
+
const current = view()
|
|
85
|
+
if (current.mode === "css") return createComponent(tagged("span"), merge(withStyle(current.attrs), rest))
|
|
86
|
+
const children = () => [
|
|
87
|
+
...(current.title === undefined ? [] : [svgElement("title", { children: current.title })]),
|
|
88
|
+
...current.nodes.map((node) => element(node, uid)),
|
|
89
|
+
]
|
|
90
|
+
return svgElement(
|
|
91
|
+
"svg",
|
|
92
|
+
merge(withStyle(current.attrs), rest, {
|
|
93
|
+
get children() {
|
|
94
|
+
return children()
|
|
95
|
+
},
|
|
96
|
+
}),
|
|
97
|
+
)
|
|
98
|
+
}) as unknown as JSX.Element
|
|
99
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { icons } from "../runtime/index.ts"
|
|
2
|
+
import { createIcon } from "./solid-icon.ts"
|
|
3
|
+
|
|
4
|
+
export type { IconProps } from "../types.ts"
|
|
5
|
+
export type { SolidIconProps } from "./solid-icon.ts"
|
|
6
|
+
|
|
7
|
+
/** An icon of a collection by name, drawn as `<svg>` from the sanitised body, or as a `<span>` and one CSS rule. */
|
|
8
|
+
export const Icon = createIcon(icons)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { cpSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"
|
|
2
|
+
import { tmpdir } from "node:os"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { afterAll, beforeAll, expect } from "bun:test"
|
|
5
|
+
import { createAppContext, createHead, createState, type RenderContext } from "hamur/adapter"
|
|
6
|
+
import { withBase } from "hamur/app"
|
|
7
|
+
import { loadIconCollections } from "../../testing.ts"
|
|
8
|
+
import type { IconPayload, IconRuntimeOptions } from "../../types.ts"
|
|
9
|
+
|
|
10
|
+
const MDI = join(import.meta.dir, "../../../../../tests/fixtures/icon-endpoint/iconify-json/mdi")
|
|
11
|
+
|
|
12
|
+
export const MDI_HOME_PATH = "M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"
|
|
13
|
+
|
|
14
|
+
export const runtimeOptions: IconRuntimeOptions = {
|
|
15
|
+
prefixes: ["mdi"],
|
|
16
|
+
serverBundle: ["mdi"],
|
|
17
|
+
provider: "server",
|
|
18
|
+
iconifyApiEndpoint: "https://api.iconify.design",
|
|
19
|
+
fetchTimeout: 1500,
|
|
20
|
+
cssSelectorPrefix: "i-",
|
|
21
|
+
cssWherePseudo: true,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const clientBundle: IconPayload = {}
|
|
25
|
+
|
|
26
|
+
const virtualModules = { "#hamur/icon/options": runtimeOptions, "#hamur/icon/client": clientBundle }
|
|
27
|
+
|
|
28
|
+
/** Gives the adapters' `Icon` the `#hamur/icon/*` modules the build writes; call it before importing one. */
|
|
29
|
+
export function registerVirtualModules(): void {
|
|
30
|
+
Bun.plugin({
|
|
31
|
+
name: "hamur-icon-virtual",
|
|
32
|
+
setup(build) {
|
|
33
|
+
for (const [name, value] of Object.entries(virtualModules))
|
|
34
|
+
build.module(name, () => ({ exports: { default: value }, loader: "object" }))
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Installs the small `@iconify-json/mdi` of the endpoint fixture under a temp cwd, loads it, and stubs `fetch` to throw. */
|
|
40
|
+
export function installMdi(): void {
|
|
41
|
+
const cwd = process.cwd()
|
|
42
|
+
const originalFetch = globalThis.fetch
|
|
43
|
+
let root = ""
|
|
44
|
+
beforeAll(() => {
|
|
45
|
+
root = mkdtempSync(join(tmpdir(), "hamur-icon-testing-"))
|
|
46
|
+
mkdirSync(join(root, "node_modules/@iconify-json"), { recursive: true })
|
|
47
|
+
cpSync(MDI, join(root, "node_modules/@iconify-json/mdi"), { recursive: true })
|
|
48
|
+
process.chdir(root)
|
|
49
|
+
loadIconCollections(["mdi"])
|
|
50
|
+
globalThis.fetch = (() => {
|
|
51
|
+
throw new Error("fetch is not allowed in this test")
|
|
52
|
+
}) as unknown as typeof fetch
|
|
53
|
+
})
|
|
54
|
+
afterAll(() => {
|
|
55
|
+
globalThis.fetch = originalFetch
|
|
56
|
+
process.chdir(cwd)
|
|
57
|
+
rmSync(root, { recursive: true, force: true })
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function renderContext(component: unknown): RenderContext {
|
|
62
|
+
return {
|
|
63
|
+
url: new URL("http://localhost/"),
|
|
64
|
+
route: { path: "/" },
|
|
65
|
+
tree: { components: [{ id: "page", component }] },
|
|
66
|
+
payload: {},
|
|
67
|
+
head: createHead(),
|
|
68
|
+
app: createAppContext({ state: createState(), config: { public: {} }, head: createHead() }),
|
|
69
|
+
stream: false,
|
|
70
|
+
baseURL: "/",
|
|
71
|
+
href: (to: string) => withBase(to, "/"),
|
|
72
|
+
} as unknown as RenderContext
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function expectHome(html: string): void {
|
|
76
|
+
expect(html).toContain(`d="${MDI_HOME_PATH}"`)
|
|
77
|
+
expect(html).toContain('data-hamur-icon="mdi:home"')
|
|
78
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { defineComponent, h, onScopeDispose, shallowRef, type PropType, type VNodeChild } from "vue"
|
|
2
|
+
import { useApp, useRuntimeConfig, useHead, useId } from "@hamur/adapter-vue"
|
|
3
|
+
import type { SvgNode } from "hamur/adapter"
|
|
4
|
+
import { svgAttributes, svgValue } from "../render.ts"
|
|
5
|
+
import { iconHead, icons } from "../runtime/index.ts"
|
|
6
|
+
import type { IconDefaults, IconCustomize, IconMode, IconProps } from "../types.ts"
|
|
7
|
+
|
|
8
|
+
export type { IconProps }
|
|
9
|
+
|
|
10
|
+
function element(node: SvgNode, uid: string): VNodeChild {
|
|
11
|
+
if (typeof node === "string" || Array.isArray(node)) return svgValue(node, uid)
|
|
12
|
+
return h(
|
|
13
|
+
node.tag,
|
|
14
|
+
svgAttributes(node, uid),
|
|
15
|
+
node.children.map((child) => element(child, uid)),
|
|
16
|
+
)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** An icon of a collection by name, drawn as `<svg>` from the sanitised body, or as a `<span>` and one CSS rule; other attributes fall through to it. */
|
|
20
|
+
export const Icon = defineComponent({
|
|
21
|
+
name: "Icon",
|
|
22
|
+
inheritAttrs: false,
|
|
23
|
+
props: {
|
|
24
|
+
name: { type: String, required: true },
|
|
25
|
+
size: { type: [String, Number] as PropType<string | number> },
|
|
26
|
+
mode: { type: String as PropType<IconMode> },
|
|
27
|
+
title: { type: String },
|
|
28
|
+
customize: { type: Function as PropType<IconCustomize> },
|
|
29
|
+
},
|
|
30
|
+
setup(props, { attrs }) {
|
|
31
|
+
const app = useApp()
|
|
32
|
+
const config = useRuntimeConfig().public as { icon?: IconDefaults }
|
|
33
|
+
const uid = useId().replace(/[^\w-]/g, "_")
|
|
34
|
+
const answers = shallowRef(icons.version())
|
|
35
|
+
onScopeDispose(icons.subscribe(() => (answers.value = icons.version())))
|
|
36
|
+
const read = () => {
|
|
37
|
+
void answers.value
|
|
38
|
+
return icons.view(
|
|
39
|
+
app,
|
|
40
|
+
{
|
|
41
|
+
name: props.name,
|
|
42
|
+
size: props.size,
|
|
43
|
+
mode: props.mode,
|
|
44
|
+
title: props.title,
|
|
45
|
+
customize: props.customize,
|
|
46
|
+
class: typeof attrs.class === "string" && attrs.class !== "" ? attrs.class : undefined,
|
|
47
|
+
labelled: attrs["aria-label"] != null || attrs["aria-labelledby"] != null,
|
|
48
|
+
},
|
|
49
|
+
config.icon,
|
|
50
|
+
)
|
|
51
|
+
}
|
|
52
|
+
useHead(() => iconHead(read()))
|
|
53
|
+
return () => {
|
|
54
|
+
const view = read()
|
|
55
|
+
const { class: _class, ...rest } = attrs
|
|
56
|
+
const own = { ...view.attrs, ...rest }
|
|
57
|
+
if (view.mode === "css") return h("span", own)
|
|
58
|
+
return h("svg", own, [
|
|
59
|
+
...(view.title === undefined ? [] : [h("title", view.title)]),
|
|
60
|
+
...view.nodes.map((node) => element(node, uid)),
|
|
61
|
+
])
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
})
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { join } from "node:path"
|
|
2
|
+
import { addTemplate, updateTemplates, useLogger, type HamurContext } from "hamur/kit"
|
|
3
|
+
import type { ResolvedIconOptions } from "../options.ts"
|
|
4
|
+
import { payloadIcon, resolveIcon } from "../render.ts"
|
|
5
|
+
import type { IconifyJSON, IconPayload } from "../types.ts"
|
|
6
|
+
import { isCustomFile } from "./custom.ts"
|
|
7
|
+
import { findSources, scanSources, SCAN_EXTENSIONS, type ScanRoot } from "./scan.ts"
|
|
8
|
+
import { DiagnosticError } from "hamur/kit"
|
|
9
|
+
|
|
10
|
+
const LISTED = "icon.clientBundle.icons"
|
|
11
|
+
|
|
12
|
+
export interface ClientBundle {
|
|
13
|
+
payload: IconPayload
|
|
14
|
+
/** The warnings, one per name that is in no installed collection. */
|
|
15
|
+
warnings: string[]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Each name of `names` (name to the place that wrote it) the collections hold, resolved, by prefix. */
|
|
19
|
+
export function createClientBundle(names: Map<string, string>, collections: Record<string, IconifyJSON>): ClientBundle {
|
|
20
|
+
const payload: IconPayload = {}
|
|
21
|
+
const warnings: string[] = []
|
|
22
|
+
for (const [full, where] of [...names].sort(([a], [b]) => a.localeCompare(b))) {
|
|
23
|
+
const at = full.indexOf(":")
|
|
24
|
+
const prefix = full.slice(0, at)
|
|
25
|
+
const name = full.slice(at + 1)
|
|
26
|
+
const collection = Object.hasOwn(collections, prefix) ? collections[prefix] : undefined
|
|
27
|
+
const data = collection && resolveIcon(collection, name)
|
|
28
|
+
if (!data) {
|
|
29
|
+
warnings.push(`[icon] "${full}" (${where}) is not in the ${prefix} collection`)
|
|
30
|
+
continue
|
|
31
|
+
}
|
|
32
|
+
;(payload[prefix] ??= { icons: {} }).icons[name] = payloadIcon(data)
|
|
33
|
+
}
|
|
34
|
+
return { payload, warnings }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The bytes of the module's data, in KB rounded up, so a bundle over the limit never reads as the limit. */
|
|
38
|
+
export function bundleSizeError(payload: IconPayload, sizeLimitKb: number): string | undefined {
|
|
39
|
+
const bytes = Buffer.byteLength(JSON.stringify(payload))
|
|
40
|
+
return bytes > sizeLimitKb * 1024
|
|
41
|
+
? `icon client bundle is ${Math.ceil(bytes / 1024)} KB, over icon.clientBundle.sizeLimitKb ${sizeLimitKb}`
|
|
42
|
+
: undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Logs each message once; the client bundle and the class utility share one, so a name both find warns once. */
|
|
46
|
+
export function createWarner(): (message: string) => void {
|
|
47
|
+
const log = useLogger("icon")
|
|
48
|
+
const warned = new Set<string>()
|
|
49
|
+
return (message) => {
|
|
50
|
+
if (warned.has(message)) return
|
|
51
|
+
warned.add(message)
|
|
52
|
+
log.warn(message)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function scanRoots(hamur: HamurContext): ScanRoot[] {
|
|
57
|
+
const { rootDir, srcDir, serverDir, layers } = hamur.options
|
|
58
|
+
return [
|
|
59
|
+
{ rootDir, dirs: [srcDir, join(rootDir, "shared")], skip: [serverDir] },
|
|
60
|
+
...layers.map((layer) => ({
|
|
61
|
+
rootDir: layer.rootDir,
|
|
62
|
+
dirs: [layer.srcDir, join(layer.rootDir, "shared")],
|
|
63
|
+
skip: [layer.serverDir],
|
|
64
|
+
})),
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* `#hamur/icon/client`, the icons of `clientBundle.icons` and the names the scan finds, read from `collections`
|
|
70
|
+
* (filled in `modules:done`) once the hook ran. A bundle over `sizeLimitKb` fails the build.
|
|
71
|
+
*/
|
|
72
|
+
export function setupClient(
|
|
73
|
+
options: ResolvedIconOptions,
|
|
74
|
+
hamur: HamurContext,
|
|
75
|
+
collections: Record<string, IconifyJSON>,
|
|
76
|
+
warn: (message: string) => void = createWarner(),
|
|
77
|
+
): void {
|
|
78
|
+
const { clientBundle } = options
|
|
79
|
+
const log = useLogger("icon")
|
|
80
|
+
let bundle: IconPayload = {}
|
|
81
|
+
|
|
82
|
+
function build(): void {
|
|
83
|
+
const names = new Map<string, string>()
|
|
84
|
+
for (const icon of clientBundle.icons) names.set(icon, LISTED)
|
|
85
|
+
if (clientBundle.scan !== false) {
|
|
86
|
+
const rules = clientBundle.scan === true ? { include: [], exclude: [] } : clientBundle.scan
|
|
87
|
+
const sources = findSources(scanRoots(hamur), hamur.options.rootDir, rules)
|
|
88
|
+
for (const [name, file] of scanSources(sources, Object.keys(collections), options.cssSelectorPrefix))
|
|
89
|
+
if (!names.has(name)) names.set(name, file)
|
|
90
|
+
}
|
|
91
|
+
const built = createClientBundle(names, collections)
|
|
92
|
+
for (const warning of built.warnings) warn(warning)
|
|
93
|
+
const error = bundleSizeError(built.payload, clientBundle.sizeLimitKb)
|
|
94
|
+
if (error) throw new DiagnosticError("HAMUR_E5904", error)
|
|
95
|
+
bundle = built.payload
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
addTemplate({ filename: "icon/client", getContents: () => `export default ${JSON.stringify(bundle)};\n` })
|
|
99
|
+
hamur.hooks.hook("modules:done", build)
|
|
100
|
+
if (!hamur.options.dev || clientBundle.scan === false) return
|
|
101
|
+
hamur.hooks.hook("dev:change", async ({ relative, file }) => {
|
|
102
|
+
if (!SCAN_EXTENSIONS.test(relative) && isCustomFile(options.customCollections, file).length === 0) return
|
|
103
|
+
const before = JSON.stringify(bundle)
|
|
104
|
+
try {
|
|
105
|
+
build()
|
|
106
|
+
} catch (error) {
|
|
107
|
+
log.error(error instanceof Error ? error.message : String(error))
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
if (JSON.stringify(bundle) !== before)
|
|
111
|
+
await updateTemplates({ filter: ({ filename }) => filename === "icon/client" })
|
|
112
|
+
})
|
|
113
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { addServerAssets, useLogger, type HamurContext } from "hamur/kit"
|
|
4
|
+
import { callCollectionsHook } from "../kit.ts"
|
|
5
|
+
import { isCustomFile, readCustomCollection } from "./custom.ts"
|
|
6
|
+
import { NAME_PATTERN } from "../name.ts"
|
|
7
|
+
import type { ResolvedIconOptions } from "../options.ts"
|
|
8
|
+
import type { IconifyJSON } from "../types.ts"
|
|
9
|
+
|
|
10
|
+
const ICONIFY_JSON = "@iconify-json/"
|
|
11
|
+
|
|
12
|
+
/** The prefixes of the `@iconify-json/<prefix>` packages in the app's `dependencies` and `devDependencies`. */
|
|
13
|
+
export function listedCollections(rootDir: string): string[] {
|
|
14
|
+
const file = join(rootDir, "package.json")
|
|
15
|
+
if (!existsSync(file)) return []
|
|
16
|
+
const manifest = JSON.parse(readFileSync(file, "utf8")) as {
|
|
17
|
+
dependencies?: Record<string, string>
|
|
18
|
+
devDependencies?: Record<string, string>
|
|
19
|
+
}
|
|
20
|
+
const names = [...Object.keys(manifest.dependencies ?? {}), ...Object.keys(manifest.devDependencies ?? {})]
|
|
21
|
+
return [
|
|
22
|
+
...new Set(names.filter((name) => name.startsWith(ICONIFY_JSON)).map((name) => name.slice(ICONIFY_JSON.length))),
|
|
23
|
+
]
|
|
24
|
+
.filter((prefix) => NAME_PATTERN.test(prefix))
|
|
25
|
+
.sort()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** `[icon] server bundle: mdi 4.1 MB, lucide 0.9 MB`; undefined when no collection is bundled. */
|
|
29
|
+
export function bundleLine(sizes: Record<string, number>): string | undefined {
|
|
30
|
+
const parts = Object.entries(sizes)
|
|
31
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
32
|
+
.map(([prefix, bytes]) => `${prefix} ${(bytes / 1024 / 1024).toFixed(1)} MB`)
|
|
33
|
+
return parts.length === 0 ? undefined : `[icon] server bundle: ${parts.join(", ")}`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The installed collections and those of `icon:collections` are written as
|
|
38
|
+
* `<buildDir>/icons/<prefix>.json` and mounted as `assets:icons`, data in the server bundle on every preset. `prefixes` is filled
|
|
39
|
+
* once the hook ran, before any template is read; `known` gets the collections themselves, for the client bundle.
|
|
40
|
+
*/
|
|
41
|
+
export function setupCollections(
|
|
42
|
+
options: ResolvedIconOptions,
|
|
43
|
+
hamur: HamurContext,
|
|
44
|
+
prefixes: string[],
|
|
45
|
+
known: Record<string, IconifyJSON> = {},
|
|
46
|
+
): void {
|
|
47
|
+
const dir = join(hamur.options.buildDir, "icons")
|
|
48
|
+
mkdirSync(dir, { recursive: true })
|
|
49
|
+
addServerAssets({ name: "icons", dir })
|
|
50
|
+
hamur.hooks.hook("modules:done", async () => {
|
|
51
|
+
const collections: Record<string, IconifyJSON> = {}
|
|
52
|
+
for (const [prefix, file] of Object.entries(options.installed))
|
|
53
|
+
collections[prefix] = JSON.parse(readFileSync(file, "utf8")) as IconifyJSON
|
|
54
|
+
for (const entry of options.customCollections)
|
|
55
|
+
collections[entry.prefix] = readCustomCollection(hamur.options.rootDir, entry)
|
|
56
|
+
await callCollectionsHook(hamur, collections)
|
|
57
|
+
for (const name of readdirSync(dir)) if (name.endsWith(".json")) rmSync(join(dir, name))
|
|
58
|
+
const sizes: Record<string, number> = {}
|
|
59
|
+
for (const [prefix, collection] of Object.entries(collections)) {
|
|
60
|
+
const text = JSON.stringify(collection)
|
|
61
|
+
sizes[prefix] = Buffer.byteLength(text)
|
|
62
|
+
writeFileSync(join(dir, `${prefix}.json`), text)
|
|
63
|
+
}
|
|
64
|
+
const line = bundleLine(sizes)
|
|
65
|
+
if (line) useLogger("icon").info(line)
|
|
66
|
+
prefixes.splice(0, prefixes.length, ...Object.keys(collections).sort())
|
|
67
|
+
Object.assign(known, collections)
|
|
68
|
+
})
|
|
69
|
+
if (!hamur.options.dev || options.customCollections.length === 0) return
|
|
70
|
+
hamur.hooks.hook("dev:change", (change) => {
|
|
71
|
+
const touched = isCustomFile(options.customCollections, change.file)
|
|
72
|
+
if (touched.length === 0) return
|
|
73
|
+
try {
|
|
74
|
+
for (const entry of touched) {
|
|
75
|
+
const collection = readCustomCollection(hamur.options.rootDir, entry)
|
|
76
|
+
writeFileSync(join(dir, `${entry.prefix}.json`), JSON.stringify(collection))
|
|
77
|
+
known[entry.prefix] = collection
|
|
78
|
+
}
|
|
79
|
+
} catch (error) {
|
|
80
|
+
useLogger("icon").error(error instanceof Error ? error.message : String(error))
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
change.rebuildServer = true
|
|
84
|
+
change.reload = true
|
|
85
|
+
})
|
|
86
|
+
}
|
package/src/build/css.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { addAppPlugin, addTemplate, createResolver, updateTemplates, useLogger, type HamurContext } from "hamur/kit"
|
|
2
|
+
import type { ResolvedIconOptions } from "../options.ts"
|
|
3
|
+
import { iconNodes, iconRule, iconStyle, resolveIcon } from "../render.ts"
|
|
4
|
+
import type { IconifyJSON } from "../types.ts"
|
|
5
|
+
import { findSources, scanClassSources, SCAN_EXTENSIONS } from "./scan.ts"
|
|
6
|
+
import { scanRoots } from "./client.ts"
|
|
7
|
+
|
|
8
|
+
/** The rule of each class the collections know; a class that names no icon is `warn`ed and has none. */
|
|
9
|
+
export function createClassesCss(
|
|
10
|
+
classes: Map<string, { name: string; file: string }>,
|
|
11
|
+
collections: Record<string, IconifyJSON>,
|
|
12
|
+
options: Pick<ResolvedIconOptions, "cssLayer" | "cssWherePseudo">,
|
|
13
|
+
warn: (message: string) => void,
|
|
14
|
+
): string {
|
|
15
|
+
const rules: string[] = []
|
|
16
|
+
for (const [className, { name, file }] of [...classes].sort(([a], [b]) => a.localeCompare(b))) {
|
|
17
|
+
const at = name.indexOf(":")
|
|
18
|
+
const prefix = name.slice(0, at)
|
|
19
|
+
const collection = Object.hasOwn(collections, prefix) ? collections[prefix] : undefined
|
|
20
|
+
const data = collection && resolveIcon(collection, name.slice(at + 1))
|
|
21
|
+
if (!data) {
|
|
22
|
+
warn(`[icon] "${name}" (${file}) is not in the ${prefix} collection`)
|
|
23
|
+
continue
|
|
24
|
+
}
|
|
25
|
+
rules.push(iconRule(className, data, iconNodes(data.body), options.cssWherePseudo))
|
|
26
|
+
}
|
|
27
|
+
return rules.length === 0 ? "" : `${iconStyle(rules, options.cssLayer)}\n`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `#hamur/icon/classes.css`, one rule per class the scan finds, imported by an app plugin so it is global CSS. */
|
|
31
|
+
export function setupCss(
|
|
32
|
+
options: ResolvedIconOptions,
|
|
33
|
+
hamur: HamurContext,
|
|
34
|
+
collections: Record<string, IconifyJSON>,
|
|
35
|
+
warn: (message: string) => void,
|
|
36
|
+
): void {
|
|
37
|
+
if (!options.cssClasses) return
|
|
38
|
+
const { clientBundle } = options
|
|
39
|
+
let css = ""
|
|
40
|
+
|
|
41
|
+
function build(): void {
|
|
42
|
+
const rules = typeof clientBundle.scan === "object" ? clientBundle.scan : { include: [], exclude: [] }
|
|
43
|
+
const sources = findSources(scanRoots(hamur), hamur.options.rootDir, rules)
|
|
44
|
+
css = createClassesCss(
|
|
45
|
+
scanClassSources(sources, Object.keys(collections), options.cssSelectorPrefix),
|
|
46
|
+
collections,
|
|
47
|
+
options,
|
|
48
|
+
warn,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
addTemplate({ filename: "icon/classes.css", getContents: () => css })
|
|
53
|
+
addAppPlugin({ src: createResolver(import.meta.url).resolve("../runtime/classes.ts"), mode: "all" })
|
|
54
|
+
hamur.hooks.hook("modules:done", build)
|
|
55
|
+
if (!hamur.options.dev) return
|
|
56
|
+
hamur.hooks.hook("dev:change", async ({ relative }) => {
|
|
57
|
+
if (!SCAN_EXTENSIONS.test(relative)) return
|
|
58
|
+
const before = css
|
|
59
|
+
try {
|
|
60
|
+
build()
|
|
61
|
+
} catch (error) {
|
|
62
|
+
useLogger("icon").error(error instanceof Error ? error.message : String(error))
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
if (css !== before) await updateTemplates({ filter: ({ filename }) => filename === "icon/classes.css" })
|
|
66
|
+
})
|
|
67
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from "node:fs"
|
|
2
|
+
import { join, relative, sep } from "node:path"
|
|
3
|
+
import { sanitizeSvg, type SvgNode, type SvgValue } from "hamur/adapter"
|
|
4
|
+
import { NAME_PATTERN } from "../name.ts"
|
|
5
|
+
import type { ResolvedIconOptions } from "../options.ts"
|
|
6
|
+
import { svgMarkup } from "../render.ts"
|
|
7
|
+
import type { IconifyIcon, IconifyJSON } from "../types.ts"
|
|
8
|
+
import { DiagnosticError } from "hamur/kit"
|
|
9
|
+
|
|
10
|
+
type CustomCollection = ResolvedIconOptions["customCollections"][number]
|
|
11
|
+
|
|
12
|
+
const SVG_FILE = /\.svg$/i
|
|
13
|
+
const DEFAULT_SIZE = 24
|
|
14
|
+
/** What the file's `<svg>` paints with; kept on a `<g>` around the body, as the body alone has lost the root. */
|
|
15
|
+
const PAINT = new Set([
|
|
16
|
+
"fill",
|
|
17
|
+
"fill-opacity",
|
|
18
|
+
"fill-rule",
|
|
19
|
+
"clip-rule",
|
|
20
|
+
"stroke",
|
|
21
|
+
"stroke-width",
|
|
22
|
+
"stroke-linecap",
|
|
23
|
+
"stroke-linejoin",
|
|
24
|
+
"stroke-miterlimit",
|
|
25
|
+
"stroke-dasharray",
|
|
26
|
+
"stroke-dashoffset",
|
|
27
|
+
"stroke-opacity",
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
const text = (value: SvgValue): string =>
|
|
31
|
+
typeof value === "string" ? value : value.map((part) => (typeof part === "string" ? part : part.id)).join("")
|
|
32
|
+
|
|
33
|
+
/** The sanitiser's `{ id }` parts written as the ids themselves: an icon's body is stored with the ids it had, and `Icon` prefixes them per use. */
|
|
34
|
+
function plain(nodes: SvgNode[]): SvgNode[] {
|
|
35
|
+
return nodes.map((node): SvgNode => {
|
|
36
|
+
if (typeof node === "string" || Array.isArray(node)) return text(node)
|
|
37
|
+
return {
|
|
38
|
+
tag: node.tag,
|
|
39
|
+
attrs: Object.fromEntries(Object.entries(node.attrs).map(([name, value]) => [name, text(value)])),
|
|
40
|
+
...(node.style
|
|
41
|
+
? { style: node.style.map((declaration) => ({ name: declaration.name, value: text(declaration.value) })) }
|
|
42
|
+
: {}),
|
|
43
|
+
children: plain(node.children),
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function box(attrs: Record<string, SvgValue>): { left: number; top: number; width: number; height: number } {
|
|
49
|
+
const viewBox =
|
|
50
|
+
attrs.viewBox === undefined
|
|
51
|
+
? []
|
|
52
|
+
: text(attrs.viewBox)
|
|
53
|
+
.trim()
|
|
54
|
+
.split(/[\s,]+/)
|
|
55
|
+
.map(Number)
|
|
56
|
+
if (viewBox.length === 4 && viewBox.every(Number.isFinite) && viewBox[2]! > 0 && viewBox[3]! > 0)
|
|
57
|
+
return { left: viewBox[0]!, top: viewBox[1]!, width: viewBox[2]!, height: viewBox[3]! }
|
|
58
|
+
const size = (name: string): number => {
|
|
59
|
+
const value = attrs[name] === undefined ? "" : text(attrs[name])
|
|
60
|
+
const number = value.endsWith("%") ? Number.NaN : Number.parseFloat(value)
|
|
61
|
+
return Number.isFinite(number) && number > 0 ? number : DEFAULT_SIZE
|
|
62
|
+
}
|
|
63
|
+
return { left: 0, top: 0, width: size("width"), height: size("height") }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One SVG file as an Iconify icon; `shown` is the file's path in an error. */
|
|
67
|
+
export function readSvgIcon(source: string, shown: string): IconifyIcon {
|
|
68
|
+
const root = sanitizeSvg(source, shown).find(
|
|
69
|
+
(node): node is Exclude<SvgNode, SvgValue> =>
|
|
70
|
+
typeof node === "object" && !Array.isArray(node) && node.tag === "svg",
|
|
71
|
+
)
|
|
72
|
+
if (!root) throw new DiagnosticError("HAMUR_E5905", "not an SVG file (no <svg> element)", { at: shown })
|
|
73
|
+
const { left, top, width, height } = box(root.attrs)
|
|
74
|
+
const paint = Object.entries(root.attrs).filter(([name]) => PAINT.has(name))
|
|
75
|
+
const children = paint.length
|
|
76
|
+
? [{ tag: "g", attrs: Object.fromEntries(paint), children: root.children }]
|
|
77
|
+
: root.children
|
|
78
|
+
return { body: svgMarkup(plain(children), ""), width, height, ...(left ? { left } : {}), ...(top ? { top } : {}) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function files(dir: string, recursive: boolean, segments: string[] = []): Array<{ file: string; segments: string[] }> {
|
|
82
|
+
const found: Array<{ file: string; segments: string[] }> = []
|
|
83
|
+
for (const name of readdirSync(dir).sort()) {
|
|
84
|
+
if (name.startsWith(".")) continue
|
|
85
|
+
const file = join(dir, name)
|
|
86
|
+
if (statSync(file).isDirectory()) {
|
|
87
|
+
if (recursive) found.push(...files(file, true, [...segments, name]))
|
|
88
|
+
} else if (SVG_FILE.test(name)) found.push({ file, segments: [...segments, name.replace(SVG_FILE, "")] })
|
|
89
|
+
}
|
|
90
|
+
return found
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The `.svg` files of `entry.dir` as one collection, each read once; an icon is named by its path segments joined with `-`. */
|
|
94
|
+
export function readCustomCollection(rootDir: string, entry: CustomCollection): IconifyJSON {
|
|
95
|
+
const icons: Record<string, IconifyIcon> = {}
|
|
96
|
+
const origin: Record<string, string> = {}
|
|
97
|
+
for (const { file, segments } of files(entry.dir, entry.recursive)) {
|
|
98
|
+
const shown = relative(rootDir, file).split(sep).join("/")
|
|
99
|
+
const name = segments.join("-")
|
|
100
|
+
if (!NAME_PATTERN.test(name))
|
|
101
|
+
throw new DiagnosticError("HAMUR_E5906", `icon name ${JSON.stringify(name)} must match ${NAME_PATTERN}`, {
|
|
102
|
+
at: shown,
|
|
103
|
+
})
|
|
104
|
+
if (Object.hasOwn(icons, name))
|
|
105
|
+
throw new DiagnosticError(
|
|
106
|
+
"HAMUR_E5907",
|
|
107
|
+
`icon name ${JSON.stringify(name)} is also the name of ${origin[name]}`,
|
|
108
|
+
{ at: shown },
|
|
109
|
+
)
|
|
110
|
+
icons[name] = readSvgIcon(readFileSync(file, "utf8"), shown)
|
|
111
|
+
origin[name] = shown
|
|
112
|
+
}
|
|
113
|
+
return { prefix: entry.prefix, icons }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The custom collections whose `dir` holds `file`, when it is an `.svg`. */
|
|
117
|
+
export const isCustomFile = (entries: CustomCollection[], file: string): CustomCollection[] =>
|
|
118
|
+
SVG_FILE.test(file)
|
|
119
|
+
? entries.filter((entry) => !relative(entry.dir, file).startsWith("..") && relative(entry.dir, file) !== "")
|
|
120
|
+
: []
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { addServer, addTemplate, createResolver, type HamurContext } from "hamur/kit"
|
|
2
|
+
import { FILE_PRESETS, type ResolvedIconOptions } from "../options.ts"
|
|
3
|
+
import type { IconEndpointOptions } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
/** The door with `/_hamur/icons/**`, on every preset that has a server and a provider. */
|
|
6
|
+
export function setupEndpoint(options: ResolvedIconOptions, hamur: HamurContext): void {
|
|
7
|
+
if (options.provider === "none" || FILE_PRESETS.has(hamur.options.preset)) return
|
|
8
|
+
const endpoint: IconEndpointOptions = {
|
|
9
|
+
dev: hamur.options.dev,
|
|
10
|
+
fallbackToApi: options.fallbackToApi,
|
|
11
|
+
iconifyApiEndpoint: options.iconifyApiEndpoint,
|
|
12
|
+
fetchTimeout: options.fetchTimeout,
|
|
13
|
+
}
|
|
14
|
+
addTemplate({ filename: "icon/endpoint", getContents: () => `export default ${JSON.stringify(endpoint)};\n` })
|
|
15
|
+
addServer(createResolver(import.meta.url).resolve("../server/door.ts"))
|
|
16
|
+
}
|