@perkyzz/emvb 0.1.0 → 0.2.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 (153) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +32 -0
  3. package/licenses/fontawesome-free.LICENSE +165 -0
  4. package/licenses/lucide-static.LICENSE +43 -0
  5. package/licenses/remixicon.LICENSE +201 -0
  6. package/licenses/tabler-icons.LICENSE +21 -0
  7. package/package.json +8 -4
  8. package/src/admin/api.ts +27 -0
  9. package/src/admin/content-api.ts +72 -9
  10. package/src/admin/editor/Editor.tsx +89 -14
  11. package/src/admin/editor/EditorOverlay.tsx +12 -0
  12. package/src/admin/editor/SmallScreenNotice.tsx +4 -3
  13. package/src/admin/editor/TopBar.tsx +76 -12
  14. package/src/admin/editor/canvas/CanvasFrame.tsx +224 -43
  15. package/src/admin/editor/canvas/DeviceBar.tsx +43 -2
  16. package/src/admin/editor/canvas/SelectionOverlay.tsx +60 -6
  17. package/src/admin/editor/canvas/canvas-events.ts +20 -7
  18. package/src/admin/editor/canvas/tab-reveal.ts +66 -0
  19. package/src/admin/editor/canvas/vnode-react.tsx +21 -1
  20. package/src/admin/editor/dialogs.tsx +39 -0
  21. package/src/admin/editor/dnd/drop-target.ts +63 -16
  22. package/src/admin/editor/dnd/new-element.ts +76 -1
  23. package/src/admin/editor/editor-css.ts +101 -15
  24. package/src/admin/editor/host.ts +30 -0
  25. package/src/admin/editor/icons/IconLibraryDialog.tsx +850 -0
  26. package/src/admin/editor/icons/library.ts +243 -0
  27. package/src/admin/editor/icons/set-format.ts +29 -0
  28. package/src/admin/editor/icons/sets/fontawesome.json +1 -0
  29. package/src/admin/editor/icons/sets/lucide.json +1 -0
  30. package/src/admin/editor/icons/sets/remix.json +1 -0
  31. package/src/admin/editor/icons/sets/tabler.json +1 -0
  32. package/src/admin/editor/panels/AddPanel.tsx +7 -3
  33. package/src/admin/editor/panels/ClassesSection.tsx +44 -6
  34. package/src/admin/editor/panels/ColorControl.tsx +268 -21
  35. package/src/admin/editor/panels/ElementPanel.tsx +237 -93
  36. package/src/admin/editor/panels/LayersPanel.tsx +303 -66
  37. package/src/admin/editor/panels/LeftPanel.tsx +4 -0
  38. package/src/admin/editor/panels/PageSettings.tsx +134 -5
  39. package/src/admin/editor/panels/SettingsPanel.tsx +12 -0
  40. package/src/admin/editor/panels/SiteStylesDrawer.tsx +158 -2
  41. package/src/admin/editor/panels/TriggersEditor.tsx +19 -2
  42. package/src/admin/editor/panels/VariableSection.tsx +47 -9
  43. package/src/admin/editor/panels/color-space.ts +195 -0
  44. package/src/admin/editor/panels/settings/AdvancedFields.tsx +119 -0
  45. package/src/admin/editor/panels/settings/BackgroundControls.tsx +153 -55
  46. package/src/admin/editor/panels/settings/BackgroundFill.tsx +221 -0
  47. package/src/admin/editor/panels/settings/BoxControl.tsx +271 -0
  48. package/src/admin/editor/panels/settings/ChoiceGroup.tsx +138 -0
  49. package/src/admin/editor/panels/settings/ClassChipInput.tsx +104 -2
  50. package/src/admin/editor/panels/settings/DraftTextField.tsx +44 -3
  51. package/src/admin/editor/panels/settings/EffectsControls.tsx +23 -16
  52. package/src/admin/editor/panels/settings/FieldBindControl.tsx +53 -17
  53. package/src/admin/editor/panels/settings/FieldControl.tsx +129 -9
  54. package/src/admin/editor/panels/settings/FormBindControl.tsx +14 -5
  55. package/src/admin/editor/panels/settings/IconControls.tsx +438 -0
  56. package/src/admin/editor/panels/settings/IconPicker.tsx +133 -72
  57. package/src/admin/editor/panels/settings/ItemList.tsx +199 -0
  58. package/src/admin/editor/panels/settings/LengthRow.tsx +97 -61
  59. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +10 -4
  60. package/src/admin/editor/panels/settings/MediaPicker.tsx +4 -2
  61. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  62. package/src/admin/editor/panels/settings/StyleRow.tsx +158 -75
  63. package/src/admin/editor/panels/settings/VariableBinding.tsx +5 -1
  64. package/src/admin/editor/panels/settings/advanced-rules.ts +63 -0
  65. package/src/admin/editor/panels/settings/background-mode.ts +112 -0
  66. package/src/admin/editor/panels/settings/box-link-name.ts +38 -0
  67. package/src/admin/editor/panels/settings/box-sides.ts +153 -0
  68. package/src/admin/editor/panels/settings/button-url.ts +27 -0
  69. package/src/admin/editor/panels/settings/class-suggest.ts +5 -3
  70. package/src/admin/editor/panels/settings/form-names.ts +38 -0
  71. package/src/admin/editor/panels/settings/heading-warning.ts +25 -0
  72. package/src/admin/editor/panels/settings/image-alt.ts +25 -0
  73. package/src/admin/editor/panels/settings/length-units.ts +40 -7
  74. package/src/admin/editor/panels/settings/loop-context.ts +26 -0
  75. package/src/admin/editor/panels/settings/style-sections.ts +114 -11
  76. package/src/admin/editor/panels/settings/svg-images.ts +14 -0
  77. package/src/admin/editor/panels/site-list.tsx +3 -0
  78. package/src/admin/editor/restore-deleted.ts +80 -0
  79. package/src/admin/editor/shortcuts.ts +1 -1
  80. package/src/admin/editor/store.ts +35 -7
  81. package/src/admin/editor/useEditorCommands.ts +66 -5
  82. package/src/admin/editor/useEditorData.ts +29 -3
  83. package/src/admin/editor/useEditorShortcuts.ts +34 -2
  84. package/src/admin/editor/useNodeActions.ts +68 -6
  85. package/src/admin/editor/useSave.ts +60 -3
  86. package/src/admin/entry-status.ts +19 -0
  87. package/src/admin/icon-uploads-api.ts +44 -0
  88. package/src/admin/pages/PageList.tsx +22 -2
  89. package/src/admin/pages/ThemePartList.tsx +23 -4
  90. package/src/admin/pages/list-kit.tsx +52 -2
  91. package/src/admin/setup/spec.ts +7 -0
  92. package/src/admin/theme-api.ts +61 -14
  93. package/src/admin/ui.ts +17 -4
  94. package/src/astro/EmVBPage.astro +28 -2
  95. package/src/astro/floats/EmVBFloatsRuntime.astro +9 -0
  96. package/src/astro/floats/index.ts +1 -0
  97. package/src/astro/floats/runtime.ts +78 -0
  98. package/src/astro/forms-definitions.ts +22 -0
  99. package/src/astro/index.ts +1 -0
  100. package/src/astro/menu/EmVBMenuRuntime.astro +9 -0
  101. package/src/astro/menu/index.ts +1 -0
  102. package/src/astro/menu/runtime.ts +37 -0
  103. package/src/astro/popups/runtime.ts +54 -4
  104. package/src/astro/render.ts +47 -13
  105. package/src/astro/resolve-theme.ts +164 -20
  106. package/src/astro/tabs/runtime.ts +6 -1
  107. package/src/astro/theme-context.ts +11 -3
  108. package/src/constants.ts +1 -1
  109. package/src/core/arrange.ts +98 -10
  110. package/src/core/clipboard.ts +91 -9
  111. package/src/core/css/generate.ts +21 -4
  112. package/src/core/design/classes.ts +95 -9
  113. package/src/core/design/transfer.ts +101 -2
  114. package/src/core/design/variables.ts +51 -11
  115. package/src/core/elements/dynamic-elements.ts +57 -5
  116. package/src/core/elements/field-id.ts +6 -0
  117. package/src/core/elements/form-elements.ts +23 -8
  118. package/src/core/elements/index.ts +267 -49
  119. package/src/core/elements/menu.ts +190 -0
  120. package/src/core/forms/definition.ts +11 -0
  121. package/src/core/index.ts +67 -3
  122. package/src/core/limits.ts +2 -0
  123. package/src/core/migrate/index.ts +51 -1
  124. package/src/core/nesting.ts +51 -0
  125. package/src/core/render/context.ts +7 -0
  126. package/src/core/render/dynamic-post.ts +39 -11
  127. package/src/core/render/extras.ts +22 -3
  128. package/src/core/render/form.ts +134 -36
  129. package/src/core/render/index.ts +123 -25
  130. package/src/core/render/loop.ts +10 -3
  131. package/src/core/render/pagination.ts +76 -0
  132. package/src/core/render/section.ts +5 -1
  133. package/src/core/render/tabs.ts +8 -4
  134. package/src/core/render/vnode.ts +1 -1
  135. package/src/core/sanitize/css.ts +197 -17
  136. package/src/core/sanitize/embed-url.ts +64 -7
  137. package/src/core/sanitize/svg-upload.ts +203 -0
  138. package/src/core/sanitize/svg.ts +102 -21
  139. package/src/core/schema/descriptors.ts +4 -0
  140. package/src/core/schema/design.ts +7 -2
  141. package/src/core/schema/layout.ts +210 -19
  142. package/src/core/schema/style.ts +87 -8
  143. package/src/core/tabs/presence.ts +9 -0
  144. package/src/core/theme/conditions.ts +4 -1
  145. package/src/core/theme/dynamic.ts +10 -0
  146. package/src/core/theme/float.ts +113 -0
  147. package/src/core/theme/pagination.ts +97 -0
  148. package/src/core/theme/part-types.ts +2 -0
  149. package/src/core/theme/popup-markup.ts +3 -1
  150. package/src/core/theme/popup-rules.ts +4 -3
  151. package/src/server/hooks.ts +20 -0
  152. package/src/server/icon-routes.ts +79 -0
  153. package/src/server/plugin.ts +5 -1
