@whzxc/agent-design-gallery 0.6.0 → 0.8.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 (41) hide show
  1. package/README.md +12 -1
  2. package/package.json +1 -1
  3. package/public/app.js +38 -10
  4. package/public/arrangement-worker.js +11 -0
  5. package/public/arrangement.js +49 -0
  6. package/public/assets.js +16 -4
  7. package/public/layout.js +29 -13
  8. package/src/cli-output.mjs +258 -0
  9. package/src/cli.mjs +120 -45
  10. package/src/http.mjs +1 -0
  11. package/src/hub/auth.mjs +2 -1
  12. package/src/hub/proxy.mjs +5 -3
  13. package/src/hub/registry.mjs +57 -23
  14. package/src/hub.mjs +36 -21
  15. package/src/lifecycle.mjs +109 -0
  16. package/src/link.mjs +10 -9
  17. package/src/open.mjs +58 -54
  18. package/src/perf.mjs +12 -0
  19. package/src/server.mjs +78 -41
  20. package/src/service.mjs +115 -94
  21. package/src/toolkit/arch-git.mjs +142 -10
  22. package/src/toolkit/arch-overlay.mjs +1 -1
  23. package/src/toolkit/arch.mjs +62 -58
  24. package/src/toolkit/browser.mjs +38 -12
  25. package/src/toolkit/build-store.mjs +11 -3
  26. package/src/toolkit/build-worker.mjs +4 -1
  27. package/src/toolkit/build.mjs +26 -2
  28. package/src/toolkit/commands.mjs +158 -86
  29. package/src/toolkit/compare.mjs +93 -46
  30. package/src/toolkit/config.mjs +23 -20
  31. package/src/toolkit/diff-inputs.mjs +239 -0
  32. package/src/toolkit/diff-policy.mjs +28 -0
  33. package/src/toolkit/diff.mjs +258 -0
  34. package/src/toolkit/migrate.mjs +42 -30
  35. package/src/toolkit/part-diff.mjs +118 -0
  36. package/src/toolkit/part-snapshot.mjs +264 -0
  37. package/src/toolkit/pixel-diff.mjs +103 -0
  38. package/src/toolkit/project.mjs +45 -33
  39. package/src/toolkit/results.mjs +44 -0
  40. package/src/toolkit/runtime.d.ts +2 -1
  41. package/src/toolkit/tokens.mjs +5 -4
package/README.md CHANGED
@@ -25,7 +25,7 @@ adg service migrate
25
25
  updates design editor paths and `.sdg/` entries in the project's `.gitignore` files, deletes the old generated
26
26
  `design/.sdg/` directory and regenerates `design/.adg/` (using the configured design directory). It prints each
27
27
  change and is safe to repeat. When both config names exist, it refuses before changing files. Normal commands
28
- finding only an old config stop with guidance to run `adg migrate`.
28
+ finding only an old current-project config stop with guidance to run `adg migrate`. `diff` migrates a legacy base inside its disposable historical tree and reports the change.
29
29
 
30
30
  On macOS, `adg service migrate` stops `org.svg-design-gallery.hub`, moves its entire state directory from
31
31
  `svg-design-gallery` to `agent-design-gallery`, and replaces the LaunchAgent with `org.agent-design-gallery.hub`
@@ -55,6 +55,8 @@ adg render components/button --frame=disabled --theme=dark --out-dir=output/revi
55
55
 
