@perkyzz/emvb 0.2.1 → 0.4.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.
Files changed (150) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +3 -1
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/api.ts +17 -7
  6. package/src/admin/content-api.ts +7 -51
  7. package/src/admin/content-item.ts +22 -0
  8. package/src/admin/design-api.ts +30 -0
  9. package/src/admin/editor/A11yCopilot.tsx +126 -0
  10. package/src/admin/editor/CommandPalette.tsx +118 -0
  11. package/src/admin/editor/Editor.tsx +188 -152
  12. package/src/admin/editor/EditorOverlay.tsx +9 -1
  13. package/src/admin/editor/PerfMeter.tsx +121 -0
  14. package/src/admin/editor/ShareLink.tsx +164 -0
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +287 -0
  17. package/src/admin/editor/TopBar.tsx +4 -0
  18. package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
  19. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  20. package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
  21. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  22. package/src/admin/editor/canvas/drop-line.ts +24 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  24. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  25. package/src/admin/editor/collection-previews.ts +114 -0
  26. package/src/admin/editor/editor-chrome.tsx +346 -0
  27. package/src/admin/editor/editor-commands.ts +360 -0
  28. package/src/admin/editor/editor-css.ts +5 -3
  29. package/src/admin/editor/element-chrome.ts +89 -0
  30. package/src/admin/editor/feature-css.ts +105 -0
  31. package/src/admin/editor/host.ts +35 -0
  32. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  33. package/src/admin/editor/icons/library.ts +29 -19
  34. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  35. package/src/admin/editor/live-data.tsx +71 -0
  36. package/src/admin/editor/palette-items.ts +136 -0
  37. package/src/admin/editor/palette.ts +68 -0
  38. package/src/admin/editor/panels/AddPanel.tsx +48 -68
  39. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  40. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  41. package/src/admin/editor/panels/ElementPanel.tsx +74 -102
  42. package/src/admin/editor/panels/LayersPanel.tsx +72 -63
  43. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  44. package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
  45. package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
  46. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  47. package/src/admin/editor/panels/VariableSection.tsx +10 -14
  48. package/src/admin/editor/panels/inline-error.tsx +11 -0
  49. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  50. package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -0
  51. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  52. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  53. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  54. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  55. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  56. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  57. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  58. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  59. package/src/admin/editor/panels/settings/StyleRow.tsx +26 -2
  60. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  61. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  62. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  63. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  64. package/src/admin/editor/panels/settings/length-units.ts +16 -5
  65. package/src/admin/editor/panels/settings/style-sections.ts +7 -2
  66. package/src/admin/editor/panels/style-target.ts +105 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +6 -1
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +30 -14
  74. package/src/admin/editor/useNodeActions.ts +44 -16
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/theme-api.ts +5 -18
  78. package/src/admin/ui.ts +4 -4
  79. package/src/astro/content-port.ts +24 -0
  80. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  81. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  82. package/src/astro/forms/client.ts +1 -0
  83. package/src/astro/forms-definitions.ts +24 -11
  84. package/src/astro/index.ts +1 -0
  85. package/src/astro/render-session.ts +85 -0
  86. package/src/astro/request-data.ts +109 -0
  87. package/src/astro/resolve-theme.ts +184 -64
  88. package/src/astro/resolve.ts +63 -16
  89. package/src/astro/theme-posts.ts +48 -5
  90. package/src/astro/visitor.ts +204 -0
  91. package/src/constants.ts +1 -1
  92. package/src/core/a11y/audit.ts +282 -0
  93. package/src/core/arrange.ts +150 -34
  94. package/src/core/audience/rules.ts +124 -0
  95. package/src/core/audience/variants.ts +51 -0
  96. package/src/core/canvas-styles.ts +24 -0
  97. package/src/core/clipboard.ts +11 -32
  98. package/src/core/css/generate.ts +29 -2
  99. package/src/core/css/print.ts +12 -0
  100. package/src/core/css/scope.ts +3 -3
  101. package/src/core/css/trace.ts +169 -0
  102. package/src/core/css-keywords.ts +83 -0
  103. package/src/core/data/bindings.ts +255 -0
  104. package/src/core/design/classes.ts +13 -15
  105. package/src/core/design/diff.ts +55 -0
  106. package/src/core/design/merge.ts +127 -0
  107. package/src/core/design/tokens.ts +127 -0
  108. package/src/core/design/variables.ts +25 -21
  109. package/src/core/elements/dynamic-elements.ts +117 -2
  110. package/src/core/elements/form-elements.ts +1 -0
  111. package/src/core/elements/index.ts +185 -7
  112. package/src/core/forms/binding.ts +4 -13
  113. package/src/core/history/diff.ts +152 -0
  114. package/src/core/index.ts +121 -0
  115. package/src/core/local-style.ts +27 -0
  116. package/src/core/migrate/index.ts +12 -4
  117. package/src/core/nesting.ts +4 -22
  118. package/src/core/perf/meter.ts +160 -0
  119. package/src/core/perf/scripts.ts +61 -0
  120. package/src/core/recipes/index.ts +433 -0
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +1 -2
  124. package/src/core/render/form.ts +133 -10
  125. package/src/core/render/index.ts +206 -17
  126. package/src/core/render/loop.ts +54 -7
  127. package/src/core/render/pagination.ts +9 -1
  128. package/src/core/render/vnode.ts +12 -2
  129. package/src/core/sanitize/css.ts +129 -80
  130. package/src/core/sanitize/motion.ts +129 -0
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/design.ts +29 -8
  134. package/src/core/schema/layout.ts +291 -169
  135. package/src/core/schema/motion.ts +14 -0
  136. package/src/core/schema/style.ts +101 -66
  137. package/src/core/share/link.ts +187 -0
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +242 -32
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/theme/pagination.ts +56 -0
  142. package/src/core/tree-ops.ts +57 -0
  143. package/src/index.ts +14 -2
  144. package/src/server/design-routes.ts +4 -1
  145. package/src/server/icon-routes.ts +68 -16
  146. package/src/server/plugin.ts +8 -2
  147. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  148. package/src/admin/editor/icons/sets/lucide.json +0 -1
  149. package/src/admin/editor/icons/sets/remix.json +0 -1
  150. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -1,24 +1,16 @@
