@tarve/core 0.4.0 → 0.5.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 (46) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/README.md +67 -10
  3. package/dist/npm/build.js +823 -83
  4. package/dist/npm/cli.js +1087 -116
  5. package/dist/npm/embedded-assets.js +15 -1
  6. package/dist/npm/index.js +2468 -181
  7. package/dist/npm/native-runtime.json +3 -3
  8. package/dist/npm/node-build.js +865 -0
  9. package/dist/npm/protocol.js +1 -1
  10. package/dist/npm/runtime.js +5 -5
  11. package/dist/types/core/app-metadata.d.ts +49 -0
  12. package/dist/types/core/build.d.ts +21 -0
  13. package/dist/types/core/cli.d.ts +1 -1
  14. package/dist/types/core/esbuild-file-imports.d.ts +8 -0
  15. package/dist/types/core/node-build.d.ts +7 -0
  16. package/dist/types/core/node-dev.d.ts +4 -0
  17. package/dist/types/core/node-target.d.ts +10 -0
  18. package/dist/types/core/runtime-select.d.ts +8 -0
  19. package/dist/types/core/src/app-metadata.d.ts +16 -0
  20. package/dist/types/core/src/app.d.ts +87 -2
  21. package/dist/types/core/src/assets.d.ts +4 -0
  22. package/dist/types/core/src/bridge/binding.d.ts +10 -34
  23. package/dist/types/core/src/canvas.d.ts +161 -0
  24. package/dist/types/core/src/components/image.d.ts +7 -3
  25. package/dist/types/core/src/components/layout.d.ts +4 -3
  26. package/dist/types/core/src/components/pressable.d.ts +2 -2
  27. package/dist/types/core/src/extra-controls.d.ts +1 -1
  28. package/dist/types/core/src/html-elements.d.ts +26 -0
  29. package/dist/types/core/src/index.d.ts +4 -1
  30. package/dist/types/core/src/inline-text.d.ts +21 -0
  31. package/dist/types/core/src/jsx-runtime.d.ts +175 -4
  32. package/dist/types/core/src/media-element.d.ts +71 -0
  33. package/dist/types/core/src/memo.d.ts +18 -0
  34. package/dist/types/core/src/png.d.ts +29 -0
  35. package/dist/types/core/src/popups.d.ts +3 -2
  36. package/dist/types/core/src/reconciler.d.ts +27 -3
  37. package/dist/types/core/src/test-renderer.d.ts +2 -0
  38. package/dist/types/core/src/theme.d.ts +2 -1
  39. package/dist/types/core/src/virtual-list.d.ts +5 -1
  40. package/dist/types/core/windows-executable.d.ts +16 -0
  41. package/dist/types/protocol/src/index.d.ts +187 -5
  42. package/native/linux-x64/libtarve_native.so +0 -0
  43. package/native/linux-x64/runtime.json +4 -4
  44. package/native/win32-x64/runtime.json +4 -4
  45. package/native/win32-x64/tarve_native.dll +0 -0
  46. package/package.json +11 -2