56
56
  Use the independent link in a change report. Add the path link when the surrounding assets matter. Use the project URL on a hub the recipient can reach. `adg open` provides a live loopback preview while its server runs. `render` exports exact frame PNGs for attachments or automation. Without `--theme`, it exports both themes. See the [review handoff workflow](docs/design-toolkit.md#review-handoff).
57
57
 
58
+ Every command accepts `--json`: finite commands return one versioned envelope, while foreground `open`/`serve` stream NDJSON events. `render` PNGs are in `data.captures`, with CSS and PNG pixel dimensions. See the [agent CLI interface](docs/agent-interface.md) for schemas, exits and recovery actions.
59
+
58
60
  The rightmost toolbar button opens the Inspector for the selected node. It starts closed and overlays the canvas. It follows the selection and shows source path, frame name, dimensions, frames, and discovered **Uses** / **Used by** relationships. Indirect relationships are muted with their shortest `via` path. Click a relationship to focus the source, or to open it by itself when outside the current scope. An element selection shows its owning export and matching frames from the current scope. `GET /relationships` explicitly computes the complete direct graph as JSON, keyed by source path with `uses` and `usedBy` arrays.
59
61
 
60
62
  Click a canvas source or frame title to select it and copy its name. The copy icon copies without changing the selection and appears on hover or keyboard focus. Section titles also copy their names. Enter and Space activate a focused title. A check confirms a successful copy for 1.2 seconds. The inspector has separate source-path and frame-name copy controls.
@@ -101,12 +103,21 @@ adg init
101
103
  adg check
102
104
  adg render surfaces/example --frame=default --scale=2
103
105
  adg check --read-only
106
+ adg diff --base=HEAD --json
104
107
  ```
105
108
 
106
109
  `init` creates tokens, components/modules/surfaces, fixtures/art, editor configuration and ignore entries. A fresh library gets one `example.tsx` per production layer, composed downward with shared fixture data; existing libraries receive no demo sources. Existing authored files are preserved, declarations are refreshed, and missing ignore entries are appended. Starter configuration requires ADG 0.5.0 or newer. `check --read-only` skips declarations and build files for an audit. Projects do not install ADG as a dependency.
107
110
 
108
111
  Builds produce standalone HTML and renders produce `<frame>-light.png` and `<frame>-dark.png` under `output/design/<source>/`. After configuring an implementation adapter and frame fixture/capture, use `adg compare <source> --frame=<name>` or `adg compare --all`. Flags override Frame capture props; `--all` writes a linked HTML index and `summary.json` under `output/design/compare/`. `sync` and `measure` have been removed.
109
112
 
113
+ `adg diff --base=<rev>` writes per-frame/theme before, after and difference PNGs plus
114
+ `report.json` for Git and working-tree sources, including added/removed frames. Existing
115
+ frames require exact pixels and size. New part Frames can declare `parent` and use
116
+ consumer `diff.thresholds`; a `structural` batch requires full existing-frame coverage
117
+ in both themes. Exit 0 is `identical`/`structural`, 1 is completed `changed`, and 2 is
118
+ incomplete execution. See [parts and classifier limits](docs/design-toolkit.md#git-frame-diff)
119
+ and the [JSON contract](docs/agent-interface.md#diff).
120
+
110
121
  See the [toolkit contract](docs/design-toolkit.md) for source format and compare adapters, and the [changelog](CHANGELOG.md) for version changes. Node.js executes design modules at build time; open sources you trust.
111
122
 
112
123
  ## Architecture sources
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whzxc/agent-design-gallery",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Local TSX design toolkit and SVG viewer",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/public/app.js CHANGED
@@ -9,6 +9,9 @@ import { sourceRelationships, relatedSources } from './relationships.js';
9
9
  import { hitSelection, frameBox, exportFrames } from './selection.js';
10
10
  import { groupTokens, renderTokenTable } from './token-catalog.js';
11
11
  import { readViewRoute, viewURL } from './view-route.js';
12
+ import { createArranger } from './arrangement.js';
13
+ const arranger = createArranger();
14
+ window.addEventListener('pagehide',()=>arranger.close());
12
15
  // ARC's gallery layout and camera model, decoupled from its React runtime.
13
16
  const $ = (selector) => document.querySelector(selector);
14
17
  const viewport = $(".gallery-viewport"),
@@ -335,10 +338,12 @@ function save() {
335
338
  }
336
339
  window.addEventListener('pagehide', () => void persistPreferences(true));
337
340
  document.addEventListener('visibilitychange', () => {if (document.hidden) void persistPreferences(true)});
338
- function layout(data, preserve = false) {
341
+ const layoutData = data => onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data;
342
+ function layout(data, preserve = false, options = {}) {
343
+ const endArrangement = globalThis.__adgTiming?.span('arrangement', undefined, {sources:data.assets.length,provisional:!!options.provisional});
339
344
  const previous = assets,
340
345
  previousGroups = groups,
341
- result = arrange(onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data);
346
+ result = arrange(layoutData(data),options);
342
347
  groups = result.groups;
343
348
  assets = result.items;
344
349
  world = result.world;
@@ -419,6 +424,8 @@ function layout(data, preserve = false) {
419
424
  );
420
425
  $("#empty").hidden = !!assets.length || !data.directory;
421
426
  if (!assets.length) $("#empty").textContent = scopedUI(data) ? 'No assets in this scope.' : 'No SVG files in this directory.';
427
+ endArrangement?.({items:assets.length});
428
+ if (assets.length) globalThis.__adgTiming?.mark('first-layout');
422
429
  }
423
430
  function makeRow(name, label, count, className = 'tree-row') {
424
431
  const button = document.createElement('button'); button.className = className;
@@ -781,6 +788,7 @@ function pump() {
781
788
  }
782
789
  }
783
790
  async function loadPreview(e) {
791
+ const endPreview = globalThis.__adgTiming?.span('preview', e.asset.path, {crop:e.part.id});
784
792
  let url,local=false;
785
793
  const theme=e.theme??effectiveTheme;
786
794
  const generated=async restore=>{
@@ -806,7 +814,8 @@ async function loadPreview(e) {
806
814
  if(cache.get(e.key)!==e)return;
807
815
  while(moving)await new Promise(resolve=>setTimeout(resolve,16));
808
816
  const img=new Image();e.image=img;img.decoding='async';img.src=source;
809
- await img.decode();e.state='ready';
817
+ const endDecode = globalThis.__adgTiming?.span('decode', e.asset.path, {crop:e.part.id});
818
+ try { await img.decode();e.state='ready'; } finally {endDecode?.();}
810
819
  };
811
820
  try {
812
821
  const cached=e.asset.hash&&e.asset.previewIds?.[theme]?.includes(e.part.id);
@@ -829,6 +838,7 @@ async function loadPreview(e) {
829
838
  if(failure.name!=='AbortError'&&cache.get(e.key)===e&&theme===effectiveTheme&&manifest?.assets.some(a=>a.path===e.asset.path&&a.version===e.asset.version))
830
839
  error(`Cannot render ${e.asset.path}: ${failure.message}`);
831
840
  } finally {
841
+ endPreview?.({state:e.state});
832
842
  if(local&&url)URL.revokeObjectURL(url);
833
843
  loading--;requestDraw(false);pump();
834
844
  }
@@ -871,12 +881,13 @@ function drawBackground() {
871
881
  }
872
882
  }
873
883
  function draw() {
884
+ const endDrawing = globalThis.__adgTiming?.span('drawing');
874
885
  raf = 0;
875
886
  drawBackground();
876
887
  if (tokenManifest) {
877
888
  window.__adg.ready = true;
878
889
  if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
879
- return;
890
+ endDrawing?.(); return;
880
891
  }
881
892
  if (!labelObstacles) readChromeBounds();
882
893
  const displayed = manifest?.renderTheme === effectiveTheme ? inspection ? [inspection] : assets : [];
@@ -927,6 +938,7 @@ function draw() {
927
938
  const sx = source.width / pos.part.width, sy = source.height / pos.part.height;
928
939
  ctx.drawImage(source, (left-pos.x)*sx, (top-pos.y)*sy, (right-left)*sx, (bottom-top)*sy, left, top, right-left, bottom-top);
929
940
  } else ctx.drawImage(source, pos.x, pos.y, pos.part.width, pos.part.height);
941
+ if (inViewport) globalThis.__adgTiming?.paint('first-content', {source:a.path,crop:pos.part.id});
930
942
  }
931
943
  ctx.restore();
932
944
  const chosen = selected === a.path && selectedForm === null;
@@ -943,10 +955,11 @@ function draw() {
943
955
  const percentage = `${Math.round(view.scale * 100)}%`;
944
956
  if (zoomValue.textContent !== percentage) zoomValue.textContent = percentage;
945
957
  if (zoomOutput.value !== percentage) zoomOutput.value = percentage;
946
- window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving;
958
+ window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving && !arranger.pending;
947
959
  if(fixtureState && fixtureApplied && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
948
960
  window.__adg.revision = manifest?.revision;
949
961
  window.__adg.visibleReady = drawingReady; window.__adg.visibleCount = drawingCount;
962
+ if (window.__adg.ready && drawingCount > 0) globalThis.__adgTiming?.paint('visible-ready', {count:drawingCount});
950
963
  drawMap();
951
964
  if(!moving&&queued.length)pump();
952
965
  if (cache.size > 100) {
@@ -954,6 +967,7 @@ function draw() {
954
967
  .flatMap(a => placements(a).map(({part}) => assetURL(a, part))));
955
968
  evictPreviews(cache, activeKeys);
956
969
  }
970
+ endDrawing?.();
957
971
  }
958
972
  function backgroundColor() { return backgroundChoice === 'theme' ? palette.canvas : backgroundColors[backgroundChoice]; }
959
973
 
@@ -1226,10 +1240,16 @@ $("#shortcuts").onclick = () => {
1226
1240
  $("#more-menu").hidePopover();
1227
1241
  $("#keys").showModal();
1228
1242
  };
1229
- $("#arrange").onclick = () => {
1243
+ $("#arrange").onclick = async () => {
1244
+ const data=manifest,previousCatalog=catalog;
1245
+ window.__adg.ready=false;
1246
+ let placed;
1247
+ try {if(!data.loading)placed=await arranger.arrange(layoutData(data));}
1248
+ catch(failure){if(failure.name!=='AbortError')error(failure.message);requestDraw();return;}
1249
+ if(manifest!==data || catalog!==previousCatalog || tokenManifest){requestDraw();return;}
1230
1250
  const old = assets,
1231
1251
  oldGroups = groups;
1232
- layout(manifest);
1252
+ layout(manifest,false,{placed,provisional:!!data.loading});
1233
1253
  if (active !== null) {
1234
1254
  const g = groups[active],
1235
1255
  prev = oldGroups[active],
@@ -1392,7 +1412,7 @@ async function applyManifest(data, force = false) {
1392
1412
  publishedCount=available.length;nextPublish=Math.max(publishedCount+1,publishedCount*2);
1393
1413
  if(streamView&&view!==streamView)streamMoved=true;
1394
1414
  manifest={...data,assets:available,renderTheme:versionTheme,loading:true};
1395
- layout(manifest,false);
1415
+ layout(manifest,false,{provisional:true});
1396
1416
  if(streaming&&!streamMoved){view=entry?.view??data.view??fitWorld(cameraArea(),data);streamView=view;}
1397
1417
  requestDraw();
1398
1418
  };
@@ -1402,7 +1422,7 @@ async function applyManifest(data, force = false) {
1402
1422
  if(metadata){results[i]=decorateMetadata(a,metadata);metadataCache.set(key,metadata);}
1403
1423
  }
1404
1424
  let completed=results.filter(Boolean).length;
1405
- if(streaming&&completed)publish();
1425
+ if(streaming&&completed&&completed<data.assets.length)publish();
1406
1426
  await Promise.all(Array.from({length:4},async()=>{
1407
1427
  while(next<data.assets.length) {
1408
1428
  signal?.throwIfAborted();
@@ -1430,6 +1450,13 @@ async function applyManifest(data, force = false) {
1430
1450
  if(publishFrame)cancelAnimationFrame(publishFrame);
1431
1451
  if(versionTheme!==effectiveTheme){pending=true;return;}
1432
1452
  signal?.throwIfAborted();
1453
+ const complete={...data,assets:results};
1454
+ const placed=await arranger.arrange(layoutData(complete),{signal,onPending:()=>{
1455
+ if(streaming&&completed>publishedCount)publish();
1456
+ }});
1457
+ if(versionTheme!==effectiveTheme){pending=true;return;}
1458
+ signal?.throwIfAborted();
1459
+ if(streamView&&view!==streamView)streamMoved=true;
1433
1460
  for(const [key,entry] of prepared)if(!data.assets.some(a=>key===sourceKey(a,versionTheme,data.directory)||key===sourceKey(a,versionTheme==='dark'?'light':'dark',data.directory)))prepared.delete(key);
1434
1461
  const live=new Set(data.assets.flatMap(a=>['light','dark'].map(t=>sourceKey(a,t,data.directory))));
1435
1462
  for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
@@ -1437,12 +1464,13 @@ async function applyManifest(data, force = false) {
1437
1464
  tokenManifest = null;
1438
1465
  // Early streamed worlds can use a much larger camera scale. Discard those
1439
1466
  // raster intermediates so the completed world starts at its exact final scale.
1440
- if(streaming&&publishedCount<data.assets.length)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
1467
+ if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
1441
1468
  catalog = null;
1442
1469
  layout(
1443
1470
  manifest,
1444
1471
  !first && !!previous &&
1445
1472
  JSON.stringify(previous.groups) === JSON.stringify(data.groups),
1473
+ {placed},
1446
1474
  );
1447
1475
  for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
1448
1476
  $("#app-directory").title=data.directory||'';
@@ -0,0 +1,11 @@
1
+ import { layoutWorld, packingSnapshot, restorePacking } from './layout.js';
2
+
3
+ self.onmessage = ({data:{id,input,packing}}) => {
4
+ try {
5
+ restorePacking(packing);
6
+ const start=performance.now(),placed=layoutWorld(input);
7
+ self.postMessage({id,placed,packing:packingSnapshot(),durationMs:performance.now()-start});
8
+ } catch(error) {
9
+ self.postMessage({id,error:error.message});
10
+ }
11
+ };
@@ -0,0 +1,49 @@
1
+ import { arrangementInput } from './assets.js';
2
+ import { packingSnapshot, restorePacking, layoutWorld } from './layout.js';
3
+
4
+ const aborted = () => new DOMException('Arrangement superseded', 'AbortError');
5
+
6
+ export function createArranger() {
7
+ let worker, nextId=0;
8
+ const pending=new Map();
9
+ function close(failure=aborted()) {
10
+ worker?.terminate();worker=undefined;
11
+ for(const task of pending.values())task.finish(failure);
12
+ pending.clear();
13
+ }
14
+ function start() {
15
+ if(worker)return;
16
+ worker=new Worker(new URL('./arrangement-worker.js',import.meta.url),{type:'module'});
17
+ worker.onmessage=({data})=>{
18
+ const task=pending.get(data.id);
19
+ if(!task)return;
20
+ if(data.error)task.finish(Error(`Cannot arrange designs: ${data.error}`));
21
+ else {restorePacking(data.packing);task.finish(null,data);}
22
+ };
23
+ worker.onerror=event=>close(Error(`Cannot start arrangement worker: ${event.message}`));
24
+ }
25
+ return {
26
+ close,
27
+ get pending() {return pending.size;},
28
+ arrange(data,{signal,onPending}={}) {
29
+ signal?.throwIfAborted();
30
+ const endProbe=globalThis.__adgTiming?.span('arrangement-cache-probe');
31
+ const input=arrangementInput(data),cached=layoutWorld(input,{cachedOnly:true});
32
+ endProbe?.({hit:!!cached});
33
+ if(cached)return Promise.resolve(cached);
34
+ onPending?.();
35
+ start();
36
+ const id=++nextId,end=globalThis.__adgTiming?.span('arrangement-wait');
37
+ return new Promise((resolve,reject)=>{
38
+ const abort=()=>close();
39
+ pending.set(id,{finish(failure,result){
40
+ pending.delete(id);signal?.removeEventListener('abort',abort);
41
+ end?.({workerMs:result?.durationMs});
42
+ failure?reject(failure):resolve(result.placed);
43
+ }});
44
+ signal?.addEventListener('abort',abort,{once:true});
45
+ worker.postMessage({id,input,packing:packingSnapshot()});
46
+ });
47
+ },
48
+ };
49
+ }
package/public/assets.js CHANGED
@@ -122,6 +122,7 @@ export function compactPreparedSource(asset) {
122
122
  }
123
123
 
124
124
  export function imageURL(asset, crop, onSource) {
125
+ const endPreview = globalThis.__adgTiming?.span('preview-generation', asset.path, {crop:crop?.id});
125
126
  if (!crop)
126
127
  return URL.createObjectURL(
127
128
  new Blob([asset.source], { type: "image/svg+xml" }),
@@ -169,7 +170,9 @@ export function imageURL(asset, crop, onSource) {
169
170
  root.setAttribute("height", crop.height);
170
171
  const rendered=new XMLSerializer().serializeToString(doc);
171
172
  onSource?.(rendered);
172
- return URL.createObjectURL(new Blob([rendered], {type:"image/svg+xml"}));
173
+ const url = URL.createObjectURL(new Blob([rendered], {type:"image/svg+xml"}));
174
+ endPreview?.();
175
+ return url;
173
176
  }
174
177
 
175
178
  // Keep current visible previews and a small LRU of offscreen previews. Identity
@@ -247,9 +250,15 @@ export function resolveScope(data, layers, requested) {
247
250
  }
248
251
 
249
252
 
250
- export function arrange(data) {
253
+ export function arrangementInput(data) {
254
+ return groupAssets(data).map(group => ({blocks:group.assets.map(blockForAsset)}));
255
+ }
256
+
257
+ export function arrange(data, { provisional = false, placed } = {}) {
251
258
  const grouped = groupAssets(data);
252
- const sections = layoutWorld(grouped.map(g => ({ ...g, blocks: g.assets.map(blockForAsset) })));
259
+ const sections = placed
260
+ ? placed.map((section,index) => ({...grouped[index],...section}))
261
+ : layoutWorld(grouped.map(g => ({ ...g, blocks: g.assets.map(blockForAsset) })), {provisional});
253
262
  const groups = sections.map(s => ({ ...s, width: s.w, height: s.h }));
254
263
  const items = [];
255
264
  for (const [group, section] of groups.entries()) {
@@ -272,6 +281,7 @@ function formDocument(form,css,theme) {
272
281
  return `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="${escape(form.name)}" style="${form.width ? `width:${form.width}px;` : 'width:max-content;'}${form.height ? `height:${form.height}px;` : ''}">${form.html}</div></body></html>`;
273
282
  }
274
283
  async function prepareSource(asset, built, theme, signal) {
284
+ const endMeasurement = globalThis.__adgTiming?.span('measurement', asset.path, {frames:built.frames.length});
275
285
  const parts = [];
276
286
  const frame = document.createElement('iframe');
277
287
  frame.setAttribute('sandbox','allow-same-origin');
@@ -280,6 +290,7 @@ async function prepareSource(asset, built, theme, signal) {
280
290
  try {
281
291
  let sliceStart=performance.now();
282
292
  for (const [index, form] of built.frames.entries()) {
293
+ const endFrame = globalThis.__adgTiming?.span('measurement-frame', asset.path, {frame:form.name});
283
294
  signal?.throwIfAborted();
284
295
  if(performance.now()-sliceStart>8) {
285
296
  await (globalThis.scheduler?.yield?.()??new Promise(resolve=>setTimeout(resolve,0)));
@@ -320,6 +331,7 @@ async function prepareSource(asset, built, theme, signal) {
320
331
  content.setAttribute('style','font:16px/1.5 var(--font-ui);color:var(--text);');
321
332
  content.append(frame.contentDocument.querySelector('style').cloneNode(true),shell.cloneNode(true));
322
333
  parts.push({id:String(index),name:form.name,note:form.note,width:box.width,height:box.height,elements,markup:new XMLSerializer().serializeToString(content)});
334
+ endFrame?.();
323
335
  }
324
336
  const wrapWidth = built.component ? componentWrapWidth(parts) : Infinity;
325
337
  let x=0,y=0,rowHeight=0;
@@ -340,5 +352,5 @@ async function prepareSource(asset, built, theme, signal) {
340
352
  });
341
353
  const source=header+markup.join('')+'</svg>';
342
354
  return {...asset,imports:built.imports,format:'tsx',source,frameRanges,full:{x:0,y:0,width,height},parts:parts.map(({markup,...p})=>p),component:built.component,background:frame.contentWindow.getComputedStyle(frame.contentDocument.documentElement).getPropertyValue('--canvas').trim()};
343
- } finally { frame.remove(); }
355
+ } finally { frame.remove(); endMeasurement?.(); }
344
356
  }
package/public/layout.js CHANGED
@@ -14,17 +14,25 @@ export function rows(blocks, limit, gapX, gapY, nextWidth) {
14
14
  });
15
15
  }
16
16
  export function skyline(blocks, limit, nextWidth, gapX = 64, gapY = 112) {
17
- const placed = [], result = [];
17
+ const lefts = [], rights = [], bottoms = [], result = [];
18
18
  // Pack tall blocks first, but keep returned identities in source order for
19
19
  // navigation, selection and incremental placement across geometry changes.
20
+ // Candidate ties prefer lower y, then lower x. Occupied edges keep exact Float arithmetic.
20
21
  const ordered = blocks.map((block, index) => ({ block, index }))
21
22
  .sort((a, b) => b.block.h - a.block.h || b.block.w - a.block.w || a.index - b.index);
22
23
  for (const { block, index } of ordered) {
23
- const candidates = [0, ...placed.map(p => p.x + p.w + gapX)].filter(x => { if (x + block.w <= limit) return true; nextWidth?.(x + block.w); return false; });
24
- const positions = candidates.map(x => ({ x, y: Math.max(0, ...placed.filter(p => x < p.x + p.w + gapX && x + block.w + gapX > p.x).map(p => p.y + p.h + gapY)) }));
25
- positions.sort((a, b) => a.y - b.y || a.x - b.x);
26
- result[index] = { ...block, ...positions[0] };
27
- placed.push(result[index]);
24
+ let bestX=Infinity,bestY=Infinity;
25
+ for(let candidate=0;candidate<=lefts.length;candidate++) {
26
+ const x=candidate ? rights[candidate-1] : 0,edge=x+block.w;
27
+ if(edge>limit){nextWidth?.(edge);continue;}
28
+ const right=edge+gapX;
29
+ let y=0;
30
+ for(let i=0;i<lefts.length;i++)
31
+ if(x<rights[i] && right>lefts[i])y=Math.max(y,bottoms[i]);
32
+ if(y<bestY || (y===bestY && x<bestX)){bestX=x;bestY=y;}
33
+ }
34
+ result[index] = { ...block, x:bestX, y:bestY };
35
+ lefts.push(bestX);rights.push(bestX+block.w+gapX);bottoms.push(bestY+block.h+gapY);
28
36
  }
29
37
  return result;
30
38
  }
@@ -38,11 +46,12 @@ export function restorePacking(entries=[]) {
38
46
  while(widthChoices.size>32)widthChoices.delete(widthChoices.keys().next().value);
39
47
  }
40
48
  const aspectPenalty = 0.6;
41
- function chooseWidth(blocks, step, ratio, gapX, gapY) {
49
+ function chooseWidth(blocks, step, ratio, gapX, gapY, cachedOnly = false) {
42
50
  if (!blocks.length) return [];
43
51
  const pack = (limit, nextWidth) => skyline(blocks, limit, nextWidth, gapX, gapY);
44
52
  const key = JSON.stringify(['area-skyline-v1', step, ratio, aspectPenalty, gapX, gapY, blocks.map(b => [b.kind, b.w, b.h])]);
45
53
  if (widthChoices.has(key)) return pack(widthChoices.get(key));
54
+ if (cachedOnly) return null;
46
55
  const minimum = Math.max(...blocks.map(b => b.w));
47
56
  const maximum = blocks.reduce((n, b) => n + b.w, 0) + blocks.length * gapX;
48
57
  // Browser layout widths are exact multiples of 1/64px. Skip only on that
@@ -66,13 +75,20 @@ function chooseWidth(blocks, step, ratio, gapX, gapY) {
66
75
  }
67
76
  return best;
68
77
  }
69
- export function layoutWorld(input) {
70
- const sections = input.map(section => {
71
- const blocks = chooseWidth(section.blocks, 50, 1.6, 64, 112);
78
+ export function layoutWorld(input, { provisional = false, cachedOnly = false } = {}) {
79
+ const place = provisional ? (blocks, step, ratio, gapX, gapY) => {
80
+ const area = blocks.reduce((sum, block) => sum + (block.w + gapX) * (block.h + gapY), 0);
81
+ return rows(blocks, Math.max(1, ...blocks.map(block => block.w), Math.sqrt(area * ratio)), gapX, gapY);
82
+ } : (...args) => chooseWidth(...args, cachedOnly);
83
+ const sections = [];
84
+ for (const section of input) {
85
+ const blocks = place(section.blocks, 50, 1.6, 64, 112);
86
+ if (!blocks) return null;
72
87
  const box = bounds(blocks);
73
- return { ...section, blocks, w: box.w + 128, h: box.h + 168 };
74
- });
75
- const placed = chooseWidth(sections, 100, 1.5, 240, 240);
88
+ sections.push({ ...section, blocks, w: box.w + 128, h: box.h + 168 });
89
+ }
90
+ const placed = place(sections, 100, 1.5, 240, 240);
91
+ if (!placed) return null;
76
92
  return placed.map(section => ({ ...section, blocks: section.blocks.map(block => {
77
93
  const x = section.x + 64 + block.x, y = section.y + 104 + block.y;
78
94
  return { ...block, x, y, ...(block.frames ? { frames: block.frames.map(frame => ({ ...frame, x: x + frame.x, y: y + frame.y })) } : {}) };