1
1
  import { Button, Dialog } from "@cloudflare/kumo";
2
- import { MagnifyingGlassIcon, UploadSimpleIcon, XIcon } from "@phosphor-icons/react";
2
+ import {
3
+ MagnifyingGlassIcon,
4
+ PencilSimpleIcon,
5
+ TrashIcon,
6
+ UploadSimpleIcon,
7
+ XIcon,
8
+ } from "@phosphor-icons/react";
3
9
  import * as React from "react";
4
10
  import type { Fetcher } from "../../api.ts";
5
- import { listUploadedIcons, uploadIconFile } from "../../icon-uploads-api.ts";
6
11
  import { BUTTON, SOLID_PRIMARY, UI_CSS } from "../../ui.ts";
7
- import {
8
- ALL_ICONS,
9
- filterIcons,
10
- ICON_CATEGORIES,
11
- ICON_SETS,
12
- loadIconSet,
13
- locateIcon,
14
- setsFor,
15
- uploadedIcons,
16
- UPLOADS,
17
- UPLOADS_CATEGORY,
18
- type IconCategory,
19
- type IconSetId,
20
- type LibraryIcon,
21
- } from "./library.ts";
12
+ import { ALL_ICONS, ICON_SETS, UPLOADS, type LibraryIcon } from "./library.ts";
13
+ import { fmt, useIconLibrary } from "./use-icon-library.ts";
22
14
 
23
15
  /** Grid geometry, in px. Tiles stretch to fill the row; this is their narrowest. */
24
16
  const TILE_MIN_WIDTH = 96;
@@ -254,16 +246,6 @@ function IconGrid({
254
246
  );
255
247
  }
256
248
 