@@ -34,7 +34,19 @@ const CURSOR = new Set([
34
34
  "zoom-in",
35
35
  ]);
36
36
  const ASPECT_RATIO = /^([1-9]\d{0,3})\/([1-9]\d{0,3})$/;
37
- const FONT_WEIGHT = new Set(["normal", "bold", "400", "500", "600", "700"]);
37
+ const FONT_WEIGHT = new Set([
38
+ "normal",
39
+ "bold",
40
+ "100",
41
+ "200",
42
+ "300",
43
+ "400",
44
+ "500",
45
+ "600",
46
+ "700",
47
+ "800",
48
+ "900",
49
+ ]);
38
50
  const FORBIDDEN = /[{};<>\\"'`]|\/\*|url\(|expression\(|@import|javascript:/i;
39
51
 
40
52
  /** Last line of defence on every emitted value, even ones built by the typed validators below. */
@@ -252,6 +264,18 @@ const keyword =
252
264
  (value: unknown): string | undefined =>
253
265
  typeof value === "string" && allowed.has(value) ? value : undefined;
254
266
 
267
+ /** W-213: a length, or a unitless number 0–100. */
268
+ function cssLineHeight(value: unknown): string | undefined {
269
+ if (typeof value === "number")
270
+ return Number.isFinite(value) && value >= 0 && value <= 100 ? String(value) : undefined;
271
+ return cssLength(value);
272
+ }
273
+
274
+ /** W-213: a length that may be negative (never `auto`). */
275
+ function cssLetterSpacing(value: unknown): string | undefined {
276
+ return value === "auto" ? undefined : cssOffset(value);
277
+ }
278
+
255
279
  function cssFontWeight(value: unknown): string | undefined {
256
280
  if (typeof value === "number" && FONT_WEIGHT.has(String(value))) return String(value);
257
281
  if (typeof value === "string" && FONT_WEIGHT.has(value)) return value;
@@ -287,6 +311,63 @@ function cssTransition(value: unknown): string | undefined {
287
311
  return properties.map((property) => `${property} ${timing}`).join(",");
288
312
  }
289
313
 
314
+ const inRangeNumber = (value: unknown, min: number, max: number): value is number =>
315
+ typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
316
+
317
+ /** Up to 3 decimals, without float noise or a trailing zero (`1.5`, not `1.5000000001`). */
318
+ const decimal = (n: number) => String(Math.round(n * 1000) / 1000);
319
+
320
+ /** W-237: glyph rotation in degrees, -360 to 360. */
321
+ const cssIconRotate = (value: unknown): string | undefined =>
322
+ Number.isInteger(value) && inRangeNumber(value, -360, 360) ? `${value}deg` : undefined;
323
+
324
+ const ICON_FLIPS: Readonly<Record<string, string>> = {
325
+ none: "1 1",
326
+ horizontal: "-1 1",
327
+ vertical: "1 -1",
328
+ both: "-1 -1",
329
+ };
330
+
331
+ /** W-237: a flip as the svg's `scale` (`none` too, so a device can undo a Desktop flip). */
332
+ const cssIconFlip = (value: unknown): string | undefined =>
333
+ typeof value === "string" && Object.hasOwn(ICON_FLIPS, value) ? ICON_FLIPS[value] : undefined;
334
+
335
+ const cssIconScale = (value: unknown): string | undefined =>
336
+ inRangeNumber(value, 0.1, 4) ? decimal(value) : undefined;
337
+
338
+ const cssIconStroke = (value: unknown): string | undefined =>
339
+ inRangeNumber(value, 0.25, 6) ? decimal(value) : undefined;
340
+
341
+ /** W-237: `drop-shadow(x y blur [color])` in px; no colour means the icon's own colour. */
342
+ function cssIconShadow(value: unknown): string | undefined {
343
+ if (!isRecord(value)) return undefined;
344
+ if (Object.keys(value).some((key) => !["x", "y", "blur", "color"].includes(key)))
345
+ return undefined;
346
+ const { x, y, blur } = value;
347
+ if (!inRangeNumber(x, -100, 100) || !inRangeNumber(y, -100, 100) || !inRangeNumber(blur, 0, 100))
348
+ return undefined;
349
+ const color = value["color"] === undefined ? "" : cssColor(value["color"]);
350
+ if (color === undefined) return undefined;
351
+ return `drop-shadow(${decimal(x)}px ${decimal(y)}px ${decimal(blur)}px${color ? ` ${color}` : ""})`;
352
+ }
353
+
354
+ const ICON_ANIMATIONS: Readonly<Record<string, string>> = {
355
+ spin: "emvb-icon-spin {ms} linear infinite",
356
+ pulse: "emvb-icon-pulse {ms} ease-in-out infinite alternate",
357
+ };
358
+
359
+ /** W-237: a looping spin or pulse; the Icon's base CSS turns it off for reduced motion. */
360
+ function cssIconAnimation(value: unknown): string | undefined {
361
+ if (!isRecord(value)) return undefined;
362
+ if (Object.keys(value).some((key) => key !== "type" && key !== "duration")) return undefined;
363
+ const { type, duration } = value;
364
+ // W-248: stops an animation inherited from a wider device.
365
+ if (type === "none") return duration === undefined ? "none" : undefined;
366
+ if (typeof type !== "string" || !Object.hasOwn(ICON_ANIMATIONS, type)) return undefined;
367
+ if (!Number.isInteger(duration) || !inRangeNumber(duration, 200, 10_000)) return undefined;
368
+ return ICON_ANIMATIONS[type]?.replace("{ms}", `${duration}ms`);
369
+ }
370
+
290
371
  export type Declaration = { property: string; value: string };
291
372
 
292
373
  const BACKGROUND_SIZE = new Set(["auto", "cover", "contain"]);
@@ -328,17 +409,62 @@ function cssBackgroundImage(value: unknown): string | undefined {
328
409
  return isSafeBackground(css) ? css : undefined;
329
410
  }
330
411
 
412
+ const GRADIENT_POSITION = new Set([
413
+ "center",
414
+ "top",
415
+ "bottom",
416
+ "left",
417
+ "right",
418
+ "top left",
419
+ "top right",
420
+ "bottom left",
421
+ "bottom right",
422
+ ]);
423
+
424
+ function cssAngle(value: unknown, fallback: number): number | undefined {
425
+ const angle = value === undefined ? fallback : value;
426
+ if (!Number.isInteger(angle) || (angle as number) < 0 || (angle as number) > 360)
427
+ return undefined;
428
+ return angle as number;
429
+ }
430
+
331
431
  function cssGradient(value: unknown): string | undefined {
332
432
  if (!isRecord(value)) return undefined;
333
- if (Object.keys(value).some((key) => key !== "angle" && key !== "from" && key !== "to"))
334
- return undefined;
335
- const { angle, from, to } = value;
336
- if (!Number.isInteger(angle) || (angle as number) < 0 || (angle as number) > 360)
433
+ if (
434
+ Object.keys(value).some(
435
+ (key) => key !== "type" && key !== "angle" && key !== "position" && key !== "stops",
436
+ )
437
+ )
337
438
  return undefined;
338
- const start = cssColor(from);
339
- const end = cssColor(to);
340
- if (!start || !end) return undefined;
341
- const css = `linear-gradient(${angle as number}deg, ${start}, ${end})`;
439
+ const { type, stops } = value;
440
+ if (type !== "linear" && type !== "radial" && type !== "conic") return undefined;
441
+ if (!Array.isArray(stops) || stops.length < 2 || stops.length > 10) return undefined;
442
+ const parts: { color: string; at: number }[] = [];
443
+ for (const stop of stops) {
444
+ if (!isRecord(stop) || Object.keys(stop).some((key) => key !== "color" && key !== "at"))
445
+ return undefined;
446
+ const color = cssColor(stop["color"]);
447
+ const at = stop["at"];
448
+ if (!color || !Number.isInteger(at) || (at as number) < 0 || (at as number) > 100)
449
+ return undefined;
450
+ parts.push({ color, at: at as number });
451
+ }
452
+ // Stops are kept in the order they were added; CSS needs them by location (W-172).
453
+ parts.sort((a, b) => a.at - b.at);
454
+ const list = parts.map((part) => `${part.color} ${part.at}%`).join(", ");
455
+ let css: string;
456
+ if (type === "radial") {
457
+ const position = value["position"] === undefined ? "center" : value["position"];
458
+ if (typeof position !== "string" || !GRADIENT_POSITION.has(position)) return undefined;
459
+ css = `radial-gradient(circle at ${position}, ${list})`;
460
+ } else {
461
+ const angle = cssAngle(value["angle"], type === "conic" ? 0 : 180);
462
+ if (angle === undefined) return undefined;
463
+ css =
464
+ type === "conic"
465
+ ? `conic-gradient(from ${angle}deg, ${list})`
466
+ : `linear-gradient(${angle}deg, ${list})`;
467
+ }
342
468
  return isSafeBackground(css) ? css : undefined;
343
469
  }
344
470
 
@@ -487,8 +613,8 @@ const PROPERTY_MAP: {
487
613
  fontFamily: { css: "font-family", toValue: cssFontFamily },
488
614
  fontSize: { css: "font-size", toValue: cssLength },
489
615
  fontWeight: { css: "font-weight", toValue: cssFontWeight },
490
- lineHeight: { css: "line-height", toValue: cssLength },
491
- letterSpacing: { css: "letter-spacing", toValue: cssLength },
616
+ lineHeight: { css: "line-height", toValue: cssLineHeight },
617
+ letterSpacing: { css: "letter-spacing", toValue: cssLetterSpacing },
492
618
  textAlign: { css: "text-align", toValue: cssTextAlign },
493
619
  textTransform: { css: "text-transform", toValue: keyword(TEXT_TRANSFORM) },
494
620
  textDecoration: { css: "text-decoration", toValue: keyword(TEXT_DECORATION) },
@@ -502,20 +628,46 @@ const PROPERTY_MAP: {
502
628
  gradient: { css: "background-image", toValue: cssGradient },
503
629
  overlay: { css: "background-image", toValue: cssOverlay },
504
630
  borderWidth: { css: "border-width", toValue: cssLength },
631
+ borderTopWidth: { css: "border-top-width", toValue: cssLength },
632
+ borderRightWidth: { css: "border-inline-end-width", toValue: cssLength },
633
+ borderBottomWidth: { css: "border-bottom-width", toValue: cssLength },
634
+ borderLeftWidth: { css: "border-inline-start-width", toValue: cssLength },
505
635
  borderStyle: { css: "border-style", toValue: keyword(BORDER_STYLE) },
506
636
  borderColor: { css: "border-color", toValue: cssColor },
507
637
  borderRadius: { css: "border-radius", toValue: cssLength },
638
+ borderTopLeftRadius: { css: "border-start-start-radius", toValue: cssLength },
639
+ borderTopRightRadius: { css: "border-start-end-radius", toValue: cssLength },
640
+ borderBottomRightRadius: { css: "border-end-end-radius", toValue: cssLength },
641
+ borderBottomLeftRadius: { css: "border-end-start-radius", toValue: cssLength },
508
642
  opacity: { css: "opacity", toValue: cssOpacity },
509
643
  boxShadow: { css: "box-shadow", toValue: cssBoxShadow },
510
644
  filter: { css: "filter", toValue: cssFilter },
511
645
  cursor: { css: "cursor", toValue: keyword(CURSOR) },
512
646
  transition: { css: "transition", toValue: cssTransition },
513
647
  entrance: { css: "animation", toValue: cssEntrance },
648
+ iconRotate: { css: "--emvb-icon-rotate", toValue: cssIconRotate },
649
+ iconFlip: { css: "--emvb-icon-flip", toValue: cssIconFlip },
650
+ iconScale: { css: "scale", toValue: cssIconScale },
651
+ iconStrokeWidth: { css: "--emvb-icon-stroke", toValue: cssIconStroke },
652
+ iconShadow: { css: "--emvb-icon-shadow", toValue: cssIconShadow },
653
+ iconAnimation: { css: "--emvb-icon-animation", toValue: cssIconAnimation },
514
654
  };
515
655
 
516
656
  /** Exported for table-driven tests (W-017). */
517
657
  export const STYLE_PROPERTY_MAP = PROPERTY_MAP;
518
658
 
659
+ /** All-sides keys whose CSS shorthand must come before the per-side longhands (W-138). */
660
+ const SHORTHANDS = new Set(["borderWidth", "borderRadius"]);
661
+
662
+ /** Entries with `borderWidth` and `borderRadius` first, so a side or corner always wins. */
663
+ const shorthandsFirst = (record: Record<string, unknown>): [string, unknown][] => {
664
+ const entries = Object.entries(record);
665
+ return [
666
+ ...entries.filter(([key]) => SHORTHANDS.has(key)),
667
+ ...entries.filter(([key]) => !SHORTHANDS.has(key)),
668
+ ];
669
+ };
670
+
519
671
  /** Converts style props into safe declarations; anything that fails validation is dropped and reported. */
520
672
  export function styleDeclarations(style: unknown): {
521
673
  declarations: Declaration[];
@@ -525,7 +677,7 @@ export function styleDeclarations(style: unknown): {
525
677
  const rejected: string[] = [];
526
678
  if (typeof style !== "object" || style === null) return { declarations, rejected };
527
679
  const record = style as Record<string, unknown>;
528
- for (const [key, raw] of Object.entries(record)) {
680
+ for (const [key, raw] of shorthandsFirst(record)) {
529
681
  if (BACKGROUND_KEYS.has(key)) continue;
530
682
  const entry = Object.hasOwn(PROPERTY_MAP, key)
531
683
  ? PROPERTY_MAP[key as keyof StyleProps]
@@ -555,10 +707,12 @@ export function styleDeclarations(style: unknown): {
555
707
  return { declarations, rejected };
556
708
  }
557
709
 
558
- /** Transitions are Normal only (W-089): a state's `transition` is dropped and reported. */
710
+ /** Normal only (W-089, W-237): a state's `transition` and `iconAnimation` are dropped and reported. */
711
+ const NORMAL_ONLY = ["transition", "iconAnimation"] as const;
559
712
  const withoutTransition = (style: unknown): unknown => {
560
- if (typeof style !== "object" || style === null || !("transition" in style)) return style;
561
- const { transition: _drop, ...rest } = style as Record<string, unknown>;
713
+ if (typeof style !== "object" || style === null) return style;
714
+ if (!NORMAL_ONLY.some((key) => key in style)) return style;
715
+ const { transition: _drop, iconAnimation: _loop, ...rest } = style as Record<string, unknown>;
562
716
  return rest;
563
717
  };
564
718
 
@@ -582,10 +736,36 @@ export function stateDeclarations(states: unknown): {
582
736
  const style = (states as Record<string, unknown>)[state];
583
737
  if (style === undefined) continue;
584
738
  const { declarations, rejected: bad } = styleDeclarations(withoutTransition(style));
585
- if (typeof style === "object" && style !== null && "transition" in style)
586
- bad.push("transition");
739
+ for (const key of NORMAL_ONLY) {
740
+ if (typeof style === "object" && style !== null && key in style) bad.push(key);
741
+ }
587
742
  if (declarations.length > 0) result[state] = declarations;
588
743
  for (const key of bad) rejected.push(`${state}.${key}`);
589
744
  }
590
745
  return { states: result, rejected };
591
746
  }
747
+
748
+ /** The style keys drawn together as one `background-image` stack (image, gradient, overlay). */
749
+ const BACKGROUND_LAYER_KEYS = [
750
+ "backgroundImage",
751
+ "gradient",
752
+ "overlay",
753
+ "backgroundSize",
754
+ "backgroundPosition",
755
+ "backgroundRepeat",
756
+ ] as const;
757
+
758
+ /**
759
+ * W-210: a tablet or mobile style that sets one background layer (say only the overlay) writes the
760
+ * whole `background-image` stack for that device, so the layers it inherits (the desktop image or
761
+ * gradient) are filled in from `inherited` here. Otherwise they vanish on that device.
762
+ */
763
+ export function withInheritedLayers(device: unknown, inherited: unknown): unknown {
764
+ if (!isRecord(device) || !isRecord(inherited)) return device;
765
+ if (!BACKGROUND_LAYER_KEYS.some((key) => device[key] !== undefined)) return device;
766
+ const next: Record<string, unknown> = { ...device };
767
+ for (const key of BACKGROUND_LAYER_KEYS) {
768
+ if (next[key] === undefined && inherited[key] !== undefined) next[key] = inherited[key];
769
+ }
770
+ return next;
771
+ }
@@ -31,22 +31,75 @@ function youtubeId(parsed: URL): string | undefined {
31
31
  const host = parsed.hostname.toLowerCase();
32
32
  const path = parsed.pathname;
33
33
  if (host === "youtu.be" || host === "www.youtu.be") return matching(firstSegment(path), YT_ID);
34
- for (const prefix of ["/embed/", "/shorts/"]) {
34
+ // W-215: /live/ links (a stream or its replay) too.
35
+ for (const prefix of ["/embed/", "/shorts/", "/live/"]) {
35
36
  if (path.startsWith(prefix)) return matching(path.slice(prefix.length).split("/")[0], YT_ID);
36
37
  }
37
38
  return matching(parsed.searchParams.get("v") ?? undefined, YT_ID);
38
39
  }
39
40
 
41
+ /** An unlisted Vimeo video's privacy hash: the player refuses the video without it (W-215). */
42
+ const VIMEO_HASH = /^[0-9a-f]{6,32}$/i;
43
+
44
+ /**
45
+ * The Vimeo id, plus `?h=<hash>` for an unlisted video (W-215): `vimeo.com/<id>/<hash>`,
46
+ * `player.vimeo.com/video/<id>?h=<hash>`, `vimeo.com/channels/<name>/<id>` and
47
+ * `vimeo.com/groups/<name>/videos/<id>`.
48
+ */
40
49
  function vimeoId(parsed: URL): string | undefined {
41
- if (parsed.hostname.toLowerCase() !== "player.vimeo.com") {
42
- return matching(firstSegment(parsed.pathname), VIMEO_ID);
43
- }
44
50
  const parts = parsed.pathname.split("/").filter(Boolean);
51
+ const player = parsed.hostname.toLowerCase() === "player.vimeo.com";
45
52
  const videoIdx = parts.indexOf("video");
46
- return matching(videoIdx >= 0 ? parts[videoIdx + 1] : parts[0], VIMEO_ID);
53
+ const at = player
54
+ ? videoIdx >= 0
55
+ ? videoIdx + 1
56
+ : 0
57
+ : parts[0] === "channels"
58
+ ? 2
59
+ : parts[0] === "groups" && parts[2] === "videos"
60
+ ? 3
61
+ : 0;
62
+ const id = matching(parts[at], VIMEO_ID);
63
+ if (!id) return undefined;
64
+ const hash = player ? parsed.searchParams.get("h") : at === 0 ? parts[1] : undefined;
65
+ return hash && VIMEO_HASH.test(hash) ? `${id}?h=${hash}` : id;
66
+ }
67
+
68
+ /** Longest start time kept, in seconds (a day). */
69
+ const MAX_START = 86_400;
70
+
71
+ /**
72
+ * A start time as whole seconds: `90`, `90s`, `1m30s`, `1h2m3s` (W-227). Undefined for anything
73
+ * else, zero, or past MAX_START, so nothing but digits reaches the embed URL.
74
+ */
75
+ export function parseStartSeconds(raw: string | null | undefined): number | undefined {
76
+ const match = /^(?:(\d{1,2})h)?(?:(\d{1,4})m)?(?:(\d{1,6})s?)?$/i.exec(raw?.trim() ?? "");
77
+ if (!match || !raw?.trim()) return undefined;
78
+ const [, h = "0", m = "0", s = "0"] = match;
79
+ const total = Number(h) * 3600 + Number(m) * 60 + Number(s);
80
+ return total > 0 && total <= MAX_START ? total : undefined;
81
+ }
82
+
83
+ /** `t=` from the query or the `#t=` fragment, YouTube's `start=` too (W-227). */
84
+ function startOf(parsed: URL): number | undefined {
85
+ const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ""));
86
+ return parseStartSeconds(
87
+ parsed.searchParams.get("t") ?? parsed.searchParams.get("start") ?? fragment.get("t"),
88
+ );
47
89
  }
48
90
 
49
- /** Embed URLs are built from the id alone, so no query param (autoplay included) carries over. */
91
+ /** Appends the start time the way each player reads it (W-227). */
92
+ const withStart = (provider: "youtube" | "vimeo", src: string, start: number | undefined) =>
93
+ start === undefined
94
+ ? src
95
+ : provider === "youtube"
96
+ ? `${src}?start=${start}`
97
+ : `${src}#t=${start}s`;
98
+
99
+ /**
100
+ * Embed URLs are built from the id alone (and an unlisted Vimeo hash and a start time in whole
101
+ * seconds, W-227), so no other query param (autoplay included) carries over.
102
+ */
50
103
  const PROVIDERS = [
51
104
  {
52
105
  provider: "youtube",
@@ -86,7 +139,11 @@ export function resolveEmbedUrl(value: string): EmbedTarget | undefined {
86
139
  if (provider) {
87
140
  const id = provider.id(parsed);
88
141
  return id
89
- ? { kind: "iframe", src: `${provider.embed}${id}`, provider: provider.provider }
142
+ ? {
143
+ kind: "iframe",
144
+ src: withStart(provider.provider, `${provider.embed}${id}`, startOf(parsed)),
145
+ provider: provider.provider,
146
+ }
90
147
  : undefined;
91
148
  }
92
149
 
@@ -0,0 +1,203 @@
1
+ import { serialize, type VNode } from "../render/vnode.ts";
2
+ import { ICON_SVG_MAX } from "../schema/layout.ts";
3
+ import { sanitizeSvgReport } from "./svg.ts";
4
+
5
+ /**
6
+ * Upload SVG (W-239). An uploaded file is tidied, then run through the same sanitizer as pasted
7
+ * SVG and every render (W-073 / W-231): scripts, event handlers, foreignObject, `<style>`, links
8
+ * and unsafe URLs refuse the file; external `<image>`s are left out. The tidy step only removes
9
+ * what design tools add around the drawing and turns inline `style` paint into attributes; the
10
+ * sanitizer still decides what is kept.
11
+ */
12
+
13
+ /** The file as picked. Design tools pad SVGs; what's stored is checked against ICON_SVG_MAX. */
14
+ export const UPLOAD_SVG_MAX_BYTES = 256 * 1024;
15
+
16
+ /** An uploaded icon as EmVB stores it (plugin storage `icons`) and lists it. */
17
+ export type UploadedIcon = { name: string; svg: string; uploadedAt: string };
18
+ export type UploadedIconItem = UploadedIcon & { id: string };
19
+
20
+ export type PreparedSvg =
21
+ | { ok: true; svg: string; imagesLeftOut: number }
22
+ | { ok: false; message: string };
23
+
24
+ const kb = (bytes: number) => `${Math.ceil(bytes / 1024)} KB`;
25
+ const utf8 = (text: string) => new TextEncoder().encode(text).length;
26
+
27
+ /** Paint properties an inline `style` may carry over as attributes (Inkscape writes them so). */
28
+ const STYLE_TO_ATTR = new Set([
29
+ "fill",
30
+ "fill-opacity",
31
+ "fill-rule",
32
+ "stroke",
33
+ "stroke-width",
34
+ "stroke-opacity",
35
+ "stroke-linecap",
36
+ "stroke-linejoin",
37
+ "stroke-miterlimit",
38
+ "stroke-dasharray",
39
+ "stroke-dashoffset",
40
+ "opacity",
41
+ "clip-rule",
42
+ "stop-color",
43
+ "stop-opacity",
44
+ ]);
45
+ /** Colours, numbers, keywords and `url(#id)`; anything else in a style is dropped. */
46
+ const STYLE_VALUE =
47
+ /^(?:#[\da-f]{3,8}|[a-z-]+|-?[\d.]+(?:px|%)?(?:[\s,]+-?[\d.]+(?:px|%)?)*|url\(#[\w.-]+\)|rgba?\([\d\s.,%]+\))$/i;
48
+
49
+ /** `style="fill:#f00;stroke:none"` → ` fill="#f00" stroke="none"`, skipping attributes already set. */
50
+ function styleToAttrs(tag: string): string {
51
+ const has = (name: string) => new RegExp(`\\s${name}\\s*=`, "i").test(tag);
52
+ return tag.replace(/\sstyle\s*=\s*("([^"]*)"|'([^']*)')/i, (_match, _quoted, dq, sq) => {
53
+ let out = "";
54
+ for (const decl of String(dq ?? sq ?? "").split(";")) {
55
+ const colon = decl.indexOf(":");
56
+ if (colon < 0) continue;
57
+ const name = decl.slice(0, colon).trim().toLowerCase();
58
+ const value = decl.slice(colon + 1).trim();
59
+ if (!STYLE_TO_ATTR.has(name) || !STYLE_VALUE.test(value) || has(name)) continue;
60
+ out += ` ${name}="${value}"`;
61
+ }
62
+ return out;
63
+ });
64
+ }
65
+
66
+ /** What design tools add around the drawing: prolog, comments, doctype, editor metadata. */
67
+ export function tidyUploadedSvg(raw: string): string {
68
+ let text = raw.replace(/^\uFEFF/, "");
69
+ text = text.replace(/<\?[\s\S]*?\?>/g, "");
70
+ text = text.replace(/<!--[\s\S]*?-->/g, "");
71
+ text = text.replace(/<!DOCTYPE[^[>]*(?:\[[\s\S]*?\])?\s*>/gi, "");
72
+ text = text.replace(/<metadata\b[\s\S]*?<\/metadata\s*>/gi, "");
73
+ text = text.replace(/<metadata\b[^>]*\/>/gi, "");
74
+ // The Icon's title names it; a file's own <title>/<desc> would add a stray tooltip.
75
+ text = text.replace(/<(title|desc)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "");
76
+ // Editor elements (sodipodi:namedview, inkscape:grid, …): any prefixed element but svg/xlink.
77
+ text = text.replace(/<((?!svg:|xlink:)[a-z][\w.-]*:[\w.-]+)\b[^>]*\/>/gi, "");
78
+ text = text.replace(/<((?!svg:|xlink:)[a-z][\w.-]*:[\w.-]+)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "");
79
+ // Prefixed attributes and namespace declarations, except xlink:href and xml:space.
80
+ text = text.replace(/<[a-z][^>]*>/gi, (tag) =>
81
+ styleToAttrs(
82
+ tag.replace(
83
+ /\s(?!xlink:href\b|xml:space\b)[a-z][\w.-]*:[\w.-]+\s*=\s*("[^"]*"|'[^']*')/gi,
84
+ "",
85
+ ),
86
+ ),
87
+ );
88
+ return text.trim();
89
+ }
90
+
91
+ /** Why the sanitizer refused a file, as an author can act on it. */
92
+ function refusal(text: string): string {
93
+ if (!/<svg\b/i.test(text)) return "This file isn't an SVG. Choose an .svg file.";
94
+ if (/<script\b|\son[a-z]+\s*=|<foreignObject\b|javascript:/i.test(text))
95
+ return "This SVG contains scripts, event handlers or embedded HTML, so EmVB won't use it.";
96
+ if (/<style\b/i.test(text))
97
+ return "This SVG styles its shapes with a <style> block, which icons can't keep. Export it with presentation attributes (Illustrator: Styling → Presentation Attributes; Inkscape: Optimized SVG) and upload it again.";
98
+ return "EmVB couldn't use this SVG: it has parts icons can't keep (links, animations or unsafe URLs) or isn't well formed. Export it again as plain SVG and retry.";
99
+ }
100
+
101
+ const tooBig = (bytes: number): PreparedSvg => ({
102
+ ok: false,
103
+ message: `After cleaning, this SVG is ${kb(bytes)}; an icon can be up to ${kb(ICON_SVG_MAX)}. Simplify it (for example with SVGO) and try again.`,
104
+ });
105
+
106
+ /** Absolute CSS units in px; em and % depend on where the file was drawn, so they can't count. */
107
+ const UNIT_PX: Record<string, number> = {
108
+ "": 1,
109
+ px: 1,
110
+ pt: 4 / 3,
111
+ pc: 16,
112
+ in: 96,
113
+ cm: 96 / 2.54,
114
+ mm: 96 / 25.4,
115
+ q: 96 / 101.6,
116
+ };
117
+ const LENGTH = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i;
118
+
119
+ /** A width or height in px (from any absolute unit), or undefined. */
120
+ function pxLength(value: string | undefined): number | undefined {
121
+ const match = LENGTH.exec(value ?? "");
122
+ const factor = match ? UNIT_PX[match[2]?.toLowerCase() ?? ""] : undefined;
123
+ if (!match || factor === undefined) return undefined;
124
+ const px = Math.round(Number(match[1]) * factor * 1000) / 1000;
125
+ return px > 0 && Number.isFinite(px) ? px : undefined;
126
+ }
127
+
128
+ /** Four numbers with a positive width and height; any other viewBox draws nothing (W-241). */
129
+ function validViewBox(value: string | undefined): boolean {
130
+ const parts = (value ?? "").trim().split(/[\s,]+/);
131
+ if (parts.length !== 4) return false;
132
+ const nums = parts.map(Number);
133
+ const [, , width = 0, height = 0] = nums;
134
+ return nums.every(Number.isFinite) && width > 0 && height > 0;
135
+ }
136
+
137
+ /** Tags that only hold parts for other shapes: an SVG with nothing else draws nothing (W-241). */
138
+ const NOT_DRAWN = new Set([
139
+ "defs",
140
+ "lineargradient",
141
+ "radialgradient",
142
+ "stop",
143
+ "clippath",
144
+ "mask",
145
+ "pattern",
146
+ "filter",
147
+ "symbol",
148
+ "marker",
149
+ ]);
150
+ const GROUPS = new Set(["g", "svg", "a", "switch"]);
151
+
152
+ function draws(children: readonly (VNode | string)[]): boolean {
153
+ return children.some((child) => {
154
+ if (typeof child === "string") return false;
155
+ const tag = child.tag.toLowerCase();
156
+ if (GROUPS.has(tag)) return draws(child.children);
157
+ // A left-out outside image stays as an empty <image>.
158
+ if (tag === "image") return Boolean(child.attrs.href ?? child.attrs["xlink:href"]);
159
+ return !NOT_DRAWN.has(tag);
160
+ });
161
+ }
162
+
163
+ /**
164
+ * An uploaded file ready to store as an icon: tidied, sanitized, a viewBox (from width and
165
+ * height when missing, so it scales), its own width/height dropped, and within ICON_SVG_MAX.
166
+ */
167
+ export function prepareUploadedSvg(raw: string): PreparedSvg {
168
+ const size = utf8(raw);
169
+ if (size > UPLOAD_SVG_MAX_BYTES)
170
+ return {
171
+ ok: false,
172
+ message: `This file is ${kb(size)}. Upload an SVG up to ${kb(UPLOAD_SVG_MAX_BYTES)}.`,
173
+ };
174
+ const text = tidyUploadedSvg(raw);
175
+ // The sanitizer refuses markup over its limit outright; say it's the size.
176
+ if (text.length > ICON_SVG_MAX) return tooBig(utf8(text));
177
+ const report = sanitizeSvgReport(text);
178
+ const tree = report.tree;
179
+ if (!tree) return { ok: false, message: refusal(text) };
180
+ const { width, height, id: _id, class: _class, ...attrs } = tree.attrs;
181
+ if (!validViewBox(attrs.viewBox)) {
182
+ const w = pxLength(width);
183
+ const h = pxLength(height);
184
+ if (w === undefined || h === undefined)
185
+ return {
186
+ ok: false,
187
+ message: attrs.viewBox
188
+ ? "This SVG's viewBox isn't four numbers with a positive width and height, and it has no width and height in px, pt, mm, cm or in to use instead, so it can't be scaled."
189
+ : "This SVG has no viewBox, nor a width and height in px, pt, mm, cm or in, so it can't be scaled.",
190
+ };
191
+ attrs.viewBox = `0 0 ${w} ${h}`;
192
+ }
193
+ if (!draws(tree.children))
194
+ return { ok: false, message: "This SVG has nothing to draw: it has no shapes, paths or text." };
195
+ const svg = serialize({
196
+ tag: "svg",
197
+ attrs: { xmlns: "http://www.w3.org/2000/svg", ...attrs },
198
+ children: tree.children,
199
+ });
200
+ const stored = utf8(svg);
201
+ if (stored > ICON_SVG_MAX) return tooBig(stored);
202
+ return { ok: true, svg, imagesLeftOut: report.images };
203
+ }