@splendidlabz/svelte 4.17.2 → 4.18.0

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/README.md CHANGED
@@ -39,6 +39,41 @@ In Astro, hydrate interactive components with `client:load`. Props that take a f
39
39
 
40
40
  Actions and utilities have their own entry points: `@splendidlabz/svelte/actions` and `@splendidlabz/svelte/utils`.
41
41
 
42
+ ## Icons
43
+
44
+ `splendidSvelte()` bundles the icons a site uses at build time. `Icon` then draws them in the server's HTML, with no request to Iconify from the browser. You don't install any icon sets.
45
+
46
+ ```js
47
+ // astro.config.js
48
+ import svelte from '@astrojs/svelte'
49
+ import { splendidSvelte } from '@splendidlabz/svelte/astro'
50
+ import { defineConfig } from 'astro/config'
51
+
52
+ export default defineConfig({
53
+ integrations: [svelte(), splendidSvelte()],
54
+ })
55
+ ```
56
+
57
+ The integration scans `src/` for icon names like `tabler:home`, fetches those icons from Iconify's API, and saves them in `src/icons.json`.
58
+
59
+ - `src/icons.json` appears the first time you run `astro dev` or `astro build`. Commit it. Builds then read from it and make no request.
60
+ - `astro dev` adds a new icon to the file as soon as you save the file that uses it. A build fetches any icon the file lacks.
61
+ - The default icons of Splendid's own components, like Accordion's `tabler:chevron-right`, are saved too.
62
+ - A name Iconify doesn't have is saved as `null`, so it isn't requested again.
63
+ - Icons whose names are built at runtime, like `` `simple-icons:${platform}` ``, are saved as they show up on a page in `astro dev`. The first time, they load from Iconify. They're listed under `captured` in `src/icons.json`.
64
+ - An icon leaves the file once your code no longer names it, except a `captured` icon, which stays until you delete it from the file.
65
+ - Because dev saves runtime icons, you rarely need `icons.names`. Use it for a runtime icon you want bundled before it shows up in dev:
66
+
67
+ ```js
68
+ splendidSvelte({ icons: { names: ['simple-icons:github'] } })
69
+ ```
70
+
71
+ - When Iconify can't be reached, the build still runs. It logs a warning, and the icons it couldn't fetch load in the browser.
72
+ - An icon that isn't bundled renders empty, then fills in at mount from Iconify's cache or its API.
73
+ - `icons: false` turns bundling off and writes no file.
74
+
75
+ Every island that renders an `Icon` loads the whole bundle, from one chunk the islands share. 84 icons come to about 35 kB raw, 10 kB gzipped.
76
+
42
77
  ## Docs
43
78
 
44
79
  https://splendidlabz.com/docs/svelte