257
- function initialCategory(currentId: string | undefined, uploads: boolean): string {
258
- const at = currentId ? locateIcon(currentId) : undefined;
259
- if (!at) return ALL_ICONS;
260
- if (at.set === UPLOADS) return uploads ? UPLOADS : ALL_ICONS;
261
- const style = ICON_CATEGORIES.find((category) => category.id === `${at.set}/${at.style}`);
262
- return style?.id ?? at.set;
263
- }
264
-
265
- const fmt = (count: number) => count.toLocaleString("en-US");
266
-
267
249
  function IconLibrary({
268
250
  currentId,
269
251
  fetcher,
@@ -274,197 +256,37 @@ function IconLibrary({
274
256
  fetcher?: Fetcher;
275
257
  onInsert: (icon: LibraryIcon) => void;
276
258
  }) {
277
- const [categoryId, setCategoryId] = React.useState(() =>
278
- initialCategory(currentId, fetcher !== undefined),
279
- );
280
- const categories = React.useMemo(
281
- () => (fetcher ? [...ICON_CATEGORIES, UPLOADS_CATEGORY] : ICON_CATEGORIES),
282
- [fetcher],
283
- );
284
- const [uploads, setUploads] = React.useState<LibraryIcon[]>();
285
- const [uploadsFailed, setUploadsFailed] = React.useState<string>();
286
- const [uploading, setUploading] = React.useState(false);
287
- const [uploadNote, setUploadNote] = React.useState<{ error: boolean; text: string }>();
288
- const fileRef = React.useRef<HTMLInputElement | null>(null);
289
- const [query, setQuery] = React.useState("");
290
- const [selectedId, setSelectedId] = React.useState(
291
- () => (currentId ? locateIcon(currentId)?.id : undefined) ?? currentId,
292
- );
293
- const [sets, setSets] = React.useState<Partial<Record<IconSetId, LibraryIcon[]>>>({});
294
- const [failed, setFailed] = React.useState<string>();
295
- const [attempt, setAttempt] = React.useState(0);
296
- const gridRef = React.useRef<HTMLDivElement | null>(null);
297
- const searchId = React.useId();
298
-
299
- const category: IconCategory =
300
- categories.find((item) => item.id === categoryId) ?? (ICON_CATEGORIES[0] as IconCategory);
301
- const inUploads = category.id === UPLOADS;
302
- const needed = inUploads ? [] : setsFor(category);
303
- const neededKey = needed.join(",");
304
-
305
- // My uploads loads when first needed: its category, All icons (which lists them first, W-295),
306
- // or a stored upload to show as picked.
307
- const inAll = category.id === ALL_ICONS;
308
- const wantUploads =
309
- fetcher !== undefined && (inUploads || inAll || locateIcon(currentId ?? "")?.set === UPLOADS);
310
- React.useEffect(() => {
311
- if (!wantUploads || !fetcher || uploads) return undefined;
312
- let live = true;
313
- setUploadsFailed(undefined);
314
- listUploadedIcons(fetcher).then(
315
- (items) => {
316
- if (live) setUploads(uploadedIcons(items));
317
- },
318
- (caught: unknown) => {
319
- if (live)
320
- setUploadsFailed(caught instanceof Error ? caught.message : "Couldn't load uploads.");
321
- },
322
- );
323
- return () => {
324
- live = false;
325
- };
326
- }, [wantUploads, fetcher, uploads, attempt]);
327
-
328
- React.useEffect(() => {
329
- let live = true;
330
- setFailed(undefined);
331
- for (const id of (neededKey ? neededKey.split(",") : []) as IconSetId[]) {
332
- loadIconSet(id).then(
333
- (icons) => {
334
- if (live) setSets((prev) => (prev[id] ? prev : { ...prev, [id]: icons }));
335
- },
336
- () => {
337
- if (live) setFailed(ICON_SETS.find((set) => set.id === id)?.label ?? id);
338
- },
339
- );
340
- }
341
- return () => {
342
- live = false;
343
- };
344
- }, [neededKey, attempt]);
345
-
346
- // All icons waits for the uploads list too, unless it failed (the sets still show, W-295).
347
- const uploadsSettled = !fetcher || uploads !== undefined || uploadsFailed !== undefined;
348
- const ready = inUploads
349
- ? uploads !== undefined
350
- : needed.every((id) => sets[id]) && (!inAll || uploadsSettled);
351
- const filtered = React.useMemo(
352
- () =>
353
- ready
354
- ? filterIcons(
355
- inUploads
356
- ? (uploads ?? [])
357
- : [...(inAll ? (uploads ?? []) : []), ...needed.flatMap((id) => sets[id] ?? [])],
358
- category,
359
- query,
360
- )
361
- : [],
362
- // `needed` follows `category`; `ready` follows `sets` and `uploads`.
363
- [ready, sets, uploads, category, query, inAll],
364
- );
365
-
366
- // Matches per sidebar entry, for the sets loaded so far (a search shows where its hits are).
367
- const counts = React.useMemo(() => {
368
- const loaded = Object.values(sets).flat();
369
- const tally = new Map<string, number>();
370
- for (const icon of filterIcons(loaded, ICON_CATEGORIES[0] as IconCategory, query)) {
371
- tally.set(icon.set, (tally.get(icon.set) ?? 0) + 1);
372
- tally.set(`${icon.set}/${icon.style}`, (tally.get(`${icon.set}/${icon.style}`) ?? 0) + 1);
373
- }
374
- if (uploads) tally.set(UPLOADS, filterIcons(uploads, UPLOADS_CATEGORY, query).length);
375
- const allLoaded = ICON_SETS.every((set) => sets[set.id]);
376
- if (allLoaded)
377
- tally.set(
378
- ALL_ICONS,
379
- [...ICON_SETS].reduce((n, s) => n + (tally.get(s.id) ?? 0), 0) + (tally.get(UPLOADS) ?? 0),
380
- );
381
- return tally;
382
- }, [sets, uploads, query]);
383
-
384
- // The keyboard cursor belongs to one list. A new list (search, category) starts from the picked
385
- // icon if it is in it, else nowhere, in the same render: an index left over from the last list
386
- // would scroll this one to a tile it doesn't have.
387
- const [cursor, setCursor] = React.useState<{ list: readonly LibraryIcon[]; index: number }>({
388
- list: [],
389
- index: -1,
390
- });
391
- const active =
392
- cursor.list === filtered ? cursor.index : filtered.findIndex((icon) => icon.id === selectedId);
393
- const setActive = (index: number) => setCursor({ list: filtered, index });
394
-
395
- const selected = React.useMemo(() => {
396
- if (!selectedId) return undefined;
397
- for (const icons of [...Object.values(sets), uploads]) {
398
- const found = icons?.find((icon) => icon.id === selectedId);
399
- if (found) return found;
400
- }
401
- return undefined;
402
- }, [sets, uploads, selectedId]);
403
-
404
- const onUpload = async (file: File | undefined) => {
405
- if (!file || !fetcher) return;
406
- setUploading(true);
407
- setUploadNote(undefined);
408
- try {
409
- const result = await uploadIconFile(fetcher, file, (svg) => {
410
- const [probe] = uploadedIcons([{ id: "new", name: "", svg, uploadedAt: "" }]);
411
- return uploads?.find((other) => other.markup === probe?.markup)?.id;
412
- });
413
- setQuery("");
414
- setCursor({ list: [], index: -1 });
415
- if ("existingId" in result) {
416
- const known = uploads?.find((other) => other.id === result.existingId);
417
- setSelectedId(result.existingId);
418
- setUploadNote({
419
- error: false,
420
- text: `You already uploaded this SVG as ${known?.label ?? "an icon"}, so it's selected. Insert adds it to the page.`,
421
- });
422
- return;
423
- }
424
- const { item, imagesLeftOut } = result;
425
- const [icon] = uploadedIcons([item]);
426
- if (!icon) throw new Error("The uploaded SVG couldn't be shown. Try another file.");
427
- setUploads((prev) => [icon, ...(prev ?? []).filter((other) => other.id !== icon.id)]);
428
- setSelectedId(icon.id);
429
- setUploadNote({
430
- error: false,
431
- text: `Uploaded ${icon.label}. Insert adds it to the page.${
432
- imagesLeftOut > 0
433
- ? ` ${imagesLeftOut} outside image${imagesLeftOut === 1 ? " was" : "s were"} left out.`
434
- : ""
435
- }`,
436
- });
437
- } catch (caught) {
438
- setUploadNote({
439
- error: true,
440
- text: caught instanceof Error ? caught.message : "The upload failed. Try again.",
441
- });
442
- } finally {
443
- setUploading(false);
444
- if (fileRef.current) fileRef.current.value = "";
445
- }
446
- };
447
-
448
- const activate = (index: number) => {
449
- setActive(index);
450
- const icon = filtered[index];
451
- if (icon) setSelectedId(icon.id);
452
- };
453
-
454
- const status = failed
455
- ? `${failed} didn't load.`
456
- : inUploads && uploadsFailed
457
- ? "Uploads didn't load."
458
- : !ready
459
- ? "Loading icons…"
460
- : filtered.length === 0
461
- ? query.trim()
462
- ? `No icons match "${query.trim()}" in ${category.label}.`
463
- : inUploads
464
- ? "No uploads yet."
465
- : "No icons here."
466
- : `${fmt(filtered.length)} icon${filtered.length === 1 ? "" : "s"}`;
467
-
259
+ const {
260
+ categories,
261
+ categoryId,
262
+ setCategoryId,
263
+ query,
264
+ setQuery,
265
+ searchId,
266
+ category,
267
+ filtered,
268
+ active,
269
+ setActive,
270
+ gridRef,
271
+ inUploads,
272
+ uploading,
273
+ fileRef,
274
+ onUpload,
275
+ uploadNote,
276
+ uploadsFailed,
277
+ setUploadsFailed,
278
+ setAttempt,
279
+ failed,
280
+ ready,
281
+ status,
282
+ counts,
283
+ selectedId,
284
+ activate,
285
+ selected,
286
+ uploadId,
287
+ renameUpload,
288
+ deleteUpload,
289
+ } = useIconLibrary({ currentId, fetcher });
468
290
  return (
469
291
  <div className="emvb-icon-library" data-emvb-dialog="icon-library">
470
292
  <header className="emvb-icon-library-head">
@@ -656,6 +478,30 @@ function IconLibrary({
656
478
  )}
657
479
  </div>
658
480
  <div className="emvb-icon-library-actions">
481
+ {uploadId && fetcher && (
482
+ <>
483
+ <Button
484
+ type="button"
485
+ variant="secondary"
486
+ className={BUTTON}
487
+ icon={<PencilSimpleIcon aria-hidden="true" />}
488
+ data-emvb-icon-rename=""
489
+ onClick={renameUpload}
490
+ >
491
+ Rename
492
+ </Button>
493
+ <Button
494
+ type="button"
495
+ variant="secondary"
496
+ className={BUTTON}
497
+ icon={<TrashIcon aria-hidden="true" />}
498
+ data-emvb-icon-delete=""
499
+ onClick={deleteUpload}
500
+ >
501
+ Delete
502
+ </Button>
503
+ </>
504
+ )}
659
505
  <Dialog.Close
660
506
  render={(props) => (
661
507
  <Button {...props} variant="secondary" className={BUTTON}>
@@ -105,10 +105,10 @@ export type LibraryIcon = {
105
105
  };
106
106
 
107
107
  const LOADERS: Record<IconSetId, () => Promise<{ default: unknown }>> = {
108
- lucide: () => import("./sets/lucide.json"),
109
- fontawesome: () => import("./sets/fontawesome.json"),
110
- tabler: () => import("./sets/tabler.json"),
111
- remix: () => import("./sets/remix.json"),
108
+ lucide: () => import("@perkyzz/emvb-icons/lucide.json"),
109
+ fontawesome: () => import("@perkyzz/emvb-icons/fontawesome.json"),
110
+ tabler: () => import("@perkyzz/emvb-icons/tabler.json"),
111
+ remix: () => import("@perkyzz/emvb-icons/remix.json"),
112
112
  };
113
113
 
114
114
  const attrText = (attrs: Record<string, string>) =>
@@ -116,27 +116,37 @@ const attrText = (attrs: Record<string, string>) =>
116
116
  .map(([name, value]) => ` ${name}="${value}"`)
117
117
  .join("");
118
118
 
119
- /** The icons of one set file, ready for the grid. */
120
- function iconsOf(file: IconSetFile): LibraryIcon[] {
119
+ /**
120
+ * The icons of one set file, ready for the grid. Tiles go through the same SVG allowlist as
121
+ * uploads: a viewBox or body that breaks out of the markup is left out, not shown.
122
+ */
123
+ export function iconsOf(file: IconSetFile): LibraryIcon[] {
121
124
  const styles = file.styles.map((style) => ({ style, root: attrText(style.attrs) }));
122
- return file.icons.map((entry: IconEntry) => {
125
+ return file.icons.flatMap((entry: IconEntry) => {
123
126
  const [name, styleIndex, label, body, tags] = entry;
124
127
  const picked = styles[styleIndex] ?? styles[0];
125
128
  if (!picked) throw new Error(`EmVB: icon set ${file.id} has no styles`);
126
129
  const { style, root } = picked;
127
130
  const viewBox = entry[5] ?? style.viewBox;
128
- return {
129
- id: `${style.prefix}:${name}`,
130
- set: file.id as IconSetId,
131
- setLabel: file.label,
132
- style: style.id,
133
- styleLabel: style.label,
134
- name,
135
- label,
136
- haystack: fold(`${label} ${name.replaceAll("-", " ")} ${tags} ${file.label} ${style.label}`),
137
- named: fold(`${label} | ${name.replaceAll("-", " ")}`),
138
- markup: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}"${root}>${body}</svg>`,
139
- };
131
+ const raw = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}"${root}>${body}</svg>`;
132
+ const safe = sanitizeSvgMarkup(raw);
133
+ if (!safe) return [];
134
+ return [
135
+ {
136
+ id: `${style.prefix}:${name}`,
137
+ set: file.id as IconSetId,
138
+ setLabel: file.label,
139
+ style: style.id,
140
+ styleLabel: style.label,
141
+ name,
142
+ label,
143
+ haystack: fold(
144
+ `${label} ${name.replaceAll("-", " ")} ${tags} ${file.label} ${style.label}`,
145
+ ),
146
+ named: fold(`${label} | ${name.replaceAll("-", " ")}`),
147
+ markup: serialize(safe),
148
+ },
149
+ ];
140
150
  });
141
151
  }
142
152
 
@@ -0,0 +1,315 @@
1
+ import * as React from "react";
2
+ import type { Fetcher } from "../../api.ts";
3
+ import {
4
+ deleteUploadedIcon,
5
+ listUploadedIcons,
6
+ renameUploadedIcon,
7
+ uploadIconFile,
8
+ } from "../../icon-uploads-api.ts";
9
+ import {
10
+ ALL_ICONS,
11
+ filterIcons,
12
+ ICON_CATEGORIES,
13
+ ICON_SETS,
14
+ loadIconSet,
15
+ locateIcon,
16
+ setsFor,
17
+ uploadedIcons,
18
+ UPLOADS,
19
+ UPLOADS_CATEGORY,
20
+ type IconCategory,
21
+ type IconSetId,
22
+ type LibraryIcon,
23
+ } from "./library.ts";
24
+
25
+ export const fmt = (count: number) => count.toLocaleString("en-US");
26
+
27
+ function initialCategory(currentId: string | undefined, uploads: boolean): string {
28
+ const at = currentId ? locateIcon(currentId) : undefined;
29
+ if (!at) return ALL_ICONS;
30
+ if (at.set === UPLOADS) return uploads ? UPLOADS : ALL_ICONS;
31
+ const style = ICON_CATEGORIES.find((category) => category.id === `${at.set}/${at.style}`);
32
+ return style?.id ?? at.set;
33
+ }
34
+
35
+ /** Category, search, uploads and the keyboard cursor for the icon library. */
36
+ export function useIconLibrary({
37
+ currentId,
38
+ fetcher,
39
+ }: {
40
+ currentId: string | undefined;
41
+ fetcher?: Fetcher;
42
+ }) {
43
+ const [categoryId, setCategoryId] = React.useState(() =>
44
+ initialCategory(currentId, fetcher !== undefined),
45
+ );
46
+ const categories = React.useMemo(
47
+ () => (fetcher ? [...ICON_CATEGORIES, UPLOADS_CATEGORY] : ICON_CATEGORIES),
48
+ [fetcher],
49
+ );
50
+ const [uploads, setUploads] = React.useState<LibraryIcon[]>();
51
+ const [uploadsFailed, setUploadsFailed] = React.useState<string>();
52
+ const [uploading, setUploading] = React.useState(false);
53
+ const [uploadNote, setUploadNote] = React.useState<{ error: boolean; text: string }>();
54
+ const fileRef = React.useRef<HTMLInputElement | null>(null);
55
+ const [query, setQuery] = React.useState("");
56
+ const [selectedId, setSelectedId] = React.useState(
57
+ () => (currentId ? locateIcon(currentId)?.id : undefined) ?? currentId,
58
+ );
59
+ const [sets, setSets] = React.useState<Partial<Record<IconSetId, LibraryIcon[]>>>({});
60
+ const [failed, setFailed] = React.useState<string>();
61
+ const [attempt, setAttempt] = React.useState(0);
62
+ const gridRef = React.useRef<HTMLDivElement | null>(null);
63
+ const searchId = React.useId();
64
+
65
+ const category: IconCategory =
66
+ categories.find((item) => item.id === categoryId) ?? (ICON_CATEGORIES[0] as IconCategory);
67
+ const inUploads = category.id === UPLOADS;
68
+ const needed = inUploads ? [] : setsFor(category);
69
+ const neededKey = needed.join(",");
70
+
71
+ // My uploads loads when first needed: its category, All icons (which lists them first, W-295),
72
+ // or a stored upload to show as picked.
73
+ const inAll = category.id === ALL_ICONS;
74
+ const wantUploads =
75
+ fetcher !== undefined && (inUploads || inAll || locateIcon(currentId ?? "")?.set === UPLOADS);
76
+ React.useEffect(() => {
77
+ if (!wantUploads || !fetcher || uploads) return undefined;
78
+ let live = true;
79
+ setUploadsFailed(undefined);
80
+ listUploadedIcons(fetcher).then(
81
+ (items) => {
82
+ if (live) setUploads(uploadedIcons(items));
83
+ },
84
+ (caught: unknown) => {
85
+ if (live)
86
+ setUploadsFailed(caught instanceof Error ? caught.message : "Couldn't load uploads.");
87
+ },
88
+ );
89
+ return () => {
90
+ live = false;
91
+ };
92
+ }, [wantUploads, fetcher, uploads, attempt]);
93
+
94
+ React.useEffect(() => {
95
+ let live = true;
96
+ setFailed(undefined);
97
+ for (const id of (neededKey ? neededKey.split(",") : []) as IconSetId[]) {
98
+ loadIconSet(id).then(
99
+ (icons) => {
100
+ if (live) setSets((prev) => (prev[id] ? prev : { ...prev, [id]: icons }));
101
+ },
102
+ () => {
103
+ if (live) setFailed(ICON_SETS.find((set) => set.id === id)?.label ?? id);
104
+ },
105
+ );
106
+ }
107
+ return () => {
108
+ live = false;
109
+ };
110
+ }, [neededKey, attempt]);
111
+
112
+ // All icons waits for the uploads list too, unless it failed (the sets still show, W-295).
113
+ const uploadsSettled = !fetcher || uploads !== undefined || uploadsFailed !== undefined;
114
+ const ready = inUploads
115
+ ? uploads !== undefined
116
+ : needed.every((id) => sets[id]) && (!inAll || uploadsSettled);
117
+ const filtered = React.useMemo(
118
+ () =>
119
+ ready
120
+ ? filterIcons(
121
+ inUploads
122
+ ? (uploads ?? [])
123
+ : [...(inAll ? (uploads ?? []) : []), ...needed.flatMap((id) => sets[id] ?? [])],
124
+ category,
125
+ query,
126
+ )
127
+ : [],
128
+ // `needed` follows `category`; `ready` follows `sets` and `uploads`.
129
+ [ready, sets, uploads, category, query, inAll],
130
+ );
131
+
132
+ // Matches per sidebar entry, for the sets loaded so far (a search shows where its hits are).
133
+ const counts = React.useMemo(() => {
134
+ const loaded = Object.values(sets).flat();
135
+ const tally = new Map<string, number>();
136
+ for (const icon of filterIcons(loaded, ICON_CATEGORIES[0] as IconCategory, query)) {
137
+ tally.set(icon.set, (tally.get(icon.set) ?? 0) + 1);
138
+ tally.set(`${icon.set}/${icon.style}`, (tally.get(`${icon.set}/${icon.style}`) ?? 0) + 1);
139
+ }
140
+ if (uploads) tally.set(UPLOADS, filterIcons(uploads, UPLOADS_CATEGORY, query).length);
141
+ const allLoaded = ICON_SETS.every((set) => sets[set.id]);
142
+ if (allLoaded)
143
+ tally.set(
144
+ ALL_ICONS,
145
+ [...ICON_SETS].reduce((n, s) => n + (tally.get(s.id) ?? 0), 0) + (tally.get(UPLOADS) ?? 0),
146
+ );
147
+ return tally;
148
+ }, [sets, uploads, query]);
149
+
150
+ // The keyboard cursor belongs to one list. A new list (search, category) starts from the picked
151
+ // icon if it is in it, else nowhere, in the same render: an index left over from the last list
152
+ // would scroll this one to a tile it doesn't have.
153
+ const [cursor, setCursor] = React.useState<{ list: readonly LibraryIcon[]; index: number }>({
154
+ list: [],
155
+ index: -1,
156
+ });
157
+ const active =
158
+ cursor.list === filtered ? cursor.index : filtered.findIndex((icon) => icon.id === selectedId);
159
+ const setActive = (index: number) => setCursor({ list: filtered, index });
160
+
161
+ const selected = React.useMemo(() => {
162
+ if (!selectedId) return undefined;
163
+ for (const icons of [...Object.values(sets), uploads]) {
164
+ const found = icons?.find((icon) => icon.id === selectedId);
165
+ if (found) return found;
166
+ }
167
+ return undefined;
168
+ }, [sets, uploads, selectedId]);
169
+
170
+ const onUpload = async (file: File | undefined) => {
171
+ if (!file || !fetcher) return;
172
+ setUploading(true);
173
+ setUploadNote(undefined);
174
+ try {
175
+ const result = await uploadIconFile(fetcher, file, (svg) => {
176
+ const [probe] = uploadedIcons([{ id: "new", name: "", svg, uploadedAt: "" }]);
177
+ return uploads?.find((other) => other.markup === probe?.markup)?.id;
178
+ });
179
+ setQuery("");
180
+ setCursor({ list: [], index: -1 });
181
+ if ("existingId" in result) {
182
+ const known = uploads?.find((other) => other.id === result.existingId);
183
+ setSelectedId(result.existingId);
184
+ setUploadNote({
185
+ error: false,
186
+ text: `You already uploaded this SVG as ${known?.label ?? "an icon"}, so it's selected. Insert adds it to the page.`,
187
+ });
188
+ return;
189
+ }
190
+ const { item, imagesLeftOut } = result;
191
+ const [icon] = uploadedIcons([item]);
192
+ if (!icon) throw new Error("The uploaded SVG couldn't be shown. Try another file.");
193
+ setUploads((prev) => [icon, ...(prev ?? []).filter((other) => other.id !== icon.id)]);
194
+ setSelectedId(icon.id);
195
+ setUploadNote({
196
+ error: false,
197
+ text: `Uploaded ${icon.label}. Insert adds it to the page.${
198
+ imagesLeftOut > 0
199
+ ? ` ${imagesLeftOut} outside image${imagesLeftOut === 1 ? " was" : "s were"} left out.`
200
+ : ""
201
+ }`,
202
+ });
203
+ } catch (caught) {
204
+ setUploadNote({
205
+ error: true,
206
+ text: caught instanceof Error ? caught.message : "The upload failed. Try again.",
207
+ });
208
+ } finally {
209
+ setUploading(false);
210
+ if (fileRef.current) fileRef.current.value = "";
211
+ }
212
+ };
213
+
214
+ const activate = (index: number) => {
215
+ setActive(index);
216
+ const icon = filtered[index];
217
+ if (icon) setSelectedId(icon.id);
218
+ };
219
+
220
+ const uploadId = selected?.id.startsWith("upload:")
221
+ ? selected.id.slice("upload:".length)
222
+ : undefined;
223
+ const renameUpload = () => {
224
+ if (!fetcher || !uploadId || !selected) return;
225
+ const name = window.prompt("Rename this upload", selected.label);
226
+ if (!name || !name.trim() || name.trim() === selected.label) return;
227
+ void renameUploadedIcon(fetcher, uploadId, name.trim())
228
+ .then((item) => {
229
+ const [icon] = uploadedIcons([item]);
230
+ if (!icon) return;
231
+ setUploads((current) => current?.map((entry) => (entry.id === icon.id ? icon : entry)));
232
+ setUploadNote({
233
+ error: false,
234
+ text: `Renamed to ${icon.label}. Pages that already use it are unchanged.`,
235
+ });
236
+ })
237
+ .catch((caught: unknown) => {
238
+ setUploadNote({
239
+ error: true,
240
+ text: caught instanceof Error ? caught.message : "Couldn't rename that upload.",
241
+ });
242
+ });
243
+ };
244
+ const deleteUpload = () => {
245
+ if (!fetcher || !uploadId || !selected) return;
246
+ if (
247
+ !window.confirm(
248
+ `Remove “${selected.label}” from My uploads? Icons already on a page stay as they are.`,
249
+ )
250
+ ) {
251
+ return;
252
+ }
253
+ void deleteUploadedIcon(fetcher, uploadId)
254
+ .then(() => {
255
+ setUploads((current) => current?.filter((entry) => entry.id !== selected.id));
256
+ setSelectedId(undefined);
257
+ setUploadNote({
258
+ error: false,
259
+ text: "Removed from My uploads. Icons already placed on a page still show.",
260
+ });
261
+ })
262
+ .catch((caught: unknown) => {
263
+ setUploadNote({
264
+ error: true,
265
+ text: caught instanceof Error ? caught.message : "Couldn't remove that upload.",
266
+ });
267
+ });
268
+ };
269
+
270
+ const status = failed
271
+ ? `${failed} didn't load.`
272
+ : inUploads && uploadsFailed
273
+ ? "Uploads didn't load."
274
+ : !ready
275
+ ? "Loading icons…"
276
+ : filtered.length === 0
277
+ ? query.trim()
278
+ ? `No icons match "${query.trim()}" in ${category.label}.`
279
+ : inUploads
280
+ ? "No uploads yet."
281
+ : "No icons here."
282
+ : `${fmt(filtered.length)} icon${filtered.length === 1 ? "" : "s"}`;
283
+
284
+ return {
285
+ categories,
286
+ categoryId,
287
+ setCategoryId,
288
+ query,
289
+ setQuery,
290
+ searchId,
291
+ category,
292
+ filtered,
293
+ active,
294
+ setActive,
295
+ gridRef,
296
+ inUploads,
297
+ uploading,
298
+ fileRef,
299
+ onUpload,
300
+ uploadNote,
301
+ uploadsFailed,
302
+ setUploadsFailed,
303
+ setAttempt,
304
+ failed,
305
+ ready,
306
+ status,
307
+ counts,
308
+ selectedId,
309
+ activate,
310
+ selected,
311
+ uploadId,
312
+ renameUpload,
313
+ deleteUpload,
314
+ };
315
+ }