package/dist/npm/index.js CHANGED
@@ -477,6 +477,7 @@ var lightTheme = {
477
477
  destructiveForeground: "#ffffff",
478
478
  destructiveHover: "#b91c1c",
479
479
  destructiveActive: "#991b1b",
480
+ destructiveText: "#dc2626",
480
481
  ring: "#a1a1aa",
481
482
  ringSoft: "#aeaeb6",
482
483
  success: "#15803d",
@@ -550,6 +551,7 @@ var darkTheme = {
550
551
  destructiveForeground: "#fafafa",
551
552
  destructiveHover: "#991b1b",
552
553
  destructiveActive: "#b91c1c",
554
+ destructiveText: "#f87171",
553
555
  ring: "#d4d4d8",
554
556
  ringSoft: "#b1b1b5",
555
557
  success: "#4ade80",
@@ -627,10 +629,20 @@ function resolveShadowColors(style, selected) {
627
629
  }
628
630
  }
629
631
  var COLOR_KEY = /^(background|foreground|color)$|(Color|Background|Foreground|Accent|Rule)$/;
632
+ var resolvedStrings = new WeakMap;
630
633
  function resolveStyleString(key, value, selected) {
631
- if (PAINT_KEYS.includes(key) && GRADIENT.test(value))
632
- return value;
633
- return resolveThemeColor(COLOR_KEY.test(key) ? cssColor(value) : value, selected);
634
+ let cache = resolvedStrings.get(selected);
635
+ if (!cache)
636
+ resolvedStrings.set(selected, cache = new Map);
637
+ const cacheKey = key + "\x00" + value;
638
+ let resolved = cache.get(cacheKey);
639
+ if (resolved === undefined) {
640
+ if (cache.size > 4096)
641
+ cache.clear();
642
+ resolved = PAINT_KEYS.includes(key) && GRADIENT.test(value) ? value : resolveThemeColor(COLOR_KEY.test(key) ? cssColor(value) : value, selected);
643
+ cache.set(cacheKey, resolved);
644
+ }
645
+ return resolved;
634
646
  }
635
647
  function resolveThemeStyle(style, selected) {
636
648
  const resolved = { ...style };
@@ -704,12 +716,13 @@ function Pressable(props) {
704
716
  }
705
717
  // packages/protocol/src/index.ts
706
718
  var NATIVE_ABI_VERSION = 5;
707
- var PROTOCOL_VERSION = 48;
719
+ var PROTOCOL_VERSION = 58;
708
720
 
709
721
  // packages/core/src/bridge/binding.ts
710
- import { dlopen } from "bun:ffi";
722
+ import { createRequire } from "module";
711
723
  function openLibrary(path) {
712
- return dlopen(path, {
724
+ const require2 = createRequire(import.meta.url);
725
+ const definitions = {
713
726
  tarve_abi_version: { args: [], returns: "u32" },
714
727
  tarve_start: { args: ["buffer", "u32"], returns: "i32" },
715
728
  tarve_send: { args: ["buffer", "u32"], returns: "i32" },
@@ -718,7 +731,22 @@ function openLibrary(path) {
718
731
  tarve_open_external: { args: ["buffer", "u32"], returns: "i32" },
719
732
  tarve_last_error: { args: ["buffer", "u32"], returns: "i32" },
720
733
  tarve_join: { args: [], returns: "i32" }
721
- });
734
+ };
735
+ if (process.versions.bun) {
736
+ const { dlopen } = require2("bun:ffi");
737
+ return dlopen(path, definitions);
738
+ }
739
+ const [major = 0, minor = 0] = (process.versions.node ?? "").split(".").map(Number);
740
+ if (major < 26 || major === 26 && minor < 10) {
741
+ throw new Error(`Tarve requires Bun or Node.js 26.10+ with node:ffi (found Node.js ${process.versions.node ?? "unknown"})`);
742
+ }
743
+ const { dlopen } = require2("node:ffi");
744
+ const signatures = Object.fromEntries(Object.entries(definitions).map(([name, signature]) => [name, {
745
+ arguments: signature.args.map((type) => type === "buffer" ? "buffer" : type === "u32" ? "uint32" : "int32"),
746
+ return: signature.returns === "u32" ? "uint32" : "int32"
747
+ }]));
748
+ const library = dlopen(path, signatures);
749
+ return { symbols: library.functions, close: () => library.lib.close() };
722
750
  }
723
751
 
724
752
  // packages/core/src/bridge/index.ts
@@ -951,6 +979,17 @@ function canonicalizeIntrinsicStyle(style) {
951
979
  result.background = result.backgroundColor;
952
980
  if (result.foreground === undefined && result.color !== undefined)
953
981
  result.foreground = result.color;
982
+ if (result.radius === undefined && result.borderRadius !== undefined)
983
+ result.radius = result.borderRadius;
984
+ delete result.borderRadius;
985
+ const edge = (value) => value === "flex-start" ? "start" : value === "flex-end" ? "end" : value === "space-between" ? "between" : value;
986
+ if (result.align === undefined && result.alignItems !== undefined)
987
+ result.align = edge(result.alignItems);
988
+ if (result.justify === undefined && result.justifyContent !== undefined)
989
+ result.justify = edge(result.justifyContent);
990
+ delete result.alignItems;
991
+ delete result.justifyContent;
992
+ delete result.objectFit;
954
993
  delete result.flexDirection;
955
994
  delete result.backgroundColor;
956
995
  delete result.color;
@@ -968,11 +1007,9 @@ function Text({ size, weight, color, style, ...props }) {
968
1007
  return jsx("text", {
969
1008
  ...props,
970
1009
  style: {
971
- fontFamily: theme.font.family,
972
- lineHeight: theme.font.lineHeight,
973
- fontSize: size ?? theme.font.size,
974
- fontWeight: weight ?? 400,
975
- foreground: color ?? theme.colors.foreground,
1010
+ ...size !== undefined ? { fontSize: size } : {},
1011
+ ...weight !== undefined ? { fontWeight: weight } : {},
1012
+ ...color !== undefined ? { foreground: color } : {},
976
1013
  ...canonicalStyle
977
1014
  }
978
1015
  });
@@ -1193,10 +1230,6 @@ function Markdown(props) {
1193
1230
  ...props,
1194
1231
  onMarkdownLink: (href) => props.onLinkClick ? props.onLinkClick(href) : openExternal(href),
1195
1232
  style: {
1196
- fontFamily: theme.font.family,
1197
- fontSize: theme.font.size,
1198
- lineHeight: theme.font.lineHeight,
1199
- foreground: theme.colors.foreground,
1200
1233
  mutedForeground: theme.colors.mutedForeground,
1201
1234
  taskMarkerColor: theme.colors.primary,
1202
1235
  taskMarkerCheckColor: theme.colors.primaryForeground,
@@ -1339,7 +1372,6 @@ function composedContent(child, foreground) {
1339
1372
  ...props,
1340
1373
  style: {
1341
1374
  fontSize: 14,
1342
- fontFamily: theme.font.family,
1343
1375
  lineHeight: theme.font.lineHeight,
1344
1376
  fontWeight: 500,
1345
1377
  foreground,
@@ -1360,7 +1392,6 @@ function Button({ variant = "default", size = "default", style, disabled, contro
1360
1392
  padding: { left: 14, right: 14 },
1361
1393
  radius: theme.radius.sm,
1362
1394
  fontSize: 14,
1363
- fontFamily: theme.font.family,
1364
1395
  lineHeight: theme.font.lineHeight,
1365
1396
  fontWeight: 500,
1366
1397
  userSelect: "none",
@@ -1469,13 +1500,22 @@ function dataUrlSource(value) {
1469
1500
  validateEncodedBytes(bytes);
1470
1501
  return { bytes, ...mediaType ? { mediaType } : {} };
1471
1502
  }
1503
+ var serializedSources = new WeakMap;
1472
1504
  function serializeImageSource(source) {
1505
+ if (typeof source === "object" && !(source instanceof Uint8Array)) {
1506
+ const cached = serializedSources.get(source);
1507
+ if (cached)
1508
+ return cached;
1509
+ const serialized = serializeImageSourceNow(source);
1510
+ serializedSources.set(source, serialized);
1511
+ return serialized;
1512
+ }
1513
+ return serializeImageSourceNow(source);
1514
+ }
1515
+ function serializeImageSourceNow(source) {
1473
1516
  if (typeof source === "string") {
1474
1517
  if (source.startsWith("data:"))
1475
- return serializeImageSource(dataUrlSource(source));
1476
- if (/^https?:\/\//i.test(source)) {
1477
- throw new TypeError("HTTP(S) Image sources must be loaded with await loadImageSource(url) before rendering");
1478
- }
1518
+ return serializeImageSourceNow(dataUrlSource(source));
1479
1519
  if (!source)
1480
1520
  throw new TypeError("Image src must not be empty");
1481
1521
  return { path: source };
@@ -1661,7 +1701,6 @@ function Input({ type = "text", value, style, ...props }) {
1661
1701
  placeholderColor: theme.colors.placeholder,
1662
1702
  selectionColor: theme.colors.selection,
1663
1703
  caretColor: theme.colors.foreground,
1664
- fontFamily: theme.font.family,
1665
1704
  lineHeight: theme.font.lineHeight,
1666
1705
  fontSize: theme.font.size,
1667
1706
  userSelect: "text",
@@ -1686,7 +1725,6 @@ function TextArea({ style, ...props }) {
1686
1725
  placeholderColor: theme.colors.placeholder,
1687
1726
  selectionColor: theme.colors.selection,
1688
1727
  caretColor: theme.colors.foreground,
1689
- fontFamily: theme.font.family,
1690
1728
  lineHeight: theme.font.lineHeight,
1691
1729
  fontSize: theme.font.size,
1692
1730
  userSelect: "text",
@@ -1695,7 +1733,12 @@ function TextArea({ style, ...props }) {
1695
1733
  });
1696
1734
  }
1697
1735
  // packages/core/src/components/titlebar.ts
1698
- function titleBarButton(action, child) {
1736
+ function translucent(color, alpha) {
1737
+ const hex = color.trim().replace(/^#/, "");
1738
+ const full = hex.length === 3 ? [...hex].map((c) => c + c).join("") : hex.slice(0, 6);
1739
+ return /^[0-9a-f]{6}$/i.test(full) ? `#${full}${Math.round(alpha).toString(16).padStart(2, "0")}` : color;
1740
+ }
1741
+ function titleBarButton(action, child, ink) {
1699
1742
  const close = action === "close";
1700
1743
  const label = action === "minimize" ? "Minimize window" : action === "toggleMaximize" ? "Maximize or restore window" : "Close window";
1701
1744
  return jsx(Pressable, {
@@ -1709,8 +1752,8 @@ function titleBarButton(action, child) {
1709
1752
  align: "center",
1710
1753
  justify: "center",
1711
1754
  background: "#00000000",
1712
- hover: { background: close ? theme.colors.windowCloseHover : theme.colors.muted },
1713
- active: { background: close ? theme.colors.windowCloseActive : theme.colors.border }
1755
+ hover: { background: close ? theme.colors.windowCloseHover : translucent(ink, 31) },
1756
+ active: { background: close ? theme.colors.windowCloseActive : translucent(ink, 51) }
1714
1757
  },
1715
1758
  children: child
1716
1759
  });
@@ -1725,18 +1768,17 @@ function TitleBar({
1725
1768
  style,
1726
1769
  ...props
1727
1770
  }) {
1728
- const minimizeIcon = jsx(View, {
1729
- style: { width: 10, height: 1, background: theme.colors.foreground }
1730
- });
1731
- const maximizeIcon = jsx(View, {
1732
- style: { width: 10, height: 10, borderWidth: 1, borderColor: theme.colors.foreground }
1733
- });
1771
+ const ink = typeof style?.foreground === "string" ? style.foreground : theme.colors.foreground;
1772
+ const glyph = (iconNode) => jsx(Icon, { iconNode, size: 12, strokeWidth: 2, color: ink });
1773
+ const minimizeIcon = glyph([["path", { d: "M3 12h18" }]]);
1774
+ const maximizeIcon = glyph([["rect", { x: 3, y: 3, width: 18, height: 18, rx: 2 }]]);
1775
+ const closeIcon = glyph([["path", { d: "M4 4l16 16M20 4 4 20" }]]);
1734
1776
  const controls = jsx(Row, {
1735
1777
  style: { height: "100%", shrink: 0 },
1736
1778
  children: [
1737
- showMinimize ? titleBarButton("minimize", minimizeIcon) : null,
1738
- showMaximize ? titleBarButton("toggleMaximize", maximizeIcon) : null,
1739
- showClose ? titleBarButton("close", jsx(Icon, { name: "x", size: 14 })) : null
1779
+ showMinimize ? titleBarButton("minimize", minimizeIcon, ink) : null,
1780
+ showMaximize ? titleBarButton("toggleMaximize", maximizeIcon, ink) : null,
1781
+ showClose ? titleBarButton("close", closeIcon, ink) : null
1740
1782
  ]
1741
1783
  });
1742
1784
  const content = children ?? (title ? jsx(Text, { size: 13, weight: 500, children: title }) : null);
@@ -2011,11 +2053,12 @@ function Separator({ orientation = "horizontal", style, ...props }) {
2011
2053
  }
2012
2054
  function Progress({ value, max = 100, label, style, ...props }) {
2013
2055
  const ratio = Number.isFinite(value) && Number.isFinite(max) && max > 0 ? Math.max(0, Math.min(value / max, 1)) : 0;
2056
+ const { foreground, ...track } = style ?? {};
2014
2057
  return jsx(View, {
2015
2058
  ...props,
2016
2059
  control: { role: "progress", label, value: ratio * max, min: 0, max },
2017
- style: { width: "100%", height: 8, radius: 4, background: c.secondary, ...style },
2018
- children: jsx(View, { style: { width: `${ratio * 100}%`, height: "100%", radius: 4, background: c.primary } })
2060
+ style: { width: "100%", height: 8, radius: 4, background: c.secondary, ...track },
2061
+ children: jsx(View, { style: { width: `${ratio * 100}%`, height: "100%", radius: track.radius ?? 4, background: foreground ?? c.primary } })
2019
2062
  });
2020
2063
  }
2021
2064
  function Tabs({ value, items, onValueChange, style, ...props }) {
@@ -2223,10 +2266,16 @@ function upperBoundPrefix(prefix, offset) {
2223
2266
  }
2224
2267
  return Math.min(low, prefix.length - 2);
2225
2268
  }
2269
+ var FILL_ESTIMATE = 800;
2270
+ var filledHeights = new WeakMap;
2271
+ var filling = false;
2272
+ function viewportStyle(style, height) {
2273
+ return filling ? { flex: 1, minHeight: 0, ...style } : { ...style, height, shrink: 0 };
2274
+ }
2226
2275
  function fixedVirtualList({
2227
2276
  items,
2228
2277
  itemHeight,
2229
- height,
2278
+ height = FILL_ESTIMATE,
2230
2279
  offset,
2231
2280
  overscan = 2,
2232
2281
  keyForItem,
@@ -2254,7 +2303,7 @@ function fixedVirtualList({
2254
2303
  ...props,
2255
2304
  onScroll,
2256
2305
  control: { role: "virtualList", value: scroll },
2257
- style: { ...style, height, shrink: 0 },
2306
+ style: viewportStyle(style, height),
2258
2307
  children: jsx(Column, { style: { width: "100%" }, children: [
2259
2308
  start > 0 ? jsx(Row, { style: { height: start * itemHeight, shrink: 0 } }, "before") : null,
2260
2309
  ...rows,
@@ -2266,7 +2315,7 @@ function variableVirtualList({
2266
2315
  id,
2267
2316
  items,
2268
2317
  estimatedItemHeight,
2269
- height,
2318
+ height = FILL_ESTIMATE,
2270
2319
  offset,
2271
2320
  overscan = 2,
2272
2321
  keyForItem,
@@ -2313,7 +2362,7 @@ function variableVirtualList({
2313
2362
  state.lastFollowTail = followTail;
2314
2363
  const requestedIndex = state.scrollRequest && items.length > 0 ? Math.min(state.scrollRequest.index, items.length - 1) : undefined;
2315
2364
  const requestedOffset = requestedIndex !== undefined ? Math.max(0, Math.min(prefix[requestedIndex] + state.scrollRequest.offset, max)) : undefined;
2316
- if (requestedOffset !== undefined) {
2365
+ if (requestedOffset !== undefined && !state.scrollRequest.smooth) {
2317
2366
  state.effectiveOffset = requestedOffset;
2318
2367
  } else if (followTail && state.followingTail) {
2319
2368
  state.effectiveOffset = max;
@@ -2385,14 +2434,15 @@ function variableVirtualList({
2385
2434
  rememberHeight(state, measurement.key, measurement.height);
2386
2435
  }
2387
2436
  };
2388
- const onVirtualListScrollToItem = (index, itemOffset) => {
2437
+ const onVirtualListScrollToItem = (index, itemOffset, smooth = false) => {
2389
2438
  if (!Number.isInteger(index) || index < 0 || !Number.isFinite(itemOffset))
2390
2439
  return;
2391
2440
  state.followingTail = false;
2392
2441
  state.scrollRequest = {
2393
2442
  generation: ++store.nextScrollGeneration,
2394
2443
  index,
2395
- offset: itemOffset
2444
+ offset: itemOffset,
2445
+ smooth
2396
2446
  };
2397
2447
  };
2398
2448
  const onVirtualListFocus = (key) => {
@@ -2422,9 +2472,9 @@ function variableVirtualList({
2422
2472
  ...retainedKey === undefined ? {} : { retainedKey },
2423
2473
  alignment,
2424
2474
  followTail,
2425
- ...requestedOffset !== undefined && state.scrollRequest ? { scrollRequest: { generation: state.scrollRequest.generation, offset: requestedOffset } } : {}
2475
+ ...requestedOffset !== undefined && state.scrollRequest ? { scrollRequest: { generation: state.scrollRequest.generation, offset: requestedOffset, ...state.scrollRequest.smooth ? { smooth: true } : {} } } : {}
2426
2476
  },
2427
- style: { ...style, height, shrink: 0 },
2477
+ style: viewportStyle(style, height),
2428
2478
  children: jsx(Column, { style: { width: "100%" }, children: [
2429
2479
  start > 0 ? jsx(Row, { style: { height: prefix[start], shrink: 0 } }, "before") : null,
2430
2480
  ...rows,
@@ -2439,7 +2489,7 @@ function windowedVariableVirtualList({
2439
2489
  itemCount,
2440
2490
  windowStart,
2441
2491
  estimatedItemHeight,
2442
- height,
2492
+ height = FILL_ESTIMATE,
2443
2493
  offset,
2444
2494
  keyForItem,
2445
2495
  renderItem,
@@ -2520,6 +2570,8 @@ function windowedVariableVirtualList({
2520
2570
  logicalTop += measured - estimatedItemHeight;
2521
2571
  }
2522
2572
  requestedOffset = Math.max(0, Math.min(logicalTop + state.scrollRequest.offset, max));
2573
+ }
2574
+ if (requestedOffset !== undefined && !state.scrollRequest.smooth) {
2523
2575
  state.effectiveOffset = requestedOffset;
2524
2576
  } else if (followTail && state.followingTail) {
2525
2577
  state.effectiveOffset = max;
@@ -2590,14 +2642,15 @@ function windowedVariableVirtualList({
2590
2642
  rememberHeight(state, measurement.key, measurement.height, windowStart + localIndex);
2591
2643
  }
2592
2644
  };
2593
- const onVirtualListScrollToItem = (index, itemOffset) => {
2645
+ const onVirtualListScrollToItem = (index, itemOffset, smooth = false) => {
2594
2646
  if (!Number.isInteger(index) || index < 0 || !Number.isFinite(itemOffset))
2595
2647
  return;
2596
2648
  state.followingTail = false;
2597
2649
  state.scrollRequest = {
2598
2650
  generation: ++store.nextScrollGeneration,
2599
2651
  index,
2600
- offset: itemOffset
2652
+ offset: itemOffset,
2653
+ smooth
2601
2654
  };
2602
2655
  };
2603
2656
  const onVirtualListFocus = (key) => {
@@ -2629,9 +2682,9 @@ function windowedVariableVirtualList({
2629
2682
  ...retainedKey === undefined ? {} : { retainedKey },
2630
2683
  alignment,
2631
2684
  followTail,
2632
- ...requestedOffset !== undefined && state.scrollRequest ? { scrollRequest: { generation: state.scrollRequest.generation, offset: requestedOffset } } : {}
2685
+ ...requestedOffset !== undefined && state.scrollRequest ? { scrollRequest: { generation: state.scrollRequest.generation, offset: requestedOffset, ...state.scrollRequest.smooth ? { smooth: true } : {} } } : {}
2633
2686
  },
2634
- style: { ...style, height, shrink: 0 },
2687
+ style: viewportStyle(style, height),
2635
2688
  children: jsx(Column, { style: { width: "100%" }, children: [
2636
2689
  windowStart > 0 ? jsx(Row, { style: { height: before, shrink: 0 } }, "before") : null,
2637
2690
  ...rows,
@@ -2641,10 +2694,49 @@ function windowedVariableVirtualList({
2641
2694
  });
2642
2695
  }
2643
2696
  function VirtualList(props) {
2697
+ if (props.height === undefined) {
2698
+ if (!props.id)
2699
+ throw new TypeError("VirtualList without a height needs an id to remember its measured height");
2700
+ let heights = filledHeights.get(currentRenderScope());
2701
+ if (!heights)
2702
+ filledHeights.set(currentRenderScope(), heights = new Map);
2703
+ const id = props.id;
2704
+ const store = heights;
2705
+ const onSize = props.onSize;
2706
+ const measured = { ...props, height: store.get(id) ?? FILL_ESTIMATE, onSize: (size) => {
2707
+ if (size.height > 0)
2708
+ store.set(id, size.height);
2709
+ onSize?.(size);
2710
+ } };
2711
+ filling = true;
2712
+ try {
2713
+ return VirtualList(measured);
2714
+ } finally {
2715
+ filling = false;
2716
+ }
2717
+ }
2644
2718
  if ("itemCount" in props)
2645
2719
  return windowedVariableVirtualList(props);
2646
2720
  return "estimatedItemHeight" in props ? variableVirtualList(props) : fixedVirtualList(props);
2647
2721
  }
2722
+ // packages/core/src/memo.ts
2723
+ var MEMO = Symbol.for("tarve.memo");
2724
+ function shallowEqual(previous, next) {
2725
+ if (previous === next)
2726
+ return true;
2727
+ const a = previous;
2728
+ const b = next;
2729
+ const keys = Object.keys(a);
2730
+ if (keys.length !== Object.keys(b).length)
2731
+ return false;
2732
+ return keys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
2733
+ }
2734
+ function memo(render, equal = shallowEqual) {
2735
+ const component = (props) => render(props);
2736
+ component[MEMO] = { render, equal };
2737
+ Object.defineProperty(component, "name", { value: `memo(${render.name || "Component"})` });
2738
+ return component;
2739
+ }
2648
2740
  // packages/core/src/motion.ts
2649
2741
  var stores = new WeakMap;
2650
2742
  var properties = [
@@ -3054,9 +3146,26 @@ function includesQuery(label, value, keywords, query) {
3054
3146
  return true;
3055
3147
  return [label, value, ...keywords ?? []].some((part) => part.toLocaleLowerCase().includes(needle));
3056
3148
  }
3149
+ var TOOLTIP_MAX_WIDTH = 320;
3150
+ var hoveredTooltip = null;
3151
+ function tooltipLane(side) {
3152
+ const gap = 6;
3153
+ const base = { position: "absolute", zIndex: POPUP_Z_INDEX + 1, pointerEvents: "auto" };
3154
+ switch (side) {
3155
+ case "top":
3156
+ return { ...base, bottom: "100%", left: 0, right: -TOOLTIP_MAX_WIDTH, align: "start", margin: { bottom: gap } };
3157
+ case "right":
3158
+ return { ...base, top: 0, left: "100%", right: -TOOLTIP_MAX_WIDTH - gap, align: "start", margin: { left: gap } };
3159
+ case "left":
3160
+ return { ...base, top: 0, right: "100%", left: -TOOLTIP_MAX_WIDTH - gap, align: "end", margin: { right: gap } };
3161
+ case "bottom":
3162
+ default:
3163
+ return { ...base, top: "100%", left: 0, right: -TOOLTIP_MAX_WIDTH, align: "start", margin: { top: gap } };
3164
+ }
3165
+ }
3057
3166
  function Tooltip({
3058
3167
  id,
3059
- open,
3168
+ open: controlledOpen,
3060
3169
  trigger,
3061
3170
  content,
3062
3171
  side = "top",
@@ -3065,6 +3174,7 @@ function Tooltip({
3065
3174
  contentStyle,
3066
3175
  style
3067
3176
  }) {
3177
+ const open = controlledOpen ?? hoveredTooltip === id;
3068
3178
  const tooltipContent = typeof content === "string" || typeof content === "number" ? jsx(Text, { size: 12, color: c2.background, children: content }) : content;
3069
3179
  return jsx(View, {
3070
3180
  id,
@@ -3074,19 +3184,36 @@ function Tooltip({
3074
3184
  id: `${id}-trigger`,
3075
3185
  focusable: false,
3076
3186
  fallbackControl: { role: "button", label: triggerLabel(label, trigger) },
3077
- onHover: (hovered) => onOpenChange?.(hovered)
3187
+ onHover: (hovered) => {
3188
+ if (controlledOpen === undefined)
3189
+ hoveredTooltip = hovered ? id : hoveredTooltip === id ? null : hoveredTooltip;
3190
+ onOpenChange?.(hovered);
3191
+ }
3078
3192
  }),
3079
3193
  open ? jsx(View, {
3080
- id: `${id}-content`,
3194
+ id: `${id}-lane`,
3081
3195
  portal: true,
3082
- style: popupSurface(side, {
3083
- minWidth: 0,
3084
- padding: { left: 8, right: 8, top: 5, bottom: 5 },
3085
- background: c2.foreground,
3086
- foreground: c2.background,
3087
- ...contentStyle
3088
- }),
3089
- children: tooltipContent
3196
+ style: tooltipLane(side),
3197
+ children: jsx(View, {
3198
+ id: `${id}-content`,
3199
+ style: {
3200
+ ...popupSurface(side, {
3201
+ minWidth: 0,
3202
+ maxWidth: TOOLTIP_MAX_WIDTH,
3203
+ padding: { left: 8, right: 8, top: 5, bottom: 5 },
3204
+ background: c2.foreground,
3205
+ foreground: c2.background,
3206
+ ...contentStyle
3207
+ }),
3208
+ position: "relative",
3209
+ top: undefined,
3210
+ right: undefined,
3211
+ bottom: undefined,
3212
+ left: undefined,
3213
+ margin: undefined
3214
+ },
3215
+ children: tooltipContent
3216
+ })
3090
3217
  }) : null
3091
3218
  ]
3092
3219
  });
@@ -3365,7 +3492,14 @@ function Combobox({
3365
3492
  placeholder: searchPlaceholder,
3366
3493
  onChange: onQueryChange,
3367
3494
  rovingGroup: true,
3368
- style: { flex: 1, minWidth: 0, borderWidth: 0, background: "#00000000" }
3495
+ style: {
3496
+ flex: 1,
3497
+ minWidth: 0,
3498
+ borderWidth: 0,
3499
+ background: "#00000000",
3500
+ focus: { outlineWidth: 0 },
3501
+ focusVisible: { outlineWidth: 0 }
3502
+ }
3369
3503
  })
3370
3504
  ]
3371
3505
  }),
@@ -3498,7 +3632,14 @@ function Command({
3498
3632
  placeholder,
3499
3633
  onChange: onQueryChange,
3500
3634
  rovingGroup: true,
3501
- style: { flex: 1, minWidth: 0, borderWidth: 0, background: "#00000000" }
3635
+ style: {
3636
+ flex: 1,
3637
+ minWidth: 0,
3638
+ borderWidth: 0,
3639
+ background: "#00000000",
3640
+ focus: { outlineWidth: 0 },
3641
+ focusVisible: { outlineWidth: 0 }
3642
+ }
3502
3643
  })
3503
3644
  ]
3504
3645
  }),
@@ -3506,7 +3647,7 @@ function Command({
3506
3647
  id: `${id}-results`,
3507
3648
  gap: 2,
3508
3649
  style: {
3509
- height: visible.length === 0 ? 46 : boundedHeight(visible.length, 36, COMMAND_MAX_HEIGHT, groups.size * 28 + 8),
3650
+ height: visible.length === 0 ? 46 : boundedHeight(visible.length, 36, COMMAND_MAX_HEIGHT, groups.size * 32 + 8),
3510
3651
  padding: 4
3511
3652
  },
3512
3653
  children: visible.length === 0 ? jsx(Text, { id: `${id}-empty`, size: 13, color: c2.mutedForeground, style: { padding: 10 }, children: emptyText }) : resultNodes
@@ -3577,31 +3718,18 @@ function Skeleton({ width = "100%", height = 16, radius = theme.radius.sm, style
3577
3718
  });
3578
3719
  }
3579
3720
  function Spinner({ size = 18, label = "Loading", style, ...props }) {
3580
- const dot = Math.max(3, Math.round(size * 0.22));
3581
- return jsx(View, {
3721
+ return jsx(Svg, {
3582
3722
  ...props,
3583
3723
  control: { role: "progress", label },
3584
- style: {
3585
- position: "relative",
3586
- width: size,
3587
- height: size,
3588
- radius: size / 2,
3589
- borderWidth: 2,
3590
- borderColor: c3.border,
3591
- shrink: 0,
3592
- ...style
3593
- },
3594
- children: jsx(View, {
3595
- style: {
3596
- position: "absolute",
3597
- top: -1,
3598
- left: (size - dot) / 2,
3599
- width: dot,
3600
- height: dot,
3601
- radius: dot / 2,
3602
- background: c3.foreground
3603
- }
3604
- })
3724
+ size,
3725
+ viewBox: "0 0 24 24",
3726
+ strokeWidth: 2.5,
3727
+ color: c3.foreground,
3728
+ style: { spin: 800, ...style },
3729
+ children: [
3730
+ jsx(Circle, { cx: 12, cy: 12, r: 9, opacity: 0.2 }),
3731
+ jsx(Path, { d: "M12 3a9 9 0 0 1 9 9" })
3732
+ ]
3605
3733
  });
3606
3734
  }
3607
3735
  function Avatar({ src, fallback = "?", size = 40, fit = "cover", style, id, ...props }) {
@@ -4477,10 +4605,15 @@ function HoverCard({ open, trigger, side = "bottom", width = 280, onOpenChange,
4477
4605
  // packages/core/src/form-controls.ts
4478
4606
  var c4 = theme.colors;
4479
4607
  var transparent2 = "#00000000";
4608
+ function tintIcon(icon, color) {
4609
+ if (!icon || typeof icon !== "object" || Array.isArray(icon) || icon.props.color !== undefined)
4610
+ return icon;
4611
+ return { ...icon, props: { ...icon.props, color } };
4612
+ }
4480
4613
  function Alert({ title, description, variant = "default", icon, children, style, ...props }) {
4481
4614
  const palette = {
4482
4615
  default: { border: c4.border, background: c4.card, foreground: c4.foreground },
4483
- destructive: { border: c4.destructive, background: c4.card, foreground: c4.destructive },
4616
+ destructive: { border: c4.destructive, background: c4.card, foreground: c4.destructiveText },
4484
4617
  success: { border: c4.success, background: c4.successMuted, foreground: c4.success }
4485
4618
  };
4486
4619
  const selected = palette[variant];
@@ -4499,7 +4632,7 @@ function Alert({ title, description, variant = "default", icon, children, style,
4499
4632
  ...style
4500
4633
  },
4501
4634
  children: [
4502
- icon,
4635
+ tintIcon(icon, selected.foreground),
4503
4636
  jsx(Column, { gap: 3, flex: 1, children: [
4504
4637
  title ? jsx(Text, { weight: 600, color: selected.foreground, children: title }) : null,
4505
4638
  description ? jsx(Text, { size: 13, color: variant === "default" ? c4.mutedForeground : selected.foreground, children: description }) : null,
@@ -4595,10 +4728,26 @@ function Field({ label, description, error, required, disabled, children, style,
4595
4728
  children: [
4596
4729
  label ? jsx(Label, { ...id ? { id: `${id}-label` } : {}, required, disabled, children: label }) : null,
4597
4730
  disableFormChild(children, disabled),
4598
- error ? jsx(Text, { ...id ? { id: `${id}-error` } : {}, control: { role: "alert", label: error }, size: 12, color: c4.destructive, children: error }) : description ? jsx(Text, { ...id ? { id: `${id}-description` } : {}, size: 12, color: c4.mutedForeground, children: description }) : null
4731
+ description ? jsx(Text, { ...id ? { id: `${id}-description` } : {}, size: 12, color: c4.mutedForeground, children: description }) : null,
4732
+ error ? jsx(Text, { ...id ? { id: `${id}-error` } : {}, control: { role: "alert", label: error }, size: 12, color: c4.destructiveText, children: error }) : null
4599
4733
  ]
4600
4734
  });
4601
4735
  }
4736
+ function groupedInput(child) {
4737
+ if (Array.isArray(child))
4738
+ return child.map(groupedInput);
4739
+ if (!child || typeof child !== "object" || child.type !== Input)
4740
+ return child;
4741
+ return { ...child, props: { ...child.props, style: {
4742
+ borderWidth: 0,
4743
+ background: transparent2,
4744
+ padding: { left: 0, right: 0 },
4745
+ minWidth: 0,
4746
+ focus: { outlineWidth: 0 },
4747
+ focusVisible: { outlineWidth: 0 },
4748
+ ...child.props.style
4749
+ } } };
4750
+ }
4602
4751
  function InputGroup({ prefix, suffix, disabled, children, style, ...props }) {
4603
4752
  return jsx(Row, {
4604
4753
  ...props,
@@ -4613,9 +4762,12 @@ function InputGroup({ prefix, suffix, disabled, children, style, ...props }) {
4613
4762
  borderColor: c4.border,
4614
4763
  radius: theme.radius.sm,
4615
4764
  background: disabled ? c4.disabled : c4.input,
4765
+ pointerEvents: "delegate",
4766
+ focus: { borderColor: c4.ring },
4767
+ focusVisible: { borderColor: c4.ring, outlineColor: c4.ring, outlineWidth: 2, outlineOffset: 2, outlineStyle: "solid" },
4616
4768
  ...style
4617
4769
  },
4618
- children: [prefix, jsx(View, { flex: 1, children: disableFormChild(children, disabled) }), suffix]
4770
+ children: [prefix, jsx(View, { flex: 1, children: disableFormChild(groupedInput(children), disabled) }), suffix]
4619
4771
  });
4620
4772
  }
4621
4773
  function matchesInputPattern(pattern, char) {
@@ -5055,6 +5207,7 @@ function NavigationMenu({ items, value, openValue, onValueChange, onOpenValueCha
5055
5207
  children: items.map((item) => {
5056
5208
  const open = openValue === item.value;
5057
5209
  const direct = !item.links || item.links.length === 0;
5210
+ const current = direct ? value === item.value : item.links.some((link) => link.value === value);
5058
5211
  return jsx(Column, {
5059
5212
  style: { position: "relative" },
5060
5213
  children: [
@@ -5068,13 +5221,19 @@ function NavigationMenu({ items, value, openValue, onValueChange, onOpenValueCha
5068
5221
  } : () => onOpenValueChange?.(open ? undefined : item.value),
5069
5222
  style: {
5070
5223
  minHeight: 36,
5071
- padding: { left: 12, right: 12 },
5224
+ padding: { left: 12, right: direct ? 12 : 8 },
5225
+ direction: "row",
5226
+ gap: 4,
5072
5227
  align: "center",
5073
5228
  justify: "center",
5074
- background: direct && value === item.value ? c5.muted : transparent3,
5229
+ radius: theme.radius.sm,
5230
+ background: open || current ? c5.muted : transparent3,
5075
5231
  hover: { background: c5.muted }
5076
5232
  },
5077
- children: jsx(Text, { weight: 500, color: item.disabled ? c5.disabledForeground : c5.foreground, children: item.label })
5233
+ children: [
5234
+ jsx(Text, { weight: 500, color: item.disabled ? c5.disabledForeground : c5.foreground, children: item.label }),
5235
+ direct ? null : jsx(Icon, { name: open ? "chevron-up" : "chevron-down", size: 14, color: c5.mutedForeground })
5236
+ ]
5078
5237
  }),
5079
5238
  open && !direct ? jsx(Column, {
5080
5239
  ...id ? { id: `${id}-content-${item.value}` } : {},
@@ -5087,6 +5246,7 @@ function NavigationMenu({ items, value, openValue, onValueChange, onOpenValueCha
5087
5246
  position: "absolute",
5088
5247
  top: "100%",
5089
5248
  left: 0,
5249
+ margin: { top: 6 },
5090
5250
  minWidth: 240,
5091
5251
  padding: 6,
5092
5252
  background: c5.card,
@@ -5104,7 +5264,13 @@ function NavigationMenu({ items, value, openValue, onValueChange, onOpenValueCha
5104
5264
  onValueChange?.(link.value);
5105
5265
  onOpenValueChange?.(undefined);
5106
5266
  },
5107
- style: { minHeight: 40, padding: 8, hover: { background: c5.muted }, background: value === link.value ? c5.muted : transparent3 },
5267
+ style: {
5268
+ minHeight: 40,
5269
+ padding: 8,
5270
+ radius: theme.radius.sm,
5271
+ hover: { background: c5.muted },
5272
+ background: value === link.value ? c5.muted : transparent3
5273
+ },
5108
5274
  children: jsx(Column, { gap: 2, children: [
5109
5275
  jsx(Text, { weight: 500, children: link.label }),
5110
5276
  link.description ? jsx(Text, { size: 12, color: c5.mutedForeground, children: link.description }) : null
@@ -5381,16 +5547,16 @@ function Attachment({
5381
5547
  ...style
5382
5548
  },
5383
5549
  children: [
5384
- jsx(Row, { gap: 8, children: [
5550
+ jsx(Row, { gap: 8, justify: "between", children: [
5385
5551
  leading,
5386
- jsx(Column, { gap: 2, flex: 1, children: [
5552
+ jsx(Column, { gap: 2, style: { shrink: 1, minWidth: 0 }, children: [
5387
5553
  jsx(Text, { weight: 500, color: statusColor, children: name }),
5388
5554
  size ? jsx(Text, { size: 11, color: c6.mutedForeground, children: size }) : null
5389
5555
  ] }),
5390
5556
  onRemove ? jsx(Button, { ...id ? { id: `${id}-remove` } : {}, variant: "ghost", size: "sm", onClick: onRemove, children: removeLabel }) : null
5391
5557
  ] }),
5392
5558
  status === "uploading" ? jsx(Progress, { ...id ? { id: `${id}-progress` } : {}, value: progress, max: 100, label: `${name} upload progress` }) : null,
5393
- status === "error" ? jsx(Text, { ...id ? { id: `${id}-error` } : {}, size: 11, color: c6.destructive, children: "Upload failed" }) : null
5559
+ status === "error" ? jsx(Text, { ...id ? { id: `${id}-error` } : {}, size: 11, color: c6.destructiveText, children: "Upload failed" }) : null
5394
5560
  ]
5395
5561
  });
5396
5562
  }
@@ -5473,7 +5639,7 @@ function Message({
5473
5639
  ...props,
5474
5640
  ...id ? { id } : {},
5475
5641
  gap: 8,
5476
- align: "end",
5642
+ align: "start",
5477
5643
  justify: side === "outgoing" ? "end" : "start",
5478
5644
  style: { width: "100%", ...style },
5479
5645
  children: side === "outgoing" ? [body, avatar] : [avatar, body]
@@ -5709,7 +5875,8 @@ function DataGrid({
5709
5875
  typeof column.header === "string" || typeof column.header === "number" ? jsx(Text, { size: 12, weight: 600, color: c7.mutedForeground, children: column.header }) : column.header,
5710
5876
  active ? jsx(Text, { size: 11, color: c7.mutedForeground, children: sort.direction === "asc" ? "\u2191" : "\u2193" }) : null
5711
5877
  ];
5712
- const common = { style: { width: column.width, flex: column.width === undefined ? 1 : undefined, minWidth: 0, height: "100%", padding: { left: 10, right: 10 }, direction: "row", align: column.align ?? "start", gap: 5 } };
5878
+ const justify = column.align === "center" || column.align === "end" ? column.align : "start";
5879
+ const common = { style: { width: column.width, flex: column.width === undefined ? 1 : undefined, minWidth: 0, height: "100%", padding: { left: 10, right: 10 }, direction: "row", align: "center", justify, gap: 5 } };
5713
5880
  if (!column.sortable)
5714
5881
  return jsx(Row, { ...common, children: content }, column.key);
5715
5882
  return jsx(Pressable, {
@@ -5723,6 +5890,7 @@ function DataGrid({
5723
5890
  ...common,
5724
5891
  style: {
5725
5892
  ...common.style,
5893
+ radius: 0,
5726
5894
  background: "#00000000",
5727
5895
  hover: { background: c7.muted },
5728
5896
  focus: { outlineWidth: 0, outlineStyle: "none" }
@@ -5757,7 +5925,7 @@ function DataGrid({
5757
5925
  toggleSelection(entry);
5758
5926
  onRowActivate?.(entry.row, entry.sourceIndex);
5759
5927
  },
5760
- style: { width: "100%", height: rowHeight, shrink: 0, direction: "row", background: selected ? c7.muted : "#00000000", hover: { background: c7.muted }, borderWidth: { bottom: 1 }, borderColor: c7.border },
5928
+ style: { width: "100%", height: rowHeight, shrink: 0, direction: "row", radius: 0, background: selected ? c7.muted : "#00000000", hover: { background: c7.muted }, borderWidth: { bottom: 1 }, borderColor: c7.border },
5761
5929
  children: columns.map((column) => jsx(View, {
5762
5930
  style: { width: column.width, flex: column.width === undefined ? 1 : undefined, minWidth: 0, height: "100%", padding: { left: 10, right: 10 }, align: column.align ?? "start", justify: "center" },
5763
5931
  children: gridCell(column, entry)
@@ -5937,11 +6105,1294 @@ function createTextSearchController() {
5937
6105
  }
5938
6106
  };
5939
6107
  }
6108
+ // packages/core/src/app.ts
6109
+ import { readFileSync as readFileSync3 } from "fs";
6110
+
6111
+ // packages/core/src/media-element.ts
6112
+ var states = new Map;
6113
+ function mediaState(id) {
6114
+ return states.get(id) ?? { paused: true, time: 0, duration: null, ended: false };
6115
+ }
6116
+ var ACTIVE_APP = Symbol.for("tarve.activeApp");
6117
+ function controller(id) {
6118
+ return globalThis[ACTIVE_APP]?.media(id);
6119
+ }
6120
+ function clock(seconds) {
6121
+ if (seconds === null || !Number.isFinite(seconds))
6122
+ return "--:--";
6123
+ const total = Math.max(0, Math.floor(seconds));
6124
+ const h = Math.floor(total / 3600), m = Math.floor(total % 3600 / 60), s = total % 60;
6125
+ return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
6126
+ }
6127
+ function mediaRequest(props) {
6128
+ return {
6129
+ ...props.src ? { src: props.src } : {},
6130
+ loop: props.loop === true,
6131
+ muted: props.muted === true,
6132
+ volume: Math.min(1, Math.max(0, props.volume ?? 1)),
6133
+ autoPlay: props.autoPlay === true,
6134
+ handlers: props
6135
+ };
6136
+ }
6137
+ function expandAudio(props, id) {
6138
+ const style = canonicalizeIntrinsicStyle(props.style);
6139
+ if (!props.controls)
6140
+ return View({ id, style: { display: "none" } });
6141
+ const state = mediaState(id);
6142
+ const label = props.ariaLabel ?? "Audio";
6143
+ return Row({
6144
+ id,
6145
+ gap: 8,
6146
+ align: "center",
6147
+ control: { role: "group", label },
6148
+ style: { width: 300, height: 54, padding: { left: 10, right: 10 }, radius: 27, background: theme.colors.muted, ...style },
6149
+ children: [
6150
+ Button({
6151
+ id: `${id}-play`,
6152
+ size: "sm",
6153
+ variant: "ghost",
6154
+ control: { role: "button", label: state.paused ? "Play" : "Pause" },
6155
+ onClick: () => mediaState(id).paused ? controller(id)?.play() : controller(id)?.pause(),
6156
+ children: state.paused ? "\u25B6" : "\u275A\u275A"
6157
+ }),
6158
+ Text({ id: `${id}-time`, size: 12, style: { fontFamily: "monospace", shrink: 0 }, children: `${clock(state.time)} / ${clock(state.duration)}` }),
6159
+ Slider({
6160
+ id: `${id}-seek`,
6161
+ label: `${label} position`,
6162
+ value: Math.min(state.time, state.duration ?? state.time),
6163
+ min: 0,
6164
+ max: Math.max(state.duration ?? 0, 0.001),
6165
+ step: 0.1,
6166
+ style: { flex: 1, minWidth: 40 },
6167
+ onValueChange: (value) => controller(id)?.seek(value)
6168
+ }),
6169
+ Button({
6170
+ id: `${id}-mute`,
6171
+ size: "sm",
6172
+ variant: "ghost",
6173
+ control: { role: "button", label: props.muted ? "Unmute" : "Mute" },
6174
+ onClick: () => controller(id)?.setMuted(!props.muted),
6175
+ children: props.muted ? "\uD83D\uDD07" : "\uD83D\uDD0A"
6176
+ })
6177
+ ]
6178
+ });
6179
+ }
6180
+ function applyMediaEvent(event, request) {
6181
+ const previous = mediaState(event.id);
6182
+ const next = { ...previous, time: event.time ?? previous.time, duration: event.duration ?? previous.duration, paused: event.paused ?? previous.paused };
6183
+ if (event.event === "ended") {
6184
+ next.ended = true;
6185
+ next.paused = true;
6186
+ }
6187
+ if (event.event === "play")
6188
+ next.ended = false;
6189
+ if (event.event === "error")
6190
+ next.error = event.message;
6191
+ states.set(event.id, next);
6192
+ const info = { currentTime: next.time, duration: next.duration, paused: next.paused };
6193
+ const h = request?.handlers;
6194
+ switch (event.event) {
6195
+ case "loadedmetadata":
6196
+ return h?.onLoadedMetadata && (() => h.onLoadedMetadata(info));
6197
+ case "play":
6198
+ return h?.onPlay && (() => h.onPlay(info));
6199
+ case "pause":
6200
+ return h?.onPause && (() => h.onPause(info));
6201
+ case "timeupdate":
6202
+ return h?.onTimeUpdate && (() => h.onTimeUpdate(info));
6203
+ case "seeked":
6204
+ return h?.onSeeked && (() => h.onSeeked(info));
6205
+ case "ended":
6206
+ return h?.onEnded && (() => h.onEnded(info));
6207
+ case "error":
6208
+ return h?.onError && (() => h.onError(event.message ?? "media error"));
6209
+ }
6210
+ return;
6211
+ }
6212
+
5940
6213
  // packages/core/src/reconciler.ts
5941
6214
  import { nativeAssetPath } from "#tarve/assets";
6215
+
6216
+ // packages/core/src/inline-text.ts
6217
+ var INLINE_TAGS = {
6218
+ span: {},
6219
+ strong: { fontWeight: "bolder" },
6220
+ b: { fontWeight: "bolder" },
6221
+ em: { fontStyle: "italic" },
6222
+ i: { fontStyle: "italic" },
6223
+ cite: { fontStyle: "italic" },
6224
+ var: { fontStyle: "italic" },
6225
+ dfn: { fontStyle: "italic" },
6226
+ u: { textDecoration: "underline" },
6227
+ ins: { textDecoration: "underline" },
6228
+ s: { textDecoration: "line-through" },
6229
+ del: { textDecoration: "line-through" },
6230
+ code: { fontFamily: "monospace" },
6231
+ kbd: { fontFamily: "monospace" },
6232
+ samp: { fontFamily: "monospace" },
6233
+ mark: { background: "#ffff00", foreground: "#000000" },
6234
+ small: { fontSize: "smaller" },
6235
+ sub: { verticalAlign: "sub", fontSize: "smaller" },
6236
+ sup: { verticalAlign: "super", fontSize: "smaller" },
6237
+ a: { textDecoration: "underline" },
6238
+ abbr: {}
6239
+ };
6240
+ var INLINE_TAG_NAMES = new Set([...Object.keys(INLINE_TAGS), "br"]);
6241
+ var RUN_KEYS = ["fontWeight", "fontStyle", "fontSize", "fontFamily", "foreground", "background", "textDecoration", "letterSpacing", "wordSpacing", "fontVariantNumeric", "fontFeatureSettings", "textTransform", "baselineShift", "textDecorationStyle"];
6242
+ function pick(style) {
6243
+ const out = {};
6244
+ if (!style)
6245
+ return out;
6246
+ for (const key of RUN_KEYS)
6247
+ if (style[key] !== undefined)
6248
+ out[key] = style[key];
6249
+ return out;
6250
+ }
6251
+ function computeStyle(parent, own) {
6252
+ const next = { ...parent, ...own };
6253
+ if (own.fontWeight === "bolder") {
6254
+ const weight = Number(parent.fontWeight ?? 400);
6255
+ next.fontWeight = weight < 350 ? 400 : weight < 550 ? 700 : 900;
6256
+ } else if (own.fontWeight === "lighter") {
6257
+ const weight = Number(parent.fontWeight ?? 400);
6258
+ next.fontWeight = weight < 550 ? 100 : weight < 750 ? 400 : 700;
6259
+ }
6260
+ if (own.verticalAlign === "super" || own.verticalAlign === "sub") {
6261
+ const size = Number(parent.fontSize ?? 14);
6262
+ const shift = own.verticalAlign === "super" ? size / 3 + 1 : -(size / 5 + 1);
6263
+ next.baselineShift = Math.round((Number(parent.baselineShift ?? 0) + shift) * 100) / 100;
6264
+ }
6265
+ delete next.verticalAlign;
6266
+ if (own.fontSize === "smaller")
6267
+ next.fontSize = Number(parent.fontSize ?? 14) / 1.2;
6268
+ else if (own.fontSize === "larger")
6269
+ next.fontSize = Number(parent.fontSize ?? 14) * 1.2;
6270
+ if (own.textDecoration !== undefined && parent.textDecoration && parent.textDecoration !== "none" && own.textDecoration !== "none") {
6271
+ const lines = new Set(`${parent.textDecoration} ${own.textDecoration}`.split(/\s+/));
6272
+ next.textDecoration = [...lines].join(" ");
6273
+ }
6274
+ return next;
6275
+ }
6276
+ function transformText(text, transform, wordStart) {
6277
+ if (transform === "uppercase")
6278
+ return text.toUpperCase();
6279
+ if (transform === "lowercase")
6280
+ return text.toLowerCase();
6281
+ if (transform === "capitalize") {
6282
+ let start = wordStart;
6283
+ let out = "";
6284
+ for (const char of text) {
6285
+ out += start && /\p{L}/u.test(char) ? char.toUpperCase() : char;
6286
+ start = /\s/.test(char);
6287
+ }
6288
+ return out;
6289
+ }
6290
+ return text;
6291
+ }
6292
+ function utf8Length(text) {
6293
+ let length = 0;
6294
+ for (let index = 0;index < text.length; index++) {
6295
+ const code = text.charCodeAt(index);
6296
+ if (code < 128)
6297
+ length += 1;
6298
+ else if (code < 2048)
6299
+ length += 2;
6300
+ else if (code >= 55296 && code <= 56319) {
6301
+ length += 4;
6302
+ index++;
6303
+ } else
6304
+ length += 3;
6305
+ }
6306
+ return length;
6307
+ }
6308
+ function collect2(child, style, id, ctx, out) {
6309
+ if (child == null || typeof child === "boolean")
6310
+ return;
6311
+ if (Array.isArray(child)) {
6312
+ for (const item of child)
6313
+ collect2(item, style, id, ctx, out);
6314
+ return;
6315
+ }
6316
+ if (typeof child === "string" || typeof child === "number") {
6317
+ out.push({ text: String(child), style, id });
6318
+ return;
6319
+ }
6320
+ const node = child;
6321
+ if (node.type === Fragment || node.type === "fragment") {
6322
+ collect2(node.props.children, style, id, ctx, out);
6323
+ return;
6324
+ }
6325
+ if (typeof node.type === "function") {
6326
+ collect2(node.type(node.props), style, id, ctx, out);
6327
+ return;
6328
+ }
6329
+ const props = node.props;
6330
+ if (node.type === "br") {
6331
+ out.push({ br: true });
6332
+ return;
6333
+ }
6334
+ if (node.type === "text") {
6335
+ collect2(props.children, computeStyle(style, pick(props.style)), id, ctx, out);
6336
+ return;
6337
+ }
6338
+ if (typeof node.type !== "string" || !(node.type in INLINE_TAGS) || node.type === "code" && props.code !== undefined) {
6339
+ throw new Error(`<${String(node.type)}> cannot be inside text; only phrasing elements (span, strong, em, a, code, br\u2026) can.`);
6340
+ }
6341
+ const own = { ...INLINE_TAGS[node.type] };
6342
+ if (node.type === "abbr" && props.title) {
6343
+ own.textDecoration = "underline";
6344
+ own.textDecorationStyle = "dotted";
6345
+ }
6346
+ if (node.type === "a")
6347
+ own.foreground = ctx.linkColor;
6348
+ Object.assign(own, pick(canonicalizeIntrinsicStyle(props.style)));
6349
+ if (props.size !== undefined)
6350
+ own.fontSize = props.size;
6351
+ if (props.weight !== undefined)
6352
+ own.fontWeight = props.weight;
6353
+ if (props.color !== undefined)
6354
+ own.foreground = props.color;
6355
+ let runId = id;
6356
+ const href = node.type === "a" && typeof props.href === "string" ? props.href : undefined;
6357
+ if (props.onClick || href) {
6358
+ const onClick = props.onClick;
6359
+ runId = ctx.register(props.id, () => {
6360
+ if (props.disabled)
6361
+ return;
6362
+ onClick?.();
6363
+ if (href)
6364
+ ctx.openExternal(href);
6365
+ });
6366
+ }
6367
+ collect2(props.children, computeStyle(style, ctx.resolve(own)), runId, ctx, out);
6368
+ }
6369
+ function compileInline(children, whiteSpace, ctx) {
6370
+ const pieces = [];
6371
+ collect2(children, ctx.base, undefined, ctx, pieces);
6372
+ const collapseSpaces = whiteSpace === "normal" || whiteSpace === "nowrap" || whiteSpace === "pre-line";
6373
+ const keepNewlines = whiteSpace !== "normal" && whiteSpace !== "nowrap";
6374
+ let text = "";
6375
+ let bytes = 0;
6376
+ const runs = [];
6377
+ let pendingSpace = false;
6378
+ let lineStart = true;
6379
+ let wordStart = true;
6380
+ const append = (value) => {
6381
+ text += value;
6382
+ bytes += utf8Length(value);
6383
+ };
6384
+ const trimLineEnd = () => {
6385
+ if (!text.endsWith(" ") || !pendingSpace)
6386
+ return;
6387
+ text = text.slice(0, -1);
6388
+ bytes -= 1;
6389
+ for (const run of runs)
6390
+ if (run.end > bytes)
6391
+ run.end = bytes;
6392
+ while (runs.length && runs.at(-1).end <= runs.at(-1).start)
6393
+ runs.pop();
6394
+ };
6395
+ for (const piece of pieces) {
6396
+ if ("br" in piece) {
6397
+ trimLineEnd();
6398
+ append(`
6399
+ `);
6400
+ pendingSpace = false;
6401
+ lineStart = true;
6402
+ wordStart = true;
6403
+ continue;
6404
+ }
6405
+ const start = bytes;
6406
+ const source = piece.text.replace(/\r\n?/g, `
6407
+ `);
6408
+ if (!collapseSpaces) {
6409
+ append(transformText(source, piece.style.textTransform, wordStart));
6410
+ if (source)
6411
+ wordStart = /\s$/.test(source);
6412
+ } else {
6413
+ for (const char of source) {
6414
+ if (char === `
6415
+ ` && keepNewlines) {
6416
+ trimLineEnd();
6417
+ append(`
6418
+ `);
6419
+ pendingSpace = false;
6420
+ lineStart = true;
6421
+ wordStart = true;
6422
+ } else if (char === " " || char === "\t" || char === `
6423
+ ` || char === "\f") {
6424
+ if (!lineStart && !pendingSpace) {
6425
+ append(" ");
6426
+ pendingSpace = true;
6427
+ wordStart = true;
6428
+ }
6429
+ } else {
6430
+ pendingSpace = false;
6431
+ append(transformText(char, piece.style.textTransform, wordStart));
6432
+ wordStart = false;
6433
+ lineStart = false;
6434
+ }
6435
+ }
6436
+ }
6437
+ const style = {};
6438
+ for (const key of RUN_KEYS) {
6439
+ if (key === "textTransform")
6440
+ continue;
6441
+ if (piece.style[key] !== undefined && piece.style[key] !== ctx.base[key])
6442
+ style[key] = piece.style[key];
6443
+ }
6444
+ if (bytes > start && (Object.keys(style).length > 0 || piece.id)) {
6445
+ const last = runs.at(-1);
6446
+ if (last && last.end === start && last.id === piece.id && JSON.stringify(last.style) === JSON.stringify(style))
6447
+ last.end = bytes;
6448
+ else
6449
+ runs.push({ start, end: bytes, style, ...piece.id ? { id: piece.id } : {} });
6450
+ }
6451
+ }
6452
+ trimLineEnd();
6453
+ return { text, runs };
6454
+ }
6455
+
6456
+ // packages/core/src/canvas.ts
6457
+ class CanvasGradient {
6458
+ id;
6459
+ kind;
6460
+ coords;
6461
+ stops = [];
6462
+ constructor(id, kind, coords) {
6463
+ this.id = id;
6464
+ this.kind = kind;
6465
+ this.coords = coords;
6466
+ }
6467
+ addColorStop(offset, color) {
6468
+ if (!(offset >= 0 && offset <= 1))
6469
+ throw new RangeError("addColorStop offset must be between 0 and 1");
6470
+ this.stops.push([offset, color]);
6471
+ }
6472
+ }
6473
+ var fmt = (n) => (Math.round(n * 1000) / 1000).toString();
6474
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
6475
+
6476
+ class CanvasRenderingContext2D {
6477
+ width;
6478
+ height;
6479
+ state = {
6480
+ fillStyle: "#000000",
6481
+ strokeStyle: "#000000",
6482
+ lineWidth: 1,
6483
+ lineCap: "butt",
6484
+ lineJoin: "miter",
6485
+ miterLimit: 10,
6486
+ globalAlpha: 1,
6487
+ font: "10px sans-serif",
6488
+ textAlign: "start",
6489
+ textBaseline: "alphabetic",
6490
+ transform: [1, 0, 0, 1, 0, 0],
6491
+ lineDash: []
6492
+ };
6493
+ stack = [];
6494
+ path = "";
6495
+ start = null;
6496
+ current = null;
6497
+ elements = [];
6498
+ defs = [];
6499
+ texts = [];
6500
+ ops = [];
6501
+ gradients = 0;
6502
+ constructor(width, height) {
6503
+ this.width = width;
6504
+ this.height = height;
6505
+ }
6506
+ get fillStyle() {
6507
+ return this.state.fillStyle;
6508
+ }
6509
+ set fillStyle(v) {
6510
+ this.state.fillStyle = v;
6511
+ }
6512
+ get strokeStyle() {
6513
+ return this.state.strokeStyle;
6514
+ }
6515
+ set strokeStyle(v) {
6516
+ this.state.strokeStyle = v;
6517
+ }
6518
+ get lineWidth() {
6519
+ return this.state.lineWidth;
6520
+ }
6521
+ set lineWidth(v) {
6522
+ if (v > 0 && Number.isFinite(v))
6523
+ this.state.lineWidth = v;
6524
+ }
6525
+ get lineCap() {
6526
+ return this.state.lineCap;
6527
+ }
6528
+ set lineCap(v) {
6529
+ this.state.lineCap = v;
6530
+ }
6531
+ get lineJoin() {
6532
+ return this.state.lineJoin;
6533
+ }
6534
+ set lineJoin(v) {
6535
+ this.state.lineJoin = v;
6536
+ }
6537
+ get miterLimit() {
6538
+ return this.state.miterLimit;
6539
+ }
6540
+ set miterLimit(v) {
6541
+ if (v > 0)
6542
+ this.state.miterLimit = v;
6543
+ }
6544
+ get globalAlpha() {
6545
+ return this.state.globalAlpha;
6546
+ }
6547
+ set globalAlpha(v) {
6548
+ if (v >= 0 && v <= 1)
6549
+ this.state.globalAlpha = v;
6550
+ }
6551
+ get font() {
6552
+ return this.state.font;
6553
+ }
6554
+ set font(v) {
6555
+ this.state.font = v;
6556
+ }
6557
+ get textAlign() {
6558
+ return this.state.textAlign;
6559
+ }
6560
+ set textAlign(v) {
6561
+ this.state.textAlign = v;
6562
+ }
6563
+ get textBaseline() {
6564
+ return this.state.textBaseline;
6565
+ }
6566
+ set textBaseline(v) {
6567
+ this.state.textBaseline = v;
6568
+ }
6569
+ setLineDash(segments) {
6570
+ this.state.lineDash = segments.length % 2 ? [...segments, ...segments] : [...segments];
6571
+ }
6572
+ getLineDash() {
6573
+ return [...this.state.lineDash];
6574
+ }
6575
+ save() {
6576
+ this.stack.push({ ...this.state, transform: [...this.state.transform], lineDash: [...this.state.lineDash] });
6577
+ }
6578
+ restore() {
6579
+ const state = this.stack.pop();
6580
+ if (state)
6581
+ this.state = state;
6582
+ }
6583
+ setTransform(a, b, c, d, e, f) {
6584
+ this.state.transform = [a, b, c, d, e, f];
6585
+ }
6586
+ resetTransform() {
6587
+ this.state.transform = [1, 0, 0, 1, 0, 0];
6588
+ }
6589
+ transform(a, b, c, d, e, f) {
6590
+ const [A, B, C, D, E, F] = this.state.transform;
6591
+ this.state.transform = [A * a + C * b, B * a + D * b, A * c + C * d, B * c + D * d, A * e + C * f + E, B * e + D * f + F];
6592
+ }
6593
+ translate(x, y) {
6594
+ this.transform(1, 0, 0, 1, x, y);
6595
+ }
6596
+ scale(x, y) {
6597
+ this.transform(x, 0, 0, y, 0, 0);
6598
+ }
6599
+ rotate(angle) {
6600
+ const c = Math.cos(angle), s = Math.sin(angle);
6601
+ this.transform(c, s, -s, c, 0, 0);
6602
+ }
6603
+ getTransform() {
6604
+ return [...this.state.transform];
6605
+ }
6606
+ point(x, y) {
6607
+ const [a, b, c, d, e, f] = this.state.transform;
6608
+ return [a * x + c * y + e, b * x + d * y + f];
6609
+ }
6610
+ scaleFactor() {
6611
+ const [a, b, c, d] = this.state.transform;
6612
+ return Math.sqrt(Math.abs(a * d - b * c));
6613
+ }
6614
+ beginPath() {
6615
+ this.path = "";
6616
+ this.start = null;
6617
+ this.current = null;
6618
+ }
6619
+ moveTo(x, y) {
6620
+ const p = this.point(x, y);
6621
+ this.path += `M${fmt(p[0])} ${fmt(p[1])}`;
6622
+ this.start = p;
6623
+ this.current = p;
6624
+ }
6625
+ lineTo(x, y) {
6626
+ if (!this.current)
6627
+ return this.moveTo(x, y);
6628
+ const p = this.point(x, y);
6629
+ this.path += `L${fmt(p[0])} ${fmt(p[1])}`;
6630
+ this.current = p;
6631
+ }
6632
+ closePath() {
6633
+ if (this.current) {
6634
+ this.path += "Z";
6635
+ this.current = this.start;
6636
+ }
6637
+ }
6638
+ quadraticCurveTo(cx, cy, x, y) {
6639
+ if (!this.current)
6640
+ this.moveTo(cx, cy);
6641
+ const c = this.point(cx, cy), p = this.point(x, y);
6642
+ this.path += `Q${fmt(c[0])} ${fmt(c[1])} ${fmt(p[0])} ${fmt(p[1])}`;
6643
+ this.current = p;
6644
+ }
6645
+ bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
6646
+ if (!this.current)
6647
+ this.moveTo(c1x, c1y);
6648
+ const a = this.point(c1x, c1y), b = this.point(c2x, c2y), p = this.point(x, y);
6649
+ this.path += `C${fmt(a[0])} ${fmt(a[1])} ${fmt(b[0])} ${fmt(b[1])} ${fmt(p[0])} ${fmt(p[1])}`;
6650
+ this.current = p;
6651
+ }
6652
+ rect(x, y, w, h) {
6653
+ this.moveTo(x, y);
6654
+ this.lineTo(x + w, y);
6655
+ this.lineTo(x + w, y + h);
6656
+ this.lineTo(x, y + h);
6657
+ this.closePath();
6658
+ this.moveTo(x, y);
6659
+ }
6660
+ roundRect(x, y, w, h, radius = 0) {
6661
+ const r = Math.max(0, Math.min(Array.isArray(radius) ? radius[0] ?? 0 : radius, Math.abs(w) / 2, Math.abs(h) / 2));
6662
+ if (r === 0)
6663
+ return this.rect(x, y, w, h);
6664
+ const q = Math.PI / 2;
6665
+ this.moveTo(x + r, y);
6666
+ this.lineTo(x + w - r, y);
6667
+ this.arc(x + w - r, y + r, r, -q, 0);
6668
+ this.lineTo(x + w, y + h - r);
6669
+ this.arc(x + w - r, y + h - r, r, 0, q);
6670
+ this.lineTo(x + r, y + h);
6671
+ this.arc(x + r, y + h - r, r, q, 2 * q);
6672
+ this.lineTo(x, y + r);
6673
+ this.arc(x + r, y + r, r, 2 * q, 3 * q);
6674
+ this.closePath();
6675
+ this.moveTo(x, y);
6676
+ }
6677
+ ellipse(x, y, rx, ry, rotation, start, end, ccw = false) {
6678
+ if (rx < 0 || ry < 0)
6679
+ throw new RangeError("ellipse radii must be non-negative");
6680
+ let sweep = end - start;
6681
+ const full = Math.PI * 2;
6682
+ if (!ccw && sweep < 0)
6683
+ sweep = sweep % full + full;
6684
+ if (ccw && sweep > 0)
6685
+ sweep = sweep % full - full;
6686
+ if (Math.abs(end - start) >= full)
6687
+ sweep = ccw ? -full : full;
6688
+ const at = (t) => {
6689
+ const cx = Math.cos(t) * rx, cy = Math.sin(t) * ry;
6690
+ return [x + cx * Math.cos(rotation) - cy * Math.sin(rotation), y + cx * Math.sin(rotation) + cy * Math.cos(rotation)];
6691
+ };
6692
+ const derivative = (t) => {
6693
+ const dx = -Math.sin(t) * rx, dy = Math.cos(t) * ry;
6694
+ return [dx * Math.cos(rotation) - dy * Math.sin(rotation), dx * Math.sin(rotation) + dy * Math.cos(rotation)];
6695
+ };
6696
+ const first = at(start);
6697
+ if (!this.current)
6698
+ this.moveTo(first[0], first[1]);
6699
+ else {
6700
+ const [px, py] = this.point(first[0], first[1]);
6701
+ if (Math.abs(px - this.current[0]) > 0.000001 || Math.abs(py - this.current[1]) > 0.000001)
6702
+ this.lineTo(first[0], first[1]);
6703
+ }
6704
+ const segments = Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 2)));
6705
+ const step = sweep / segments;
6706
+ const k = 4 / 3 * Math.tan(step / 4);
6707
+ for (let i = 0;i < segments; i++) {
6708
+ const t0 = start + step * i, t1 = t0 + step;
6709
+ const p0 = at(t0), p1 = at(t1), d0 = derivative(t0), d1 = derivative(t1);
6710
+ this.bezierCurveTo(p0[0] + k * d0[0], p0[1] + k * d0[1], p1[0] - k * d1[0], p1[1] - k * d1[1], p1[0], p1[1]);
6711
+ }
6712
+ }
6713
+ arc(x, y, r, start, end, ccw = false) {
6714
+ this.ellipse(x, y, r, r, 0, start, end, ccw);
6715
+ }
6716
+ arcTo(x1, y1, x2, y2, r) {
6717
+ if (r < 0)
6718
+ throw new RangeError("arcTo radius must be non-negative");
6719
+ if (!this.current)
6720
+ this.moveTo(x1, y1);
6721
+ const [a, b, c, d, e, f] = this.state.transform;
6722
+ const det = a * d - b * c;
6723
+ const [cx, cy] = this.current;
6724
+ const x0 = (d * (cx - e) - c * (cy - f)) / det, y0 = (-b * (cx - e) + a * (cy - f)) / det;
6725
+ const l1 = Math.hypot(x0 - x1, y0 - y1), l2 = Math.hypot(x2 - x1, y2 - y1);
6726
+ if (r === 0 || l1 === 0 || l2 === 0)
6727
+ return this.lineTo(x1, y1);
6728
+ const u1 = [(x0 - x1) / l1, (y0 - y1) / l1], u2 = [(x2 - x1) / l2, (y2 - y1) / l2];
6729
+ const cross = u1[0] * u2[1] - u1[1] * u2[0];
6730
+ if (Math.abs(cross) < 0.000000001)
6731
+ return this.lineTo(x1, y1);
6732
+ const angle = Math.acos(Math.max(-1, Math.min(1, u1[0] * u2[0] + u1[1] * u2[1])));
6733
+ const tangent = r / Math.tan(angle / 2);
6734
+ const t1 = [x1 + u1[0] * tangent, y1 + u1[1] * tangent];
6735
+ const bisector = [u1[0] + u2[0], u1[1] + u2[1]];
6736
+ const length = Math.hypot(bisector[0], bisector[1]);
6737
+ const distance = r / Math.sin(angle / 2);
6738
+ const center = [x1 + bisector[0] / length * distance, y1 + bisector[1] / length * distance];
6739
+ const t2 = [x1 + u2[0] * tangent, y1 + u2[1] * tangent];
6740
+ const start = Math.atan2(t1[1] - center[1], t1[0] - center[0]);
6741
+ const end = Math.atan2(t2[1] - center[1], t2[0] - center[0]);
6742
+ let sweep = end - start;
6743
+ while (sweep > Math.PI)
6744
+ sweep -= 2 * Math.PI;
6745
+ while (sweep < -Math.PI)
6746
+ sweep += 2 * Math.PI;
6747
+ this.lineTo(t1[0], t1[1]);
6748
+ this.arc(center[0], center[1], r, start, start + sweep, sweep < 0);
6749
+ }
6750
+ createLinearGradient(x0, y0, x1, y1) {
6751
+ const a = this.point(x0, y0), b = this.point(x1, y1);
6752
+ return new CanvasGradient(`g${this.gradients++}`, "linear", [...a, ...b]);
6753
+ }
6754
+ createRadialGradient(x0, y0, r0, x1, y1, r1) {
6755
+ const a = this.point(x0, y0), b = this.point(x1, y1), s = this.scaleFactor();
6756
+ return new CanvasGradient(`g${this.gradients++}`, "radial", [...a, r0 * s, ...b, r1 * s]);
6757
+ }
6758
+ paint(style) {
6759
+ if (typeof style === "string")
6760
+ return esc(style);
6761
+ if (!this.defs.some((def) => def.includes(`id="${style.id}"`))) {
6762
+ const stops = [...style.stops].sort((p, q) => p[0] - q[0]).map(([o, c]) => `<stop offset="${fmt(o)}" stop-color="${esc(c)}"/>`).join("");
6763
+ const [p, q, r, s, t, u] = style.coords.map(fmt);
6764
+ this.defs.push(style.kind === "linear" ? `<linearGradient id="${style.id}" gradientUnits="userSpaceOnUse" x1="${p}" y1="${q}" x2="${r}" y2="${s}">${stops}</linearGradient>` : `<radialGradient id="${style.id}" gradientUnits="userSpaceOnUse" fx="${p}" fy="${q}" fr="${r}" cx="${s}" cy="${t}" r="${u}">${stops}</radialGradient>`);
6765
+ }
6766
+ return `url(#${style.id})`;
6767
+ }
6768
+ emit(path, fill, stroke, rule = "nonzero") {
6769
+ if (!path)
6770
+ return;
6771
+ const s = this.state;
6772
+ const attrs = [`d="${path}"`, `fill="${fill ?? "none"}"`];
6773
+ if (fill)
6774
+ attrs.push(`fill-rule="${rule}"`);
6775
+ if (stroke) {
6776
+ const width = s.lineWidth * this.scaleFactor();
6777
+ attrs.push(`stroke="${stroke}"`, `stroke-width="${fmt(width)}"`, `stroke-linecap="${s.lineCap}"`, `stroke-linejoin="${s.lineJoin}"`, `stroke-miterlimit="${fmt(s.miterLimit)}"`);
6778
+ if (s.lineDash.length)
6779
+ attrs.push(`stroke-dasharray="${s.lineDash.map((v) => fmt(v * this.scaleFactor())).join(" ")}"`);
6780
+ }
6781
+ if (s.globalAlpha < 1)
6782
+ attrs.push(`opacity="${fmt(s.globalAlpha)}"`);
6783
+ this.elements.push(`<path ${attrs.join(" ")}/>`);
6784
+ }
6785
+ fill(rule = "nonzero") {
6786
+ this.emit(this.path, this.paint(this.state.fillStyle), null, rule);
6787
+ }
6788
+ stroke() {
6789
+ this.emit(this.path, null, this.paint(this.state.strokeStyle));
6790
+ }
6791
+ rectPath(x, y, w, h) {
6792
+ const corners = [this.point(x, y), this.point(x + w, y), this.point(x + w, y + h), this.point(x, y + h)];
6793
+ return `M${corners.map((p) => `${fmt(p[0])} ${fmt(p[1])}`).join("L")}Z`;
6794
+ }
6795
+ fillRect(x, y, w, h) {
6796
+ this.emit(this.rectPath(x, y, w, h), this.paint(this.state.fillStyle), null);
6797
+ }
6798
+ strokeRect(x, y, w, h) {
6799
+ this.emit(this.rectPath(x, y, w, h), null, this.paint(this.state.strokeStyle));
6800
+ }
6801
+ flush() {
6802
+ if (this.elements.length)
6803
+ this.ops.push({ svg: this.elements });
6804
+ this.elements = [];
6805
+ }
6806
+ clearRect(x, y, w, h) {
6807
+ const corners = [this.point(x, y), this.point(x + w, y), this.point(x + w, y + h), this.point(x, y + h)];
6808
+ const inside = (px, py) => {
6809
+ let hit = false;
6810
+ for (let i = 0, j = 3;i < 4; j = i++) {
6811
+ const [xi, yi] = corners[i], [xj, yj] = corners[j];
6812
+ if (yi > py !== yj > py && px < (xj - xi) * (py - yi) / (yj - yi) + xi)
6813
+ hit = !hit;
6814
+ }
6815
+ return hit;
6816
+ };
6817
+ const eps = 0.000001;
6818
+ if ([[-eps, -eps], [this.width + eps, -eps], [this.width + eps, this.height + eps], [-eps, this.height + eps]].every(([px, py]) => inside(px, py))) {
6819
+ this.elements = [];
6820
+ this.texts.length = 0;
6821
+ this.ops.length = 0;
6822
+ return;
6823
+ }
6824
+ this.flush();
6825
+ this.ops.push({ clear: `M${corners.map((p) => `${fmt(p[0])} ${fmt(p[1])}`).join("L")}Z` });
6826
+ }
6827
+ text(text, x, y, stroke) {
6828
+ const style = this.state[stroke ? "strokeStyle" : "fillStyle"];
6829
+ const color = typeof style === "string" ? style : style.stops[0]?.[1] ?? "#000000";
6830
+ const entry = { text, x, y, matrix: [...this.state.transform], font: this.state.font, color, align: this.state.textAlign, baseline: this.state.textBaseline, alpha: this.state.globalAlpha, stroke, lineWidth: this.state.lineWidth };
6831
+ this.flush();
6832
+ this.texts.push(entry);
6833
+ this.ops.push({ text: entry });
6834
+ }
6835
+ drawImage(image, ...args) {
6836
+ const source = typeof image === "object" && image !== null && "src" in image && !("rgba" in image) ? image.src : image;
6837
+ const base = { source, matrix: [...this.state.transform], alpha: this.state.globalAlpha };
6838
+ let entry;
6839
+ if (args.length === 2)
6840
+ entry = { ...base, dx: args[0], dy: args[1] };
6841
+ else if (args.length === 4)
6842
+ entry = { ...base, dx: args[0], dy: args[1], dw: args[2], dh: args[3] };
6843
+ else if (args.length === 8)
6844
+ entry = { ...base, crop: [args[0], args[1], args[2], args[3]], dx: args[4], dy: args[5], dw: args[6], dh: args[7] };
6845
+ else
6846
+ throw new TypeError("drawImage takes 3, 5 or 9 arguments");
6847
+ this.flush();
6848
+ this.ops.push({ image: entry });
6849
+ }
6850
+ fillText(text, x, y) {
6851
+ this.text(text, x, y, false);
6852
+ }
6853
+ strokeText(text, x, y) {
6854
+ this.text(text, x, y, true);
6855
+ }
6856
+ toSvg(elements = [...this.ops.flatMap((op) => ("svg" in op) ? op.svg : []), ...this.elements]) {
6857
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${this.width}" height="${this.height}" viewBox="0 0 ${this.width} ${this.height}">${this.defs.length ? `<defs>${this.defs.join("")}</defs>` : ""}${elements.join("")}</svg>`;
6858
+ }
6859
+ layers() {
6860
+ return this.elements.length ? [...this.ops, { svg: this.elements }] : [...this.ops];
6861
+ }
6862
+ }
6863
+ function parseCanvasFont(font) {
6864
+ const match = /^\s*(?:(italic|oblique|normal)\s+)?(?:(small-caps|normal)\s+)?(?:(bold|bolder|lighter|normal|[1-9]00)\s+)?([\d.]+)px(?:\/[\d.]+\w*)?\s+(.+?)\s*$/i.exec(font);
6865
+ if (!match)
6866
+ return { fontSize: 10, fontFamily: "sans-serif" };
6867
+ const weight = match[3]?.toLowerCase();
6868
+ return {
6869
+ ...match[1] && match[1] !== "normal" ? { fontStyle: "italic" } : {},
6870
+ ...weight && weight !== "normal" ? { fontWeight: weight === "bold" || weight === "bolder" ? 700 : weight === "lighter" ? 300 : Number(weight) } : {},
6871
+ fontSize: Number(match[4]),
6872
+ fontFamily: match[5].replace(/["']/g, "").split(",")[0].trim()
6873
+ };
6874
+ }
6875
+ var isIdentity = (m) => m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;
6876
+ var matrixStyle = (m) => isIdentity(m) ? {} : { transformMatrix: [...m] };
6877
+ var layerBox = { position: "absolute", left: 0, top: 0 };
6878
+ function canvasText(text, index) {
6879
+ const font = parseCanvasFont(text.font);
6880
+ const top = text.baseline === "top" || text.baseline === "hanging" ? text.y : text.baseline === "middle" ? text.y - font.fontSize / 2 : text.baseline === "bottom" || text.baseline === "ideographic" ? text.y - font.fontSize : text.y - font.fontSize * 0.86;
6881
+ const align = text.align === "center" ? "center" : text.align === "right" || text.align === "end" ? "end" : "start";
6882
+ return View({ key: `t${index}`, style: { ...layerBox, width: 0, height: 0, ...matrixStyle(text.matrix) }, children: View({
6883
+ style: { position: "absolute", left: text.x, top, width: 0, direction: "column", align, opacity: text.alpha },
6884
+ children: Text({ style: { ...font, lineHeight: 1, whiteSpace: "pre", foreground: text.color }, children: text.text })
6885
+ }) });
6886
+ }
6887
+ function canvasImage(image, index) {
6888
+ const [a, b, c, d, e, f] = image.matrix;
6889
+ const at = (x, y, sx = 1, sy = 1) => [a * sx, b * sx, c * sy, d * sy, a * x + c * y + e, b * x + d * y + f];
6890
+ if (image.crop) {
6891
+ const [sx, sy, sw, sh] = image.crop;
6892
+ return View({
6893
+ key: `i${index}`,
6894
+ style: { ...layerBox, width: sw, height: sh, overflow: "hidden", opacity: image.alpha, ...matrixStyle(at(image.dx, image.dy, image.dw / sw, image.dh / sh)) },
6895
+ children: Image({ src: image.source, fit: "fill", style: { position: "absolute", left: -sx, top: -sy, radius: 0 } })
6896
+ });
6897
+ }
6898
+ return View({
6899
+ key: `i${index}`,
6900
+ style: { ...layerBox, opacity: image.alpha, ...matrixStyle(at(image.dx, image.dy)) },
6901
+ children: Image({ src: image.source, fit: "fill", style: { radius: 0 }, ...image.dw !== undefined ? { width: image.dw, height: image.dh } : {} })
6902
+ });
6903
+ }
6904
+ function expandCanvas(props, key) {
6905
+ const width = Number(props.width ?? 300), height = Number(props.height ?? 150);
6906
+ const context = new CanvasRenderingContext2D(width, height);
6907
+ props.onDraw?.(context);
6908
+ const id = String(props.id ?? key);
6909
+ let children = [];
6910
+ let layer = 0;
6911
+ context.layers().forEach((op, index) => {
6912
+ if ("svg" in op)
6913
+ children.push(_nativeJsx("svg", { id: layer === 0 ? `${id}-scene` : `${id}-scene-${layer}`, svg: context.toSvg(op.svg), style: { ...layerBox, width, height } }, `s${index}`));
6914
+ if ("svg" in op)
6915
+ layer++;
6916
+ if ("text" in op)
6917
+ children.push(canvasText(op.text, index));
6918
+ if ("image" in op)
6919
+ children.push(canvasImage(op.image, index));
6920
+ if ("clear" in op)
6921
+ children = [View({ key: `c${index}`, style: { ...layerBox, width, height, clipPath: `path(evenodd, "M0 0H${width}V${height}H0Z${op.clear}")` }, children })];
6922
+ });
6923
+ return View({
6924
+ id,
6925
+ ...props.ariaLabel ? { control: { role: "group", label: props.ariaLabel } } : {},
6926
+ style: { width, height, shrink: 0, position: "relative", overflow: "hidden", ...canonicalizeIntrinsicStyle(props.style) },
6927
+ children
6928
+ });
6929
+ }
6930
+
6931
+ // packages/core/src/html-elements.ts
6932
+ var HTML_ELEMENTS = new Set(["pre", "blockquote", "meter", "form", "fieldset", "legend", "ul", "ol", "li", "dl", "dt", "dd", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "details", "summary"]);
6933
+ var HTML_INPUT_TYPES = new Set(["checkbox", "radio", "range", "date", "file", "color", "time"]);
6934
+ var COLOR_PALETTE = ["#000000", "#ffffff", "#ef4444", "#f97316", "#eab308", "#22c55e", "#14b8a6", "#3b82f6", "#6366f1", "#a855f7", "#ec4899", "#78716c"];
6935
+ var state = new Map;
6936
+ function formValues(key) {
6937
+ const id = `form:${key}`;
6938
+ let values = state.get(id);
6939
+ if (!values)
6940
+ state.set(id, values = new Map);
6941
+ return values;
6942
+ }
6943
+ function storedValue(key, initial) {
6944
+ return state.has(key) ? state.get(key) : initial;
6945
+ }
6946
+ function storeValue(key, value) {
6947
+ state.set(key, value);
6948
+ }
6949
+ var ACTIVE_APP2 = Symbol.for("tarve.activeApp");
6950
+ function activeApp() {
6951
+ return globalThis[ACTIVE_APP2];
6952
+ }
6953
+ function uncontrolled(key, controlled, initial) {
6954
+ if (controlled !== undefined)
6955
+ return controlled;
6956
+ return state.has(key) ? state.get(key) : initial;
6957
+ }
6958
+ function acceptFilters(accept) {
6959
+ if (typeof accept !== "string" || !accept.trim())
6960
+ return;
6961
+ const extensions = accept.split(",").map((part) => part.trim()).filter((part) => part.startsWith(".")).map((part) => part.slice(1));
6962
+ return extensions.length ? [{ name: "Accepted files", extensions }] : undefined;
6963
+ }
6964
+ function expandInput(props, key, form) {
6965
+ const id = String(props.id ?? key);
6966
+ const name = props.name;
6967
+ const style = canonicalizeIntrinsicStyle(props.style);
6968
+ const record = (value) => {
6969
+ if (form && name)
6970
+ form.values.set(name, value);
6971
+ };
6972
+ if (form && name && props.required)
6973
+ form.required.add(name);
6974
+ switch (props.type) {
6975
+ case "checkbox": {
6976
+ const checked = uncontrolled(id, props.checked, props.defaultChecked === true);
6977
+ if (!form?.values.has(name ?? ""))
6978
+ record(checked);
6979
+ return Checkbox({
6980
+ id,
6981
+ style,
6982
+ label: props.label ?? props.ariaLabel ?? "",
6983
+ checked,
6984
+ disabled: props.disabled,
6985
+ onCheckedChange: (next) => {
6986
+ state.set(id, next);
6987
+ record(next);
6988
+ props.onCheckedChange?.(next);
6989
+ props.onChange?.(String(next));
6990
+ }
6991
+ });
6992
+ }
6993
+ case "radio": {
6994
+ const group = `radio:${name ?? id}`;
6995
+ const value = String(props.value ?? "on");
6996
+ const selected = props.checked !== undefined ? props.checked ? value : undefined : uncontrolled(group, undefined, props.defaultChecked ? value : undefined);
6997
+ if (props.checked === undefined && props.defaultChecked && !state.has(group))
6998
+ state.set(group, value);
6999
+ if (selected === value)
7000
+ record(value);
7001
+ return RadioGroup({
7002
+ id,
7003
+ style,
7004
+ value: selected === value ? value : "",
7005
+ disabled: props.disabled,
7006
+ options: [{ value, label: props.label ?? props.ariaLabel ?? "" }],
7007
+ onValueChange: (next) => {
7008
+ state.set(group, next);
7009
+ record(next);
7010
+ props.onChange?.(next);
7011
+ }
7012
+ });
7013
+ }
7014
+ case "range": {
7015
+ const min = Number(props.min ?? 0);
7016
+ const max = Number(props.max ?? 100);
7017
+ const fallback = max < min ? min : min + (max - min) / 2;
7018
+ const value = Number(uncontrolled(id, props.value, props.defaultValue ?? fallback));
7019
+ record(String(value));
7020
+ return Slider({
7021
+ id,
7022
+ style,
7023
+ value,
7024
+ min,
7025
+ max,
7026
+ step: Number(props.step ?? 1),
7027
+ label: props.label ?? props.ariaLabel,
7028
+ disabled: props.disabled,
7029
+ onValueChange: (next) => {
7030
+ state.set(id, next);
7031
+ record(String(next));
7032
+ props.onChange?.(String(next));
7033
+ }
7034
+ });
7035
+ }
7036
+ case "date": {
7037
+ const value = uncontrolled(id, props.value, props.defaultValue);
7038
+ if (value)
7039
+ record(value);
7040
+ const open = state.get(`${id}:open`) ?? false;
7041
+ const month = state.get(`${id}:month`) ?? (value ?? new Date().toISOString()).slice(0, 7);
7042
+ return DatePicker({
7043
+ id,
7044
+ style,
7045
+ value,
7046
+ open,
7047
+ month,
7048
+ min: props.min,
7049
+ max: props.max,
7050
+ disabled: props.disabled,
7051
+ placeholder: props.placeholder ?? "yyyy-mm-dd",
7052
+ onOpenChange: (next) => {
7053
+ state.set(`${id}:open`, next);
7054
+ },
7055
+ onMonthChange: (next) => {
7056
+ state.set(`${id}:month`, next);
7057
+ },
7058
+ onValueChange: (next) => {
7059
+ state.set(id, next);
7060
+ record(next);
7061
+ props.onChange?.(next);
7062
+ }
7063
+ });
7064
+ }
7065
+ case "color": {
7066
+ const value = uncontrolled(id, props.value, props.defaultValue ?? "#000000").toLowerCase();
7067
+ record(value);
7068
+ const open = state.get(`${id}:open`) ?? false;
7069
+ const pick = (next) => {
7070
+ const normalized = next.trim().toLowerCase();
7071
+ if (!/^#[0-9a-f]{6}$/.test(normalized))
7072
+ return;
7073
+ state.set(id, normalized);
7074
+ record(normalized);
7075
+ props.onChange?.(normalized);
7076
+ };
7077
+ return Column({ id, gap: 6, style, children: [
7078
+ Row({ gap: 8, align: "center", children: [
7079
+ Pressable({
7080
+ id: `${id}-swatch`,
7081
+ disabled: props.disabled,
7082
+ control: { role: "button", label: props.label ?? props.ariaLabel ?? "Choose colour", expanded: open },
7083
+ onClick: () => {
7084
+ state.set(`${id}:open`, !open);
7085
+ },
7086
+ style: { width: 44, height: 24, radius: 4, borderWidth: 1, borderColor: theme.colors.border, background: value }
7087
+ }),
7088
+ Input({ id: `${id}-hex`, value, disabled: props.disabled, onChange: pick, style: { width: 100, fontFamily: "monospace" } })
7089
+ ] }),
7090
+ ...open ? [Row({ gap: 4, wrap: true, style: { width: 180 }, children: COLOR_PALETTE.map((color) => Pressable({
7091
+ key: color,
7092
+ id: `${id}-${color.slice(1)}`,
7093
+ control: { role: "button", label: color },
7094
+ onClick: () => {
7095
+ pick(color);
7096
+ state.set(`${id}:open`, false);
7097
+ },
7098
+ style: { width: 24, height: 24, radius: 4, borderWidth: color === value ? 2 : 1, borderColor: color === value ? theme.colors.ring : theme.colors.border, background: color }
7099
+ })) })] : []
7100
+ ] });
7101
+ }
7102
+ case "time": {
7103
+ const value = uncontrolled(id, props.value, props.defaultValue ?? "");
7104
+ const valid = /^([01]\d|2[0-3]):[0-5]\d$/.test(value);
7105
+ record(valid ? value : "");
7106
+ return Input({
7107
+ id,
7108
+ value,
7109
+ placeholder: props.placeholder ?? "--:--",
7110
+ disabled: props.disabled,
7111
+ style: { width: 110, fontFamily: "monospace", ...value && !valid ? { borderColor: theme.colors.destructive } : {}, ...style },
7112
+ onChange: (next) => {
7113
+ const digits = next.replace(/[^0-9]/g, "").slice(0, 4);
7114
+ const formatted = digits.length > 2 ? `${digits.slice(0, 2)}:${digits.slice(2)}` : digits;
7115
+ state.set(id, formatted);
7116
+ const ok = /^([01]\d|2[0-3]):[0-5]\d$/.test(formatted);
7117
+ record(ok ? formatted : "");
7118
+ if (ok)
7119
+ props.onChange?.(formatted);
7120
+ },
7121
+ onSubmit: () => form?.submit()
7122
+ });
7123
+ }
7124
+ case "file": {
7125
+ const files = uncontrolled(id, undefined, []);
7126
+ record(props.multiple ? files : files[0] ?? "");
7127
+ const label = files.length === 0 ? "No file chosen" : files.length === 1 ? files[0].split(/[\\/]/).pop() : `${files.length} files`;
7128
+ return Row({ id, gap: 8, align: "center", style, children: [
7129
+ Button({
7130
+ id: `${id}-choose`,
7131
+ variant: "outline",
7132
+ size: "sm",
7133
+ disabled: props.disabled,
7134
+ children: props.multiple ? "Choose files\u2026" : "Choose file\u2026",
7135
+ onClick: () => {
7136
+ const app = activeApp();
7137
+ if (!app)
7138
+ throw new Error('<input type="file"> needs a running app');
7139
+ const options = { filters: acceptFilters(props.accept) };
7140
+ const done = (paths) => {
7141
+ if (paths.length === 0)
7142
+ return;
7143
+ state.set(id, paths);
7144
+ record(props.multiple ? paths : paths[0]);
7145
+ props.onFiles?.(paths);
7146
+ props.onChange?.(paths[0]);
7147
+ app.update();
7148
+ };
7149
+ if (props.multiple)
7150
+ app.openFilesDialog(options).then(done);
7151
+ else
7152
+ app.openFileDialog(options).then((path) => done(path ? [path] : []));
7153
+ }
7154
+ }),
7155
+ Text({ id: `${id}-name`, color: theme.colors.mutedForeground, children: label })
7156
+ ] });
7157
+ }
7158
+ }
7159
+ throw new Error(`Unsupported input type: ${String(props.type)}`);
7160
+ }
7161
+ function childList(children) {
7162
+ return (Array.isArray(children) ? children.flat(Infinity) : [children]).filter((child) => child != null && typeof child !== "boolean");
7163
+ }
7164
+ function isElement(child, type) {
7165
+ return typeof child === "object" && child != null && !Array.isArray(child) && child.type === type;
7166
+ }
7167
+ function isInline(child) {
7168
+ if (typeof child === "string" || typeof child === "number")
7169
+ return true;
7170
+ return typeof child === "object" && child != null && !Array.isArray(child) && typeof child.type === "string" && INLINE_TAG_NAMES.has(child.type);
7171
+ }
7172
+ function flow(children) {
7173
+ const items = childList(children);
7174
+ if (!items.some((child) => typeof child === "object") || items.every((child) => !isInline(child)))
7175
+ return children;
7176
+ const out = [];
7177
+ let run = [];
7178
+ const flush = () => {
7179
+ if (run.length)
7180
+ out.push(run.length === 1 && typeof run[0] !== "object" ? run[0] : Text({ children: run }));
7181
+ run = [];
7182
+ };
7183
+ for (const child of items) {
7184
+ if (isInline(child))
7185
+ run.push(child);
7186
+ else {
7187
+ flush();
7188
+ out.push(child);
7189
+ }
7190
+ }
7191
+ flush();
7192
+ return out;
7193
+ }
7194
+ function block(props, extra, children, uaMargin) {
7195
+ return View({ ...props.id ? { id: props.id } : {}, ...uaMargin ? { uaMargin } : {}, style: { ...extra, ...canonicalizeIntrinsicStyle(props.style) }, children });
7196
+ }
7197
+ function expandHtml(type, props, key) {
7198
+ const children = props.children;
7199
+ switch (type) {
7200
+ case "pre":
7201
+ return jsx("p", { ...props, style: { fontFamily: "monospace", whiteSpace: "pre", ...canonicalizeIntrinsicStyle(props.style) } });
7202
+ case "blockquote":
7203
+ return block(props, { direction: "column" }, children, { block: 1, inline: 40 });
7204
+ case "meter": {
7205
+ const min = Number(props.min ?? 0);
7206
+ const max = Number(props.max ?? 1);
7207
+ const value = Math.min(max, Math.max(min, Number(props.value ?? 0)));
7208
+ return Progress({
7209
+ ...props.id ? { id: props.id } : {},
7210
+ value: value - min,
7211
+ max: max - min,
7212
+ label: props.ariaLabel ?? props.title ?? "Meter",
7213
+ style: { width: 80, height: 16, radius: 3, background: "#e6e6e6", foreground: "#107c10", ...canonicalizeIntrinsicStyle(props.style) }
7214
+ });
7215
+ }
7216
+ case "fieldset": {
7217
+ const items = childList(children);
7218
+ const legend = items.find((child) => isElement(child, "legend"));
7219
+ const rest = items.filter((child) => child !== legend);
7220
+ const legendProps = legend?.props;
7221
+ return block(props, {
7222
+ direction: "column",
7223
+ gap: 4,
7224
+ position: "relative",
7225
+ padding: { top: legend ? 10 : 6, right: 12, bottom: 10, left: 12 },
7226
+ margin: { left: 2, right: 2, top: legend ? 9 : 0 },
7227
+ borderWidth: 1,
7228
+ borderColor: "#b4b4b4"
7229
+ }, [
7230
+ legend ? View({ ...legendProps.id ? { id: legendProps.id } : {}, style: {
7231
+ position: "absolute",
7232
+ top: -10,
7233
+ left: 8,
7234
+ padding: { left: 2, right: 2 },
7235
+ background: theme.colors.background,
7236
+ ...canonicalizeIntrinsicStyle(legendProps.style)
7237
+ }, children: Text({ children: legendProps.children }) }) : null,
7238
+ jsx(View, { control: { role: "group", label: textOf(legend) }, style: { direction: "column", gap: 4 }, children: rest })
7239
+ ]);
7240
+ }
7241
+ case "legend":
7242
+ return Text({ ...props.id ? { id: props.id } : {}, style: canonicalizeIntrinsicStyle(props.style), children });
7243
+ case "ul":
7244
+ case "ol": {
7245
+ const items = childList(children);
7246
+ let number = Number(props.start ?? 1);
7247
+ return block(props, { direction: "column", padding: { left: 40 } }, items.map((item, index) => {
7248
+ if (!isElement(item, "li"))
7249
+ return item;
7250
+ const marker = type === "ul" ? "\u2022" : `${number++}.`;
7251
+ const itemProps = item.props;
7252
+ return Row({ key: itemProps.id ?? index, align: "start", style: { width: "100%" }, children: [
7253
+ View({ style: { position: "absolute", left: -40, width: 34, align: "end" }, children: Text({ children: marker }) }),
7254
+ View({ ...itemProps.id ? { id: itemProps.id } : {}, style: { flex: 1, direction: "column", ...canonicalizeIntrinsicStyle(itemProps.style) }, children: flow(itemProps.children) })
7255
+ ] });
7256
+ }), { block: 1 });
7257
+ }
7258
+ case "li":
7259
+ return block(props, { direction: "column" }, flow(children));
7260
+ case "dl":
7261
+ return block(props, { direction: "column" }, children, { block: 1 });
7262
+ case "dt":
7263
+ return block(props, { direction: "column" }, flow(children));
7264
+ case "dd":
7265
+ return block(props, { direction: "column", padding: { left: 40 } }, flow(children));
7266
+ case "details": {
7267
+ const id = String(props.id ?? key);
7268
+ const open = uncontrolled(id, props.open, false);
7269
+ const items = childList(children);
7270
+ const summary = items.find((child) => isElement(child, "summary"));
7271
+ const rest = items.filter((child) => child !== summary);
7272
+ const toggle = () => {
7273
+ const next = !open;
7274
+ state.set(id, next);
7275
+ props.onToggle?.(next);
7276
+ };
7277
+ return block({ ...props, id }, { direction: "column" }, [
7278
+ Pressable({
7279
+ id: `${id}-summary`,
7280
+ control: { role: "button", label: textOf(summary) || "Details", expanded: open },
7281
+ onClick: toggle,
7282
+ style: { direction: "row", gap: 6, align: "center", radius: 0 },
7283
+ children: [
7284
+ Icon({ name: open ? "chevron-down" : "chevron-right", size: 12 }),
7285
+ ...summary ? childList(summary.props.children).map((child) => typeof child === "string" ? Text({ children: child }) : child) : [Text({ children: "Details" })]
7286
+ ]
7287
+ }),
7288
+ ...open ? rest : []
7289
+ ]);
7290
+ }
7291
+ case "summary":
7292
+ return Text({ children });
7293
+ case "table":
7294
+ return expandTable(props, key);
7295
+ case "thead":
7296
+ case "tbody":
7297
+ case "tfoot":
7298
+ case "tr":
7299
+ case "th":
7300
+ case "td":
7301
+ case "caption":
7302
+ throw new Error(`<${type}> must be inside a <table>`);
7303
+ }
7304
+ throw new Error(`Unknown HTML element <${type}>`);
7305
+ }
7306
+ function textOf(child) {
7307
+ if (child == null || typeof child === "boolean")
7308
+ return "";
7309
+ if (typeof child === "string" || typeof child === "number")
7310
+ return String(child);
7311
+ if (Array.isArray(child))
7312
+ return child.map(textOf).join("");
7313
+ return textOf(child.props?.children);
7314
+ }
7315
+ function expandTable(props, key) {
7316
+ const rows = [];
7317
+ let caption;
7318
+ const collect = (children, section) => {
7319
+ for (const child of childList(children)) {
7320
+ if (isElement(child, "caption"))
7321
+ caption = child;
7322
+ else if (isElement(child, "thead") || isElement(child, "tbody") || isElement(child, "tfoot"))
7323
+ collect(child.props.children, String(child.type));
7324
+ else if (isElement(child, "tr")) {
7325
+ const trProps = child.props;
7326
+ rows.push({
7327
+ section,
7328
+ style: canonicalizeIntrinsicStyle(trProps.style),
7329
+ cells: childList(trProps.children).filter((cell) => isElement(cell, "td") || isElement(cell, "th"))
7330
+ });
7331
+ } else
7332
+ throw new Error("table children must be caption, thead, tbody, tfoot or tr");
7333
+ }
7334
+ };
7335
+ collect(props.children, "tbody");
7336
+ let columns = 1;
7337
+ const carried = [];
7338
+ for (const row of rows) {
7339
+ let width = 0;
7340
+ for (const cell of row.cells)
7341
+ width += Number(cell.props.colSpan ?? 1);
7342
+ const pending = carried.filter((rowsLeft) => rowsLeft > 0).length;
7343
+ columns = Math.max(columns, width + pending);
7344
+ for (let i = 0;i < carried.length; i++)
7345
+ carried[i]--;
7346
+ for (const cell of row.cells) {
7347
+ const span = Number(cell.props.rowSpan ?? 1);
7348
+ for (let c = 0;c < Number(cell.props.colSpan ?? 1); c++)
7349
+ if (span > 1)
7350
+ carried.push(span - 1);
7351
+ }
7352
+ }
7353
+ const id = String(props.id ?? key);
7354
+ const cells = rows.flatMap((row, r) => row.cells.map((cell, c) => {
7355
+ const cellProps = cell.props;
7356
+ const header = cell.type === "th" || row.section === "thead";
7357
+ const { background } = row.style;
7358
+ const colSpan = Number(cellProps.colSpan ?? 1);
7359
+ const rowSpan = Number(cellProps.rowSpan ?? 1);
7360
+ const content = typeof cellProps.children === "object" && cellProps.children !== null && !Array.isArray(cellProps.children) && typeof cellProps.children.type !== "string" ? cellProps.children : Text({ ...header ? { weight: 700 } : {}, style: { textAlign: header ? "center" : "start" }, children: cellProps.children });
7361
+ return View({
7362
+ key: `${r}:${c}`,
7363
+ ...cellProps.id ? { id: cellProps.id } : {},
7364
+ style: { padding: 1, justify: "center", ...colSpan > 1 ? { gridColumn: `span ${colSpan}` } : {}, ...rowSpan > 1 ? { gridRow: `span ${rowSpan}` } : {}, ...background ? { background } : {}, ...canonicalizeIntrinsicStyle(cellProps.style) },
7365
+ children: content
7366
+ });
7367
+ }));
7368
+ const grid = View({
7369
+ id,
7370
+ control: { role: "grid", label: textOf(caption) || "Table" },
7371
+ style: { display: "grid", columns: `repeat(${columns}, auto)`, gap: 2, padding: 2, justify: "start", ...canonicalizeIntrinsicStyle(props.style) },
7372
+ children: cells
7373
+ });
7374
+ return Column({ align: "start", children: [caption ? View({ style: { display: "grid", columns: "auto", justify: "start" }, children: [Text({ style: { textAlign: "center", width: "100%" }, children: caption.props.children }), grid] }) : grid] });
7375
+ }
7376
+
7377
+ // packages/core/src/reconciler.ts
7378
+ function luminance(color) {
7379
+ const hex = color.trim().replace(/^#/, "");
7380
+ const full = hex.length === 3 || hex.length === 4 ? [...hex.slice(0, 3)].map((c) => c + c).join("") : hex.slice(0, 6);
7381
+ if (!/^[0-9a-f]{6}$/i.test(full))
7382
+ return null;
7383
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16) / 255);
7384
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
7385
+ }
7386
+ function windowBorder(background, selected) {
7387
+ const own = luminance(background), themed = luminance(selected.colors.background);
7388
+ if (own === null || themed === null || own < 0.5 === themed < 0.5)
7389
+ return selected.colors.border;
7390
+ return own < 0.5 ? "#ffffff1f" : "#0000001f";
7391
+ }
5942
7392
  var kinds = new Set(["window", "titlebar", "view", "row", "column", "text", "markdown", "code", "diff", "button", "image", "svg", "scroll", "input", "textarea", "pressable", "slider", "splitter"]);
5943
7393
  var interactiveKinds = new Set(["button", "input", "textarea", "pressable", "slider", "splitter"]);
5944
7394
  var svgIntrinsicElements = new Set(["path", "circle", "ellipse", "g", "line", "polygon", "polyline", "rect"]);
7395
+ var UA_HEADING_MARGIN = { h1: 0.67, h2: 0.83, h3: 1, h4: 1.33, h5: 1.67, h6: 2.33 };
5945
7396
  var headingPreset = {
5946
7397
  h1: { size: 32, weight: 700 },
5947
7398
  h2: { size: 24, weight: 700 },
@@ -5965,14 +7416,140 @@ function textContent(value) {
5965
7416
  throw new Error("Text/Button children must be strings or numbers.");
5966
7417
  return String(value);
5967
7418
  }
7419
+ var INHERITED_FONT = ["fontFamily", "fontStyle", "letterSpacing", "wordSpacing", "fontVariantNumeric", "fontFeatureSettings", "fontSize", "fontWeight", "lineHeight", "foreground", "textAlign", "textTransform", "whiteSpace"];
7420
+ var INHERITING_TEXT = new Set(["text", "markdown"]);
7421
+ var TEXT_KINDS = new Set(["text", "button", "input", "textarea", "markdown", "code", "diff"]);
7422
+ var DIV_SHORTHANDS = ["gap", "padding", "flex", "align", "justify"];
7423
+ var COPIED_PROPS = [
7424
+ "value",
7425
+ "placeholder",
7426
+ "inputType",
7427
+ "scrollSpeed",
7428
+ "scrollOrientation",
7429
+ "virtualList",
7430
+ "disabled",
7431
+ "modal",
7432
+ "portal",
7433
+ "dismissOnOutside",
7434
+ "focusable",
7435
+ "dragRegion",
7436
+ "draggable",
7437
+ "dropTarget",
7438
+ "windowAction"
7439
+ ];
7440
+ var memoStores = new WeakMap;
7441
+ function invalidateMemos(renderScope, id) {
7442
+ const store = memoStores.get(renderScope);
7443
+ if (!store)
7444
+ return;
7445
+ for (const [path, entry] of store) {
7446
+ entry.idSet ??= new Set(entry.ids);
7447
+ if (entry.idSet.has(id))
7448
+ store.delete(path);
7449
+ }
7450
+ }
5968
7451
  function compileTree(element, debug = false, renderer = "auto", componentAdapters = [], renderScope, visible = true) {
5969
7452
  const handlers = new Map;
5970
7453
  const ids = new Set;
7454
+ const idLog = [];
5971
7455
  const nodes = new Map;
5972
7456
  const labelAssociations = new Map;
5973
7457
  const labelableTargets = new Map;
5974
7458
  let windowOptions;
5975
7459
  let selectedTheme = lightTheme;
7460
+ let inheritedFont = {};
7461
+ let currentForm;
7462
+ const media = new Map;
7463
+ let memoStore;
7464
+ if (renderScope) {
7465
+ memoStore = memoStores.get(renderScope);
7466
+ if (!memoStore)
7467
+ memoStores.set(renderScope, memoStore = new Map);
7468
+ }
7469
+ const memoSeen = new Set;
7470
+ function claimedSince(mark) {
7471
+ const own = idLog.slice(mark).filter((id) => ids.has(id));
7472
+ const pick = (map) => {
7473
+ const out = [];
7474
+ for (const id of own) {
7475
+ const value = map.get(id);
7476
+ if (value !== undefined)
7477
+ out.push([id, value]);
7478
+ }
7479
+ return out;
7480
+ };
7481
+ return { ids: own, nodes: pick(nodes), handlers: pick(handlers), media: pick(media) };
7482
+ }
7483
+ function added(set, skip) {
7484
+ const out = [];
7485
+ let index = 0;
7486
+ for (const value of set)
7487
+ if (index++ >= skip)
7488
+ out.push(value);
7489
+ return out;
7490
+ }
7491
+ function visitMemo(store, info, props, path, group) {
7492
+ memoSeen.add(path);
7493
+ const previous = store.get(path);
7494
+ if (previous && previous.render === info.render && previous.group === group && previous.theme === selectedTheme && previous.form === currentForm && sameValue(previous.font, inheritedFont) && info.equal(previous.props, props)) {
7495
+ for (const id of previous.ids) {
7496
+ if (ids.has(id))
7497
+ throw new Error(`Duplicate node id: ${id}`);
7498
+ ids.add(id);
7499
+ idLog.push(id);
7500
+ }
7501
+ for (const [id, node] of previous.nodes)
7502
+ nodes.set(id, node);
7503
+ for (const [id, handler] of previous.handlers)
7504
+ handlers.set(id, handler);
7505
+ for (const [id, request] of previous.media)
7506
+ media.set(id, request);
7507
+ for (const key of previous.nested)
7508
+ memoSeen.add(key);
7509
+ previous.props = props;
7510
+ return previous.result;
7511
+ }
7512
+ const seenBefore = memoSeen.size;
7513
+ const before = { log: idLog.length, labels: labelAssociations.size, labelable: labelableTargets.size, window: windowOptions };
7514
+ const font = inheritedFont;
7515
+ const theme2 = selectedTheme;
7516
+ const form = currentForm;
7517
+ const result = visit(info.render(props), path, group);
7518
+ const selfContained = labelAssociations.size === before.labels && labelableTargets.size === before.labelable && windowOptions === before.window;
7519
+ if (selfContained) {
7520
+ store.set(path, {
7521
+ render: info.render,
7522
+ props,
7523
+ group,
7524
+ theme: theme2,
7525
+ font,
7526
+ form,
7527
+ result,
7528
+ ...claimedSince(before.log),
7529
+ nested: added(memoSeen, seenBefore)
7530
+ });
7531
+ } else
7532
+ store.delete(path);
7533
+ return result;
7534
+ }
7535
+ function inlineContext(textId, base) {
7536
+ let runs = 0;
7537
+ return {
7538
+ base,
7539
+ linkColor: resolveStyleString("foreground", theme.colors.primary, selectedTheme),
7540
+ resolve: (style) => resolveThemeStyle(style, selectedTheme),
7541
+ register(id, onClick) {
7542
+ const runId = id ?? `${textId}/run:${runs++}`;
7543
+ if (ids.has(runId))
7544
+ throw new Error(`Duplicate node id: ${runId}`);
7545
+ ids.add(runId);
7546
+ idLog.push(runId);
7547
+ handlers.set(runId, { onClick });
7548
+ return runId;
7549
+ },
7550
+ openExternal
7551
+ };
7552
+ }
5976
7553
  function visit(child, path, group, adapterNative = false) {
5977
7554
  if (child == null || typeof child === "boolean")
5978
7555
  return [];
@@ -5985,9 +7562,9 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
5985
7562
  if (ids.has(path))
5986
7563
  throw new Error(`Duplicate node id: ${path}`);
5987
7564
  ids.add(path);
5988
- const node = { id: path, kind: "text", style: {}, text: String(child), children: [] };
5989
- nodes.set(path, node);
5990
- return [node];
7565
+ idLog.push(path);
7566
+ ids.delete(path);
7567
+ return visit(Text({ id: path, children: String(child) }), path, group);
5991
7568
  }
5992
7569
  if (child.type === Fragment || child.type === "fragment")
5993
7570
  return visit(child.props.children, path, group);
@@ -6002,38 +7579,143 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6002
7579
  return visit(adapted, path, group, adaptedIsNative);
6003
7580
  }
6004
7581
  }
6005
- if (typeof child.type === "function")
7582
+ if (typeof child.type === "function") {
7583
+ const info = child.type[MEMO];
7584
+ if (info && memoStore)
7585
+ return visitMemo(memoStore, info, child.props, path, group);
6006
7586
  return visit(child.type(child.props), path, group);
7587
+ }
6007
7588
  const isNativeVNode = adapterNative || _isNativeVNode(child);
6008
7589
  if (!isNativeVNode && child.type in headingPreset) {
6009
7590
  const props = child.props;
6010
7591
  const preset = headingPreset[child.type];
6011
7592
  return visit(Text({
7593
+ ...{ uaMargin: { block: UA_HEADING_MARGIN[child.type] } },
6012
7594
  ...props,
6013
7595
  size: props.size ?? preset.size,
6014
7596
  weight: props.weight ?? preset.weight,
6015
7597
  style: canonicalizeIntrinsicStyle(props.style)
6016
7598
  }), path, group);
6017
7599
  }
7600
+ if (!isNativeVNode && typeof child.type === "string" && child.type !== "span" && child.type !== "a" && INLINE_TAG_NAMES.has(child.type) && !(child.type === "code" && child.props.code !== undefined)) {
7601
+ return visit(Text({ id: child.props.id, children: child }), path, group);
7602
+ }
6018
7603
  if (!isNativeVNode && (child.type === "span" || child.type === "p")) {
6019
7604
  const props = child.props;
6020
- return visit(Text({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7605
+ return visit(Text({ ...child.type === "p" ? { uaMargin: { block: 1 } } : {}, ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
6021
7606
  }
6022
7607
  if (!isNativeVNode && child.type === "img") {
6023
7608
  const props = child.props;
6024
- return visit(Image({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7609
+ const objectFit = props.style?.objectFit;
7610
+ const fit = props.fit ?? (objectFit === "scale-down" ? "contain" : objectFit);
7611
+ return visit(Image({ ...props, ...fit ? { fit } : {}, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7612
+ }
7613
+ if (!isNativeVNode && child.type === "form") {
7614
+ const formProps = child.props;
7615
+ const values = formValues(String(formProps.id ?? path));
7616
+ const required = new Set;
7617
+ const form = {
7618
+ values,
7619
+ required,
7620
+ submit() {
7621
+ for (const name of required) {
7622
+ const value = values.get(name);
7623
+ if (value === undefined || value === "" || value === false || Array.isArray(value) && value.length === 0) {
7624
+ formProps.onInvalid?.(name);
7625
+ return;
7626
+ }
7627
+ }
7628
+ formProps.onSubmit?.(Object.fromEntries(values));
7629
+ }
7630
+ };
7631
+ const previous = currentForm;
7632
+ currentForm = form;
7633
+ try {
7634
+ return visit(jsx("div", { id: formProps.id, style: formProps.style, control: { role: "group", label: formProps.ariaLabel ?? "Form" }, children: formProps.children }), path, group);
7635
+ } finally {
7636
+ currentForm = previous;
7637
+ }
7638
+ }
7639
+ if (!isNativeVNode && child.type === "audio") {
7640
+ const props = child.props;
7641
+ const id = String(props.id ?? path);
7642
+ media.set(id, mediaRequest(props));
7643
+ return visit(expandAudio(props, id), path, group);
7644
+ }
7645
+ if (!isNativeVNode && child.type === "canvas") {
7646
+ return visit(expandCanvas(child.props, path), path, group);
7647
+ }
7648
+ if (!isNativeVNode && typeof child.type === "string" && HTML_ELEMENTS.has(child.type)) {
7649
+ if (child.type === "meter" && child.props.id !== undefined)
7650
+ labelableTargets.set(String(child.props.id), String(child.props.id));
7651
+ return visit(expandHtml(child.type, child.props, path), path, group);
7652
+ }
7653
+ if (!isNativeVNode && child.type === "input" && HTML_INPUT_TYPES.has(String(child.props.type))) {
7654
+ return visit(expandInput(child.props, path, currentForm), path, group);
6025
7655
  }
6026
7656
  if (!isNativeVNode && child.type === "input") {
6027
7657
  const props = child.props;
6028
- return visit(Input({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7658
+ const form = currentForm;
7659
+ const name = props.name;
7660
+ if (form && name) {
7661
+ form.values.set(name, props.value ?? form.values.get(name) ?? props.defaultValue ?? "");
7662
+ if (props.required)
7663
+ form.required.add(name);
7664
+ }
7665
+ const { name: _name, required: _required, defaultValue, ...rest } = props;
7666
+ return visit(Input({
7667
+ ...rest,
7668
+ ...rest.value === undefined && defaultValue !== undefined ? { value: defaultValue } : {},
7669
+ style: canonicalizeIntrinsicStyle(props.style),
7670
+ onChange: (value) => {
7671
+ if (form && name)
7672
+ form.values.set(name, value);
7673
+ props.onChange?.(value);
7674
+ },
7675
+ onSubmit: (value) => {
7676
+ props.onSubmit?.(value);
7677
+ if (form) {
7678
+ if (name)
7679
+ form.values.set(name, value);
7680
+ form.submit();
7681
+ }
7682
+ }
7683
+ }), path, group);
6029
7684
  }
6030
7685
  if (!isNativeVNode && child.type === "textarea") {
6031
7686
  const props = child.props;
6032
- return visit(TextArea({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7687
+ const form = currentForm;
7688
+ const name = props.name;
7689
+ if (form && name) {
7690
+ form.values.set(name, props.value ?? form.values.get(name) ?? props.defaultValue ?? "");
7691
+ if (props.required)
7692
+ form.required.add(name);
7693
+ }
7694
+ const { name: _name, required: _required, defaultValue, ...rest } = props;
7695
+ return visit(TextArea({
7696
+ ...rest,
7697
+ ...rest.value === undefined && defaultValue !== undefined ? { value: defaultValue } : {},
7698
+ style: canonicalizeIntrinsicStyle(props.style),
7699
+ onChange: (value) => {
7700
+ if (form && name)
7701
+ form.values.set(name, value);
7702
+ props.onChange?.(value);
7703
+ }
7704
+ }), path, group);
6033
7705
  }
6034
7706
  if (!isNativeVNode && child.type === "button") {
6035
- const props = child.props;
6036
- return visit(Button({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7707
+ const { type, ...props } = child.props;
7708
+ const form = currentForm;
7709
+ const submits = form && (type ?? "submit") === "submit";
7710
+ return visit(Button({
7711
+ ...props,
7712
+ style: canonicalizeIntrinsicStyle(props.style),
7713
+ onClick: () => {
7714
+ props.onClick?.();
7715
+ if (submits)
7716
+ form.submit();
7717
+ }
7718
+ }), path, group);
6037
7719
  }
6038
7720
  if (!isNativeVNode && child.type === "a") {
6039
7721
  const { ariaLabel, style, ...props } = child.props;
@@ -6062,7 +7744,7 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6062
7744
  return visit(Label({ ...props, id: String(id), style: canonicalizeIntrinsicStyle(props.style) }), path, group);
6063
7745
  }
6064
7746
  if (!isNativeVNode && child.type === "select") {
6065
- const { children, onChange, onValueChange, ...rawProps } = child.props;
7747
+ const { children, onChange, onValueChange, name, required, defaultValue, ...rawProps } = child.props;
6066
7748
  const id = String(rawProps.id ?? path);
6067
7749
  const optionNodes = Array.isArray(children) ? children.flat(Infinity) : [children];
6068
7750
  const options = optionNodes.filter((option) => option != null && option !== false && option !== true).map((option) => {
@@ -6079,14 +7761,26 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6079
7761
  });
6080
7762
  labelableTargets.set(id, `${id}-trigger`);
6081
7763
  const props = rawProps;
7764
+ const form = currentForm;
7765
+ const key = `select:${id}`;
7766
+ const value = props.value ?? (form && name && form.values.has(name) ? String(form.values.get(name)) : undefined) ?? storedValue(key, defaultValue ?? options.find((option) => !option.disabled)?.value);
7767
+ if (form && name) {
7768
+ form.values.set(name, value ?? "");
7769
+ if (required)
7770
+ form.required.add(name);
7771
+ }
6082
7772
  return visit(Select({
6083
7773
  ...props,
6084
7774
  id,
6085
7775
  options,
7776
+ value,
6086
7777
  style: canonicalizeIntrinsicStyle(props.style),
6087
- onValueChange: (value) => {
6088
- onValueChange?.(value);
6089
- onChange?.(value);
7778
+ onValueChange: (next) => {
7779
+ storeValue(key, next);
7780
+ if (form && name)
7781
+ form.values.set(name, next);
7782
+ onValueChange?.(next);
7783
+ onChange?.(next);
6090
7784
  }
6091
7785
  }), path, group);
6092
7786
  }
@@ -6095,12 +7789,36 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6095
7789
  }
6096
7790
  if (!isNativeVNode && child.type === "progress") {
6097
7791
  const props = child.props;
6098
- return visit(Progress({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
7792
+ if (props.id !== undefined)
7793
+ labelableTargets.set(String(props.id), String(props.id));
7794
+ return visit(Progress({ ...props, style: { width: 160, height: 16, radius: 3, background: "#e6e6e6", foreground: "#0075ff", ...canonicalizeIntrinsicStyle(props.style) } }), path, group);
6099
7795
  }
6100
7796
  if (!isNativeVNode && child.type === "hr") {
6101
7797
  const props = child.props;
6102
7798
  return visit(Separator({ ...props, style: canonicalizeIntrinsicStyle(props.style) }), path, group);
6103
7799
  }
7800
+ if (!isNativeVNode && child.type === "div") {
7801
+ const { style: divStyle, ...divProps } = child.props;
7802
+ const { overflow, overflowX: explicitX, overflowY = overflow, ...rest } = divStyle ?? {};
7803
+ const scrolls = (value) => value === "auto" || value === "scroll";
7804
+ const overflowX = explicitX ?? (scrolls(overflow) ? "visible" : overflow);
7805
+ if (scrolls(overflowX) || scrolls(overflowY)) {
7806
+ const shorthands = {};
7807
+ for (const key of DIV_SHORTHANDS)
7808
+ if (divProps[key] !== undefined) {
7809
+ shorthands[key] = divProps[key];
7810
+ delete divProps[key];
7811
+ }
7812
+ return visit(Scroll({
7813
+ ...divProps,
7814
+ orientation: scrolls(overflowX) && scrolls(overflowY) ? "both" : scrolls(overflowX) ? "horizontal" : "vertical",
7815
+ style: { ...shorthands, ...canonicalizeIntrinsicStyle(rest) }
7816
+ }), path, group);
7817
+ }
7818
+ if (explicitX !== undefined || overflowY !== overflow) {
7819
+ return visit(jsx("div", { ...child.props, style: { ...rest, overflow: (overflowX ?? "visible") === "visible" && (overflowY ?? "visible") === "visible" ? "visible" : "hidden" } }, child.key), path, group);
7820
+ }
7821
+ }
6104
7822
  const isIntrinsicDiv = child.type === "div";
6105
7823
  const nativeType = isIntrinsicDiv ? "view" : child.type;
6106
7824
  if (!kinds.has(nativeType))
@@ -6110,6 +7828,7 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6110
7828
  if (ids.has(id))
6111
7829
  throw new Error(`Duplicate node id: ${id}`);
6112
7830
  ids.add(id);
7831
+ idLog.push(id);
6113
7832
  if (nativeType === "window") {
6114
7833
  if (windowOptions)
6115
7834
  throw new Error("This bootstrap supports one Window per app.");
@@ -6135,7 +7854,7 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6135
7854
  else
6136
7855
  p.onMouseLeave?.();
6137
7856
  } : p.onHover;
6138
- handlers.set(id, { onClick: p.onClick, onMarkdownLink: p.onMarkdownLink, onDiffToggleFile: p.onToggleFile, onDiffShowMore: p.onShowMore, onDiffLineClick: p.onLineClick, onHighlight: p.onHighlight, onContextMenu: p.onContextMenu, onOutsideClick: p.onOutsideClick, onHover: hoverHandler, onChange: p.onChange, onSubmit: p.onSubmit, onPaste: p.onPaste, onValueChange: p.onValueChange, onScroll: p.onScroll, onScrollPosition: p.onScrollPosition, onVirtualListLayout: p.onVirtualListLayout, onVirtualListScrollToItem: p.onVirtualListScrollToItem, onVirtualListFocus: p.onVirtualListFocus, onEscape: p.onEscape, onKeyDown: p.onKeyDown, onBlur: p.onBlur, onCloseRequest: p.onCloseRequest, onTransitionEnd: p.onTransitionEnd });
7857
+ handlers.set(id, { onClick: p.onClick, onMarkdownLink: p.onMarkdownLink, onDiffToggleFile: p.onToggleFile, onDiffShowMore: p.onShowMore, onDiffLineClick: p.onLineClick, onHighlight: p.onHighlight, onContextMenu: p.onContextMenu, onOutsideClick: p.onOutsideClick, onHover: hoverHandler, onChange: p.onChange, onSubmit: p.onSubmit, onPaste: p.onPaste, onValueChange: p.onValueChange, onScroll: p.onScroll, onScrollPosition: p.onScrollPosition, onVirtualListLayout: p.onVirtualListLayout, onVirtualListScrollToItem: p.onVirtualListScrollToItem, onVirtualListFocus: p.onVirtualListFocus, onEscape: p.onEscape, onKeyDown: p.onKeyDown, onBlur: p.onBlur, onCloseRequest: p.onCloseRequest, onTransitionEnd: p.onTransitionEnd, onDragStart: p.onDragStart, onDragMove: p.onDragMove, onDragEnd: p.onDragEnd, onDragEnter: p.onDragEnter, onDragLeave: p.onDragLeave, onDrop: p.onDrop, onSize: p.onSize, onPointerMove: p.onPointerMove, onPointerLeave: p.onPointerLeave });
6139
7858
  const control = p.control ? { ...p.control } : undefined;
6140
7859
  const childGroup = control?.role === "radiogroup" || control?.role === "tablist" || control?.role === "navigation" || control?.role === "togglegroup" || control?.role === "tree" || control?.role === "grid" ? id : group;
6141
7860
  const semanticRoving = control && (control.role === "radio" || control.role === "tab" || control.role === "menuitem" || control.role === "toggle" || control.role === "treeitem" || control.role === "row");
@@ -6146,8 +7865,15 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6146
7865
  const isRichLeaf = nativeType === "markdown" || nativeType === "code" || nativeType === "diff";
6147
7866
  if (isRichLeaf && p.children != null)
6148
7867
  throw new Error(`${nativeType} is a native leaf and cannot have children.`);
6149
- const divShorthands = isIntrinsicDiv ? Object.fromEntries(Object.entries({ gap: p.gap, padding: p.padding, flex: p.flex, align: p.align, justify: p.justify }).filter(([, value]) => value !== undefined)) : {};
7868
+ const divShorthands = {};
7869
+ if (isIntrinsicDiv) {
7870
+ for (const key of DIV_SHORTHANDS)
7871
+ if (p[key] !== undefined)
7872
+ divShorthands[key] = p[key];
7873
+ }
6150
7874
  const rawStyle = isIntrinsicDiv ? { ...divShorthands, ...canonicalizeIntrinsicStyle(p.style) } : { ...p.style };
7875
+ if (isIntrinsicDiv && rawStyle.display === "flex" && rawStyle.direction === undefined)
7876
+ rawStyle.direction = "row";
6151
7877
  if (interactiveKinds.has(nativeType) && p.focusable !== false || control?.role === "otpSlot") {
6152
7878
  rawStyle.focusVisible = {
6153
7879
  outlineColor: theme.colors.ring,
@@ -6165,51 +7891,122 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6165
7891
  style[key] = { ...style[key] };
6166
7892
  }
6167
7893
  const imageSource = nativeType === "image" && p.src !== undefined ? serializeImageSource(p.src) : undefined;
6168
- const node = {
6169
- id,
6170
- kind: nativeType,
6171
- style,
6172
- children: isText || isRichLeaf ? [] : visit(p.children, `${path}/children`, childGroup),
6173
- ...isText ? { text: textContent(p.children) } : {},
6174
- ...nativeType === "code" ? { text: p.code } : {},
6175
- ...nativeType === "markdown" || nativeType === "diff" ? { source: p.source } : {},
6176
- ...p.language !== undefined ? { language: p.language } : {},
6177
- ...p.path !== undefined ? { path: p.path } : {},
6178
- ...p.showLineNumbers !== undefined ? { showLineNumbers: p.showLineNumbers } : {},
6179
- ...p.wordDiff !== undefined ? { wordDiff: p.wordDiff } : {},
6180
- ...p.collapsedPaths !== undefined ? { collapsedPaths: [...p.collapsedPaths] } : {},
6181
- ...p.maxLines !== undefined ? { maxLines: p.maxLines } : {},
6182
- ...p.highlight !== undefined ? { highlight: p.highlight } : {},
6183
- ...isRichLeaf ? { syntaxTheme: { ...selectedTheme.syntax, ...p.syntaxTheme } } : {},
6184
- ...p.oldText !== undefined ? { oldText: p.oldText } : {},
6185
- ...p.newText !== undefined ? { newText: p.newText } : {},
6186
- ...p.svg !== undefined ? { svg: p.svg } : {},
6187
- ...control ? { control } : {},
6188
- ...imageSource && "path" in imageSource ? { src: nativeAssetPath(imageSource.path), fit: p.fit ?? "cover" } : imageSource ? { image: imageSource.image, fit: p.fit ?? "cover" } : {},
6189
- ...p.value !== undefined ? { value: p.value } : {},
6190
- ...p.placeholder !== undefined ? { placeholder: p.placeholder } : {},
6191
- ...p.inputType !== undefined ? { inputType: p.inputType } : {},
6192
- ...p.submitOnEnter !== undefined ? { submitOnEnter: p.submitOnEnter === true } : {},
6193
- ...p.scrollSpeed !== undefined ? { scrollSpeed: p.scrollSpeed } : {},
6194
- ...p.scrollOrientation !== undefined ? { scrollOrientation: p.scrollOrientation } : {},
6195
- ...p.virtualList !== undefined ? { virtualList: p.virtualList } : {},
6196
- ...p.disabled !== undefined ? { disabled: p.disabled } : {},
6197
- ...p.modal !== undefined ? { modal: p.modal } : {},
6198
- ...rovingGroup ? { rovingGroup } : {},
6199
- ...p.portal !== undefined ? { portal: p.portal } : {},
6200
- ...p.dismissOnOutside !== undefined ? { dismissOnOutside: p.dismissOnOutside } : {},
6201
- ...nativeType === "window" && p.onCloseRequest !== undefined ? { closeIntercept: true } : {},
6202
- ...p.focusable !== undefined ? { focusable: p.focusable } : {},
6203
- ...p.dragRegion !== undefined ? { dragRegion: p.dragRegion } : {},
6204
- ...p.windowAction !== undefined ? { windowAction: p.windowAction } : {},
6205
- ...p.motionFrom !== undefined ? { motionFrom: { ...p.motionFrom } } : {}
6206
- };
7894
+ const parentFont = inheritedFont;
7895
+ const fontStyle = style;
7896
+ if (INHERITING_TEXT.has(nativeType)) {
7897
+ const initial = {
7898
+ fontFamily: theme.font.family,
7899
+ fontSize: theme.font.size,
7900
+ fontWeight: 400,
7901
+ lineHeight: theme.font.lineHeight,
7902
+ foreground: resolveStyleString("foreground", theme.colors.foreground, selectedTheme)
7903
+ };
7904
+ for (const key of INHERITED_FONT)
7905
+ if (fontStyle[key] === undefined)
7906
+ fontStyle[key] = parentFont[key] ?? initial[key];
7907
+ for (const key of INHERITED_FONT)
7908
+ if (fontStyle[key] === undefined)
7909
+ delete fontStyle[key];
7910
+ } else if (TEXT_KINDS.has(nativeType)) {
7911
+ for (const key of ["fontFamily", "fontStyle", "letterSpacing", "wordSpacing", "textTransform"]) {
7912
+ if (fontStyle[key] === undefined && parentFont[key] !== undefined)
7913
+ fontStyle[key] = parentFont[key];
7914
+ }
7915
+ fontStyle.fontFamily ??= theme.font.family;
7916
+ }
7917
+ let ownFont = parentFont;
7918
+ for (const key of INHERITED_FONT) {
7919
+ if (fontStyle[key] !== undefined && fontStyle[key] !== parentFont[key]) {
7920
+ if (ownFont === parentFont)
7921
+ ownFont = { ...parentFont };
7922
+ ownFont[key] = fontStyle[key];
7923
+ }
7924
+ }
7925
+ inheritedFont = ownFont;
7926
+ const uaMargin = p.uaMargin;
7927
+ if (uaMargin && style.margin === undefined) {
7928
+ const size = Number(fontStyle.fontSize ?? parentFont.fontSize ?? theme.font.size);
7929
+ const vertical = Math.round(uaMargin.block * size * 100) / 100;
7930
+ style.margin = { top: vertical, bottom: vertical, left: uaMargin.inline ?? 0, right: uaMargin.inline ?? 0 };
7931
+ }
7932
+ let children;
7933
+ try {
7934
+ children = isText || isRichLeaf ? [] : visit(p.children, `${id}/children`, childGroup);
7935
+ } finally {
7936
+ inheritedFont = parentFont;
7937
+ }
7938
+ const node = { id, kind: nativeType, style, children };
7939
+ const optional = node;
7940
+ if (nativeType === "text") {
7941
+ const inline = compileInline(p.children, String(style.whiteSpace ?? "normal"), inlineContext(id, style));
7942
+ node.text = inline.text;
7943
+ if (inline.runs.length)
7944
+ node.runs = inline.runs;
7945
+ } else if (isText)
7946
+ node.text = textContent(p.children);
7947
+ if (nativeType === "code")
7948
+ node.text = p.code;
7949
+ if (nativeType === "markdown" || nativeType === "diff")
7950
+ node.source = p.source;
7951
+ if (p.language !== undefined)
7952
+ node.language = p.language;
7953
+ if (p.path !== undefined)
7954
+ node.path = p.path;
7955
+ if (p.dropTarget === undefined && (p.onDrop || p.onDragEnter || p.onDragLeave))
7956
+ node.dropTarget = true;
7957
+ if (p.onSize)
7958
+ node.reportSize = true;
7959
+ if (p.onPointerMove || p.onPointerLeave)
7960
+ node.reportPointer = true;
7961
+ if (p.showLineNumbers !== undefined)
7962
+ node.showLineNumbers = p.showLineNumbers;
7963
+ if (p.wordDiff !== undefined)
7964
+ node.wordDiff = p.wordDiff;
7965
+ if (p.collapsedPaths !== undefined)
7966
+ node.collapsedPaths = [...p.collapsedPaths];
7967
+ if (p.maxLines !== undefined)
7968
+ node.maxLines = p.maxLines;
7969
+ if (p.highlight !== undefined)
7970
+ node.highlight = p.highlight;
7971
+ if (isRichLeaf)
7972
+ node.syntaxTheme = { ...selectedTheme.syntax, ...p.syntaxTheme };
7973
+ if (p.oldText !== undefined)
7974
+ node.oldText = p.oldText;
7975
+ if (p.newText !== undefined)
7976
+ node.newText = p.newText;
7977
+ if (p.svg !== undefined)
7978
+ node.svg = p.svg;
7979
+ if (control)
7980
+ node.control = control;
7981
+ if (imageSource && "path" in imageSource) {
7982
+ node.src = nativeAssetPath(imageSource.path);
7983
+ node.fit = p.fit ?? "cover";
7984
+ } else if (imageSource) {
7985
+ node.image = imageSource.image;
7986
+ node.fit = p.fit ?? "cover";
7987
+ }
7988
+ for (const key of COPIED_PROPS)
7989
+ if (p[key] !== undefined)
7990
+ optional[key] = p[key];
7991
+ if (p.submitOnEnter !== undefined)
7992
+ node.submitOnEnter = p.submitOnEnter === true;
7993
+ if (rovingGroup)
7994
+ node.rovingGroup = rovingGroup;
7995
+ if (nativeType === "window" && p.onCloseRequest !== undefined)
7996
+ node.closeIntercept = true;
7997
+ if (p.motionFrom !== undefined)
7998
+ node.motionFrom = { ...p.motionFrom };
6207
7999
  if (nativeType === "input" || nativeType === "textarea")
6208
8000
  labelableTargets.set(id, id);
6209
8001
  nodes.set(id, node);
6210
8002
  return [node];
6211
8003
  }
6212
8004
  const roots = withRenderScope(renderScope, () => visit(element, "root"));
8005
+ if (memoStore) {
8006
+ for (const path of memoStore.keys())
8007
+ if (!memoSeen.has(path))
8008
+ memoStore.delete(path);
8009
+ }
6213
8010
  for (const [targetId, labelIds] of labelAssociations) {
6214
8011
  const nativeTargetId = labelableTargets.get(targetId);
6215
8012
  if (!nativeTargetId)
@@ -6227,10 +8024,10 @@ function compileTree(element, debug = false, renderer = "auto", componentAdapter
6227
8024
  if (titleBars.length === 1) {
6228
8025
  windowOptions.decorations = false;
6229
8026
  roots[0].style.borderWidth ??= 1;
6230
- roots[0].style.borderColor ??= selectedTheme.colors.border;
8027
+ roots[0].style.borderColor ??= windowBorder(String(roots[0].style.background ?? ""), selectedTheme);
6231
8028
  roots[0].style.radius ??= theme.radius.md;
6232
8029
  }
6233
- return { document: { version: PROTOCOL_VERSION, renderer, window: windowOptions, root: roots[0] }, handlers, nodes };
8030
+ return { document: { version: PROTOCOL_VERSION, renderer, window: windowOptions, root: roots[0] }, handlers, nodes, media };
6234
8031
  }
6235
8032
  function sameValue(a, b) {
6236
8033
  if (a === b)
@@ -6257,12 +8054,12 @@ function sameChildren(a, b) {
6257
8054
  return a.children.length === b.children.length && a.children.every((child, index) => child.id === b.children[index]?.id);
6258
8055
  }
6259
8056
  function nodePropertiesChanged(old, node) {
6260
- return old.text !== node.text || old.source !== node.source || old.language !== node.language || old.path !== node.path || old.showLineNumbers !== node.showLineNumbers || !sameValue(old.syntaxTheme, node.syntaxTheme) || old.wordDiff !== node.wordDiff || !sameValue(old.collapsedPaths, node.collapsedPaths) || old.maxLines !== node.maxLines || old.oldText !== node.oldText || old.newText !== node.newText || old.src !== node.src || old.fit !== node.fit || !sameValue(old.svg, node.svg) || old.value !== node.value || old.placeholder !== node.placeholder || old.inputType !== node.inputType || old.submitOnEnter !== node.submitOnEnter || old.scrollSpeed !== node.scrollSpeed || old.scrollOrientation !== node.scrollOrientation || !sameValue(old.virtualList, node.virtualList) || old.disabled !== node.disabled || old.modal !== node.modal || old.rovingGroup !== node.rovingGroup || old.portal !== node.portal || old.dismissOnOutside !== node.dismissOnOutside || !sameValue(old.labelledBy, node.labelledBy) || old.closeIntercept !== node.closeIntercept || old.focusable !== node.focusable || old.dragRegion !== node.dragRegion || old.windowAction !== node.windowAction || !sameValue(old.motionFrom, node.motionFrom) || !sameValue(old.highlight, node.highlight) || !sameFields(old.control ?? {}, node.control ?? {}) || !sameStyle(old.style, node.style);
8057
+ return old.text !== node.text || old.source !== node.source || old.language !== node.language || old.path !== node.path || old.showLineNumbers !== node.showLineNumbers || !sameValue(old.syntaxTheme, node.syntaxTheme) || old.wordDiff !== node.wordDiff || !sameValue(old.collapsedPaths, node.collapsedPaths) || old.maxLines !== node.maxLines || old.oldText !== node.oldText || old.newText !== node.newText || old.src !== node.src || old.fit !== node.fit || !sameValue(old.svg, node.svg) || old.image?.key !== node.image?.key || old.image?.kind !== node.image?.kind || old.image?.data !== node.image?.data || old.value !== node.value || old.placeholder !== node.placeholder || old.inputType !== node.inputType || old.submitOnEnter !== node.submitOnEnter || old.scrollSpeed !== node.scrollSpeed || old.scrollOrientation !== node.scrollOrientation || !sameValue(old.virtualList, node.virtualList) || old.disabled !== node.disabled || old.modal !== node.modal || old.rovingGroup !== node.rovingGroup || old.portal !== node.portal || old.dismissOnOutside !== node.dismissOnOutside || !sameValue(old.labelledBy, node.labelledBy) || old.closeIntercept !== node.closeIntercept || old.focusable !== node.focusable || old.dragRegion !== node.dragRegion || old.draggable !== node.draggable || old.dropTarget !== node.dropTarget || old.reportSize !== node.reportSize || old.reportPointer !== node.reportPointer || old.windowAction !== node.windowAction || !sameValue(old.motionFrom, node.motionFrom) || !sameValue(old.highlight, node.highlight) || !sameFields(old.control ?? {}, node.control ?? {}) || !sameStyle(old.style, node.style);
6261
8058
  }
6262
8059
  function flatNode(node) {
6263
8060
  return { ...node, children: [] };
6264
8061
  }
6265
- function diffTreeMutations(previous, next) {
8062
+ function diffTreeMutations(previous, next, unchanged) {
6266
8063
  if (previous.document.root.id !== next.document.root.id)
6267
8064
  return null;
6268
8065
  const creates = [];
@@ -6278,6 +8075,8 @@ function diffTreeMutations(previous, next) {
6278
8075
  }
6279
8076
  continue;
6280
8077
  }
8078
+ if (old === node || unchanged?.(old, node))
8079
+ continue;
6281
8080
  if (old.kind !== node.kind)
6282
8081
  return null;
6283
8082
  if (nodePropertiesChanged(old, node))
@@ -6322,9 +8121,178 @@ function DevErrorOverlay(props) {
6322
8121
  });
6323
8122
  }
6324
8123
 
8124
+ // packages/core/src/app-metadata.ts
8125
+ import { createHash as createHash3 } from "crypto";
8126
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
8127
+ import { homedir, tmpdir as tmpdir2 } from "os";
8128
+ import { join as join2, resolve as resolve2 } from "path";
8129
+
8130
+ // packages/core/src/embedded-assets.ts
8131
+ import { createHash as createHash2, randomUUID } from "crypto";
8132
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
8133
+ import { tmpdir } from "os";
8134
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
8135
+ import { createRequire as createRequire2 } from "module";
8136
+ var materialized = new Map;
8137
+ function nativeAssetPath2(source) {
8138
+ if (/^https?:\/\//i.test(source))
8139
+ return source;
8140
+ const path = isAbsolute(source) ? source : resolve(sourceRoot(source), source);
8141
+ const normalized = path.replaceAll("\\", "/");
8142
+ if (normalized.startsWith("/$bunfs/") || /^[a-z]:\/~BUN\//i.test(normalized)) {
8143
+ return materializeAsset(path, basename(path));
8144
+ }
8145
+ if (typeof Bun === "undefined" && path.startsWith(import.meta.dirname + (process.platform === "win32" ? "\\" : "/"))) {
8146
+ const { isSea } = createRequire2(import.meta.url)("node:sea");
8147
+ if (isSea())
8148
+ return materializeAsset(path, basename(path));
8149
+ }
8150
+ return path;
8151
+ }
8152
+ function materializeAsset(source, filename, digest) {
8153
+ if (!filename || filename === "." || filename === ".." || basename(filename) !== filename) {
8154
+ throw new Error("An embedded asset filename must be a simple filename");
8155
+ }
8156
+ const key = `${source}\x00${filename}`;
8157
+ const cached = materialized.get(key);
8158
+ if (cached)
8159
+ return cached;
8160
+ if (digest) {
8161
+ const path = join(tmpdir(), "tarve-assets", digest.sha256, filename);
8162
+ if (sizeOf(path) === digest.size) {
8163
+ materialized.set(key, path);
8164
+ return path;
8165
+ }
8166
+ }
8167
+ const bytes = readFileSync(source);
8168
+ const hash = createHash2("sha256").update(bytes).digest("hex");
8169
+ if (digest && hash !== digest.sha256) {
8170
+ throw new Error(`Embedded asset ${filename} does not match its build-time digest; rebuild the executable.`);
8171
+ }
8172
+ const directory = join(tmpdir(), "tarve-assets", hash);
8173
+ const path = join(directory, filename);
8174
+ mkdirSync(directory, { recursive: true });
8175
+ if (!existsSync(path) || digest && sizeOf(path) !== digest.size) {
8176
+ const temporary = join(directory, `${filename}.${randomUUID()}.tmp`);
8177
+ try {
8178
+ writeFileSync(temporary, bytes, { flag: "wx" });
8179
+ try {
8180
+ renameSync(temporary, path);
8181
+ } catch (error) {
8182
+ if (!existsSync(path))
8183
+ throw error;
8184
+ }
8185
+ } finally {
8186
+ rmSync(temporary, { force: true });
8187
+ }
8188
+ }
8189
+ const actual = createHash2("sha256").update(readFileSync(path)).digest("hex");
8190
+ if (actual !== hash)
8191
+ throw new Error(`Embedded asset cache is corrupt. Remove this file and retry: ${path}`);
8192
+ materialized.set(key, path);
8193
+ return path;
8194
+ }
8195
+ function sizeOf(path) {
8196
+ try {
8197
+ return statSync(path).size;
8198
+ } catch {
8199
+ return;
8200
+ }
8201
+ }
8202
+ function sourceRoot(source) {
8203
+ if (typeof Bun !== "undefined")
8204
+ return dirname(Bun.main);
8205
+ const roots = [import.meta.dirname, process.env.TARVE_ENTRY && dirname(process.env.TARVE_ENTRY), process.argv[1] && dirname(resolve(process.argv[1]))].filter((root) => !!root);
8206
+ return roots.find((root) => existsSync(resolve(root, source))) ?? roots[0];
8207
+ }
8208
+
8209
+ // packages/core/src/png.ts
8210
+ var SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
8211
+ function isPng(bytes) {
8212
+ return SIGNATURE.every((value, index) => bytes[index] === value);
8213
+ }
8214
+ function pngSize(bytes) {
8215
+ if (!isPng(bytes) || bytes.length < 24)
8216
+ return;
8217
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
8218
+ return { width: view.getUint32(16), height: view.getUint32(20) };
8219
+ }
8220
+ var CRC_TABLE = new Uint32Array(256).map((_, n) => {
8221
+ let c = n;
8222
+ for (let k = 0;k < 8; k++)
8223
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
8224
+ return c >>> 0;
8225
+ });
8226
+ function encodeIco(entries) {
8227
+ const header = Buffer.alloc(6 + entries.length * 16);
8228
+ header.writeUInt16LE(0, 0);
8229
+ header.writeUInt16LE(1, 2);
8230
+ header.writeUInt16LE(entries.length, 4);
8231
+ let offset = header.length;
8232
+ entries.forEach(({ size, png }, index) => {
8233
+ const at = 6 + index * 16;
8234
+ header[at] = size >= 256 ? 0 : size;
8235
+ header[at + 1] = size >= 256 ? 0 : size;
8236
+ header.writeUInt16LE(1, at + 4);
8237
+ header.writeUInt16LE(32, at + 6);
8238
+ header.writeUInt32LE(png.length, at + 8);
8239
+ header.writeUInt32LE(offset, at + 12);
8240
+ offset += png.length;
8241
+ });
8242
+ return new Uint8Array(Buffer.concat([header, ...entries.map((entry) => Buffer.from(entry.png))]));
8243
+ }
8244
+ function isIco(bytes) {
8245
+ return bytes.length >= 6 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0;
8246
+ }
8247
+
8248
+ // packages/core/src/app-metadata.ts
8249
+ var cached;
8250
+ function runtimeAppMetadata() {
8251
+ if (cached)
8252
+ return cached;
8253
+ const raw = typeof process === "undefined" ? undefined : process.env.TARVE_APP_METADATA;
8254
+ try {
8255
+ cached = raw ? JSON.parse(raw) : {};
8256
+ } catch {
8257
+ cached = {};
8258
+ }
8259
+ return cached;
8260
+ }
8261
+ function iconBytes(icon) {
8262
+ if (icon.startsWith("data:")) {
8263
+ const comma = icon.indexOf(",");
8264
+ if (comma < 0)
8265
+ throw new TypeError("Invalid icon data URL");
8266
+ return new Uint8Array(Buffer.from(icon.slice(comma + 1), icon.slice(0, comma).endsWith(";base64") ? "base64" : "utf8"));
8267
+ }
8268
+ return new Uint8Array(readFileSync2(nativeAssetPath2(icon)));
8269
+ }
8270
+ function iconFileForShell(icon) {
8271
+ if (!icon.startsWith("data:") && icon.toLowerCase().endsWith(".ico"))
8272
+ return resolve2(nativeAssetPath2(icon));
8273
+ const bytes = iconBytes(icon);
8274
+ if (isIco(bytes))
8275
+ return writeCached(bytes);
8276
+ const size = pngSize(bytes);
8277
+ if (!size)
8278
+ return;
8279
+ return writeCached(encodeIco([{ size: Math.min(256, Math.max(size.width, size.height)), png: bytes }]));
8280
+ }
8281
+ function writeCached(ico) {
8282
+ const base = process.env.LOCALAPPDATA ?? (homedir() ? join2(homedir(), ".cache") : tmpdir2());
8283
+ const directory = join2(base, "tarve", "icons");
8284
+ const path = join2(directory, createHash3("sha256").update(ico).digest("hex").slice(0, 32) + ".ico");
8285
+ if (!existsSync2(path)) {
8286
+ mkdirSync2(directory, { recursive: true });
8287
+ writeFileSync2(path, ico);
8288
+ }
8289
+ return path;
8290
+ }
8291
+
6325
8292
  // packages/core/src/app.ts
6326
8293
  var DEV_OVERLAY_SOURCES = new Set(["render", "event-handler", "listener", "hotkey"]);
6327
8294
  var DEV_APP_KEY = Symbol.for("tarve.devApp");
8295
+ var ACTIVE_APP_KEY = Symbol.for("tarve.activeApp");
6328
8296
  function envFlag(name) {
6329
8297
  return typeof process !== "undefined" && process.env?.[name] === "1";
6330
8298
  }
@@ -6349,10 +8317,25 @@ function validateFileDialogOptions(options) {
6349
8317
  throw new TypeError("Invalid file dialog extension");
6350
8318
  }
6351
8319
  }
8320
+ var shadowSources = new WeakMap;
8321
+ var shadowEdited = false;
6352
8322
  function nativeShadow(tree, previous) {
6353
8323
  const nodes = new Map;
8324
+ const reuse = !shadowEdited;
8325
+ shadowEdited = false;
8326
+ const keep = (node) => {
8327
+ nodes.set(node.id, node);
8328
+ for (const child of node.children)
8329
+ keep(child);
8330
+ };
6354
8331
  const copy = (source) => {
8332
+ const kept = previous?.nodes.get(source.id);
8333
+ if (reuse && kept && shadowSources.get(kept) === source) {
8334
+ keep(kept);
8335
+ return kept;
8336
+ }
6355
8337
  const node = { ...source, children: source.children.map(copy) };
8338
+ shadowSources.set(node, source);
6356
8339
  const old = previous?.nodes.get(node.id);
6357
8340
  if ((node.kind === "input" || node.kind === "textarea") && node.value === undefined && old?.kind === node.kind) {
6358
8341
  node.value = old.value;
@@ -6364,7 +8347,7 @@ function nativeShadow(tree, previous) {
6364
8347
  return { document, handlers: tree.handlers, nodes };
6365
8348
  }
6366
8349
  function reconciliationCommand(previous, next) {
6367
- const mutations = diffTreeMutations(previous, next);
8350
+ const mutations = diffTreeMutations(previous, next, (old, node) => shadowSources.get(old) === node);
6368
8351
  if (mutations === null)
6369
8352
  return { type: "update", root: next.document.root };
6370
8353
  if (mutations.length === 0)
@@ -6384,9 +8367,24 @@ function createApp(view, options = {}) {
6384
8367
  let overlayCompiled = false;
6385
8368
  const overlayScope = {};
6386
8369
  let appWindow;
8370
+ let identityDocument;
8371
+ const appIcon = () => options.icon ?? runtimeAppMetadata().icon;
8372
+ function appIdentityDocument() {
8373
+ if (identityDocument)
8374
+ return identityDocument;
8375
+ const metadata = runtimeAppMetadata();
8376
+ const icon = appIcon();
8377
+ const identity = options.appIdentity ?? (metadata.appId ? { id: metadata.appId, name: metadata.name ?? metadata.appId, ...icon ? { icon } : {} } : undefined);
8378
+ const shellIcon = identity?.icon ? iconFileForShell(identity.icon) : undefined;
8379
+ identityDocument = {
8380
+ ...icon ? { windowIcon: Buffer.from(iconBytes(icon)).toString("base64") } : {},
8381
+ ...identity ? { appIdentity: { id: identity.id, name: identity.name, ...shellIcon ? { icon: shellIcon } : {} } } : {}
8382
+ };
8383
+ return identityDocument;
8384
+ }
6387
8385
  function compileView() {
6388
8386
  const scope = renderScope;
6389
- const renderer = options.renderer ?? "auto";
8387
+ const renderer = options.renderer ?? (options.headless ? "cpu" : "auto");
6390
8388
  const shown = devError;
6391
8389
  const shownWindow = appWindow;
6392
8390
  overlayCompiled = false;
@@ -6395,6 +8393,8 @@ function createApp(view, options = {}) {
6395
8393
  const overlay = withRenderScope(overlayScope, () => compileTree(DevErrorOverlay({ event: shown, onDismiss: dismissDevError, decorations: shownWindow.decorations }), options.debug, renderer, undefined, overlayScope, !options.headless));
6396
8394
  overlayCompiled = true;
6397
8395
  overlay.document.window = shownWindow;
8396
+ if (options.closeBehavior === "hide")
8397
+ overlay.document.root.closeIntercept = true;
6398
8398
  return overlay;
6399
8399
  } catch (overlayError) {
6400
8400
  devOverlayBroken = true;
@@ -6403,8 +8403,16 @@ function createApp(view, options = {}) {
6403
8403
  } catch {}
6404
8404
  }
6405
8405
  }
8406
+ globalThis[ACTIVE_APP_KEY] = app;
6406
8407
  const tree = withRenderScope(scope, () => compileTree(currentView(), options.debug, renderer, options.componentAdapters, scope, !options.headless));
6407
8408
  appWindow = tree.document.window;
8409
+ if (options.closeBehavior === "hide")
8410
+ tree.document.root.closeIntercept = true;
8411
+ Object.assign(tree.document, appIdentityDocument());
8412
+ if (options.msaa !== undefined)
8413
+ tree.document.msaa = options.msaa;
8414
+ if (options.memoryTrimDelay !== undefined)
8415
+ tree.document.memoryTrimDelay = options.memoryTrimDelay === false ? -1 : options.memoryTrimDelay;
6408
8416
  return tree;
6409
8417
  }
6410
8418
  function dismissDevError() {
@@ -6464,6 +8472,9 @@ function createApp(view, options = {}) {
6464
8472
  readySettled = true;
6465
8473
  started = true;
6466
8474
  resolveReady();
8475
+ if (options.maxFps !== undefined) {
8476
+ sendInternal({ type: "frameRate", maxFps: options.maxFps }, { source: "bridge", event: "frameRate" });
8477
+ }
6467
8478
  if (options.frameOverlay ?? envFlag("TARVE_FRAME_OVERLAY")) {
6468
8479
  sendInternal({ type: "frameOverlay", enabled: true }, { source: "bridge", event: "frameOverlay" });
6469
8480
  }
@@ -6572,6 +8583,7 @@ function createApp(view, options = {}) {
6572
8583
  }
6573
8584
  committed = next;
6574
8585
  observed = nextObserved;
8586
+ syncMedia();
6575
8587
  });
6576
8588
  }
6577
8589
  async function flushQueuedUpdate() {
@@ -6643,7 +8655,48 @@ function createApp(view, options = {}) {
6643
8655
  }
6644
8656
  });
6645
8657
  }
8658
+ const drags = new Map;
8659
+ function dispatchDrag(event, handlers) {
8660
+ let handled = false;
8661
+ let succeeded = true;
8662
+ const call = (name, id, handler, arg) => {
8663
+ if (!handler)
8664
+ return;
8665
+ handled = true;
8666
+ succeeded = invokeHandler(name, id, handler, arg) && succeeded;
8667
+ };
8668
+ const target = (id) => committed?.handlers.get(id);
8669
+ const source = event.id;
8670
+ if (event.type === "dragStart") {
8671
+ drags.set(source, { x: event.x, y: event.y, over: null });
8672
+ call("dragStart", source, handlers?.onDragStart, { x: event.x, y: event.y });
8673
+ return { handled, succeeded };
8674
+ }
8675
+ const state = drags.get(source) ?? { x: 0, y: 0, over: null };
8676
+ if (event.type === "dragMove") {
8677
+ drags.set(source, { x: event.x, y: event.y, over: event.over });
8678
+ if (state.over !== event.over) {
8679
+ if (state.over)
8680
+ call("dragLeave", state.over, target(state.over)?.onDragLeave, source);
8681
+ if (event.over)
8682
+ call("dragEnter", event.over, target(event.over)?.onDragEnter, source);
8683
+ }
8684
+ call("dragMove", source, handlers?.onDragMove, { x: event.x, y: event.y, over: event.over });
8685
+ return { handled, succeeded };
8686
+ }
8687
+ drags.delete(source);
8688
+ const dropped = event.type === "drop" ? event.target : null;
8689
+ const x = event.type === "drop" ? event.x : state.x;
8690
+ const y = event.type === "drop" ? event.y : state.y;
8691
+ if (state.over && state.over !== dropped)
8692
+ call("dragLeave", state.over, target(state.over)?.onDragLeave, source);
8693
+ if (dropped)
8694
+ call("drop", dropped, target(dropped)?.onDrop, { source, x, y });
8695
+ call("dragEnd", source, handlers?.onDragEnd, { target: dropped, x, y, cancelled: event.type === "dragCancel" });
8696
+ return { handled, succeeded };
8697
+ }
6646
8698
  function dispatchNativeEvent(event) {
8699
+ globalThis[ACTIVE_APP_KEY] = app;
6647
8700
  if (event.type === "ready")
6648
8701
  settleReadySuccess();
6649
8702
  if (event.type === "error") {
@@ -6666,7 +8719,10 @@ function createApp(view, options = {}) {
6666
8719
  const targetId = committed.document.root.id;
6667
8720
  const handler = committed.handlers.get(targetId)?.onCloseRequest;
6668
8721
  if (!handler) {
6669
- if (sendInternal({ type: "close" }, { source: "bridge", event: "closeRequest:close", targetId }))
8722
+ if (options.closeBehavior === "hide") {
8723
+ sendInternal({ type: "window", action: "hide" }, { source: "bridge", event: "closeRequest:hide", targetId });
8724
+ sendInternal({ type: "cancelCloseRequest" }, { source: "bridge", event: "cancelCloseRequest", targetId });
8725
+ } else if (sendInternal({ type: "close" }, { source: "bridge", event: "closeRequest:close", targetId }))
6670
8726
  closing = true;
6671
8727
  } else {
6672
8728
  let defaultPrevented = false;
@@ -6691,6 +8747,49 @@ function createApp(view, options = {}) {
6691
8747
  }
6692
8748
  }
6693
8749
  }
8750
+ if (!ended && (event.type === "tray" || event.type === "trayMenu" || event.type === "notificationClick")) {
8751
+ const run = (name, handler) => {
8752
+ if (!handler)
8753
+ return false;
8754
+ try {
8755
+ handler();
8756
+ return true;
8757
+ } catch (error) {
8758
+ reportError(error, { source: "event-handler", event: name });
8759
+ return false;
8760
+ }
8761
+ };
8762
+ let ran = false;
8763
+ if (event.type === "tray")
8764
+ ran = run(event.action === "click" ? "trayClick" : "trayDoubleClick", event.action === "click" ? trayOptions?.onClick : trayOptions?.onDoubleClick);
8765
+ else if (event.type === "trayMenu") {
8766
+ ran = run("trayMenu", trayItemHandlers.get(event.id));
8767
+ const onMenu = trayOptions?.onMenu;
8768
+ if (onMenu)
8769
+ ran = run("trayMenu", () => onMenu(event.id)) || ran;
8770
+ } else
8771
+ ran = run("notificationClick", notificationClick);
8772
+ if (ran)
8773
+ update();
8774
+ }
8775
+ if (!ended && event.type === "systemMedia" && systemMediaAction) {
8776
+ try {
8777
+ systemMediaAction(event.action, event.time);
8778
+ } catch (error) {
8779
+ reportError(error, { source: "event-handler", event: `systemMedia:${event.action}` });
8780
+ }
8781
+ }
8782
+ if (!ended && event.type === "media") {
8783
+ const handler = applyMediaEvent(event, committed?.media?.get(event.id));
8784
+ if (handler) {
8785
+ try {
8786
+ handler();
8787
+ } catch (error) {
8788
+ reportError(error, { source: "event-handler", event: `media:${event.event}`, targetId: event.id });
8789
+ }
8790
+ }
8791
+ update();
8792
+ }
6694
8793
  if (!ended && event.type === "shortcut") {
6695
8794
  const handlers = hotkeys.get(event.shortcut);
6696
8795
  if (handlers) {
@@ -6718,11 +8817,15 @@ function createApp(view, options = {}) {
6718
8817
  }
6719
8818
  if (!ended && committed && observed && "id" in event) {
6720
8819
  const handlers = committed.handlers.get(event.id);
8820
+ if (handlers)
8821
+ invalidateMemos(renderScope, event.id);
6721
8822
  let optimisticEdit = false;
6722
8823
  if (event.type === "change") {
6723
8824
  const node = observed.nodes.get(event.id);
6724
8825
  if (node && (node.kind === "input" || node.kind === "textarea")) {
6725
8826
  node.value = event.value;
8827
+ shadowSources.delete(node);
8828
+ shadowEdited = true;
6726
8829
  optimisticEdit = true;
6727
8830
  }
6728
8831
  }
@@ -6730,6 +8833,8 @@ function createApp(view, options = {}) {
6730
8833
  const node = observed.nodes.get(event.id);
6731
8834
  if (node?.control) {
6732
8835
  node.control = { ...node.control, value: event.value };
8836
+ shadowSources.delete(node);
8837
+ shadowEdited = true;
6733
8838
  optimisticEdit = true;
6734
8839
  }
6735
8840
  }
@@ -6804,14 +8909,31 @@ function createApp(view, options = {}) {
6804
8909
  handled = true;
6805
8910
  succeeded = invokeHandler("virtualListLayout", event.id, handlers.onVirtualListLayout, event.items) && succeeded;
6806
8911
  }
8912
+ if (event.type === "size" && handlers?.onSize) {
8913
+ handled = true;
8914
+ succeeded = invokeHandler("size", event.id, handlers.onSize, { width: event.width, height: event.height }) && succeeded;
8915
+ }
8916
+ if (event.type === "pointerMove" && handlers?.onPointerMove) {
8917
+ handled = true;
8918
+ succeeded = invokeHandler("pointerMove", event.id, handlers.onPointerMove, { x: event.x, y: event.y }) && succeeded;
8919
+ }
8920
+ if (event.type === "pointerLeave" && handlers?.onPointerLeave) {
8921
+ handled = true;
8922
+ succeeded = invokeHandler("pointerLeave", event.id, handlers.onPointerLeave) && succeeded;
8923
+ }
6807
8924
  if (event.type === "virtualListScrollToItem" && handlers?.onVirtualListScrollToItem) {
6808
8925
  handled = true;
6809
- succeeded = invokeHandler("virtualListScrollToItem", event.id, handlers.onVirtualListScrollToItem, event.index, event.offset) && succeeded;
8926
+ succeeded = invokeHandler("virtualListScrollToItem", event.id, handlers.onVirtualListScrollToItem, event.index, event.offset, event.smooth === true) && succeeded;
6810
8927
  }
6811
8928
  if (event.type === "virtualListFocus" && handlers?.onVirtualListFocus) {
6812
8929
  handled = true;
6813
8930
  succeeded = invokeHandler("virtualListFocus", event.id, handlers.onVirtualListFocus, event.key) && succeeded;
6814
8931
  }
8932
+ if (event.type === "dragStart" || event.type === "dragMove" || event.type === "drop" || event.type === "dragCancel") {
8933
+ const result = dispatchDrag(event, handlers);
8934
+ handled = result.handled;
8935
+ succeeded = result.succeeded && succeeded;
8936
+ }
6815
8937
  if (event.type === "hover" && handlers?.onHover) {
6816
8938
  handled = true;
6817
8939
  succeeded = invokeHandler("hover", event.id, handlers.onHover, event.entered);
@@ -6837,6 +8959,74 @@ function createApp(view, options = {}) {
6837
8959
  update();
6838
8960
  }
6839
8961
  }
8962
+ let systemMediaAction;
8963
+ let trayOwner;
8964
+ let trayOptions;
8965
+ let notificationClick;
8966
+ let trayIconPath;
8967
+ let trayIconData;
8968
+ let trayIconSent = false;
8969
+ const trayItemHandlers = new Map;
8970
+ function applyTray() {
8971
+ if (!trayOptions)
8972
+ return;
8973
+ trayItemHandlers.clear();
8974
+ const seen = new Set;
8975
+ const convert = (items) => items.map((item) => {
8976
+ if (item.type === "separator")
8977
+ return { separator: true };
8978
+ if (!item.id)
8979
+ throw new TypeError("tray menu items need an id");
8980
+ if (item.items?.length)
8981
+ return { label: item.label, ...item.disabled ? { disabled: true } : {}, items: convert(item.items) };
8982
+ if (seen.has(item.id))
8983
+ throw new TypeError(`duplicate tray menu id "${item.id}"`);
8984
+ seen.add(item.id);
8985
+ if (item.onSelect)
8986
+ trayItemHandlers.set(item.id, item.onSelect);
8987
+ return { id: item.id, label: item.label, ...item.checked !== undefined ? { checked: item.checked } : {}, ...item.disabled ? { disabled: true } : {} };
8988
+ });
8989
+ const menu = convert(trayOptions.menu ?? []);
8990
+ const trayIcon = trayOptions.icon ?? appIcon();
8991
+ if (trayIcon !== trayIconPath) {
8992
+ trayIconData = trayIcon ? Buffer.from(iconBytes(trayIcon)).toString("base64") : undefined;
8993
+ trayIconPath = trayIcon;
8994
+ trayIconSent = false;
8995
+ }
8996
+ const iconData = trayIconSent ? undefined : trayIconData;
8997
+ trayIconSent = true;
8998
+ if (!ended)
8999
+ sendPublic({ type: "tray", tray: { ...iconData ? { iconData } : {}, ...trayOptions.tooltip ? { tooltip: trayOptions.tooltip } : {}, menu } });
9000
+ }
9001
+ const loadedMedia = new Map;
9002
+ function syncMedia() {
9003
+ if (ended || !committed)
9004
+ return;
9005
+ const wanted = committed.media ?? new Map;
9006
+ for (const id of [...loadedMedia.keys()]) {
9007
+ if (!wanted.has(id) || !wanted.get(id).src) {
9008
+ loadedMedia.delete(id);
9009
+ sendInternal({ type: "media", id, action: "unload" }, { source: "bridge", event: "media:unload", targetId: id });
9010
+ }
9011
+ }
9012
+ for (const [id, request] of wanted) {
9013
+ if (!request.src)
9014
+ continue;
9015
+ const previous = loadedMedia.get(id);
9016
+ const src = resolveMediaPath(request.src);
9017
+ if (!previous || resolveMediaPath(previous.src) !== src) {
9018
+ sendInternal({ type: "media", id, action: "load", src, loop: request.loop, muted: request.muted, volume: request.volume }, { source: "bridge", event: "media:load", targetId: id });
9019
+ if (request.autoPlay)
9020
+ sendInternal({ type: "media", id, action: "play" }, { source: "bridge", event: "media:play", targetId: id });
9021
+ } else if (previous.loop !== request.loop || previous.muted !== request.muted || previous.volume !== request.volume) {
9022
+ sendInternal({ type: "media", id, action: "set", loop: request.loop, muted: request.muted, volume: request.volume }, { source: "bridge", event: "media:set", targetId: id });
9023
+ }
9024
+ loadedMedia.set(id, request);
9025
+ }
9026
+ }
9027
+ function resolveMediaPath(src) {
9028
+ return src.startsWith("file://") ? new URL(src).pathname.replace(/^\/([A-Za-z]:)/, "$1") : src;
9029
+ }
6840
9030
  function onNativeEvent(event) {
6841
9031
  try {
6842
9032
  dispatchNativeEvent(event);
@@ -6866,7 +9056,7 @@ function createApp(view, options = {}) {
6866
9056
  if (!ended)
6867
9057
  sendPublic({ type: "focus", id });
6868
9058
  },
6869
- scrollToItem(id, index, offset = 0) {
9059
+ scrollToItem(id, index, offset = 0, options = {}) {
6870
9060
  if (!id)
6871
9061
  throw new TypeError("scrollToItem requires a list id");
6872
9062
  if (!Number.isInteger(index) || index < 0)
@@ -6874,7 +9064,77 @@ function createApp(view, options = {}) {
6874
9064
  if (!Number.isFinite(offset))
6875
9065
  throw new RangeError("scrollToItem offset must be finite");
6876
9066
  if (!ended)
6877
- sendPublic({ type: "scrollToItem", id, index, ...offset !== 0 ? { offset } : {} });
9067
+ sendPublic({ type: "scrollToItem", id, index, ...offset !== 0 ? { offset } : {}, ...options.smooth ? { smooth: true } : {} });
9068
+ },
9069
+ show() {
9070
+ if (!ended)
9071
+ sendPublic({ type: "window", action: "show" });
9072
+ },
9073
+ hide() {
9074
+ if (!ended)
9075
+ sendPublic({ type: "window", action: "hide" });
9076
+ },
9077
+ minimize() {
9078
+ if (!ended)
9079
+ sendPublic({ type: "window", action: "minimize" });
9080
+ },
9081
+ tray(initial) {
9082
+ const token = {};
9083
+ trayOwner = token;
9084
+ trayOptions = { ...initial };
9085
+ trayIconSent = false;
9086
+ applyTray();
9087
+ return {
9088
+ update(next) {
9089
+ if (trayOwner !== token)
9090
+ return;
9091
+ trayOptions = { ...trayOptions, ...next };
9092
+ applyTray();
9093
+ },
9094
+ remove() {
9095
+ if (trayOwner !== token)
9096
+ return;
9097
+ trayOwner = undefined;
9098
+ trayOptions = undefined;
9099
+ trayIconPath = undefined;
9100
+ trayIconData = undefined;
9101
+ trayItemHandlers.clear();
9102
+ if (!ended)
9103
+ sendPublic({ type: "tray", tray: null });
9104
+ }
9105
+ };
9106
+ },
9107
+ systemMedia(session) {
9108
+ if (session) {
9109
+ const { onAction, ...nativeSession } = session;
9110
+ systemMediaAction = onAction;
9111
+ if (!ended)
9112
+ sendPublic({ type: "systemMedia", session: nativeSession });
9113
+ } else {
9114
+ systemMediaAction = undefined;
9115
+ if (!ended)
9116
+ sendPublic({ type: "systemMedia", session: null });
9117
+ }
9118
+ },
9119
+ notify({ title, body = "", onClick }) {
9120
+ if (!title)
9121
+ throw new TypeError("notify requires a title");
9122
+ notificationClick = onClick;
9123
+ if (!ended)
9124
+ sendPublic({ type: "notify", title, body });
9125
+ },
9126
+ media(id) {
9127
+ const send = (command) => {
9128
+ if (!ended)
9129
+ sendPublic({ type: "media", id, ...command });
9130
+ };
9131
+ return {
9132
+ play: () => send({ action: "play" }),
9133
+ pause: () => send({ action: "pause" }),
9134
+ seek: (seconds) => send({ action: "seek", time: Math.max(0, seconds) }),
9135
+ setVolume: (volume) => send({ action: "set", volume: Math.min(1, Math.max(0, volume)) }),
9136
+ setMuted: (muted) => send({ action: "set", muted })
9137
+ };
6878
9138
  },
6879
9139
  registerHotkey(shortcut, handler) {
6880
9140
  const canonical = normalizeHotkey(shortcut);
@@ -6965,6 +9225,12 @@ function createApp(view, options = {}) {
6965
9225
  setFrameOverlay(enabled) {
6966
9226
  if (!ended)
6967
9227
  sendPublic({ type: "frameOverlay", enabled });
9228
+ },
9229
+ setMaxFps(fps) {
9230
+ if (fps !== null && !(Number.isFinite(fps) && fps > 0))
9231
+ throw new RangeError("setMaxFps expects a positive number or null");
9232
+ if (!ended)
9233
+ sendPublic({ type: "frameRate", maxFps: fps });
6968
9234
  }
6969
9235
  };
6970
9236
  try {
@@ -6979,7 +9245,9 @@ function createApp(view, options = {}) {
6979
9245
  return app;
6980
9246
  }
6981
9247
  try {
6982
- bridge.start(committed.document, onNativeEvent);
9248
+ const fonts = options.fontFaces?.map((path) => Buffer.from(readFileSync3(nativeAssetPath2(path))).toString("base64"));
9249
+ bridge.start(fonts?.length ? { ...committed.document, fonts } : committed.document, onNativeEvent);
9250
+ syncMedia();
6983
9251
  } catch (error) {
6984
9252
  const startupError = reportError(error, { source: "bridge", event: "start" });
6985
9253
  terminalError = startupError;
@@ -6991,7 +9259,7 @@ function createApp(view, options = {}) {
6991
9259
  return app;
6992
9260
  }
6993
9261
  async function render(view, options) {
6994
- const hot = process.execArgv.includes("--hot");
9262
+ const hot = process.execArgv.includes("--hot") || process.env.TARVE_HOT === "1";
6995
9263
  const registry = globalThis;
6996
9264
  const existing = registry[DEV_APP_KEY];
6997
9265
  if (existing) {
@@ -7028,6 +9296,9 @@ function pastePayload(event) {
7028
9296
  return;
7029
9297
  }
7030
9298
  // packages/core/src/test-renderer.ts
9299
+ import { spawn } from "child_process";
9300
+ import { Readable } from "stream";
9301
+ import { setTimeout as sleep } from "timers/promises";
7031
9302
  function center(node) {
7032
9303
  return { x: node.x + node.width / 2, y: node.y + node.height / 2 };
7033
9304
  }
@@ -7065,7 +9336,7 @@ async function waitFor(predicate, options = {}) {
7065
9336
  const suffix = lastError instanceof Error ? ` Last error: ${lastError.message}` : "";
7066
9337
  throw new Error(`waitFor timed out after ${timeout}ms.${suffix}`);
7067
9338
  }
7068
- await Bun.sleep(interval);
9339
+ await sleep(interval);
7069
9340
  }
7070
9341
  }
7071
9342
 
@@ -7104,6 +9375,13 @@ class Locator {
7104
9375
  this.renderer.app.debug({ type: "input", action: "down" });
7105
9376
  this.renderer.app.debug({ type: "input", action: "up" });
7106
9377
  }
9378
+ async hover(offset) {
9379
+ const node = await this.node();
9380
+ const point = offset ? { x: node.x + offset.x, y: node.y + offset.y } : center(node);
9381
+ if (![point.x, point.y].every(Number.isFinite))
9382
+ throw new RangeError("hover coordinates must be finite");
9383
+ this.renderer.app.debug({ type: "input", action: "move", ...point });
9384
+ }
7107
9385
  async fill(value) {
7108
9386
  if (typeof value !== "string")
7109
9387
  throw new TypeError("fill value must be a string");
@@ -7173,11 +9451,12 @@ class TestRenderer {
7173
9451
  getByRole(role, options = {}) {
7174
9452
  const exact = options.exact ?? true;
7175
9453
  return new Locator(this, (snapshot) => snapshot.nodes.filter((node) => {
7176
- if (node.control?.role !== role)
9454
+ const nodeRole = node.control?.role ?? (node.kind === "button" ? "button" : undefined);
9455
+ if (nodeRole !== role)
7177
9456
  return false;
7178
9457
  if (options.name === undefined)
7179
9458
  return true;
7180
- return textMatches(node.control.label ?? node.text, options.name, exact);
9459
+ return textMatches(node.control?.label ?? node.text, options.name, exact);
7181
9460
  }), options.name === undefined ? `role ${JSON.stringify(role)}` : `role ${JSON.stringify(role)} named ${String(options.name)}`);
7182
9461
  }
7183
9462
  locator(predicate, description = "custom locator") {
@@ -7207,22 +9486,24 @@ async function createTestRenderer(view, options) {
7207
9486
  function launchTestProcess(options) {
7208
9487
  if (options.command.length === 0)
7209
9488
  throw new TypeError("launchTestProcess requires a command");
7210
- const child = Bun.spawn([...options.command], {
9489
+ const child = spawn(options.command[0], options.command.slice(1), {
7211
9490
  cwd: options.cwd,
7212
9491
  env: {
7213
9492
  ...process.env,
7214
9493
  ...options.env,
7215
9494
  ...options.renderer ? { TARVE_RENDERER: options.renderer } : {}
7216
9495
  },
7217
- stdin: "ignore",
7218
- stdout: options.stdout ?? "inherit",
7219
- stderr: options.stderr ?? "inherit"
9496
+ stdio: ["ignore", options.stdout ?? "inherit", options.stderr ?? "inherit"]
9497
+ });
9498
+ const exited = new Promise((resolve, reject) => {
9499
+ child.once("error", reject);
9500
+ child.once("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
7220
9501
  });
7221
9502
  return {
7222
9503
  pid: child.pid,
7223
- exited: child.exited,
7224
- ...options.stdout === "pipe" ? { stdout: child.stdout } : {},
7225
- ...options.stderr === "pipe" ? { stderr: child.stderr } : {},
9504
+ exited,
9505
+ ...options.stdout === "pipe" ? { stdout: Readable.toWeb(child.stdout) } : {},
9506
+ ...options.stderr === "pipe" ? { stderr: Readable.toWeb(child.stderr) } : {},
7226
9507
  kill(signal) {
7227
9508
  child.kill(signal);
7228
9509
  }
@@ -7230,6 +9511,7 @@ function launchTestProcess(options) {
7230
9511
  }
7231
9512
  // packages/core/src/visual-testing.ts
7232
9513
  import { inflateSync } from "zlib";
9514
+ import { readFile } from "fs/promises";
7233
9515
  function validateRgbaImage(image, label) {
7234
9516
  if (!Number.isInteger(image.width) || !Number.isInteger(image.height) || image.width <= 0 || image.height <= 0) {
7235
9517
  throw new RangeError(`${label} image dimensions must be positive integers`);
@@ -7243,7 +9525,7 @@ function validateRgbaImage(image, label) {
7243
9525
  }
7244
9526
  }
7245
9527
  async function readPngRgba(path) {
7246
- const bytes = new Uint8Array(await Bun.file(path).arrayBuffer());
9528
+ const bytes = await readFile(path);
7247
9529
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
7248
9530
  if (!signature.every((value, index) => bytes[index] === value))
7249
9531
  throw new Error(`Not a PNG capture: ${path}`);
@@ -7389,6 +9671,8 @@ export {
7389
9671
  Button,
7390
9672
  ButtonGroup,
7391
9673
  Calendar,
9674
+ CanvasGradient,
9675
+ CanvasRenderingContext2D,
7392
9676
  Card,
7393
9677
  Carousel,
7394
9678
  Chart,
@@ -7489,10 +9773,13 @@ export {
7489
9773
  launchTestProcess,
7490
9774
  lightTheme,
7491
9775
  loadImageSource,
9776
+ memo,
7492
9777
  normalizeHotkey,
7493
9778
  openExternal,
9779
+ parseCanvasFont,
7494
9780
  readPngRgba,
7495
9781
  render,
9782
+ shallowEqual,
7496
9783
  theme,
7497
9784
  waitFor
7498
9785
  };