@@ -0,0 +1,342 @@
1
+ /**
2
+ * @file Bundles the Iconify icons a site names.
3
+ */
4
+
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
6
+ import { readFile, writeFile } from 'node:fs/promises'
7
+ import { createRequire } from 'node:module'
8
+ import { dirname, join, sep } from 'node:path'
9
+ import { getIconData } from '@iconify/utils/lib/icon-set/get-icon'
10
+ import { defaultIconDimensions } from '@iconify/utils/lib/icon/defaults'
11
+ import zlFetch from 'zl-fetch'
12
+
13
+ /**
14
+ * @import { AstroIntegrationLogger } from 'astro'
15
+ * @import { IconifyJSON } from '@iconify/types'
16
+ * @import { Plugin } from './unbarrel.js'
17
+ */
18
+
19
+ /**
20
+ * bundleIcons
21
+ * Serves the icons a site uses as `@splendidlabz/svelte/bundled-icons`.
22
+ *
23
+ * @typedef {{ body: string, width: number, height: number }} BundledIcon
24
+ * @typedef {Record<string, BundledIcon | null>} CachedIcons Null when Iconify has no such icon.
25
+ * @typedef {{ captured: string[], icons: CachedIcons }} IconCache `captured` lists names Icon loaded at runtime in dev.
26
+ *
27
+ * @param {object} opts
28
+ * @param {string} opts.root The site's root folder.
29
+ * @param {string} opts.srcDir Folder scanned for icon names.
30
+ * @param {string[]} [opts.names] Names the source doesn't spell out.
31
+ * @param {Pick<AstroIntegrationLogger, 'warn'>} opts.logger
32
+ * @returns {Plugin}
33
+ */
34
+ export function bundleIcons(opts) {
35
+ const { root, srcDir, names = [], logger } = opts
36
+ const id = '@splendidlabz/svelte/bundled-icons'
37
+ const resolvedId = '\0splendid:bundled-icons'
38
+ const cacheFile = join(srcDir, 'icons.json')
39
+ const prefixes = getSetPrefixes()
40
+ const namesByFile = scanFolder({ folder: srcDir, prefixes })
41
+ const componentNames = getComponentNames({ root, prefixes })
42
+ const capturedNames = new Set()
43
+ /** @type {Promise<IconCache> | undefined} */
44
+ let cacheUpdate
45
+
46
+ // Leaves out the cache, whose keys would count as used names
47
+ namesByFile.delete(cacheFile)
48
+
49
+ return {
50
+ name: 'splendid:bundle-icons',
51
+ // Runs ahead of Vite's resolver, which would find the empty file
52
+ enforce: 'pre',
53
+ // Keeps the bundle out of dev prebundles, so the browser gets the server's icons
54
+ config() {
55
+ return { optimizeDeps: { exclude: [id] } }
56
+ },
57
+ resolveId(source) {
58
+ if (source === id) return resolvedId
59
+ },
60
+ async load(source) {
61
+ if (source !== resolvedId) return
62
+
63
+ // Serves the cached icons, leaving out names Iconify doesn't have
64
+ const cache = await getCache()
65
+ const icons = Object.fromEntries(
66
+ Object.entries(cache.icons).filter(([, icon]) => icon),
67
+ )
68
+ return `export const bundledIcons = ${JSON.stringify(icons)}`
69
+ },
70
+ configureServer(server) {
71
+ // Fills the cache as dev starts, before a page asks for it
72
+ getCache()
73
+
74
+ server.watcher.on('all', async (event, file) => {
75
+ // Skips the cache, files outside srcDir and files that can't name an icon
76
+ if (file === cacheFile) return
77
+ if (!file.startsWith(join(srcDir, sep)) || !isSourceFile(file)) return
78
+
79
+ // Rescans the file that changed
80
+ const previous = namesByFile.get(file) ?? []
81
+ if (event === 'unlink') namesByFile.delete(file)
82
+ if (event === 'add' || event === 'change') {
83
+ const code = readFileSync(file, 'utf8')
84
+ namesByFile.set(file, getIconNames({ code, prefixes }))
85
+ }
86
+
87
+ const current = namesByFile.get(file) ?? []
88
+ if (current.join() === previous.join()) return
89
+
90
+ // Fetches new names into the cache, after any update in flight
91
+ cacheUpdate = getCache().then(updateCache)
92
+ await cacheUpdate
93
+
94
+ // Rebuilds the bundle and reloads the page
95
+ for (const environment of Object.values(server.environments)) {
96
+ const module = environment.moduleGraph.getModuleById(resolvedId)
97
+ if (module) environment.moduleGraph.invalidateModule(module)
98
+ }
99
+ server.ws.send({ type: 'full-reload' })
100
+ })
101
+
102
+ // Caches an icon Icon loaded at runtime, for the next page load
103
+ server.ws.on('splendid:icon', async ({ name }) => {
104
+ const isIconName = getIconNames({ code: name, prefixes })[0] === name
105
+ if (!isIconName || capturedNames.has(name)) return
106
+ if (getScannedNames().has(name)) return
107
+
108
+ capturedNames.add(name)
109
+ cacheUpdate = getCache().then(updateCache)
110
+ await cacheUpdate
111
+
112
+ // Rebuilds the bundle on the next request
113
+ for (const environment of Object.values(server.environments)) {
114
+ const module = environment.moduleGraph.getModuleById(resolvedId)
115
+ if (module) environment.moduleGraph.invalidateModule(module)
116
+ }
117
+ })
118
+ },
119
+ }
120
+
121
+ /**
122
+ * getCache
123
+ * Returns the cache, updating it on the first call.
124
+ *
125
+ * @returns {Promise<IconCache>}
126
+ */
127
+ function getCache() {
128
+ if (!cacheUpdate) cacheUpdate = updateCache()
129
+ return cacheUpdate
130
+ }
131
+
132
+ /**
133
+ * getScannedNames
134
+ * Lists the names the source, `names` and Splendid's components use.
135
+ *
136
+ * @returns {Set<string>}
137
+ */
138
+ function getScannedNames() {
139
+ return new Set([
140
+ ...names,
141
+ ...[...namesByFile.values()].flat(),
142
+ ...componentNames,
143
+ ])
144
+ }
145
+
146
+ /**
147
+ * updateCache
148
+ * Fetches the used icons the cache lacks, and drops unused ones.
149
+ *
150
+ * @returns {Promise<IconCache>}
151
+ */
152
+ async function updateCache() {
153
+ /** @type {IconCache} */
154
+ const cache = existsSync(cacheFile)
155
+ ? JSON.parse(await readFile(cacheFile, 'utf8'))
156
+ : { captured: [], icons: {} }
157
+
158
+ // Keeps captured names until they're removed from the file by hand
159
+ const captured = [...new Set([...cache.captured, ...capturedNames])].sort()
160
+ const usedNames = new Set([...getScannedNames(), ...captured])
161
+
162
+ // Fetches the missing names, which stay missing when Iconify can't be reached
163
+ const missingNames = [...usedNames].filter(name => !(name in cache.icons))
164
+ const { icons, failedNames } = await fetchIcons(missingNames)
165
+ if (failedNames.length) {
166
+ logger.warn(
167
+ `Couldn't fetch ${failedNames.length} icons from Iconify. They load in the browser instead.`,
168
+ )
169
+ }
170
+
171
+ const unusedNames = Object.keys(cache.icons).filter(
172
+ name => !usedNames.has(name),
173
+ )
174
+ const isUnchanged =
175
+ !Object.keys(icons).length &&
176
+ !unusedNames.length &&
177
+ captured.length === cache.captured.length
178
+ if (isUnchanged) return cache
179
+
180
+ // Writes the used names, sorted so the file diffs cleanly
181
+ const nextCache = {
182
+ captured,
183
+ icons: Object.fromEntries(
184
+ Object.entries({ ...cache.icons, ...icons })
185
+ .filter(([name]) => usedNames.has(name))
186
+ .sort(([a], [b]) => a.localeCompare(b)),
187
+ ),
188
+ }
189
+ await writeFile(cacheFile, `${JSON.stringify(nextCache, null, 2)}\n`)
190
+ return nextCache
191
+ }
192
+ }
193
+
194
+ /**
195
+ * getIconNames
196
+ * Lists the `prefix:name` icons a file's text mentions.
197
+ *
198
+ * @param {object} opts
199
+ * @param {string} opts.code
200
+ * @param {Set<string>} opts.prefixes Iconify set prefixes.
201
+ * @returns {string[]}
202
+ */
203
+ export function getIconNames({ code, prefixes }) {
204
+ const matches = code.matchAll(
205
+ /(?<![\w:-])([a-z0-9]+(?:-[a-z0-9]+)*):[a-z0-9]+(?:-[a-z0-9]+)*(?![\w:-])/g,
206
+ )
207
+ const names = [...matches]
208
+ .filter(([, prefix]) => prefixes.has(prefix))
209
+ .map(([name]) => name)
210
+
211
+ return [...new Set(names)]
212
+ }
213
+
214
+ /**
215
+ * getSetPrefixes
216
+ * Lists the prefix of every Iconify icon set.
217
+ *
218
+ * @returns {Set<string>}
219
+ */
220
+ function getSetPrefixes() {
221
+ const require = createRequire(import.meta.url)
222
+ return new Set(Object.keys(require('@iconify/collections/collections.json')))
223
+ }
224
+
225
+ /**
226
+ * scanFolder
227
+ * Lists the icon names in each source file under a folder.
228
+ *
229
+ * @param {object} opts
230
+ * @param {string} opts.folder
231
+ * @param {Set<string>} opts.prefixes
232
+ * @returns {Map<string, string[]>} File to icon names.
233
+ */
234
+ function scanFolder({ folder, prefixes }) {
235
+ const files = readdirSync(folder, { recursive: true, encoding: 'utf8' })
236
+ .map(file => join(folder, file))
237
+ .filter(isSourceFile)
238
+
239
+ return new Map(
240
+ files.map(file => [
241
+ file,
242
+ getIconNames({ code: readFileSync(file, 'utf8'), prefixes }),
243
+ ]),
244
+ )
245
+ }
246
+
247
+ /**
248
+ * getComponentNames
249
+ * Lists the default icons Splendid's own components use.
250
+ *
251
+ * @param {object} opts
252
+ * @param {string} opts.root The site's root folder.
253
+ * @param {Set<string>} opts.prefixes
254
+ * @returns {string[]}
255
+ */
256
+ function getComponentNames({ root, prefixes }) {
257
+ // Finds the components folder of the package the site installed
258
+ const require = createRequire(join(root, 'package.json'))
259
+ const bundledIconsFile = require.resolve('@splendidlabz/svelte/bundled-icons')
260
+ const folder = join(dirname(bundledIconsFile), '..')
261
+
262
+ return [...scanFolder({ folder, prefixes })]
263
+ .filter(([file]) => !/\.(spec|test)\.js$|[\\/]fixtures[\\/]/.test(file))
264
+ .flatMap(([, names]) => names)
265
+ }
266
+
267
+ /**
268
+ * isSourceFile
269
+ * Tells whether a file is text that can name an icon.
270
+ *
271
+ * @param {string} file
272
+ * @returns {boolean}
273
+ */
274
+ function isSourceFile(file) {
275
+ return /\.(astro|svelte|[cm]?[jt]sx?|mdx?|json|ya?ml|html)$/.test(file)
276
+ }
277
+
278
+ /**
279
+ * fetchIcons
280
+ * Fetches icons from Iconify's API, one request per set.
281
+ *
282
+ * @param {string[]} names
283
+ * @returns {Promise<{ icons: CachedIcons, failedNames: string[] }>}
284
+ */
285
+ async function fetchIcons(names) {
286
+ const namesByPrefix = Map.groupBy(names, name => name.split(':')[0])
287
+ const responses = await Promise.all(
288
+ [...namesByPrefix].map(async ([prefix, prefixNames]) => ({
289
+ prefix,
290
+ prefixNames,
291
+ iconSet: await fetchIconSet({ prefix, names: prefixNames }),
292
+ })),
293
+ )
294
+
295
+ /** @type {CachedIcons} */
296
+ const icons = {}
297
+ const failedNames = []
298
+
299
+ for (const { prefix, prefixNames, iconSet } of responses) {
300
+ if (!iconSet) {
301
+ failedNames.push(...prefixNames)
302
+ continue
303
+ }
304
+
305
+ // Records a name the set doesn't have as null, so it isn't asked for again
306
+ for (const name of prefixNames) {
307
+ const icon = getIconData(iconSet, name.slice(prefix.length + 1))
308
+ icons[name] = icon && {
309
+ body: icon.body,
310
+ width: icon.width ?? defaultIconDimensions.width,
311
+ height: icon.height ?? defaultIconDimensions.height,
312
+ }
313
+ }
314
+ }
315
+
316
+ return { icons, failedNames }
317
+ }
318
+
319
+ /**
320
+ * fetchIconSet
321
+ * Fetches some icons of one set from Iconify's API.
322
+ *
323
+ * @param {object} opts
324
+ * @param {string} opts.prefix
325
+ * @param {string[]} opts.names Full `prefix:name` names.
326
+ * @returns {Promise<IconifyJSON | null>} Null when the request fails.
327
+ */
328
+ async function fetchIconSet({ prefix, names }) {
329
+ const icons = names.map(name => name.slice(prefix.length + 1)).join(',')
330
+
331
+ try {
332
+ const response = await zlFetch(
333
+ `https://api.iconify.design/${prefix}.json`,
334
+ {
335
+ query: { icons },
336
+ },
337
+ )
338
+ return /** @type {{ body: IconifyJSON }} */ (response).body
339
+ } catch {
340
+ return null
341
+ }
342
+ }
package/astro/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { fileURLToPath } from 'node:url'
6
+ import { bundleIcons } from './bundle-icons.js'
6
7
  import { unbarrel } from './unbarrel.js'
