@prunellejs/icons 0.0.0-stage → 0.5.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/llms.txt +49 -0
- package/package.json +27 -4
- package/src/Icon.tsx +25 -0
- package/src/ambient.d.ts +5 -0
- package/src/diagnose.ts +44 -0
- package/src/find.ts +47 -0
- package/src/icon-data.ts +74 -0
- package/src/index.ts +7 -0
- package/src/name-words.ts +50 -0
- package/src/plugin.ts +183 -0
- package/src/search.ts +250 -0
- package/src/sets.ts +46 -0
- package/src/spelling.ts +84 -0
- package/src/svg-dir.ts +64 -0
- package/src/table.ts +119 -0
- package/src/types.ts +25 -0
- package/src/words.json +1 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @prunellejs/icons Reference
|
|
2
|
+
|
|
3
|
+
> Compile-time Iconify & local SVG icon imports (`~icons/<set>/<name>`) with zero runtime set overhead, accessible `<Icon>`, CLI discovery, and server-side search.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/icons`: `Icon`, `iconData`; types `IconComponentProps`, `IconData`, `IconifyIcon`, `IconSet`.
|
|
8
|
+
- `@prunellejs/icons/plugin`: `icons(options?)`; type `IconsPluginOptions`. Registering it in `prunelle.config.ts` automatically loads ambient `~icons/*` types.
|
|
9
|
+
- `@prunellejs/icons/ambient`: `/// <reference types="@prunellejs/icons/ambient" />` (only needed if `prunelle.config.ts` is outside your `tsconfig` include).
|
|
10
|
+
- `@prunellejs/icons/search` (server-only — 1.7 MB word table; build warns if imported in an island): `findIcons(source, query, { limit?, offset? }?)`, `relatedWords(word)`; types `IconifyNames`, `IconPage`.
|
|
11
|
+
|
|
12
|
+
## Plugin Setup (`icons(options?)`)
|
|
13
|
+
|
|
14
|
+
- `sets`: optional `Record<string, IconSet>` of custom in-memory sets keyed by prefix.
|
|
15
|
+
- `dirs`: optional `Record<string, string>` mapping prefixes to local `.svg` folders relative to app root (e.g. `{ brand: 'assets/brand' }`). `src/icons` is automatically mounted as `~icons/local/<name>` unless overridden; edited files reload in `prunelle dev`.
|
|
16
|
+
- Install Iconify icon packs as dev dependencies (e.g. `bun add -d @iconify-json/tabler`), then import `~icons/tabler/home`.
|
|
17
|
+
- CLI & checks: run `prunelle icons-find <words> [--set <prefix>] [--limit <n>]` instead of guessing names. `prunelle check` and `prunelle build` fail on missing/invalid icons and suggest closest matches.
|
|
18
|
+
|
|
19
|
+
## `<Icon>` Component
|
|
20
|
+
|
|
21
|
+
- Props: `IconComponentProps = Omit<JSX.IntrinsicElements['svg'], 'children' | 'innerHTML'> & { icon: IconData }`.
|
|
22
|
+
- Accessibility: when `aria-label` or `aria-labelledby` is provided, `<Icon>` sets `role="img"`; otherwise it sets `aria-hidden="true"`. Works in both static pages and client islands.
|
|
23
|
+
|
|
24
|
+
## Snippets
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// prunelle.config.ts
|
|
28
|
+
import { icons } from '@prunellejs/icons/plugin'
|
|
29
|
+
import { defineConfig } from 'prunelle/config'
|
|
30
|
+
|
|
31
|
+
export default defineConfig({
|
|
32
|
+
plugins: [icons({ dirs: { brand: 'assets/brand' } })],
|
|
33
|
+
})
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
import { Icon } from '@prunellejs/icons'
|
|
38
|
+
import check from '~icons/tabler/check'
|
|
39
|
+
import logo from '~icons/brand/logo'
|
|
40
|
+
|
|
41
|
+
export function Badge() {
|
|
42
|
+
return (
|
|
43
|
+
<span>
|
|
44
|
+
<Icon icon={logo} width={20} height={20} aria-label="Acme" />
|
|
45
|
+
<Icon icon={check} class="ok" /> Verified
|
|
46
|
+
</span>
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/icons",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.2",
|
|
4
|
+
"description": "Compile-time Iconify SVG icon plugin (~icons/<set>/<name>) for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts",
|
|
14
|
+
"./plugin": "./src/plugin.ts",
|
|
15
|
+
"./search": "./src/search.ts",
|
|
16
|
+
"./ambient": "./src/ambient.d.ts"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"bun": ">=1.4.0"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
24
|
+
"directory": "packages/plugin-icons"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"prunelle": "^0.5.2"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/Icon.tsx
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** @jsxImportSource prunelle */
|
|
2
|
+
import type { JSX } from 'prunelle/jsx-runtime'
|
|
3
|
+
import type { IconData } from './types'
|
|
4
|
+
|
|
5
|
+
export type IconComponentProps = Omit<JSX.IntrinsicElements['svg'], 'children' | 'innerHTML'> & { icon: IconData }
|
|
6
|
+
|
|
7
|
+
function isName(value: unknown): boolean {
|
|
8
|
+
return typeof value === 'string' && value.trim() !== ''
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// An icon is an image when the caller names it, and hidden from assistive tech otherwise.
|
|
12
|
+
export function Icon({ icon, viewBox, width, height, role, 'aria-hidden': ariaHidden, ...rest }: IconComponentProps) {
|
|
13
|
+
const named = (): boolean => isName(rest['aria-label']) || isName(rest['aria-labelledby'])
|
|
14
|
+
return (
|
|
15
|
+
<svg
|
|
16
|
+
{...rest}
|
|
17
|
+
viewBox={viewBox ?? icon.viewBox}
|
|
18
|
+
width={width ?? icon.width}
|
|
19
|
+
height={height ?? icon.height}
|
|
20
|
+
role={role ?? (named() ? 'img' : undefined)}
|
|
21
|
+
aria-hidden={ariaHidden ?? (named() ? undefined : 'true')}
|
|
22
|
+
innerHTML={icon.body}
|
|
23
|
+
/>
|
|
24
|
+
)
|
|
25
|
+
}
|
package/src/ambient.d.ts
ADDED
package/src/diagnose.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Why an `~icons/<set>/<name>` import cannot load, with the closest imports that can, for the build error and `prunelle check`.
|
|
2
|
+
|
|
3
|
+
import type { IconSet } from './types'
|
|
4
|
+
import { iconData } from './icon-data'
|
|
5
|
+
import { isSetPrefix } from './sets'
|
|
6
|
+
import { closeWords } from './spelling'
|
|
7
|
+
|
|
8
|
+
const SUGGESTED = 3
|
|
9
|
+
|
|
10
|
+
export interface IconLookup {
|
|
11
|
+
/** The set of `prefix`, undefined when it is not installed. */
|
|
12
|
+
set: (prefix: string) => Promise<IconSet | undefined>
|
|
13
|
+
/** The prefixes an app could import from: its own sets and the installed ones. */
|
|
14
|
+
prefixes: () => string[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function didYouMean(specifiers: string[]): string {
|
|
18
|
+
return specifiers.length > 0 ? `Did you mean ${specifiers.join(', ')}? ` : ''
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The problem with importing `name` from `prefix`, `where` naming the importer; undefined when the icon exists. */
|
|
22
|
+
export async function iconProblem(prefix: string, name: string, where: string, lookup: IconLookup): Promise<string | undefined> {
|
|
23
|
+
const set = await lookup.set(prefix)
|
|
24
|
+
if (set !== undefined) {
|
|
25
|
+
if (iconData(set, name) !== undefined)
|
|
26
|
+
return undefined
|
|
27
|
+
// Imported here, as it reads the word table: only a failing import pays for it.
|
|
28
|
+
const { findIcons } = await import('./search')
|
|
29
|
+
// A mistyped import is closest to a whole name; the search fills in names sharing its words.
|
|
30
|
+
const names = [...Object.keys(set.icons), ...Object.keys(set.aliases ?? {})]
|
|
31
|
+
const closest = [...new Set([...closeWords(name, names), ...findIcons(set, name, { limit: SUGGESTED })])].slice(0, SUGGESTED).map(found => `~icons/${prefix}/${found}`)
|
|
32
|
+
return `no icon "${name}" in set "${prefix}"${where}. ${didYouMean(closest)}Search with prunelle icons-find <words>.`
|
|
33
|
+
}
|
|
34
|
+
if (!isSetPrefix(prefix))
|
|
35
|
+
return `"${prefix}" is not an icon set name${where}: write ~icons/<set>/<name>, such as ~icons/tabler/home.`
|
|
36
|
+
|
|
37
|
+
const closest: string[] = []
|
|
38
|
+
for (const other of closeWords(prefix, lookup.prefixes())) {
|
|
39
|
+
const otherSet = await lookup.set(other)
|
|
40
|
+
if (otherSet !== undefined && iconData(otherSet, name) !== undefined)
|
|
41
|
+
closest.push(`~icons/${other}/${name}`)
|
|
42
|
+
}
|
|
43
|
+
return `no icon set "${prefix}" is installed${where}. ${didYouMean(closest)}Otherwise install @iconify-json/${prefix}, or add it to icons({ sets }) or icons({ dirs }).`
|
|
44
|
+
}
|
package/src/find.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`: prints the `~icons/<set>/<name>` imports matching the words, so an agent imports icons that exist.
|
|
2
|
+
|
|
3
|
+
import type { IconLookup } from './diagnose'
|
|
4
|
+
|
|
5
|
+
const FOUND_PER_SET = 10
|
|
6
|
+
const USAGE = 'Usage: prunelle icons-find <words> [--set <prefix>] [--limit <n>]'
|
|
7
|
+
|
|
8
|
+
function fail(message: string): never {
|
|
9
|
+
console.error(message)
|
|
10
|
+
process.exit(1)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function iconsFind(args: string[], lookup: IconLookup): Promise<void> {
|
|
14
|
+
const words: string[] = []
|
|
15
|
+
let only: string | undefined
|
|
16
|
+
let limit = FOUND_PER_SET
|
|
17
|
+
for (let i = 0; i < args.length; i++) {
|
|
18
|
+
const arg = args[i]!
|
|
19
|
+
if (arg === '--set' || arg === '--limit') {
|
|
20
|
+
const value = args[++i] ?? fail(USAGE)
|
|
21
|
+
if (arg === '--set')
|
|
22
|
+
only = value
|
|
23
|
+
else
|
|
24
|
+
limit = Number(value)
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
words.push(arg)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const query = words.join(' ')
|
|
31
|
+
if (query.trim() === '' || !Number.isInteger(limit) || limit < 1)
|
|
32
|
+
fail(USAGE)
|
|
33
|
+
|
|
34
|
+
const installed = lookup.prefixes().sort()
|
|
35
|
+
if (installed.length === 0)
|
|
36
|
+
fail('No icon set installed. Install one, such as @iconify-json/tabler.')
|
|
37
|
+
if (only !== undefined && !installed.includes(only))
|
|
38
|
+
fail(`No icon set "${only}" is installed. Installed: ${installed.join(', ')}.`)
|
|
39
|
+
|
|
40
|
+
const prefixes = only === undefined ? installed : [only]
|
|
41
|
+
// Imported here so the word table never reaches a bundle that only draws icons.
|
|
42
|
+
const [{ findIcons }, sets] = await Promise.all([import('./search'), Promise.all(prefixes.map(prefix => lookup.set(prefix)))])
|
|
43
|
+
for (const [i, prefix] of prefixes.entries()) {
|
|
44
|
+
for (const name of findIcons(sets[i]!, query, { limit }))
|
|
45
|
+
console.log(`~icons/${prefix}/${name}`)
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/icon-data.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { IconData, IconifyIcon, IconSet } from './types'
|
|
2
|
+
|
|
3
|
+
const DEFAULT_SIZE = 16
|
|
4
|
+
|
|
5
|
+
function resolveIcon(set: IconSet, name: string, depth: number): IconifyIcon | undefined {
|
|
6
|
+
const own = set.icons[name]
|
|
7
|
+
if (own !== undefined)
|
|
8
|
+
return own
|
|
9
|
+
|
|
10
|
+
const alias = set.aliases?.[name]
|
|
11
|
+
if (alias?.parent === undefined || alias.parent === '' || depth > 8)
|
|
12
|
+
return undefined
|
|
13
|
+
|
|
14
|
+
const parent = resolveIcon(set, alias.parent, depth + 1)
|
|
15
|
+
if (parent === undefined)
|
|
16
|
+
return undefined
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
...parent,
|
|
20
|
+
...alias,
|
|
21
|
+
body: parent.body,
|
|
22
|
+
hFlip: Boolean(parent.hFlip) !== Boolean(alias.hFlip),
|
|
23
|
+
vFlip: Boolean(parent.vFlip) !== Boolean(alias.vFlip),
|
|
24
|
+
rotate: (parent.rotate ?? 0) + (alias.rotate ?? 0),
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The viewBox, size and body Iconify's `iconToSVG` would draw: flips first, then the rotation around them, a quarter turn swapping the sides.
|
|
29
|
+
export function iconData(set: IconSet, name: string): IconData | undefined {
|
|
30
|
+
const ownPrefix = `${set.prefix}:`
|
|
31
|
+
const icon = resolveIcon(set, name.startsWith(ownPrefix) ? name.slice(ownPrefix.length) : name, 0)
|
|
32
|
+
if (icon?.body === undefined || icon.body === '')
|
|
33
|
+
return undefined
|
|
34
|
+
|
|
35
|
+
const box = {
|
|
36
|
+
left: icon.left ?? set.left ?? 0,
|
|
37
|
+
top: icon.top ?? set.top ?? 0,
|
|
38
|
+
width: icon.width ?? set.width ?? DEFAULT_SIZE,
|
|
39
|
+
height: icon.height ?? set.height ?? DEFAULT_SIZE,
|
|
40
|
+
}
|
|
41
|
+
if (!(box.width > 0 && box.height > 0))
|
|
42
|
+
return undefined
|
|
43
|
+
|
|
44
|
+
const hFlip = icon.hFlip ?? set.hFlip ?? false
|
|
45
|
+
const vFlip = icon.vFlip ?? set.vFlip ?? false
|
|
46
|
+
let rotate = icon.rotate ?? set.rotate ?? 0
|
|
47
|
+
const transforms: string[] = []
|
|
48
|
+
|
|
49
|
+
if (hFlip && vFlip) {
|
|
50
|
+
rotate += 2
|
|
51
|
+
}
|
|
52
|
+
else if (hFlip || vFlip) {
|
|
53
|
+
transforms.push(hFlip ? `translate(${box.width + box.left} ${-box.top})` : `translate(${-box.left} ${box.height + box.top})`, hFlip ? 'scale(-1 1)' : 'scale(1 -1)')
|
|
54
|
+
box.left = 0
|
|
55
|
+
box.top = 0
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
rotate = ((rotate % 4) + 4) % 4
|
|
59
|
+
if (rotate === 1)
|
|
60
|
+
transforms.unshift(`rotate(90 ${box.height / 2 + box.top} ${box.height / 2 + box.top})`)
|
|
61
|
+
else if (rotate === 2)
|
|
62
|
+
transforms.unshift(`rotate(180 ${box.width / 2 + box.left} ${box.height / 2 + box.top})`)
|
|
63
|
+
else if (rotate === 3)
|
|
64
|
+
transforms.unshift(`rotate(-90 ${box.width / 2 + box.left} ${box.width / 2 + box.left})`)
|
|
65
|
+
if (rotate % 2 === 1)
|
|
66
|
+
[box.left, box.top, box.width, box.height] = [box.top, box.left, box.height, box.width]
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
viewBox: `${box.left} ${box.top} ${box.width} ${box.height}`,
|
|
70
|
+
width: `${Math.round((box.width / box.height) * 1000) / 1000}em`,
|
|
71
|
+
height: '1em',
|
|
72
|
+
body: transforms.length > 0 ? `<g transform="${transforms.join(' ')}">${icon.body}</g>` : icon.body,
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/// <reference path="./ambient.d.ts" />
|
|
2
|
+
// The browser-safe side of @prunellejs/icons: the <Icon> component and the icon data types. The plugin is `@prunellejs/icons/plugin`.
|
|
3
|
+
|
|
4
|
+
export { Icon } from './Icon'
|
|
5
|
+
export type { IconComponentProps } from './Icon'
|
|
6
|
+
export { iconData } from './icon-data'
|
|
7
|
+
export type { IconData, IconifyIcon, IconSet } from './types'
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const SPLIT = /[^a-z0-9]+/
|
|
2
|
+
const DIGITS = /^\d+$/
|
|
3
|
+
|
|
4
|
+
// The words of an icon name or a query, `arrow-left-2` giving `arrow` and `left`, and `circle-x` giving `circle` and `x`.
|
|
5
|
+
export function nameWords(text: string): string[] {
|
|
6
|
+
return text.toLowerCase().split(SPLIT).filter(word => word !== '' && !DIGITS.test(word))
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// How many parts a name has, numbers included, so `user-2` and `user-x` weigh as variants of `user`.
|
|
10
|
+
export function nameParts(name: string): number {
|
|
11
|
+
return name.toLowerCase().split(SPLIT).filter(part => part !== '').length
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const KEEPS_S = /(?:ss|us|is)$/
|
|
15
|
+
const DOUBLED = /([^aeiouylsz])\1$/
|
|
16
|
+
|
|
17
|
+
// What the forms of a word share, so `saves`, `saved` and `saving` give `sav`, `users` gives `user` and `boxes` gives `box`; a stem keeps 3 letters at least, and a doubled letter goes only past 3, as `running` gives `run` but `added` gives `add`.
|
|
18
|
+
export function stem(word: string): string {
|
|
19
|
+
const cut = (form: string, letters: number) => form.length - letters >= 3 ? form.slice(0, -letters) : form
|
|
20
|
+
let base = word
|
|
21
|
+
|
|
22
|
+
if (base.endsWith('ies'))
|
|
23
|
+
base = `${cut(base, 3)}y`
|
|
24
|
+
else if (base.endsWith('s') && !KEEPS_S.test(base))
|
|
25
|
+
base = cut(base, 1)
|
|
26
|
+
|
|
27
|
+
const ending = base.endsWith('ing') ? 3 : base.endsWith('ed') && !base.endsWith('eed') ? 2 : 0
|
|
28
|
+
|
|
29
|
+
if (ending > 0)
|
|
30
|
+
base = cut(base, ending)
|
|
31
|
+
if (ending > 0 && base.length > 3)
|
|
32
|
+
base = base.replace(DOUBLED, '$1')
|
|
33
|
+
|
|
34
|
+
return base.endsWith('e') ? cut(base, 1) : base
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Each stem to the shortest of the words holding it, which is most often the plain form.
|
|
38
|
+
export function byStem(words: Iterable<string>): Map<string, string> {
|
|
39
|
+
const forms = new Map<string, string>()
|
|
40
|
+
|
|
41
|
+
for (const word of words) {
|
|
42
|
+
const key = stem(word)
|
|
43
|
+
const known = forms.get(key)
|
|
44
|
+
|
|
45
|
+
if (known === undefined || word.length < known.length)
|
|
46
|
+
forms.set(key, word)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return forms
|
|
50
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/// <reference path="./ambient.d.ts" />
|
|
2
|
+
// The build side of @prunellejs/icons: resolves `~icons/<set>/<name>` imports to inline SVG data at compile time, and adds `prunelle icons-find`.
|
|
3
|
+
// The reference above types those imports in every app registering icons() in prunelle.config.ts.
|
|
4
|
+
|
|
5
|
+
import type { BunPlugin } from 'bun'
|
|
6
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
7
|
+
import type { IconLookup } from './diagnose'
|
|
8
|
+
import type { IconSet } from './types'
|
|
9
|
+
import type { SvgDirSet } from './svg-dir'
|
|
10
|
+
import { existsSync } from 'node:fs'
|
|
11
|
+
import { join, relative, resolve } from 'node:path'
|
|
12
|
+
import { definePlugin } from 'prunelle/config'
|
|
13
|
+
import { iconData } from './icon-data'
|
|
14
|
+
import { iconProblem } from './diagnose'
|
|
15
|
+
import { iconsFind } from './find'
|
|
16
|
+
import { installedPrefixes, isSetPrefix, setFile } from './sets'
|
|
17
|
+
import { readSvgDir } from './svg-dir'
|
|
18
|
+
|
|
19
|
+
const ICON_SPEC_RE = /^~icons\/([^/]+)\/(.+)$/
|
|
20
|
+
const SEARCH_ENTRY_RE = /^@prunellejs\/icons\/search$/
|
|
21
|
+
const ICON_IMPORT_RE = /\b(?:from|import)\s*\(?\s*(['"])(~icons\/[^/'"]+\/[^'"]+)\1/g
|
|
22
|
+
const SELF_CLOSING_RE = /<([a-z][\w:-]*)([^<>]*?)\s*\/>/gi
|
|
23
|
+
const LOCAL_DIR = 'src/icons'
|
|
24
|
+
|
|
25
|
+
const transpilers = { ts: new Bun.Transpiler({ loader: 'ts' }), tsx: new Bun.Transpiler({ loader: 'tsx' }) }
|
|
26
|
+
|
|
27
|
+
// The ~icons specifiers a file imports or loads with import(), leaving out one only spelled in a string or a comment. A file that does not parse is left to the typecheck.
|
|
28
|
+
function importedIcons(code: string, file: string): Set<string> {
|
|
29
|
+
try {
|
|
30
|
+
const imports = transpilers[file.endsWith('.tsx') ? 'tsx' : 'ts'].scanImports(code)
|
|
31
|
+
return new Set(imports.map(i => i.path).filter(path => path.startsWith('~icons/')))
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return new Set()
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Spells `<path d="…"/>` as `<path d="…"></path>`, the way a browser serializes SVG, so hydrating an island finds the server's body unchanged and keeps its nodes.
|
|
39
|
+
function withEndTags(body: string): string {
|
|
40
|
+
return body.replace(SELF_CLOSING_RE, '<$1$2></$1>')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface IconsPluginOptions {
|
|
44
|
+
/** Optional preloaded custom icon sets keyed by prefix (e.g. `{ custom: mySet }`). */
|
|
45
|
+
sets?: Record<string, IconSet> | undefined
|
|
46
|
+
/** Folders of `.svg` files read as sets, keyed by prefix, relative to the app root (e.g. `{ brand: 'assets/brand' }`). `src/icons` is the set `local` unless named here. */
|
|
47
|
+
dirs?: Record<string, string> | undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface PluginLookup extends IconLookup {
|
|
51
|
+
/** Each folder set's absolute folder, keyed by prefix. */
|
|
52
|
+
dirs: Map<string, string>
|
|
53
|
+
/** The folder set of `prefix`, with the files that are not icons. */
|
|
54
|
+
dirSet: (prefix: string) => Promise<SvgDirSet | undefined>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function svgDirs(root: string, dirs: Record<string, string> = {}): Map<string, string> {
|
|
58
|
+
const local = resolve(root, LOCAL_DIR)
|
|
59
|
+
const named = Object.entries(dirs).map(([prefix, dir]): [string, string] => [prefix, resolve(root, dir)])
|
|
60
|
+
return new Map(named.some(([, dir]) => dir === local) ? named : [['local', local], ...named])
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function lineAndColumn(code: string, offset: number): string {
|
|
64
|
+
const before = code.slice(0, offset).split('\n')
|
|
65
|
+
return `${before.length}:${before.at(-1)!.length + 1}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function icons(options: IconsPluginOptions = {}): PrunellePlugin {
|
|
69
|
+
// The in-flight read of each set, so icons loaded in parallel parse their set once; a set not installed is looked for again next time.
|
|
70
|
+
const cache = new Map<string, Promise<IconSet | undefined>>(Object.entries(options.sets ?? {}).map(([prefix, set]) => [prefix, Promise.resolve(set)]))
|
|
71
|
+
const installedSet = (root: string, prefix: string): Promise<IconSet | undefined> => {
|
|
72
|
+
let set = cache.get(prefix)
|
|
73
|
+
if (set === undefined) {
|
|
74
|
+
const file = setFile(prefix, root)
|
|
75
|
+
if (file === undefined)
|
|
76
|
+
return Promise.resolve(undefined)
|
|
77
|
+
set = Bun.file(file).json() as Promise<IconSet>
|
|
78
|
+
cache.set(prefix, set)
|
|
79
|
+
}
|
|
80
|
+
return set
|
|
81
|
+
}
|
|
82
|
+
// Folder sets are read again by each build, so `prunelle dev` sees an edited file.
|
|
83
|
+
const lookupIn = (root: string): PluginLookup => {
|
|
84
|
+
const dirs = svgDirs(root, options.dirs)
|
|
85
|
+
if (options.sets?.local !== undefined && options.dirs?.local === undefined)
|
|
86
|
+
dirs.delete('local')
|
|
87
|
+
const dirSets = new Map<string, Promise<SvgDirSet | undefined>>()
|
|
88
|
+
const dirSet = (prefix: string): Promise<SvgDirSet | undefined> => {
|
|
89
|
+
let read = dirSets.get(prefix)
|
|
90
|
+
if (read === undefined) {
|
|
91
|
+
const dir = dirs.get(prefix)
|
|
92
|
+
read = dir === undefined ? Promise.resolve(undefined) : readSvgDir(prefix, dir)
|
|
93
|
+
dirSets.set(prefix, read)
|
|
94
|
+
}
|
|
95
|
+
return read
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
dirs,
|
|
99
|
+
dirSet,
|
|
100
|
+
set: async prefix => dirs.has(prefix) ? (await dirSet(prefix))?.set : await installedSet(root, prefix),
|
|
101
|
+
prefixes: () => [...new Set([...Object.keys(options.sets ?? {}), ...[...dirs].filter(([, dir]) => existsSync(dir)).map(([prefix]) => prefix), ...installedPrefixes(root)])],
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Why the icon `name` of a folder set cannot load, naming its file; undefined when it is no folder set or its file is fine.
|
|
106
|
+
async function fileProblem(lookup: PluginLookup, root: string, prefix: string, name: string): Promise<{ file: string, problem: string } | undefined> {
|
|
107
|
+
const problem = (await lookup.dirSet(prefix))?.problems.get(name)
|
|
108
|
+
return problem === undefined ? undefined : { file: relative(root, join(lookup.dirs.get(prefix)!, `${name}.svg`)), problem }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return definePlugin({
|
|
112
|
+
name: '@prunellejs/icons',
|
|
113
|
+
async check(ctx) {
|
|
114
|
+
const lookup = lookupIn(ctx.root)
|
|
115
|
+
for (const [prefix, dir] of Object.entries(options.dirs ?? {})) {
|
|
116
|
+
if (!isSetPrefix(prefix))
|
|
117
|
+
ctx.error(`@prunellejs/icons: "${prefix}" in icons({ dirs }) is not an icon set name: name it in lowercase words joined by dashes, such as brand.`)
|
|
118
|
+
else if (!existsSync(lookup.dirs.get(prefix)!))
|
|
119
|
+
ctx.error(`@prunellejs/icons: icons({ dirs }) reads the set "${prefix}" from ${dir}, which does not exist.`)
|
|
120
|
+
}
|
|
121
|
+
for (const prefix of lookup.dirs.keys()) {
|
|
122
|
+
for (const [name, problem] of (await lookup.dirSet(prefix))?.problems ?? [])
|
|
123
|
+
ctx.error(`${relative(ctx.root, join(lookup.dirs.get(prefix)!, `${name}.svg`))}:1:1: error: @prunellejs/icons: this file ${problem}.`)
|
|
124
|
+
}
|
|
125
|
+
for (const file of new Bun.Glob('src/**/*.{ts,tsx,mts}').scanSync({ cwd: ctx.root })) {
|
|
126
|
+
const code = await Bun.file(join(ctx.root, file)).text()
|
|
127
|
+
const imported = importedIcons(code, file)
|
|
128
|
+
for (const found of code.matchAll(ICON_IMPORT_RE)) {
|
|
129
|
+
// The regex finds where a specifier is spelled; only one the file really imports is checked, once.
|
|
130
|
+
if (!imported.delete(found[2]!))
|
|
131
|
+
continue
|
|
132
|
+
const [, prefix, name] = ICON_SPEC_RE.exec(found[2]!)!
|
|
133
|
+
// A broken file is reported once above, not at each import.
|
|
134
|
+
if (await fileProblem(lookup, ctx.root, prefix!, name!) !== undefined)
|
|
135
|
+
continue
|
|
136
|
+
const problem = await iconProblem(prefix!, name!, '', lookup)
|
|
137
|
+
if (problem !== undefined)
|
|
138
|
+
ctx.error(`${file}:${lineAndColumn(code, found.index + found[0].length - found[2]!.length - 2)}: error: @prunellejs/icons: ${problem}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
watchPaths: root => [...lookupIn(root).dirs.values()],
|
|
143
|
+
bunPlugins: ({ root, target }): BunPlugin[] => [{
|
|
144
|
+
name: 'prunelle-icons',
|
|
145
|
+
setup(b) {
|
|
146
|
+
const lookup = lookupIn(root)
|
|
147
|
+
if (target === 'client') {
|
|
148
|
+
b.onResolve({ filter: SEARCH_ENTRY_RE }, (args) => {
|
|
149
|
+
console.warn(`@prunellejs/icons: ${relative(root, args.importer)} imports @prunellejs/icons/search into an island, which ships its 1.7 MB word table to the browser. Search on the server instead, in a route or an action.`)
|
|
150
|
+
return undefined
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
// The first file importing each icon, for an error to name it.
|
|
154
|
+
const importers = new Map<string, string>()
|
|
155
|
+
b.onResolve({ filter: ICON_SPEC_RE }, (args) => {
|
|
156
|
+
if (!importers.has(args.path))
|
|
157
|
+
importers.set(args.path, relative(root, args.importer))
|
|
158
|
+
return { path: args.path, namespace: 'prunelle-icon' }
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
b.onLoad({ filter: /.*/, namespace: 'prunelle-icon' }, async (args) => {
|
|
162
|
+
const [, prefix, name] = ICON_SPEC_RE.exec(args.path)!
|
|
163
|
+
const set = await lookup.set(prefix!)
|
|
164
|
+
const data = set === undefined ? undefined : iconData(set, name!)
|
|
165
|
+
if (data === undefined) {
|
|
166
|
+
const broken = await fileProblem(lookup, root, prefix!, name!)
|
|
167
|
+
if (broken !== undefined)
|
|
168
|
+
throw new Error(`@prunellejs/icons: ${broken.file}, imported by ${importers.get(args.path)}, ${broken.problem}.`)
|
|
169
|
+
throw new Error(`@prunellejs/icons: ${await iconProblem(prefix!, name!, `, imported by ${importers.get(args.path)}`, lookup)}`)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
contents: `export default ${JSON.stringify(target === 'client' ? { ...data, body: withEndTags(data.body) } : data)};\n`,
|
|
174
|
+
loader: 'js',
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
},
|
|
178
|
+
}],
|
|
179
|
+
commands: {
|
|
180
|
+
'icons-find': async (args, root) => await iconsFind(args, lookupIn(root)),
|
|
181
|
+
},
|
|
182
|
+
})
|
|
183
|
+
}
|