@kayjs/icons 2.0.0-beta.2 → 2.0.0-beta.4
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/package.json +4 -2
- package/src/Icon.tsx +13 -14
- package/src/diagnose.ts +44 -0
- package/src/find.ts +47 -0
- package/src/icon-data.ts +74 -0
- package/src/index.ts +2 -116
- package/src/name-words.ts +50 -0
- package/src/plugin.ts +166 -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 +2 -3
- package/src/words.json +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/icons",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.4",
|
|
4
4
|
"description": "Compile-time Iconify SVG icon plugin (~icons/<set>/<name>) for Kay v2",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
],
|
|
11
11
|
"exports": {
|
|
12
12
|
".": "./src/index.ts",
|
|
13
|
+
"./plugin": "./src/plugin.ts",
|
|
14
|
+
"./search": "./src/search.ts",
|
|
13
15
|
"./ambient": "./src/ambient.d.ts"
|
|
14
16
|
},
|
|
15
17
|
"engines": {
|
|
@@ -21,6 +23,6 @@
|
|
|
21
23
|
"directory": "packages/plugin-icons"
|
|
22
24
|
},
|
|
23
25
|
"peerDependencies": {
|
|
24
|
-
"@kayjs/kay": "^2.0.0-beta.
|
|
26
|
+
"@kayjs/kay": "^2.0.0-beta.4"
|
|
25
27
|
}
|
|
26
28
|
}
|
package/src/Icon.tsx
CHANGED
|
@@ -1,25 +1,24 @@
|
|
|
1
1
|
/** @jsxImportSource @kayjs/kay */
|
|
2
|
+
import type { JSX } from '@kayjs/kay/jsx-runtime'
|
|
2
3
|
import type { IconData } from './types'
|
|
3
4
|
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
style?: string | Record<string, string | number | undefined> | undefined
|
|
9
|
-
'aria-label'?: string | undefined
|
|
10
|
-
[attr: string]: unknown
|
|
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() !== ''
|
|
11
9
|
}
|
|
12
10
|
|
|
13
|
-
|
|
14
|
-
|
|
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'])
|
|
15
14
|
return (
|
|
16
15
|
<svg
|
|
17
|
-
viewBox={icon.viewBox}
|
|
18
|
-
width={icon.width}
|
|
19
|
-
height={icon.height}
|
|
20
|
-
aria-hidden={hasLabel ? undefined : 'true'}
|
|
21
|
-
role={hasLabel ? 'img' : undefined}
|
|
22
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')}
|
|
23
22
|
innerHTML={icon.body}
|
|
24
23
|
/>
|
|
25
24
|
)
|
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 `kay 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 kay 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
|
+
// `kay 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: kay 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
CHANGED
|
@@ -1,121 +1,7 @@
|
|
|
1
1
|
/// <reference path="./ambient.d.ts" />
|
|
2
|
-
// @kayjs/icons
|
|
3
|
-
// Built strictly on the public KayPlugin API (bunPlugins).
|
|
4
|
-
|
|
5
|
-
import type { BunPlugin } from 'bun'
|
|
6
|
-
import type { KayPlugin } from '@kayjs/kay/server'
|
|
7
|
-
import type { IconData, IconifyIcon, IconSet } from './types'
|
|
8
|
-
import { definePlugin } from '@kayjs/kay/server'
|
|
2
|
+
// The browser-safe side of @kayjs/icons: the <Icon> component and the icon data types. The plugin is `@kayjs/icons/plugin`.
|
|
9
3
|
|
|
10
4
|
export { Icon } from './Icon'
|
|
11
5
|
export type { IconComponentProps } from './Icon'
|
|
6
|
+
export { iconData } from './icon-data'
|
|
12
7
|
export type { IconData, IconifyIcon, IconSet } from './types'
|
|
13
|
-
|
|
14
|
-
const DEFAULT_SIZE = 16
|
|
15
|
-
const ICON_SPEC_RE = /^~icons\/([^/]+)\/(.+)$/
|
|
16
|
-
|
|
17
|
-
function resolveIconSetFile(prefix: string, root: string): string {
|
|
18
|
-
const pkgPath = `@iconify-json/${prefix}/icons.json`
|
|
19
|
-
for (const from of [root, process.cwd()]) {
|
|
20
|
-
try {
|
|
21
|
-
return Bun.resolveSync(pkgPath, from)
|
|
22
|
-
}
|
|
23
|
-
catch {}
|
|
24
|
-
}
|
|
25
|
-
throw new Error(`@kayjs/icons: could not resolve "${pkgPath}". Install @iconify-json/${prefix}.`)
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function resolveIcon(set: IconSet, name: string, depth: number): IconifyIcon | undefined {
|
|
29
|
-
const own = set.icons[name]
|
|
30
|
-
if (own !== undefined)
|
|
31
|
-
return own
|
|
32
|
-
|
|
33
|
-
const alias = set.aliases?.[name]
|
|
34
|
-
if (alias?.parent === undefined || alias.parent === '' || depth > 8)
|
|
35
|
-
return undefined
|
|
36
|
-
|
|
37
|
-
const parent = resolveIcon(set, alias.parent, depth + 1)
|
|
38
|
-
if (parent === undefined)
|
|
39
|
-
return undefined
|
|
40
|
-
|
|
41
|
-
return {
|
|
42
|
-
...parent,
|
|
43
|
-
...alias,
|
|
44
|
-
body: parent.body,
|
|
45
|
-
hFlip: Boolean(parent.hFlip) !== Boolean(alias.hFlip),
|
|
46
|
-
vFlip: Boolean(parent.vFlip) !== Boolean(alias.vFlip),
|
|
47
|
-
rotate: (parent.rotate ?? 0) + (alias.rotate ?? 0),
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function iconData(set: IconSet, name: string): IconData | undefined {
|
|
52
|
-
const ownPrefix = `${set.prefix}:`
|
|
53
|
-
const icon = resolveIcon(set, name.startsWith(ownPrefix) ? name.slice(ownPrefix.length) : name, 0)
|
|
54
|
-
if (icon?.body === undefined || icon.body === '')
|
|
55
|
-
return undefined
|
|
56
|
-
|
|
57
|
-
const width = icon.width ?? set.width ?? DEFAULT_SIZE
|
|
58
|
-
const height = icon.height ?? set.height ?? DEFAULT_SIZE
|
|
59
|
-
const left = icon.left ?? 0
|
|
60
|
-
const top = icon.top ?? 0
|
|
61
|
-
const transforms: string[] = []
|
|
62
|
-
|
|
63
|
-
if (icon.hFlip)
|
|
64
|
-
transforms.push(`translate(${left * 2 + width} 0) scale(-1 1)`)
|
|
65
|
-
if (icon.vFlip)
|
|
66
|
-
transforms.push(`translate(0 ${top * 2 + height}) scale(1 -1)`)
|
|
67
|
-
if (icon.rotate !== undefined && icon.rotate !== 0)
|
|
68
|
-
transforms.push(`rotate(${(icon.rotate % 4) * 90} ${left + width / 2} ${top + height / 2})`)
|
|
69
|
-
|
|
70
|
-
const body = transforms.length > 0 ? `<g transform="${transforms.join(' ')}">${icon.body}</g>` : icon.body
|
|
71
|
-
|
|
72
|
-
return {
|
|
73
|
-
viewBox: `${left} ${top} ${width} ${height}`,
|
|
74
|
-
width: `${Math.round((width / height) * 1000) / 1000}em`,
|
|
75
|
-
height: '1em',
|
|
76
|
-
body,
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export interface IconsPluginOptions {
|
|
81
|
-
/** Optional preloaded custom icon sets keyed by prefix (e.g. `{ custom: mySet }`). */
|
|
82
|
-
sets?: Record<string, IconSet> | undefined
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function icons(options: IconsPluginOptions = {}): KayPlugin {
|
|
86
|
-
const cache = new Map<string, IconSet>(Object.entries(options.sets ?? {}))
|
|
87
|
-
|
|
88
|
-
return definePlugin({
|
|
89
|
-
name: '@kayjs/icons',
|
|
90
|
-
bunPlugins: ({ root }): BunPlugin[] => [{
|
|
91
|
-
name: 'kayjs-icons',
|
|
92
|
-
setup(b) {
|
|
93
|
-
b.onResolve({ filter: ICON_SPEC_RE }, args => ({ path: args.path, namespace: 'kay-icon' }))
|
|
94
|
-
|
|
95
|
-
b.onLoad({ filter: /.*/, namespace: 'kay-icon' }, async (args) => {
|
|
96
|
-
const match = ICON_SPEC_RE.exec(args.path)
|
|
97
|
-
if (match === null)
|
|
98
|
-
throw new Error(`@kayjs/icons: invalid specifier "${args.path}" (expected ~icons/<prefix>/<name>)`)
|
|
99
|
-
|
|
100
|
-
const prefix = match[1]!
|
|
101
|
-
const name = match[2]!
|
|
102
|
-
let set = cache.get(prefix)
|
|
103
|
-
|
|
104
|
-
if (set === undefined) {
|
|
105
|
-
set = await Bun.file(resolveIconSetFile(prefix, root)).json() as IconSet
|
|
106
|
-
cache.set(prefix, set)
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const data = iconData(set, name)
|
|
110
|
-
if (data === undefined)
|
|
111
|
-
throw new Error(`@kayjs/icons: icon "${name}" not found in set "${prefix}"`)
|
|
112
|
-
|
|
113
|
-
return {
|
|
114
|
-
contents: `export default ${JSON.stringify(data)};\n`,
|
|
115
|
-
loader: 'js',
|
|
116
|
-
}
|
|
117
|
-
})
|
|
118
|
-
},
|
|
119
|
-
}],
|
|
120
|
-
})
|
|
121
|
-
}
|
|
@@ -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,166 @@
|
|
|
1
|
+
/// <reference path="./ambient.d.ts" />
|
|
2
|
+
// The build side of @kayjs/icons: resolves `~icons/<set>/<name>` imports to inline SVG data at compile time, and adds `kay icons-find`.
|
|
3
|
+
// The reference above types those imports in every app registering icons() in kay.config.ts.
|
|
4
|
+
|
|
5
|
+
import type { BunPlugin } from 'bun'
|
|
6
|
+
import type { KayPlugin } from '@kayjs/kay/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 '@kayjs/kay/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 = /^@kayjs\/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
|
+
// 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.
|
|
26
|
+
function withEndTags(body: string): string {
|
|
27
|
+
return body.replace(SELF_CLOSING_RE, '<$1$2></$1>')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface IconsPluginOptions {
|
|
31
|
+
/** Optional preloaded custom icon sets keyed by prefix (e.g. `{ custom: mySet }`). */
|
|
32
|
+
sets?: Record<string, IconSet> | undefined
|
|
33
|
+
/** 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. */
|
|
34
|
+
dirs?: Record<string, string> | undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface PluginLookup extends IconLookup {
|
|
38
|
+
/** Each folder set's absolute folder, keyed by prefix. */
|
|
39
|
+
dirs: Map<string, string>
|
|
40
|
+
/** The folder set of `prefix`, with the files that are not icons. */
|
|
41
|
+
dirSet: (prefix: string) => Promise<SvgDirSet | undefined>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function svgDirs(root: string, dirs: Record<string, string> = {}): Map<string, string> {
|
|
45
|
+
const local = resolve(root, LOCAL_DIR)
|
|
46
|
+
const named = Object.entries(dirs).map(([prefix, dir]): [string, string] => [prefix, resolve(root, dir)])
|
|
47
|
+
return new Map(named.some(([, dir]) => dir === local) ? named : [['local', local], ...named])
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function lineAndColumn(code: string, offset: number): string {
|
|
51
|
+
const before = code.slice(0, offset).split('\n')
|
|
52
|
+
return `${before.length}:${before.at(-1)!.length + 1}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function icons(options: IconsPluginOptions = {}): KayPlugin {
|
|
56
|
+
// 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.
|
|
57
|
+
const cache = new Map<string, Promise<IconSet | undefined>>(Object.entries(options.sets ?? {}).map(([prefix, set]) => [prefix, Promise.resolve(set)]))
|
|
58
|
+
const installedSet = (root: string, prefix: string): Promise<IconSet | undefined> => {
|
|
59
|
+
let set = cache.get(prefix)
|
|
60
|
+
if (set === undefined) {
|
|
61
|
+
const file = setFile(prefix, root)
|
|
62
|
+
if (file === undefined)
|
|
63
|
+
return Promise.resolve(undefined)
|
|
64
|
+
set = Bun.file(file).json() as Promise<IconSet>
|
|
65
|
+
cache.set(prefix, set)
|
|
66
|
+
}
|
|
67
|
+
return set
|
|
68
|
+
}
|
|
69
|
+
// Folder sets are read again by each build, so `kay dev` sees an edited file.
|
|
70
|
+
const lookupIn = (root: string): PluginLookup => {
|
|
71
|
+
const dirs = svgDirs(root, options.dirs)
|
|
72
|
+
if (options.sets?.local !== undefined && options.dirs?.local === undefined)
|
|
73
|
+
dirs.delete('local')
|
|
74
|
+
const dirSets = new Map<string, Promise<SvgDirSet | undefined>>()
|
|
75
|
+
const dirSet = (prefix: string): Promise<SvgDirSet | undefined> => {
|
|
76
|
+
let read = dirSets.get(prefix)
|
|
77
|
+
if (read === undefined) {
|
|
78
|
+
const dir = dirs.get(prefix)
|
|
79
|
+
read = dir === undefined ? Promise.resolve(undefined) : readSvgDir(prefix, dir)
|
|
80
|
+
dirSets.set(prefix, read)
|
|
81
|
+
}
|
|
82
|
+
return read
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
dirs,
|
|
86
|
+
dirSet,
|
|
87
|
+
set: async prefix => dirs.has(prefix) ? (await dirSet(prefix))?.set : await installedSet(root, prefix),
|
|
88
|
+
prefixes: () => [...new Set([...Object.keys(options.sets ?? {}), ...[...dirs].filter(([, dir]) => existsSync(dir)).map(([prefix]) => prefix), ...installedPrefixes(root)])],
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 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.
|
|
93
|
+
async function fileProblem(lookup: PluginLookup, root: string, prefix: string, name: string): Promise<{ file: string, problem: string } | undefined> {
|
|
94
|
+
const problem = (await lookup.dirSet(prefix))?.problems.get(name)
|
|
95
|
+
return problem === undefined ? undefined : { file: relative(root, join(lookup.dirs.get(prefix)!, `${name}.svg`)), problem }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return definePlugin({
|
|
99
|
+
name: '@kayjs/icons',
|
|
100
|
+
async check(ctx) {
|
|
101
|
+
const lookup = lookupIn(ctx.root)
|
|
102
|
+
for (const [prefix, dir] of Object.entries(options.dirs ?? {})) {
|
|
103
|
+
if (!isSetPrefix(prefix))
|
|
104
|
+
ctx.error(`@kayjs/icons: "${prefix}" in icons({ dirs }) is not an icon set name: name it in lowercase words joined by dashes, such as brand.`)
|
|
105
|
+
else if (!existsSync(lookup.dirs.get(prefix)!))
|
|
106
|
+
ctx.error(`@kayjs/icons: icons({ dirs }) reads the set "${prefix}" from ${dir}, which does not exist.`)
|
|
107
|
+
}
|
|
108
|
+
for (const prefix of lookup.dirs.keys()) {
|
|
109
|
+
for (const [name, problem] of (await lookup.dirSet(prefix))?.problems ?? [])
|
|
110
|
+
ctx.error(`${relative(ctx.root, join(lookup.dirs.get(prefix)!, `${name}.svg`))}:1:1: error: @kayjs/icons: this file ${problem}.`)
|
|
111
|
+
}
|
|
112
|
+
for (const file of new Bun.Glob('src/**/*.{ts,tsx,mts}').scanSync({ cwd: ctx.root })) {
|
|
113
|
+
const code = await Bun.file(join(ctx.root, file)).text()
|
|
114
|
+
for (const found of code.matchAll(ICON_IMPORT_RE)) {
|
|
115
|
+
const [, prefix, name] = ICON_SPEC_RE.exec(found[2]!)!
|
|
116
|
+
// A broken file is reported once above, not at each import.
|
|
117
|
+
if (await fileProblem(lookup, ctx.root, prefix!, name!) !== undefined)
|
|
118
|
+
continue
|
|
119
|
+
const problem = await iconProblem(prefix!, name!, '', lookup)
|
|
120
|
+
if (problem !== undefined)
|
|
121
|
+
ctx.error(`${file}:${lineAndColumn(code, found.index + found[0].length - found[2]!.length - 2)}: error: @kayjs/icons: ${problem}`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
watchPaths: root => [...lookupIn(root).dirs.values()],
|
|
126
|
+
bunPlugins: ({ root, target }): BunPlugin[] => [{
|
|
127
|
+
name: 'kayjs-icons',
|
|
128
|
+
setup(b) {
|
|
129
|
+
const lookup = lookupIn(root)
|
|
130
|
+
if (target === 'client') {
|
|
131
|
+
b.onResolve({ filter: SEARCH_ENTRY_RE }, (args) => {
|
|
132
|
+
console.warn(`@kayjs/icons: ${relative(root, args.importer)} imports @kayjs/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.`)
|
|
133
|
+
return undefined
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
// The first file importing each icon, for an error to name it.
|
|
137
|
+
const importers = new Map<string, string>()
|
|
138
|
+
b.onResolve({ filter: ICON_SPEC_RE }, (args) => {
|
|
139
|
+
if (!importers.has(args.path))
|
|
140
|
+
importers.set(args.path, relative(root, args.importer))
|
|
141
|
+
return { path: args.path, namespace: 'kay-icon' }
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
b.onLoad({ filter: /.*/, namespace: 'kay-icon' }, async (args) => {
|
|
145
|
+
const [, prefix, name] = ICON_SPEC_RE.exec(args.path)!
|
|
146
|
+
const set = await lookup.set(prefix!)
|
|
147
|
+
const data = set === undefined ? undefined : iconData(set, name!)
|
|
148
|
+
if (data === undefined) {
|
|
149
|
+
const broken = await fileProblem(lookup, root, prefix!, name!)
|
|
150
|
+
if (broken !== undefined)
|
|
151
|
+
throw new Error(`@kayjs/icons: ${broken.file}, imported by ${importers.get(args.path)}, ${broken.problem}.`)
|
|
152
|
+
throw new Error(`@kayjs/icons: ${await iconProblem(prefix!, name!, `, imported by ${importers.get(args.path)}`, lookup)}`)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
contents: `export default ${JSON.stringify(target === 'client' ? { ...data, body: withEndTags(data.body) } : data)};\n`,
|
|
157
|
+
loader: 'js',
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
},
|
|
161
|
+
}],
|
|
162
|
+
commands: {
|
|
163
|
+
'icons-find': async (args, root) => await iconsFind(args, lookupIn(root)),
|
|
164
|
+
},
|
|
165
|
+
})
|
|
166
|
+
}
|