7
8
 
8
9
  /**
@@ -11,25 +12,32 @@ import { unbarrel } from './unbarrel.js'
11
12
 
12
13
  /**
13
14
  * splendidSvelte
14
- * Loads each `@splendidlabz/svelte` component from its own file.
15
+ * Loads each component from its own file, and bundles the site's icons.
15
16
  *
17
+ * @param {object} [opts]
18
+ * @param {false | { names?: string[] }} [opts.icons] Extra names, or false.
16
19
  * @returns {AstroIntegration}
17
20
  */
18
- export function splendidSvelte() {
21
+ export function splendidSvelte({ icons = {} } = {}) {
19
22
  return {
20
23
  name: '@splendidlabz/svelte',
21
24
  hooks: {
22
- 'astro:config:setup': ({ config, updateConfig }) => {
23
- updateConfig({
24
- vite: {
25
- plugins: [
26
- unbarrel({
27
- root: fileURLToPath(config.root),
28
- pkg: '@splendidlabz/svelte',
29
- }),
30
- ],
31
- },
32
- })
25
+ 'astro:config:setup': ({ config, updateConfig, logger }) => {
26
+ const root = fileURLToPath(config.root)
27
+ const plugins = [unbarrel({ root, pkg: '@splendidlabz/svelte' })]
28
+
29
+ if (icons) {
30
+ plugins.push(
31
+ bundleIcons({
32
+ root,
33
+ srcDir: fileURLToPath(config.srcDir),
34
+ names: icons.names,
35
+ logger,
36
+ }),
37
+ )
38
+ }
39
+
40
+ updateConfig({ vite: { plugins } })
33
41
  },
34
42
  },
35
43
  }
@@ -1,5 +1,6 @@
1
1
  <script>
2
2
  import { getIcon, loadIcon } from '@iconify/svelte'
3
+ import { bundledIcons } from '@splendidlabz/svelte/bundled-icons'
3
4
  import { toStyleString } from '@splendidlabz/utils'
4
5
  import { onMount } from 'svelte'
5
6
 
@@ -9,7 +10,8 @@
9
10
  if (typeof style === 'object') style = toStyleString(style)
10
11
  if (!icon) throw new Error('icon property is required')
11
12
 
12
- let iconData
13
+ // Draws a bundled icon on the first render, on the server and in the browser
14
+ let iconData = bundledIcons[icon]
13
15
  let innerHTML
14
16
  const attributes = {
15
17
  class: `${icon.split(':')[1]}`,
@@ -21,12 +23,16 @@
21
23
  ...$$restProps,
22
24
  }
23
25
 
24
- // If there is an icon set, we use Iconify.
25
- // This stores the icon in localStorage after loading it for the first time. Subsequent loads will use the localStorage cached version.
26
+ // Fills any other icon after hydration, from the cache or from Iconify
27
+ onMount(async _ => {
28
+ if (iconData) return
26
29
 
27
- // Reads the cache after hydration so the first render matches the server
28
- // If icon is not in cache, loads the icon from Iconify
29
- onMount(async _ => (iconData = getIcon(icon) || (await loadIcon(icon))))
30
+ // Asks the dev server to cache the icon for the next page load
31
+ // @ts-expect-error: Vite's client types aren't loaded in this package
32
+ if (import.meta.hot) import.meta.hot.send('splendid:icon', { name: icon })
33
+
34
+ iconData = getIcon(icon) || (await loadIcon(icon))
35
+ })
30
36
 
31
37
  $: if (iconData) {
32
38
  attributes.viewBox = `0 0 ${iconData.width} ${iconData.height}`
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @file Bundled icons, empty without `splendidSvelte()`.
3
+ */
4
+
5
+ /**
6
+ * @import { BundledIcon } from '../../astro/bundle-icons.js'
7
+ */
8
+
9
+ /** @type {Record<string, BundledIcon>} */
10
+ export const bundledIcons = {}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@splendidlabz/svelte",
3
3
  "type": "module",
4
- "version": "4.17.2",
4
+ "version": "4.18.0",
5
5
  "license": "Elastic-2.0",
6
6
  "sideEffects": false,
7
7
  "homepage": "https://splendidlabz.com/docs/svelte",
@@ -22,7 +22,8 @@
22
22
  },
23
23
  "./actions": "./actions/index.js",
24
24
  "./astro": "./astro/index.js",
25
- "./utils": "./utils/index.js"
25
+ "./utils": "./utils/index.js",
26
+ "./bundled-icons": "./components/Icon/bundled-icons.js"
26
27
  },
27
28
  "files": [
28
29
  "actions",
@@ -31,12 +32,16 @@
31
32
  "utils",
32
33
  "!**/*.spec.js",
33
34
  "!**/*.test.js",
35
+ "!astro/fixtures",
34
36
  "!components/DisclosureOld"
35
37
  ],
36
38
  "dependencies": {
37
39
  "@floating-ui/dom": "^1.7.6",
40
+ "@iconify/collections": "^1.0.766",
38
41
  "@iconify/svelte": "^5.2.1",
39
- "@splendidlabz/utils": "*"
42
+ "@iconify/utils": "^3.1.7",
43
+ "@splendidlabz/utils": "*",
44
+ "zl-fetch": "^6.3.1"
40
45
  },
41
46
  "devDependencies": {
42
47
  "@splendidlabz/eslint-config": "3.0.0",
@@ -44,6 +49,7 @@
44
49
  "happy-dom": "^20.9.0",
45
50
  "svelte": "^5.57.1",
46
51
  "svelte-check": "^4.4.6",
52
+ "vite": "^8.3.8",
47
53
  "vitest": "^4.1.4"
48
54
  }
49
55
  }