@whzxc/agent-design-gallery 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +69 -0
- package/README.md +218 -2
- package/package.json +43 -4
- package/public/access.css +10 -0
- package/public/app.js +1674 -0
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +356 -0
- package/public/auth.js +69 -0
- package/public/favicon.svg +6 -0
- package/public/hub.css +67 -0
- package/public/hub.html +33 -0
- package/public/hub.js +165 -0
- package/public/icons.js +50 -0
- package/public/index.html +70 -0
- package/public/instance-actions.js +27 -0
- package/public/labels.js +122 -0
- package/public/layout.js +119 -0
- package/public/relationships.js +28 -0
- package/public/selection.js +20 -0
- package/public/style.css +194 -0
- package/public/switcher.css +37 -0
- package/public/switcher.js +176 -0
- package/public/token-catalog.js +129 -0
- package/public/tokens.css +61 -0
- package/public/view-route.js +66 -0
- package/src/cli-output.mjs +236 -0
- package/src/cli.mjs +176 -0
- package/src/http.mjs +38 -0
- package/src/hub/auth.mjs +41 -0
- package/src/hub/instances.mjs +99 -0
- package/src/hub/proxy.mjs +30 -0
- package/src/hub/registry.mjs +181 -0
- package/src/hub.mjs +128 -0
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +55 -0
- package/src/open.mjs +61 -0
- package/src/perf.mjs +12 -0
- package/src/server.mjs +679 -0
- package/src/service.mjs +184 -0
- package/src/toolkit/arch-browser.mjs +40 -0
- package/src/toolkit/arch-git.mjs +55 -0
- package/src/toolkit/arch-overlay.mjs +225 -0
- package/src/toolkit/arch.mjs +221 -0
- package/src/toolkit/asset-rules.mjs +14 -0
- package/src/toolkit/browser.mjs +33 -0
- package/src/toolkit/build-store.mjs +266 -0
- package/src/toolkit/build-worker.mjs +35 -0
- package/src/toolkit/build.mjs +147 -0
- package/src/toolkit/commands.mjs +345 -0
- package/src/toolkit/compare.mjs +222 -0
- package/src/toolkit/config.mjs +136 -0
- package/src/toolkit/document.mjs +85 -0
- package/src/toolkit/migrate.mjs +85 -0
- package/src/toolkit/project.mjs +172 -0
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/runtime.d.ts +14 -0
- package/src/toolkit/runtime.mjs +54 -0
- package/src/toolkit/text.mjs +12 -0
- package/src/toolkit/tokens.mjs +37 -0
- package/src/viewer-cache.mjs +85 -0
package/public/app.js
ADDED
|
@@ -0,0 +1,1674 @@
|
|
|
1
|
+
import { initSwitcher, updateSwitcherLabels } from './switcher.js';
|
|
2
|
+
import { dataFetch, keyURL, isUnauthorized } from './auth.js';
|
|
3
|
+
import { Labels } from "./labels.js";
|
|
4
|
+
import { fitArea, fitView, packingSnapshot, restorePacking } from "./layout.js";
|
|
5
|
+
import { icon, hydrateIcons } from "./icons.js";
|
|
6
|
+
hydrateIcons();
|
|
7
|
+
import { prepare, imageURL, arrange, groupAssets, evictPreviews, metadataContext, measuredMetadata, previewAddress, compactPreparedSource, scopeKind, scopeTarget } from "./assets.js";
|
|
8
|
+
import { sourceRelationships, relatedSources } from './relationships.js';
|
|
9
|
+
import { hitSelection, frameBox, exportFrames } from './selection.js';
|
|
10
|
+
import { groupTokens, renderTokenTable } from './token-catalog.js';
|
|
11
|
+
import { readViewRoute, viewURL } from './view-route.js';
|
|
12
|
+
import { createArranger } from './arrangement.js';
|
|
13
|
+
const arranger = createArranger();
|
|
14
|
+
window.addEventListener('pagehide',()=>arranger.close());
|
|
15
|
+
// ARC's gallery layout and camera model, decoupled from its React runtime.
|
|
16
|
+
const $ = (selector) => document.querySelector(selector);
|
|
17
|
+
const viewport = $(".gallery-viewport"),
|
|
18
|
+
canvas = $("#drawings"),
|
|
19
|
+
ctx = canvas.getContext("2d"),
|
|
20
|
+
background = $("#canvas-background"),
|
|
21
|
+
backgroundContext = background.getContext("2d", { alpha: false });
|
|
22
|
+
let manifest,
|
|
23
|
+
catalog = null,
|
|
24
|
+
tokenManifest = null,
|
|
25
|
+
tokenCategory = null,
|
|
26
|
+
pendingNavigation = null,
|
|
27
|
+
groups = [],
|
|
28
|
+
assets = [],
|
|
29
|
+
world = { x: 0, y: 0, width: 1, height: 1 },
|
|
30
|
+
view = { x: 0, y: 0, scale: 1 };
|
|
31
|
+
let width = viewport.clientWidth,
|
|
32
|
+
height = viewport.clientHeight,
|
|
33
|
+
dpr = devicePixelRatio,
|
|
34
|
+
theme = "system",
|
|
35
|
+
effectiveTheme = "dark",
|
|
36
|
+
selected = null,
|
|
37
|
+
active = null;
|
|
38
|
+
let raf = 0,
|
|
39
|
+
idleTimer,
|
|
40
|
+
saveTimer,
|
|
41
|
+
moving = false,
|
|
42
|
+
loading = 0,
|
|
43
|
+
queued = [],
|
|
44
|
+
palette = {};
|
|
45
|
+
const labelLayer = new Labels($("#labels"), copyError => {
|
|
46
|
+
if (copyError) error(`Cannot copy name: ${copyError.message}`);
|
|
47
|
+
else if ($('#error').textContent.startsWith('Cannot copy name:')) error('');
|
|
48
|
+
}, target => {
|
|
49
|
+
const a=assets.find(a=>a.path===target.path && (target.form===undefined || a.component || a.shown[0].id===target.form));
|
|
50
|
+
if (target.form !== undefined) selectFrame(a,a?.parts.find(p=>p.id===target.form));
|
|
51
|
+
else selectSource(a);
|
|
52
|
+
});
|
|
53
|
+
document.fonts.ready.then(() => {labelLayer.metrics.clear();requestDraw()});
|
|
54
|
+
let labelsDirty = true, labelObstacles = null;
|
|
55
|
+
let drawingDirty = true, drawingView = null, drawingMargin = 0, drawingReady = 0, drawingCount = 0;
|
|
56
|
+
const zoomValue = $("#zoom-value"), zoomOutput = $("output");
|
|
57
|
+
const cache = new Map(),
|
|
58
|
+
pointers = new Map();
|
|
59
|
+
let gesture = {};
|
|
60
|
+
let sidebar = false,
|
|
61
|
+
inspector = false,
|
|
62
|
+
selectedId = null,
|
|
63
|
+
selectedForm = null,
|
|
64
|
+
selectedElement = null,
|
|
65
|
+
hoveredElement = null,
|
|
66
|
+
inspection = null;
|
|
67
|
+
let backgroundChoice = "theme", backgroundColors = {};
|
|
68
|
+
let history = [],
|
|
69
|
+
searchReturn = null;
|
|
70
|
+
const expanded = new Set(),
|
|
71
|
+
prepared = new Map(), metadataCache = new Map(), preparingSources = new Map();
|
|
72
|
+
let initializedDirectory, uploadActive = 0, cacheWrites = 0, cacheFailures = 0;
|
|
73
|
+
const uploadQueue=[], uploadPromises=new Set();
|
|
74
|
+
function cacheWrite(url,data,raw=false) {
|
|
75
|
+
cacheWrites++;
|
|
76
|
+
const promise=new Promise(resolve=>uploadQueue.push({url,data,raw,resolve}));
|
|
77
|
+
uploadPromises.add(promise);promise.finally(()=>uploadPromises.delete(promise));
|
|
78
|
+
pumpUploads();return promise;
|
|
79
|
+
}
|
|
80
|
+
function pumpUploads() {
|
|
81
|
+
while(uploadActive<3&&uploadQueue.length) {
|
|
82
|
+
const task=uploadQueue.shift();uploadActive++;
|
|
83
|
+
dataFetch(task.url,{method:'POST',headers:{'Content-Type':task.raw?'image/svg+xml':'application/json'},body:task.raw?task.data:JSON.stringify(task.data)})
|
|
84
|
+
.then(response=>{if(response.status===409)return false;if(!response.ok)throw Error(`Derived cache HTTP ${response.status}`);return true})
|
|
85
|
+
.catch(()=>{cacheFailures++;return false})
|
|
86
|
+
.then(result=>{uploadActive--;cacheWrites--;task.resolve(result);pumpUploads()});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function flushCache() {
|
|
90
|
+
while(cacheWrites||loading||queued.length) {
|
|
91
|
+
await Promise.all([...uploadPromises]);
|
|
92
|
+
await new Promise(resolve=>setTimeout(resolve,20));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const sourceKey=(asset,theme,directory=manifest?.directory??catalog?.directory)=>`${directory}|${asset.path}|${asset.hash??asset.version}|${theme}${asset.onlyFrame ? `|frame:${asset.onlyFrame}` : ''}`;
|
|
96
|
+
function keepSource(key,entry) {
|
|
97
|
+
entry=compactPreparedSource(entry);
|
|
98
|
+
prepared.delete(key);prepared.set(key,entry);
|
|
99
|
+
let bytes=[...prepared.values()].reduce((n,a)=>n+(a.source?.length??0)*2,0);
|
|
100
|
+
for(const [old,value] of prepared) {
|
|
101
|
+
if(bytes<=64*1024*1024)break;
|
|
102
|
+
bytes-=(value.source?.length??0)*2;prepared.delete(old);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function decorateMetadata(asset,metadata) {
|
|
106
|
+
const entry={...asset,...metadata};
|
|
107
|
+
if(Number.isFinite(asset.modifiedAt)) {
|
|
108
|
+
const date=new Date(asset.modifiedAt);
|
|
109
|
+
entry.modified={text:modifiedDate.format(date),timestamp:date.toISOString(),title:date.toLocaleString(undefined,{dateStyle:'full',timeStyle:'long'})};
|
|
110
|
+
}
|
|
111
|
+
return entry;
|
|
112
|
+
}
|
|
113
|
+
function persistSource(entry,theme) {
|
|
114
|
+
if(!entry.hash || entry.onlyFrame)return Promise.resolve(false);
|
|
115
|
+
const query=new URLSearchParams({theme,context:metadataContext()});
|
|
116
|
+
const promise=cacheWrite(`metadata/${entry.hash}?${query}`,{metadata:measuredMetadata(entry)});
|
|
117
|
+
entry.cacheWrite=promise;
|
|
118
|
+
return promise;
|
|
119
|
+
}
|
|
120
|
+
async function sourceFor(asset,theme) {
|
|
121
|
+
const key=sourceKey(asset,theme),cached=prepared.get(key);
|
|
122
|
+
if(cached?.source)return cached;
|
|
123
|
+
if(preparingSources.has(key))return preparingSources.get(key);
|
|
124
|
+
const pending=(async()=>{
|
|
125
|
+
const entry=await prepare(asset,theme);
|
|
126
|
+
persistSource(entry,theme);
|
|
127
|
+
keepSource(sourceKey(entry,theme),entry);return entry;
|
|
128
|
+
})();
|
|
129
|
+
preparingSources.set(key,pending);
|
|
130
|
+
try{return await pending}finally{preparingSources.delete(key)}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const fixtureName = new URL(location.href).searchParams.get("fixture");
|
|
134
|
+
let fixtureState = null, fixtureApplied = false;
|
|
135
|
+
let route = {}, routeError;
|
|
136
|
+
try { route = readViewRoute(new URL(location.href)); }
|
|
137
|
+
catch (error) { routeError = error; }
|
|
138
|
+
let initialLink = route.target, strictRoute = route.strict, queryView = !!route.isolated;
|
|
139
|
+
let scopeRequest = fixtureName ? 'all' : route.scope ?? 'default', onlyFrame = route.onlyFrame ?? null;
|
|
140
|
+
let initializedScope, initializedFrame, scopeEntry;
|
|
141
|
+
const currentItem = () => inspection || assets.find((a) => a.id === selectedId);
|
|
142
|
+
function remember() {
|
|
143
|
+
history.push({
|
|
144
|
+
view: { ...view },
|
|
145
|
+
scope: initializedScope,
|
|
146
|
+
onlyFrame,
|
|
147
|
+
queryView,
|
|
148
|
+
target: selectionTarget(),
|
|
149
|
+
active,
|
|
150
|
+
selected,
|
|
151
|
+
selectedId,
|
|
152
|
+
selectedForm,
|
|
153
|
+
selectedElement,
|
|
154
|
+
inspection,
|
|
155
|
+
inspector,
|
|
156
|
+
});
|
|
157
|
+
if (history.length > 40) history.shift();
|
|
158
|
+
}
|
|
159
|
+
function back() {
|
|
160
|
+
if (catalog) return;
|
|
161
|
+
const old = history.pop();
|
|
162
|
+
if (!old && onlyFrame) {
|
|
163
|
+
changeScope(initializedScope, null, false);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (old) {
|
|
167
|
+
if (old.scope && (old.scope !== initializedScope || (old.onlyFrame ?? null) !== onlyFrame)) {
|
|
168
|
+
changeScope(old.scope, old, false);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
|
|
172
|
+
selection();
|
|
173
|
+
commit(old.view);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function changeScope(next, entry = null, record = true) {
|
|
177
|
+
const nextFrame = entry?.onlyFrame ?? null;
|
|
178
|
+
if (next === scopeRequest && nextFrame === onlyFrame) return;
|
|
179
|
+
if ((initializedScope || tokenManifest) && !catalog) {
|
|
180
|
+
if (record && !tokenManifest && next !== 'tokens') remember();
|
|
181
|
+
void persistPreferences();
|
|
182
|
+
}
|
|
183
|
+
scopeRequest = next;
|
|
184
|
+
onlyFrame = nextFrame;
|
|
185
|
+
queryView = entry?.queryView ?? !['all', 'layer'].includes(scopeKind(next));
|
|
186
|
+
strictRoute = false;
|
|
187
|
+
scopeEntry = entry;
|
|
188
|
+
initialLink = null;
|
|
189
|
+
pendingNavigation = null;
|
|
190
|
+
if (searchReturn) sidebar = searchReturn.sidebar;
|
|
191
|
+
searchReturn = null;
|
|
192
|
+
$("#search").value = '';
|
|
193
|
+
void refresh(true);
|
|
194
|
+
}
|
|
195
|
+
function toggleSidebar(value = !sidebar) {
|
|
196
|
+
sidebar = value;
|
|
197
|
+
updateChrome();
|
|
198
|
+
requestDraw(true, false);
|
|
199
|
+
}
|
|
200
|
+
function updateChrome() {
|
|
201
|
+
updateSwitcherLabels();
|
|
202
|
+
const opened = !!(tokenManifest ?? catalog ?? manifest)?.directory;
|
|
203
|
+
const showTokens = !!tokenManifest;
|
|
204
|
+
const canInspect = opened && !showTokens && !!selected;
|
|
205
|
+
$('.gallery').classList.toggle('tokens-mode', showTokens);
|
|
206
|
+
$('#token-catalog').hidden = !showTokens;
|
|
207
|
+
viewport.inert = showTokens;
|
|
208
|
+
$('#sidebar').hidden = !opened || !sidebar;
|
|
209
|
+
$('#app-bar').hidden = !opened;
|
|
210
|
+
if (fixtureState) $('#app-directory .switcher-chevron').hidden = false;
|
|
211
|
+
$('#tools').hidden = !opened;
|
|
212
|
+
$('.zoom').hidden = !opened || showTokens;
|
|
213
|
+
$('#source').hidden = !canInspect || !inspector;
|
|
214
|
+
$('#inspect').disabled = !canInspect;
|
|
215
|
+
$('#inspect').setAttribute('aria-expanded', String(canInspect && inspector));
|
|
216
|
+
$('#arrange').hidden = showTokens;
|
|
217
|
+
if (!opened) $('#minimap').hidden = true;
|
|
218
|
+
$('#sidebar-toggle').setAttribute('aria-expanded', String(opened && sidebar));
|
|
219
|
+
positionZoomMenu();
|
|
220
|
+
}
|
|
221
|
+
function positionZoomMenu() {
|
|
222
|
+
const r = $("#zoom-options").getBoundingClientRect();
|
|
223
|
+
$("#zoom-menu").style.left = `${r.x + r.width / 2}px`;
|
|
224
|
+
$("#zoom-menu").style.bottom = `${height - $(".zoom").getBoundingClientRect().top + 8}px`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const media = matchMedia("(prefers-color-scheme: dark)");
|
|
228
|
+
const modifiedDate = new Intl.DateTimeFormat('en-US', {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
|
|
229
|
+
window.__adg = {
|
|
230
|
+
ready: false,
|
|
231
|
+
get metadataComplete() {return !!tokenManifest || (!!manifest && !manifest.loading);},
|
|
232
|
+
get scope() {return tokenManifest?.scope ?? initializedScope;},
|
|
233
|
+
get cachePending() {return cacheWrites+loading+queued.length;},
|
|
234
|
+
get cacheFlush() {return flushCache();},
|
|
235
|
+
get cacheFailures() {return cacheFailures;},
|
|
236
|
+
get view() {
|
|
237
|
+
return { ...view };
|
|
238
|
+
},
|
|
239
|
+
get assets() {
|
|
240
|
+
return tokenManifest ? 0 : assets.length;
|
|
241
|
+
},
|
|
242
|
+
get previews() {
|
|
243
|
+
return {entries: cache.size, decoded: [...cache.values()].filter(e => e.image).length,
|
|
244
|
+
rasterBytes: [...cache.values()].reduce((n, e) => n + (e.bitmap ? e.bitmap.width * e.bitmap.height * 4 : 0), 0)};
|
|
245
|
+
},
|
|
246
|
+
get selection() {return {path:selected, frame:currentItem()?.parts.find(p=>p.id===selectedForm)?.name ?? null, element:selectedElement?.owner ?? null}},
|
|
247
|
+
get items() {
|
|
248
|
+
return assets.map(({ id, path, x, y, width, height, group }) => ({
|
|
249
|
+
id,
|
|
250
|
+
path,
|
|
251
|
+
x,
|
|
252
|
+
y,
|
|
253
|
+
width,
|
|
254
|
+
height,
|
|
255
|
+
group,
|
|
256
|
+
}));
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
const clamp = (s) => Math.max(0.025, Math.min(32, s));
|
|
260
|
+
function error(message) {
|
|
261
|
+
if (isUnauthorized()) return;
|
|
262
|
+
if(fixtureState && message) document.documentElement.dataset.fixtureError=message;
|
|
263
|
+
$("#error").textContent = message;
|
|
264
|
+
$("#error").hidden = !message;
|
|
265
|
+
}
|
|
266
|
+
async function api(url, data, keepalive = false, signal) {
|
|
267
|
+
if(fixtureName && url.startsWith("manifest")) url += `${url.includes("?")?"&":"?"}fixture=${encodeURIComponent(fixtureName)}`;
|
|
268
|
+
const response = await dataFetch(
|
|
269
|
+
url,
|
|
270
|
+
data
|
|
271
|
+
? {
|
|
272
|
+
method: "POST",
|
|
273
|
+
headers: { "Content-Type": "application/json" },
|
|
274
|
+
body: JSON.stringify(data),
|
|
275
|
+
keepalive,
|
|
276
|
+
}
|
|
277
|
+
: { signal },
|
|
278
|
+
);
|
|
279
|
+
const result = await response.json();
|
|
280
|
+
if (signal && response.status === 409) throw new DOMException(result.error,'AbortError');
|
|
281
|
+
if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`);
|
|
282
|
+
return result;
|
|
283
|
+
}
|
|
284
|
+
function preferences() {
|
|
285
|
+
if (tokenManifest || onlyFrame) return { theme };
|
|
286
|
+
return {
|
|
287
|
+
view,
|
|
288
|
+
scope: initializedScope,
|
|
289
|
+
selection: selectionTarget(),
|
|
290
|
+
theme,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function selectionTarget() {
|
|
294
|
+
return {
|
|
295
|
+
path: selected,
|
|
296
|
+
form: currentItem()?.parts.find(p => p.id === selectedForm)?.name ?? null,
|
|
297
|
+
element: selectedElement ? {id:selectedElement.id, owner:selectedElement.owner} : null,
|
|
298
|
+
group: groups[active]?.title ?? null,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
function syncSelectionURL() {
|
|
302
|
+
if (fixtureState || catalog || !manifest?.directory) return;
|
|
303
|
+
const target = selectionTarget();
|
|
304
|
+
if (!['layer', 'all'].includes(scopeKind(initializedScope))) target.group = null;
|
|
305
|
+
if (onlyFrame) target.path = scopeTarget(initializedScope);
|
|
306
|
+
const url = viewURL(location.href, initializedScope, target, { isolated: queryView, onlyFrame });
|
|
307
|
+
if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
|
|
308
|
+
}
|
|
309
|
+
function restoreSelection(target) {
|
|
310
|
+
if (!target) return;
|
|
311
|
+
const source = manifest.assets.find(a => a.path === target.path);
|
|
312
|
+
const form = source?.parts.find(p => p.name === target.form);
|
|
313
|
+
const item = assets.find(a => a.path === target.path && (a.component || !form || a.shown[0].id === form.id));
|
|
314
|
+
if (item) {
|
|
315
|
+
selected = item.path;
|
|
316
|
+
selectedId = item.id;
|
|
317
|
+
selectedForm = form?.id ?? null;
|
|
318
|
+
const element = target.element && form?.elements?.find(e => e.id === target.element.id);
|
|
319
|
+
const owner = target.element?.owner;
|
|
320
|
+
if (element && (!owner || element.owners.some(o => o.source === owner.source && o.export === owner.export)))
|
|
321
|
+
selectedElement = {...element, owner:owner ?? element.owners.at(-1)};
|
|
322
|
+
active = item.group;
|
|
323
|
+
} else {
|
|
324
|
+
const group = groups.findIndex(g => g.title === target.group);
|
|
325
|
+
active = group >= 0 ? group : null;
|
|
326
|
+
}
|
|
327
|
+
if (active !== null) expanded.add(active);
|
|
328
|
+
}
|
|
329
|
+
function persistPreferences(keepalive = false) {
|
|
330
|
+
clearTimeout(saveTimer);
|
|
331
|
+
if (fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
|
|
332
|
+
return api('preferences', preferences(), keepalive).catch(e => error(e.message));
|
|
333
|
+
}
|
|
334
|
+
function save() {
|
|
335
|
+
if(fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
|
|
336
|
+
clearTimeout(saveTimer);
|
|
337
|
+
saveTimer = setTimeout(persistPreferences, 220);
|
|
338
|
+
}
|
|
339
|
+
window.addEventListener('pagehide', () => void persistPreferences(true));
|
|
340
|
+
document.addEventListener('visibilitychange', () => {if (document.hidden) void persistPreferences(true)});
|
|
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});
|
|
344
|
+
const previous = assets,
|
|
345
|
+
previousGroups = groups,
|
|
346
|
+
result = arrange(layoutData(data),options);
|
|
347
|
+
groups = result.groups;
|
|
348
|
+
assets = result.items;
|
|
349
|
+
world = result.world;
|
|
350
|
+
if (preserve) {
|
|
351
|
+
const previousById = new Map(previous.map(item => [item.id, item]));
|
|
352
|
+
const currentIds = new Set(assets.map(item => item.id));
|
|
353
|
+
const previousByTitle = new Map();
|
|
354
|
+
for (const group of previousGroups) if (!previousByTitle.has(group.title)) previousByTitle.set(group.title, group);
|
|
355
|
+
for (const group of groups) {
|
|
356
|
+
const old = previousByTitle.get(group.title);
|
|
357
|
+
if (old) {
|
|
358
|
+
group.x = old.x;
|
|
359
|
+
group.y = old.y;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const occupied = previous.filter((p) => currentIds.has(p.id));
|
|
363
|
+
const shape = (a) =>
|
|
364
|
+
JSON.stringify(a.shown.map(p => [p.width, p.height]));
|
|
365
|
+
for (const a of assets) {
|
|
366
|
+
const old = previousById.get(a.id);
|
|
367
|
+
if (old) {
|
|
368
|
+
a.x = old.x;
|
|
369
|
+
a.y = old.y;
|
|
370
|
+
}
|
|
371
|
+
if (
|
|
372
|
+
old &&
|
|
373
|
+
(shape(old) === shape(a) ||
|
|
374
|
+
(a.width <= old.width && a.height <= old.height))
|
|
375
|
+
) {
|
|
376
|
+
a.width = old.width;
|
|
377
|
+
a.height = old.height;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
const group = groups[a.group];
|
|
381
|
+
a.x = old?.x ?? group.x + 64;
|
|
382
|
+
a.y =
|
|
383
|
+
Math.max(
|
|
384
|
+
group.y + 104,
|
|
385
|
+
...occupied
|
|
386
|
+
.filter((p) => previousGroups[p.group]?.title === group.title)
|
|
387
|
+
.map((p) => p.y + p.height),
|
|
388
|
+
) + 112;
|
|
389
|
+
let collision;
|
|
390
|
+
while (
|
|
391
|
+
(collision = occupied.find(
|
|
392
|
+
(p) =>
|
|
393
|
+
p.id !== a.id &&
|
|
394
|
+
a.x < p.x + p.width + 20 &&
|
|
395
|
+
a.x + a.width + 20 > p.x &&
|
|
396
|
+
a.y < p.y + p.height + 20 &&
|
|
397
|
+
a.y + a.height + 20 > p.y,
|
|
398
|
+
))
|
|
399
|
+
)
|
|
400
|
+
a.y = collision.y + collision.height + 112;
|
|
401
|
+
const index = occupied.findIndex((p) => p.id === a.id);
|
|
402
|
+
if (index >= 0) occupied[index] = a;
|
|
403
|
+
else occupied.push(a);
|
|
404
|
+
}
|
|
405
|
+
for (const g of groups) {
|
|
406
|
+
const list = assets.filter((a) => groups[a.group] === g);
|
|
407
|
+
g.width = Math.max(g.width, ...list.map((a) => a.x + a.width - g.x + 64));
|
|
408
|
+
g.height = Math.max(
|
|
409
|
+
g.height,
|
|
410
|
+
...list.map((a) => a.y + a.height - g.y + 64),
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
world.width = Math.max(1, ...groups.map((g) => g.x + g.width));
|
|
414
|
+
world.height = Math.max(1, ...groups.map((g) => g.y + g.height));
|
|
415
|
+
}
|
|
416
|
+
renderNav();
|
|
417
|
+
$("#asset-access").replaceChildren(
|
|
418
|
+
...assets.map((a) => {
|
|
419
|
+
const b = document.createElement("button");
|
|
420
|
+
b.textContent = `View ${a.name}${a.kind === "flow" ? " / " + a.shown[0].name : ""}`;
|
|
421
|
+
b.onclick = () => focusAsset(a);
|
|
422
|
+
return b;
|
|
423
|
+
}),
|
|
424
|
+
);
|
|
425
|
+
$("#empty").hidden = !!assets.length || !data.directory;
|
|
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');
|
|
429
|
+
}
|
|
430
|
+
function makeRow(name, label, count, className = 'tree-row') {
|
|
431
|
+
const button = document.createElement('button'); button.className = className;
|
|
432
|
+
button.innerHTML = icon(name, 14);
|
|
433
|
+
const text = document.createElement('span'); text.textContent = label; button.append(text);
|
|
434
|
+
if (count !== undefined) { const detail = document.createElement('span'); detail.className='count'; detail.textContent=count; button.append(detail); }
|
|
435
|
+
return button;
|
|
436
|
+
}
|
|
437
|
+
function searchResults(query) {
|
|
438
|
+
const entries = (catalog ?? manifest).assets;
|
|
439
|
+
const files = entries.filter(a => a.name.toLowerCase().includes(query)).map(a => ({ a }));
|
|
440
|
+
const forms = entries.flatMap(a => a.name.toLowerCase().includes(query) ? [] : (a.parts ?? []).filter(p => p.name.toLowerCase().includes(query)).map(p => ({ a, p })));
|
|
441
|
+
return [...files, ...forms];
|
|
442
|
+
}
|
|
443
|
+
function navigate(action) {
|
|
444
|
+
if (catalog) pendingNavigation = action;
|
|
445
|
+
else action();
|
|
446
|
+
}
|
|
447
|
+
function scopedUI(data) { return !!data.layers && (!data.fixture || !!data.fixture.scope); }
|
|
448
|
+
function scopeLabel(scope) {
|
|
449
|
+
const target = scopeTarget(scope);
|
|
450
|
+
if (scope === 'all') return 'All designs';
|
|
451
|
+
if (scope === 'tokens') return 'Tokens';
|
|
452
|
+
if (scopeKind(scope) === 'layer') return target[0].toUpperCase() + target.slice(1);
|
|
453
|
+
if (scopeKind(scope) === 'asset') return target.split('/').at(-1).replace(/\.(tsx|svg)$/i,'');
|
|
454
|
+
return target;
|
|
455
|
+
}
|
|
456
|
+
function renderScopeTabs(data) {
|
|
457
|
+
const tabs = $('#scope-tabs');
|
|
458
|
+
const choices = [...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
|
|
459
|
+
const signature = JSON.stringify([data.scope, choices]);
|
|
460
|
+
$('#sidebar').classList.toggle('scoped', scopedUI(data));
|
|
461
|
+
if (tabs.dataset.signature === signature) return;
|
|
462
|
+
tabs.dataset.signature = signature;
|
|
463
|
+
const focused = tabs.contains(document.activeElement) ? document.activeElement.dataset.scope : null;
|
|
464
|
+
const selected = choices.includes(data.scope) ? data.scope : null;
|
|
465
|
+
tabs.replaceChildren(...choices.map((choice, index) => {
|
|
466
|
+
const tab = document.createElement('button');
|
|
467
|
+
tab.type = 'button';
|
|
468
|
+
tab.setAttribute('role', 'tab');
|
|
469
|
+
tab.setAttribute('aria-selected', String(choice === selected));
|
|
470
|
+
tab.tabIndex = (selected ? choice === selected : index === 0) ? 0 : -1;
|
|
471
|
+
tab.dataset.scope = choice;
|
|
472
|
+
tab.textContent = scopeLabel(choice);
|
|
473
|
+
tab.onclick = () => changeScope(choice);
|
|
474
|
+
return tab;
|
|
475
|
+
}));
|
|
476
|
+
if (focused) [...tabs.children].find(tab => tab.dataset.scope === focused)?.focus({ preventScroll: true });
|
|
477
|
+
const active = tabs.querySelector('[aria-selected="true"]');
|
|
478
|
+
active?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
479
|
+
}
|
|
480
|
+
$('#scope-tabs').addEventListener('keydown', event => {
|
|
481
|
+
const tabs = [...event.currentTarget.children], index = tabs.indexOf(event.target);
|
|
482
|
+
if (index < 0) return;
|
|
483
|
+
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
|
|
484
|
+
const target = event.key === 'Home' ? tabs[0] : event.key === 'End' ? tabs.at(-1)
|
|
485
|
+
: step ? tabs[(index + step + tabs.length) % tabs.length] : null;
|
|
486
|
+
if (!target) return;
|
|
487
|
+
event.preventDefault();
|
|
488
|
+
target.focus();
|
|
489
|
+
target.click();
|
|
490
|
+
});
|
|
491
|
+
function scopeAction(kind, key, label) {
|
|
492
|
+
const action = document.createElement('button');
|
|
493
|
+
action.type = 'button';action.className='icon-button scope-only';action.innerHTML=icon('square-dashed');
|
|
494
|
+
action.dataset.navkey=`only:${kind}:${key}`;
|
|
495
|
+
const text = `Render only this ${kind}`;
|
|
496
|
+
action.setAttribute('aria-label',`${text}: ${label}`);
|
|
497
|
+
action.dataset.tooltip = text;
|
|
498
|
+
bindTooltip(action,true);
|
|
499
|
+
action.onclick = () => changeScope(`${kind}:${key}`);
|
|
500
|
+
return action;
|
|
501
|
+
}
|
|
502
|
+
function navFile(a, options = {}) {
|
|
503
|
+
const { indent=false, isolate=false } = options;
|
|
504
|
+
const item=makeRow((a.component ?? a.path.startsWith('components/'))?'component':'app-window',a.name,undefined,'tree-row file');
|
|
505
|
+
item.dataset.navkey=`file:${a.path}`;
|
|
506
|
+
item.setAttribute('aria-current',String(selected===a.path));
|
|
507
|
+
item.onclick=()=>navigate(()=>focusAsset(assets.find(x=>x.path===a.path)));
|
|
508
|
+
if (!isolate) return item;
|
|
509
|
+
const row=document.createElement('div');row.className='scope-row';
|
|
510
|
+
if (indent) row.classList.add('scope-row-indent');
|
|
511
|
+
row.append(item,scopeAction('asset',a.path,a.name));
|
|
512
|
+
return row;
|
|
513
|
+
}
|
|
514
|
+
function renderNav() {
|
|
515
|
+
const data = tokenManifest ?? catalog ?? manifest;
|
|
516
|
+
if (!data) return;
|
|
517
|
+
renderScopeTabs(data);
|
|
518
|
+
const scoped = scopedUI(data), kind = scoped ? scopeKind(data.scope) : null;
|
|
519
|
+
const focusKey = document.activeElement?.dataset.navkey;
|
|
520
|
+
const query = $("#search").value.trim().toLowerCase(), nodes = [];
|
|
521
|
+
const searchLabel = tokenManifest ? 'Find tokens' : 'Find assets';
|
|
522
|
+
$('#search').placeholder = `${searchLabel}…`;
|
|
523
|
+
$('#search').setAttribute('aria-label', searchLabel);
|
|
524
|
+
$('#modules').setAttribute('aria-label', tokenManifest ? 'Token categories' : 'Design modules');
|
|
525
|
+
$(".gallery").classList.toggle('searching', !tokenManifest && !!query);
|
|
526
|
+
$("#search-clear").hidden = !query; $("#search-key").hidden = !!query;
|
|
527
|
+
if (tokenManifest) {
|
|
528
|
+
const addCategory = (label, glyph, count, category) => {
|
|
529
|
+
const button = makeRow(glyph, label, count, `tree-row ${category ? 'token-category' : 'token-all'}`);
|
|
530
|
+
button.dataset.navkey = `token:${label}`;
|
|
531
|
+
button.setAttribute('aria-current', String(tokenCategory === category));
|
|
532
|
+
button.onclick = () => {
|
|
533
|
+
tokenCategory = category;
|
|
534
|
+
$('.token-scroll').scrollTop = 0;
|
|
535
|
+
renderNav();
|
|
536
|
+
};
|
|
537
|
+
nodes.push(button);
|
|
538
|
+
};
|
|
539
|
+
addCategory('All tokens', 'layout-grid', data.tokenGroups.reduce((total, group) => total + group.rows.length, 0), null);
|
|
540
|
+
const rule = document.createElement('div'); rule.className = 'rule'; nodes.push(rule);
|
|
541
|
+
for (const {label, glyph, rows} of data.tokenGroups) addCategory(label, glyph, rows.length, label);
|
|
542
|
+
renderTokenTable($('#token-catalog'), data, tokenCategory, query, copyError => {
|
|
543
|
+
if (copyError) error(`Cannot copy token name: ${copyError.message}`);
|
|
544
|
+
else if ($('#error').textContent.startsWith('Cannot copy token name:')) error('');
|
|
545
|
+
});
|
|
546
|
+
} else if (query) {
|
|
547
|
+
const results = searchResults(query), heading = document.createElement('h3');
|
|
548
|
+
heading.className='search-count'; heading.textContent=`${results.length} ${results.length === 1 ? 'result' : 'results'}`; nodes.push(heading);
|
|
549
|
+
for (const { a, p } of results) {
|
|
550
|
+
const component = a.component ?? a.path.startsWith('components/');
|
|
551
|
+
const button=makeRow(component?'component':'app-window',p ? `${a.name} · ${p.name}` : a.name,p ? 'form' : a.parts ? `${a.parts.length} ${component?'forms':'frames'}` : undefined,'tree-row search-result');
|
|
552
|
+
button.dataset.navkey=`search:${a.path}:${p?.id ?? ''}`;
|
|
553
|
+
button.setAttribute('aria-current',String(selected===a.path && (!p || selectedForm===p.id)));
|
|
554
|
+
button.onclick=()=>navigate(()=>p ? inspectForm(a,p) : focusAsset(assets.find(item=>item.path===a.path)));
|
|
555
|
+
if (scoped && kind!=='asset' && !p) {
|
|
556
|
+
const row=document.createElement('div');row.className='scope-row';
|
|
557
|
+
row.append(button,scopeAction('asset',a.path,a.name));nodes.push(row);
|
|
558
|
+
} else nodes.push(button);
|
|
559
|
+
}
|
|
560
|
+
} else if (kind === 'asset') {
|
|
561
|
+
const a=manifest?.scope===data.scope ? manifest.assets[0] : null;
|
|
562
|
+
for (const p of a?.parts ?? []) {
|
|
563
|
+
const button=makeRow('app-window',p.name);
|
|
564
|
+
button.dataset.navkey=`form:${p.name}`;
|
|
565
|
+
button.setAttribute('aria-current',String(selectedForm===p.id));
|
|
566
|
+
button.onclick=()=>navigate(()=>inspectForm(a,p));
|
|
567
|
+
nodes.push(button);
|
|
568
|
+
}
|
|
569
|
+
} else if (kind === 'group') {
|
|
570
|
+
for (const a of data.assets) nodes.push(navFile(a,{isolate:true}));
|
|
571
|
+
} else {
|
|
572
|
+
if (!scoped) {
|
|
573
|
+
const all=makeRow('layout-grid','All designs',data.assets.length); all.id='all'; all.onclick=()=>navigate(fit); nodes.push(all);
|
|
574
|
+
const rule=document.createElement('div');rule.className='rule';nodes.push(rule);
|
|
575
|
+
}
|
|
576
|
+
(catalog ? groupAssets(catalog) : groups).forEach((g,i)=>{
|
|
577
|
+
const section=document.createElement('section'), row=document.createElement('div'), toggle=document.createElement('button'), button=document.createElement('button');
|
|
578
|
+
row.className=scoped?'group-row scope-row':'group-row'; toggle.innerHTML=icon(expanded.has(i)?'chevron-down':'chevron-right',12);
|
|
579
|
+
toggle.setAttribute('aria-label',`Toggle ${g.title}`);toggle.setAttribute('aria-expanded',String(expanded.has(i)));toggle.dataset.navkey=`toggle:${g.title}`;
|
|
580
|
+
toggle.onclick=()=>{expanded.has(i)?expanded.delete(i):expanded.add(i);renderNav()};
|
|
581
|
+
button.className='group-name';button.dataset.navkey=`group:${g.title}`;
|
|
582
|
+
const title=document.createElement('span'), count=document.createElement('span'); title.textContent=g.title;count.textContent=g.assets.length;count.className='count';button.append(title,count);
|
|
583
|
+
button.onclick=()=>navigate(()=>{remember();inspection=null;active=i;selected=null;selectedId=null;selectedForm=null;selectedElement=null;expanded.add(i);selection();frame(groups[i])});
|
|
584
|
+
row.append(toggle,button);section.append(row);
|
|
585
|
+
if (scoped) row.append(scopeAction('group',g.title,g.title));
|
|
586
|
+
if(expanded.has(i)) { const files=document.createElement('div');files.className='group-files';
|
|
587
|
+
for(const a of g.assets) files.append(navFile(a,{indent:true,isolate:scoped}));
|
|
588
|
+
section.append(files);
|
|
589
|
+
}
|
|
590
|
+
nodes.push(section);
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
$("#modules").replaceChildren(...nodes);
|
|
594
|
+
if(focusKey) $("#modules").querySelector(`[data-navkey="${CSS.escape(focusKey)}"]`)?.focus({preventScroll:true});
|
|
595
|
+
requestDraw();
|
|
596
|
+
}
|
|
597
|
+
function renderRelationships(source) {
|
|
598
|
+
const basename = path => path.split('/').at(-1).replace(/\.tsx$/, '');
|
|
599
|
+
for (const [id,direction] of [['uses','uses'],['used-by','usedBy']]) {
|
|
600
|
+
const entries=relatedSources(manifest?.relationships ?? {},source,direction), directories=new Map();
|
|
601
|
+
for (const entry of entries) {
|
|
602
|
+
const directory=entry.path.split('/')[0];
|
|
603
|
+
if (!directories.has(directory)) directories.set(directory,[]);
|
|
604
|
+
directories.get(directory).push(entry);
|
|
605
|
+
}
|
|
606
|
+
const nodes=[];
|
|
607
|
+
for (const directory of [...directories.keys()].sort().reverse()) {
|
|
608
|
+
const group=document.createElement('section'),heading=document.createElement('h5');
|
|
609
|
+
heading.className='relationship-directory';heading.textContent=directory;group.append(heading);
|
|
610
|
+
for (const entry of directories.get(directory)) {
|
|
611
|
+
const via=entry.via.map(path=>basename(path)===basename(entry.path)?path.replace(/\.tsx$/,''):basename(path)).join(' → ');
|
|
612
|
+
const button=makeRow(directory==='surfaces'?'app-window':'component',basename(entry.path)+(via?` · via ${via}`:''),undefined,'tree-row relationship-row'+(entry.direct?'':' indirect'));
|
|
613
|
+
button.dataset.relatedPath=entry.path;button.dataset.direct=String(entry.direct);
|
|
614
|
+
button.title=entry.path+(entry.via.length?` via ${entry.via.join(' → ')}`:'');
|
|
615
|
+
button.setAttribute('aria-label',`Open ${entry.path}`+(via?` via ${via}`:''));
|
|
616
|
+
button.onclick=()=>navigate(()=>{
|
|
617
|
+
const item=assets.find(a=>a.path===entry.path);
|
|
618
|
+
if (item) focusAsset(item);
|
|
619
|
+
else changeScope(`asset:${entry.path}`,{target:{path:entry.path}});
|
|
620
|
+
});
|
|
621
|
+
group.append(button);
|
|
622
|
+
}
|
|
623
|
+
nodes.push(group);
|
|
624
|
+
}
|
|
625
|
+
if (!nodes.length) {const empty=document.createElement('p');empty.className='relationship-empty';empty.textContent='None';nodes.push(empty)}
|
|
626
|
+
$('#'+id).replaceChildren(...nodes);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
function selection() {
|
|
630
|
+
hoveredElement=null;
|
|
631
|
+
if (!selected) inspector = false;
|
|
632
|
+
syncSelectionURL();
|
|
633
|
+
renderNav(); updateChrome();
|
|
634
|
+
$('#back').disabled = !history.length && !onlyFrame;
|
|
635
|
+
const host=currentItem(), part=host?.parts.find(p=>p.id===selectedForm);
|
|
636
|
+
const owner=selectedElement?.owner;
|
|
637
|
+
const a=owner ? manifest?.assets.find(a=>a.path===owner.source) ?? {path:owner.source,parts:[]} : host;
|
|
638
|
+
if(a) {
|
|
639
|
+
$('#source-name').textContent=owner?.export ?? a.name;$('#source-path').textContent=a.path;
|
|
640
|
+
$('#source-path').title=a.path;
|
|
641
|
+
$('#frame-detail').hidden=!part;
|
|
642
|
+
$('#frame-name').textContent=part?.name ?? '';
|
|
643
|
+
const size=selectedElement ?? part;
|
|
644
|
+
$('#frame-size').textContent=size?`${Math.round(size.width)} × ${Math.round(size.height)}`:'';
|
|
645
|
+
$('#forms-heading').textContent=owner?'Frames using this export':a.component?'Forms':'Frames';
|
|
646
|
+
const forms=owner?exportFrames(a,owner):a.parts;
|
|
647
|
+
$('#forms').replaceChildren(...forms.map(p=>{
|
|
648
|
+
const button=makeRow(a.component?'component':'app-window',p.name,`${Math.round(p.width)} × ${Math.round(p.height)}`);
|
|
649
|
+
button.classList.add('frame-row');button.title=p.name;
|
|
650
|
+
button.dataset.frame=p.name;
|
|
651
|
+
button.setAttribute('aria-current',String(!owner && selectedForm===p.id));
|
|
652
|
+
button.onclick=()=>inspectForm(a,p);
|
|
653
|
+
if (p.note) { const row=document.createElement('div');row.append(button);const note=document.createElement('p');note.textContent=p.note;note.className='frame-note';row.append(note);return row; }
|
|
654
|
+
return button;
|
|
655
|
+
}));
|
|
656
|
+
if (!forms.length) {const empty=document.createElement('p');empty.className='relationship-empty';empty.textContent='No matching frames';$('#forms').append(empty)}
|
|
657
|
+
renderRelationships(a.path);
|
|
658
|
+
}
|
|
659
|
+
updateOutlines();requestDraw();save();
|
|
660
|
+
}
|
|
661
|
+
function selectSource(a) {
|
|
662
|
+
if (!a) return;
|
|
663
|
+
remember();inspection=null;selected=a.path;selectedId=a.id;selectedForm=null;selectedElement=null;active=a.group;expanded.add(active);selection();
|
|
664
|
+
}
|
|
665
|
+
function selectFrame(a,p,element=null) {
|
|
666
|
+
if (!a || !p) return;
|
|
667
|
+
remember();selected=a.path;selectedId=a.id;selectedForm=p.id;active=a.group;selectedElement=element?{...element,owner:element.owners.at(-1)}:null;
|
|
668
|
+
expanded.add(active);selection();
|
|
669
|
+
}
|
|
670
|
+
function clearSelection() { selected=null;selectedId=null;selectedForm=null;selectedElement=null;inspection=null;selection(); }
|
|
671
|
+
function selectedBox() {
|
|
672
|
+
const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);
|
|
673
|
+
if (!p) return null;
|
|
674
|
+
const box=frameBox(a,p);
|
|
675
|
+
return selectedElement?{...selectedElement,x:box.x+selectedElement.x,y:box.y+selectedElement.y}:box;
|
|
676
|
+
}
|
|
677
|
+
function updateOutlines() {
|
|
678
|
+
const hover=hoveredElement,origin=hover?.part?frameBox(hover.asset,hover.part):null;
|
|
679
|
+
const hoverBox=hover?.element?{...hover.element,x:origin.x+hover.element.x,y:origin.y+hover.element.y}:null;
|
|
680
|
+
for (const [id,box] of [['selection-outline',selectedBox()],['hover-outline',hoverBox]]) {
|
|
681
|
+
const el=$('#'+id);el.hidden=!box || moving;
|
|
682
|
+
if (box) Object.assign(el.style,{left:`${view.x+box.x*view.scale}px`,top:`${view.y+box.y*view.scale}px`,width:`${box.width*view.scale}px`,height:`${box.height*view.scale}px`});
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function cameraArea() { return fitArea(width, height, false, false); }
|
|
687
|
+
function fitWorld(area, data) {
|
|
688
|
+
if (scopeKind(data?.scope) !== 'asset' || !assets.length) return fitView(world,area);
|
|
689
|
+
const x=Math.min(...assets.map(a=>a.x)), y=Math.min(...assets.map(a=>a.y));
|
|
690
|
+
const box={x,y,width:Math.max(...assets.map(a=>a.x+a.width))-x,height:Math.max(...assets.map(a=>a.y+a.height))-y};
|
|
691
|
+
const fit=fitView(box,area,24);
|
|
692
|
+
return fit.scale <= 1 ? fit : {scale:1,x:area.x+(area.width-box.width)/2-x,y:area.y+(area.height-box.height)/2-y};
|
|
693
|
+
}
|
|
694
|
+
function frame(box, padding = 0) {
|
|
695
|
+
const target=box===world?'all':groups.includes(box)?'group':'selection';
|
|
696
|
+
for(const name of ['all','group','selection']) $("#zoom-fit-"+name).setAttribute('aria-current',String(name===target));
|
|
697
|
+
commit(box===world ? fitWorld(cameraArea(),manifest) : fitView(box, cameraArea(), padding));
|
|
698
|
+
}
|
|
699
|
+
function fit() {
|
|
700
|
+
remember();
|
|
701
|
+
inspection = null;
|
|
702
|
+
selected = null;
|
|
703
|
+
selectedId = null;selectedForm=null;selectedElement=null;
|
|
704
|
+
active = null;
|
|
705
|
+
selection();
|
|
706
|
+
frame(world);
|
|
707
|
+
}
|
|
708
|
+
function focusAsset(a) {
|
|
709
|
+
if (!a) return;
|
|
710
|
+
selectSource(a);
|
|
711
|
+
frame(a,24);
|
|
712
|
+
}
|
|
713
|
+
function inspectForm(a,p) {
|
|
714
|
+
if (!a || !p) return;
|
|
715
|
+
const item=assets.find(item=>item.path===a.path && (a.component || item.shown[0].id===p.id));
|
|
716
|
+
if (!item) return;
|
|
717
|
+
inspection=null;selectFrame(item,p);frame(frameBox(item,p),24);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function zoom(scale, x = cameraArea().x + cameraArea().width / 2, y = cameraArea().y + cameraArea().height / 2) {
|
|
721
|
+
const next = clamp(scale);
|
|
722
|
+
commit({
|
|
723
|
+
scale: next,
|
|
724
|
+
x: x - ((x - view.x) * next) / view.scale,
|
|
725
|
+
y: y - ((y - view.y) * next) / view.scale,
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
function commit(next) {
|
|
729
|
+
window.__adg.ready = false;
|
|
730
|
+
labelsDirty ||= view.scale !== next.scale;
|
|
731
|
+
view = next;
|
|
732
|
+
moving = true;
|
|
733
|
+
requestDraw(false, false);
|
|
734
|
+
save();
|
|
735
|
+
clearTimeout(idleTimer);
|
|
736
|
+
idleTimer = setTimeout(() => {
|
|
737
|
+
moving = false;
|
|
738
|
+
requestDraw();
|
|
739
|
+
}, 150);
|
|
740
|
+
}
|
|
741
|
+
function requestDraw(labelsChanged = true, drawingChanged = true) {
|
|
742
|
+
drawingDirty ||= drawingChanged;
|
|
743
|
+
if (labelsChanged) { labelsDirty = true; labelObstacles = null; }
|
|
744
|
+
if (!raf) raf = requestAnimationFrame(draw);
|
|
745
|
+
}
|
|
746
|
+
function visible(a, margin = 0) {
|
|
747
|
+
return (
|
|
748
|
+
view.x + (a.x + a.width) * view.scale > -margin &&
|
|
749
|
+
view.x + a.x * view.scale < width + margin &&
|
|
750
|
+
view.y + (a.y + a.height) * view.scale > -margin &&
|
|
751
|
+
view.y + a.y * view.scale < height + margin
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
function rounded(x, y, w, h, r, fill) {
|
|
755
|
+
ctx.fillStyle = fill;
|
|
756
|
+
ctx.beginPath();
|
|
757
|
+
ctx.roundRect(x, y, w, h, r);
|
|
758
|
+
ctx.fill();
|
|
759
|
+
}
|
|
760
|
+
function assetURL(a, p) {
|
|
761
|
+
return `${a.path}|${effectiveTheme}|${a.version}|${p.id}${a.onlyFrame ? `|frame:${a.onlyFrame}` : ''}`;
|
|
762
|
+
}
|
|
763
|
+
function ensureImage(a, p) {
|
|
764
|
+
const key = assetURL(a, p);
|
|
765
|
+
let e = cache.get(key);
|
|
766
|
+
if (e) {
|
|
767
|
+
e.used = performance.now();e.asset=a;e.part=p;
|
|
768
|
+
return e;
|
|
769
|
+
}
|
|
770
|
+
e = { key, asset: a, part: p, theme:effectiveTheme, used: performance.now(), state: "queued" };
|
|
771
|
+
cache.set(key, e);
|
|
772
|
+
queued.push(e);
|
|
773
|
+
queueMicrotask(pump);
|
|
774
|
+
return e;
|
|
775
|
+
}
|
|
776
|
+
function pump() {
|
|
777
|
+
// New vector parsing/decoding waits until the gesture settles. Existing exact
|
|
778
|
+
// raster previews continue to move with the camera during interaction.
|
|
779
|
+
if(moving)return;
|
|
780
|
+
queued.sort((a,b)=>Number(visible(b.asset))-Number(visible(a.asset))||
|
|
781
|
+
Math.hypot(view.x+(a.asset.x+a.asset.width/2)*view.scale-width/2,view.y+(a.asset.y+a.asset.height/2)*view.scale-height/2)-
|
|
782
|
+
Math.hypot(view.x+(b.asset.x+b.asset.width/2)*view.scale-width/2,view.y+(b.asset.y+b.asset.height/2)*view.scale-height/2));
|
|
783
|
+
while (loading < 3 && queued.length) {
|
|
784
|
+
const e = queued.shift();
|
|
785
|
+
if (!cache.has(e.key)) continue;
|
|
786
|
+
loading++;e.state='loading';
|
|
787
|
+
void loadPreview(e);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
async function loadPreview(e) {
|
|
791
|
+
const endPreview = globalThis.__adgTiming?.span('preview', e.asset.path, {crop:e.part.id});
|
|
792
|
+
let url,local=false;
|
|
793
|
+
const theme=e.theme??effectiveTheme;
|
|
794
|
+
const generated=async restore=>{
|
|
795
|
+
if(cache.get(e.key)!==e)throw new DOMException('Preview superseded','AbortError');
|
|
796
|
+
const asset=await sourceFor(e.asset,theme);
|
|
797
|
+
if(e.asset.hash&&asset.hash!==e.asset.hash)throw Object.assign(Error('Preview superseded'),{name:'AbortError',waitForRevision:true});
|
|
798
|
+
if(restore)persistSource(asset,theme);
|
|
799
|
+
while(moving)await new Promise(resolve=>setTimeout(resolve,16));
|
|
800
|
+
// Yield the parse/serialization task to pending input before starting it.
|
|
801
|
+
await (globalThis.scheduler?.yield?.()??new Promise(resolve=>setTimeout(resolve,0)));
|
|
802
|
+
local=true;
|
|
803
|
+
return imageURL(asset,e.part,source=>{
|
|
804
|
+
if(!asset.hash || asset.onlyFrame)return;
|
|
805
|
+
const saved=asset.cacheWrite??Promise.resolve(true);
|
|
806
|
+
void saved.then(ok=>{
|
|
807
|
+
if(!ok)return;
|
|
808
|
+
const query=new URLSearchParams({theme,context:metadataContext(),crop:e.part.id});
|
|
809
|
+
return cacheWrite(`preview/${asset.hash}?${query}`,source,true);
|
|
810
|
+
});
|
|
811
|
+
});
|
|
812
|
+
};
|
|
813
|
+
const decode=async source=>{
|
|
814
|
+
if(cache.get(e.key)!==e)return;
|
|
815
|
+
while(moving)await new Promise(resolve=>setTimeout(resolve,16));
|
|
816
|
+
const img=new Image();e.image=img;img.decoding='async';img.src=source;
|
|
817
|
+
const endDecode = globalThis.__adgTiming?.span('decode', e.asset.path, {crop:e.part.id});
|
|
818
|
+
try { await img.decode();e.state='ready'; } finally {endDecode?.();}
|
|
819
|
+
};
|
|
820
|
+
try {
|
|
821
|
+
const cached=e.asset.hash&&e.asset.previewIds?.[theme]?.includes(e.part.id);
|
|
822
|
+
if(cached) {
|
|
823
|
+
const address=previewAddress(e.asset,theme,e.part.id);
|
|
824
|
+
url=keyURL(address);
|
|
825
|
+
try {await decode(url)}
|
|
826
|
+
catch(failure) {
|
|
827
|
+
// A disk LRU eviction after the manifest is a cache miss. dataFetch also
|
|
828
|
+
// preserves the normal unauthorized flow if an access key was rotated.
|
|
829
|
+
const response=await dataFetch(address);
|
|
830
|
+
if(response.ok){local=true;url=URL.createObjectURL(await response.blob());await decode(url);}
|
|
831
|
+
else if(response.status===404){url=await generated(true);await decode(url);}
|
|
832
|
+
else throw failure;
|
|
833
|
+
}
|
|
834
|
+
} else {url=await generated(false);await decode(url);}
|
|
835
|
+
} catch(failure) {
|
|
836
|
+
e.state='error';
|
|
837
|
+
if(failure.name==='AbortError'&&!failure.waitForRevision&&cache.get(e.key)===e)cache.delete(e.key);
|
|
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))
|
|
839
|
+
error(`Cannot render ${e.asset.path}: ${failure.message}`);
|
|
840
|
+
} finally {
|
|
841
|
+
endPreview?.({state:e.state});
|
|
842
|
+
if(local&&url)URL.revokeObjectURL(url);
|
|
843
|
+
loading--;requestDraw(false);pump();
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
function thumbnail(e, upgrade = false) {
|
|
848
|
+
const scale = Math.min(2, view.scale) * dpr;
|
|
849
|
+
if (e.bitmap && (!upgrade || e.bitmapScale >= scale)) return e.bitmap;
|
|
850
|
+
const limit = Math.min(scale, 4096 / Math.max(e.part.width, e.part.height));
|
|
851
|
+
const c = document.createElement('canvas');
|
|
852
|
+
c.width = Math.max(1, Math.ceil(e.part.width * limit));
|
|
853
|
+
c.height = Math.max(1, Math.ceil(e.part.height * limit));
|
|
854
|
+
const preview = c.getContext('2d', { alpha: false });
|
|
855
|
+
preview.fillStyle = e.asset.background || palette.canvas;
|
|
856
|
+
preview.fillRect(0, 0, c.width, c.height);
|
|
857
|
+
preview.drawImage(e.image, 0, 0, c.width, c.height);
|
|
858
|
+
e.bitmap = c;
|
|
859
|
+
e.bitmapScale = limit;
|
|
860
|
+
return c;
|
|
861
|
+
}
|
|
862
|
+
function placements(a) { return a.shown.map(part => ({ part, x: a.x, y: a.y })); }
|
|
863
|
+
// Rasterize the screen-space dots once instead of submitting thousands of arcs per frame.
|
|
864
|
+
let backgroundKey;
|
|
865
|
+
function drawBackground() {
|
|
866
|
+
const color = backgroundColor(), key = `${width}|${height}|${dpr}|${color}|${palette.dot}`;
|
|
867
|
+
if (key !== backgroundKey) {
|
|
868
|
+
const tile = document.createElement('canvas');
|
|
869
|
+
tile.width = tile.height = Math.round(20 * dpr);
|
|
870
|
+
const c = tile.getContext('2d');
|
|
871
|
+
c.scale(dpr, dpr);
|
|
872
|
+
c.fillStyle = color; c.fillRect(0, 0, 20, 20);
|
|
873
|
+
c.fillStyle = palette.dot; c.beginPath(); c.arc(1, 1, 1, 0, Math.PI * 2); c.fill();
|
|
874
|
+
const pattern = backgroundContext.createPattern(tile, 'repeat');
|
|
875
|
+
pattern.setTransform(new DOMMatrix().scale(1 / dpr));
|
|
876
|
+
background.width = Math.round(width * dpr); background.height = Math.round(height * dpr);
|
|
877
|
+
backgroundContext.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
878
|
+
backgroundContext.fillStyle = pattern;
|
|
879
|
+
backgroundContext.fillRect(0, 0, width, height);
|
|
880
|
+
backgroundKey = key;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
function draw() {
|
|
884
|
+
const endDrawing = globalThis.__adgTiming?.span('drawing');
|
|
885
|
+
raf = 0;
|
|
886
|
+
drawBackground();
|
|
887
|
+
if (tokenManifest) {
|
|
888
|
+
window.__adg.ready = true;
|
|
889
|
+
if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
|
|
890
|
+
endDrawing?.(); return;
|
|
891
|
+
}
|
|
892
|
+
if (!labelObstacles) readChromeBounds();
|
|
893
|
+
const displayed = manifest?.renderTheme === effectiveTheme ? inspection ? [inspection] : assets : [];
|
|
894
|
+
// Keep a margin around a settled drawing. Pans can move that
|
|
895
|
+
// retained Canvas layer without replaying or resampling the entire scene.
|
|
896
|
+
const dx = view.x - (drawingView?.x ?? 0), dy = view.y - (drawingView?.y ?? 0);
|
|
897
|
+
const reuse = !drawingDirty && drawingView?.scale === view.scale &&
|
|
898
|
+
Math.abs(dx) <= drawingMargin && Math.abs(dy) <= drawingMargin;
|
|
899
|
+
if (!reuse) {
|
|
900
|
+
const zooming = moving && drawingView?.scale !== view.scale;
|
|
901
|
+
drawingMargin = zooming ? 0 : Math.ceil(Math.min(width, height) / 4);
|
|
902
|
+
const bufferWidth = Math.round((width + drawingMargin * 2) * dpr), bufferHeight = Math.round((height + drawingMargin * 2) * dpr);
|
|
903
|
+
if (canvas.width !== bufferWidth || canvas.height !== bufferHeight) {
|
|
904
|
+
canvas.width = bufferWidth; canvas.height = bufferHeight;
|
|
905
|
+
canvas.style.width = `${width + drawingMargin * 2}px`; canvas.style.height = `${height + drawingMargin * 2}px`;
|
|
906
|
+
}
|
|
907
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
908
|
+
ctx.clearRect(0, 0, width + drawingMargin * 2, height + drawingMargin * 2);
|
|
909
|
+
ctx.save(); ctx.translate(view.x + drawingMargin, view.y + drawingMargin); ctx.scale(view.scale, view.scale);
|
|
910
|
+
if (!inspection && scopeKind(manifest?.scope)!=='asset') for (const g of groups) {
|
|
911
|
+
if (!visible(g, drawingMargin)) continue;
|
|
912
|
+
rounded(g.x, g.y, g.width, g.height, 16 / view.scale, palette['surface-section']);
|
|
913
|
+
ctx.strokeStyle = palette.border; ctx.lineWidth = 1 / view.scale; ctx.stroke();
|
|
914
|
+
}
|
|
915
|
+
let ready = 0, count = 0;
|
|
916
|
+
for (const a of displayed) {
|
|
917
|
+
if (!visible(a, drawingMargin)) continue;
|
|
918
|
+
const parts = placements(a).map(pos => ({ ...pos, image: ensureImage(a, pos.part) }));
|
|
919
|
+
const raster = moving || view.scale < .8;
|
|
920
|
+
ctx.beginPath(); ctx.roundRect(a.x, a.y, a.width, a.height, Math.min(6 / view.scale, a.width / 2, a.height / 2));
|
|
921
|
+
// Cached previews already contain the asset background; avoid painting it twice.
|
|
922
|
+
if (!raster || parts.some(pos => pos.image.state !== 'ready')) {
|
|
923
|
+
ctx.fillStyle = a.background || palette.canvas; ctx.fill();
|
|
924
|
+
}
|
|
925
|
+
ctx.save(); ctx.clip();
|
|
926
|
+
const inViewport = visible(a);
|
|
927
|
+
for (const pos of parts) {
|
|
928
|
+
if (inViewport) count++;
|
|
929
|
+
const e = pos.image;
|
|
930
|
+
if (e.state !== 'ready') continue;
|
|
931
|
+
if (inViewport) ready++;
|
|
932
|
+
const source = moving ? thumbnail(e) : view.scale < .8 ? thumbnail(e, true) : e.image;
|
|
933
|
+
if (moving) {
|
|
934
|
+
const left = Math.max(pos.x, (-view.x - drawingMargin) / view.scale);
|
|
935
|
+
const top = Math.max(pos.y, (-view.y - drawingMargin) / view.scale);
|
|
936
|
+
const right = Math.min(pos.x + pos.part.width, (width + drawingMargin - view.x) / view.scale);
|
|
937
|
+
const bottom = Math.min(pos.y + pos.part.height, (height + drawingMargin - view.y) / view.scale);
|
|
938
|
+
const sx = source.width / pos.part.width, sy = source.height / pos.part.height;
|
|
939
|
+
ctx.drawImage(source, (left-pos.x)*sx, (top-pos.y)*sy, (right-left)*sx, (bottom-top)*sy, left, top, right-left, bottom-top);
|
|
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});
|
|
942
|
+
}
|
|
943
|
+
ctx.restore();
|
|
944
|
+
const chosen = selected === a.path && selectedForm === null;
|
|
945
|
+
ctx.strokeStyle = chosen ? palette.accent : palette.border;
|
|
946
|
+
ctx.lineWidth = (chosen ? 2 : 1) / view.scale; ctx.stroke();
|
|
947
|
+
}
|
|
948
|
+
ctx.restore();
|
|
949
|
+
drawingReady = ready; drawingCount = count;
|
|
950
|
+
drawingView = { ...view }; drawingDirty = false;
|
|
951
|
+
}
|
|
952
|
+
canvas.style.transform = `translate(${view.x - drawingView.x - drawingMargin}px,${view.y - drawingView.y - drawingMargin}px)`;
|
|
953
|
+
updateOutlines();
|
|
954
|
+
drawLabels(displayed);
|
|
955
|
+
const percentage = `${Math.round(view.scale * 100)}%`;
|
|
956
|
+
if (zoomValue.textContent !== percentage) zoomValue.textContent = percentage;
|
|
957
|
+
if (zoomOutput.value !== percentage) zoomOutput.value = percentage;
|
|
958
|
+
window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving && !arranger.pending;
|
|
959
|
+
if(fixtureState && fixtureApplied && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
|
|
960
|
+
window.__adg.revision = manifest?.revision;
|
|
961
|
+
window.__adg.visibleReady = drawingReady; window.__adg.visibleCount = drawingCount;
|
|
962
|
+
if (window.__adg.ready && drawingCount > 0) globalThis.__adgTiming?.paint('visible-ready', {count:drawingCount});
|
|
963
|
+
drawMap();
|
|
964
|
+
if(!moving&&queued.length)pump();
|
|
965
|
+
if (cache.size > 100) {
|
|
966
|
+
const activeKeys = new Set(displayed.filter(a => visible(a, drawingMargin))
|
|
967
|
+
.flatMap(a => placements(a).map(({part}) => assetURL(a, part))));
|
|
968
|
+
evictPreviews(cache, activeKeys);
|
|
969
|
+
}
|
|
970
|
+
endDrawing?.();
|
|
971
|
+
}
|
|
972
|
+
function backgroundColor() { return backgroundChoice === 'theme' ? palette.canvas : backgroundColors[backgroundChoice]; }
|
|
973
|
+
|
|
974
|
+
function readChromeBounds() {
|
|
975
|
+
const vr = viewport.getBoundingClientRect();
|
|
976
|
+
labelObstacles = [];
|
|
977
|
+
for (const el of document.querySelectorAll('.floating, :popover-open, dialog[open], #tooltip:not([hidden])')) {
|
|
978
|
+
if (el.hidden) continue;
|
|
979
|
+
const style = getComputedStyle(el);
|
|
980
|
+
if (style.visibility === 'hidden' || style.display === 'none') continue;
|
|
981
|
+
const r = el.getBoundingClientRect(), box = { x:r.x-vr.x, y:r.y-vr.y, width:r.width, height:r.height };
|
|
982
|
+
labelObstacles.push(box);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
function drawLabels(displayed) {
|
|
986
|
+
if (!labelsDirty && labelLayer.pan(view)) return;
|
|
987
|
+
const candidates = [], screen = box => ({ x: view.x + box.x * view.scale, y: view.y + box.y * view.scale });
|
|
988
|
+
const caption = Number.parseFloat(palette['text-caption']), meta = Number.parseFloat(palette['text-meta']), section = Number.parseFloat(palette['text-section']);
|
|
989
|
+
const part = (text, size, weight, color, gap = 0) => ({ text, size, weight, color, gap });
|
|
990
|
+
const title = (...args) => ({...part(...args),copyText:args[0]});
|
|
991
|
+
const sourceTitle = (a,...args) => ({...title(...args),selection:{path:a.path}});
|
|
992
|
+
const frameTitle = (a,p,...args) => ({...title(...args),selection:{path:a.path,form:p.id}});
|
|
993
|
+
const modified = a => a.modified ? [{...part(a.modified.text,meta,400,palette['text-tertiary'],10),...a.modified,optional:true}] : [];
|
|
994
|
+
const heading = (x, y, right) => {
|
|
995
|
+
const half = meta * .6;
|
|
996
|
+
let left = Math.max(8, x), edge = Math.min(width - 8, right);
|
|
997
|
+
const center = Math.max(8 + half, y);
|
|
998
|
+
for (const obstacle of labelObstacles) {
|
|
999
|
+
if (center + half <= obstacle.y || center - half >= obstacle.y + obstacle.height) continue;
|
|
1000
|
+
if (obstacle.x + obstacle.width <= left || obstacle.x >= edge) continue;
|
|
1001
|
+
if (obstacle.x - 12 - left >= edge - obstacle.x - obstacle.width - 12) edge = obstacle.x - 12;
|
|
1002
|
+
else left = obstacle.x + obstacle.width + 12;
|
|
1003
|
+
}
|
|
1004
|
+
return {x:left,y:center,slot:Math.max(0,edge-left),pinned:left !== x || center !== y};
|
|
1005
|
+
};
|
|
1006
|
+
if (!inspection && scopeKind(manifest?.scope)!=='asset') for (const g of groups) {
|
|
1007
|
+
if (!visible(g)) continue;
|
|
1008
|
+
const p = screen(g);
|
|
1009
|
+
candidates.push({ id: `section:${g.title}`, x: p.x, y: p.y - 16, slot: g.width * view.scale, parts: [title(g.title, section, 650, palette.text), {...part(`${g.assets.length} assets`, meta, 400, palette['text-tertiary'], 8),optional:true}] });
|
|
1010
|
+
}
|
|
1011
|
+
if (view.scale >= .2) {
|
|
1012
|
+
const flows = new Set();
|
|
1013
|
+
const labeled = selectedId ? [...displayed].sort((a,b) => Number(b.id === selectedId) - Number(a.id === selectedId)) : displayed;
|
|
1014
|
+
for (const a of labeled) {
|
|
1015
|
+
if (!visible(a)) continue;
|
|
1016
|
+
const p = screen(a), chosen = selectedId === a.id;
|
|
1017
|
+
if (a.kind === 'set' || inspection) {
|
|
1018
|
+
candidates.push({ id: `set:${a.id}`, ...heading(p.x,p.y-12,p.x+(a.width+64)*view.scale-10),
|
|
1019
|
+
parts:[sourceTitle(a,inspection ? a.shown[0].name : a.name,meta,550,chosen ? palette.text : palette['text-secondary']), ...(!inspection ? [{ ...part(`${a.parts.length} ${a.parts.length === 1 ? 'form' : 'forms'}`,meta,400,palette['text-tertiary'],6), optional: true },...modified(a)] : [])] });
|
|
1020
|
+
if (!inspection && view.scale >= .75 && a.parts.length > 1) {
|
|
1021
|
+
const crop = a.shown[0];
|
|
1022
|
+
candidates.push(...a.parts.map(form => ({ id:`form:${a.id}:${form.id}`,x:p.x+(form.x-crop.x)*view.scale,y:p.y+(form.y-crop.y)*view.scale-9.5,slot:Infinity,height:13,paddingRight:6,within:{x:p.x,y:p.y,width:a.width*view.scale,height:a.height*view.scale},
|
|
1023
|
+
parts:[frameTitle(a,form,form.name,caption,400,palette['text-tertiary'])] })));
|
|
1024
|
+
}
|
|
1025
|
+
} else {
|
|
1026
|
+
if (!flows.has(a.path)) {
|
|
1027
|
+
flows.add(a.path);
|
|
1028
|
+
const family = displayed.filter(item => item.path === a.path), first = family[0];
|
|
1029
|
+
const origin = screen(first), right = Math.max(...family.map(item => item.x+item.width));
|
|
1030
|
+
candidates.push({ id:`flow:${a.path}`,...heading(origin.x,origin.y-34,origin.x+(right-first.x)*view.scale),parts:[sourceTitle(a,a.name,meta,600,palette['text-secondary']),{...part(`${a.parts.length} ${a.parts.length === 1 ? 'frame' : 'frames'}`,meta,400,palette['text-tertiary'],6),optional:true},...modified(a)] });
|
|
1031
|
+
}
|
|
1032
|
+
candidates.push({ id:`frame:${a.id}`,x:p.x,y:p.y-12,slot:(a.width+64)*view.scale,parts:[frameTitle(a,a.shown[0],a.shown[0].name,caption,chosen?550:400,chosen?palette.text:palette['text-tertiary'])] });
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
labelLayer.update(candidates,labelObstacles,width,height,palette['font-ui'],view);
|
|
1037
|
+
labelsDirty = false;
|
|
1038
|
+
}
|
|
1039
|
+
function mapGeometry() {
|
|
1040
|
+
const scale=Math.min(168/world.width,100/world.height);
|
|
1041
|
+
return {scale,x:(200-world.width*scale)/2,y:(132-world.height*scale)/2};
|
|
1042
|
+
}
|
|
1043
|
+
function drawMap() {
|
|
1044
|
+
const map=$("#minimap");if(map.hidden)return;
|
|
1045
|
+
if(map.width!==200*dpr||map.height!==132*dpr){map.width=200*dpr;map.height=132*dpr}
|
|
1046
|
+
const c=map.getContext('2d'),{scale:s,x,y}=mapGeometry();c.setTransform(dpr,0,0,dpr,0,0);c.clearRect(0,0,200,132);
|
|
1047
|
+
for(const g of groups){c.fillStyle=palette['surface-section'];c.strokeStyle=palette.border;c.beginPath();c.roundRect(x+g.x*s,y+g.y*s,g.width*s,g.height*s,4);c.fill();c.stroke()}
|
|
1048
|
+
c.strokeStyle=palette.accent;c.lineWidth=1;
|
|
1049
|
+
const area=cameraArea();
|
|
1050
|
+
c.strokeRect(x+(area.x-view.x)/view.scale*s,y+(area.y-view.y)/view.scale*s,area.width/view.scale*s,area.height/view.scale*s);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
function applyTheme() {
|
|
1054
|
+
window.__adg.ready = false;
|
|
1055
|
+
effectiveTheme =
|
|
1056
|
+
theme === "system" ? (media.matches ? "dark" : "light") : theme;
|
|
1057
|
+
document.documentElement.dataset.theme = effectiveTheme;
|
|
1058
|
+
const css = getComputedStyle(document.documentElement);
|
|
1059
|
+
palette = Object.fromEntries(
|
|
1060
|
+
["canvas", "surface", "surface-section", "surface-sunken", "text", "text-secondary", "text-tertiary", "accent", "border", "dot", "font-ui", "text-caption", "text-meta", "text-section"].map(
|
|
1061
|
+
(k) => [k, css.getPropertyValue("--" + k).trim()],
|
|
1062
|
+
),
|
|
1063
|
+
);
|
|
1064
|
+
palette.raised = css.getPropertyValue("--surface-sunken").trim();
|
|
1065
|
+
palette.muted = css.getPropertyValue("--text-secondary").trim();
|
|
1066
|
+
for (const sheet of document.styleSheets) for(const rule of sheet.cssRules ?? []) {
|
|
1067
|
+
if(rule.selectorText === ':root' && rule.style.getPropertyValue('--canvas')) backgroundColors.light=rule.style.getPropertyValue('--canvas').trim();
|
|
1068
|
+
if(rule.selectorText === ':root[data-theme="dark"]' && rule.style.getPropertyValue('--canvas')) backgroundColors.dark=rule.style.getPropertyValue('--canvas').trim();
|
|
1069
|
+
}
|
|
1070
|
+
backgroundColors.neutral=`color-mix(in srgb, ${backgroundColors.light} 50%, ${backgroundColors.dark})`;
|
|
1071
|
+
updateChoices();
|
|
1072
|
+
requestDraw();
|
|
1073
|
+
}
|
|
1074
|
+
for (const b of $("#themes").children)
|
|
1075
|
+
b.onclick = () => {
|
|
1076
|
+
theme = b.dataset.theme;
|
|
1077
|
+
applyTheme();
|
|
1078
|
+
void refresh(true);
|
|
1079
|
+
save();
|
|
1080
|
+
};
|
|
1081
|
+
media.addEventListener("change", () => {
|
|
1082
|
+
applyTheme();
|
|
1083
|
+
void refresh(true);
|
|
1084
|
+
});
|
|
1085
|
+
viewport.addEventListener(
|
|
1086
|
+
"wheel",
|
|
1087
|
+
(e) => {
|
|
1088
|
+
e.preventDefault();
|
|
1089
|
+
const r = viewport.getBoundingClientRect(),
|
|
1090
|
+
unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? height : 1;
|
|
1091
|
+
if (e.ctrlKey || e.metaKey)
|
|
1092
|
+
zoom(
|
|
1093
|
+
view.scale *
|
|
1094
|
+
Math.exp(-Math.max(-300, Math.min(300, e.deltaY * unit)) * 0.008),
|
|
1095
|
+
e.clientX - r.left,
|
|
1096
|
+
e.clientY - r.top,
|
|
1097
|
+
);
|
|
1098
|
+
else
|
|
1099
|
+
commit({
|
|
1100
|
+
...view,
|
|
1101
|
+
x: view.x - e.deltaX * unit,
|
|
1102
|
+
y: view.y - e.deltaY * unit,
|
|
1103
|
+
});
|
|
1104
|
+
},
|
|
1105
|
+
{ passive: false },
|
|
1106
|
+
);
|
|
1107
|
+
viewport.addEventListener("pointerdown", (e) => {
|
|
1108
|
+
if (e.button !== 0 && e.button !== 1) return;
|
|
1109
|
+
e.preventDefault();
|
|
1110
|
+
viewport.focus({ preventScroll: true });
|
|
1111
|
+
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
1112
|
+
if (pointers.size === 1)
|
|
1113
|
+
gesture = { x: e.clientX, y: e.clientY, moved: false };
|
|
1114
|
+
else gesture.moved = true;
|
|
1115
|
+
viewport.setPointerCapture(e.pointerId);
|
|
1116
|
+
});
|
|
1117
|
+
viewport.addEventListener("pointermove", (e) => {
|
|
1118
|
+
const old = pointers.get(e.pointerId);
|
|
1119
|
+
if (!old) {
|
|
1120
|
+
const rect=viewport.getBoundingClientRect();
|
|
1121
|
+
hoveredElement=hitSelection(inspection?[inspection]:assets,(e.clientX-rect.left-view.x)/view.scale,(e.clientY-rect.top-view.y)/view.scale);
|
|
1122
|
+
updateOutlines();return;
|
|
1123
|
+
}
|
|
1124
|
+
hoveredElement=null;updateOutlines();
|
|
1125
|
+
const before = [...pointers.values()];
|
|
1126
|
+
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
1127
|
+
if (Math.hypot(e.clientX - gesture.x, e.clientY - gesture.y) > 4)
|
|
1128
|
+
gesture.moved = true;
|
|
1129
|
+
if (pointers.size === 1)
|
|
1130
|
+
commit({
|
|
1131
|
+
...view,
|
|
1132
|
+
x: view.x + e.clientX - old.x,
|
|
1133
|
+
y: view.y + e.clientY - old.y,
|
|
1134
|
+
});
|
|
1135
|
+
else if (pointers.size === 2) {
|
|
1136
|
+
const after = [...pointers.values()],
|
|
1137
|
+
distance = (p) => Math.hypot(p[1].x - p[0].x, p[1].y - p[0].y),
|
|
1138
|
+
d = distance(before);
|
|
1139
|
+
if (d < 1) return;
|
|
1140
|
+
const rect = viewport.getBoundingClientRect(),
|
|
1141
|
+
s = clamp((view.scale * distance(after)) / d),
|
|
1142
|
+
ox = (before[0].x + before[1].x) / 2 - rect.left,
|
|
1143
|
+
oy = (before[0].y + before[1].y) / 2 - rect.top,
|
|
1144
|
+
nx = (after[0].x + after[1].x) / 2 - rect.left,
|
|
1145
|
+
ny = (after[0].y + after[1].y) / 2 - rect.top;
|
|
1146
|
+
commit({
|
|
1147
|
+
scale: s,
|
|
1148
|
+
x: nx - ((ox - view.x) * s) / view.scale,
|
|
1149
|
+
y: ny - ((oy - view.y) * s) / view.scale,
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
});
|
|
1153
|
+
viewport.addEventListener('pointerleave',()=>{hoveredElement=null;updateOutlines()});
|
|
1154
|
+
function up(e) {
|
|
1155
|
+
if (!pointers.delete(e.pointerId)) return;
|
|
1156
|
+
if (e.type === "pointerup" && !gesture.moved) {
|
|
1157
|
+
const rect = viewport.getBoundingClientRect(),
|
|
1158
|
+
x = (e.clientX - rect.left - view.x) / view.scale,
|
|
1159
|
+
y = (e.clientY - rect.top - view.y) / view.scale;
|
|
1160
|
+
const hit=hitSelection(inspection?[inspection]:assets,x,y);
|
|
1161
|
+
if(hit?.part) selectFrame(hit.asset,hit.part,hit.element);
|
|
1162
|
+
else if(hit) selectSource(hit.asset);
|
|
1163
|
+
else clearSelection();
|
|
1164
|
+
}
|
|
1165
|
+
if (viewport.hasPointerCapture(e.pointerId))
|
|
1166
|
+
viewport.releasePointerCapture(e.pointerId);
|
|
1167
|
+
if (!pointers.size && gesture.moved) requestDraw();
|
|
1168
|
+
}
|
|
1169
|
+
for (const event of ["pointerup", "pointercancel", "lostpointercapture"])
|
|
1170
|
+
viewport.addEventListener(event, up);
|
|
1171
|
+
document.addEventListener("keydown", (e) => {
|
|
1172
|
+
if (e.metaKey || e.ctrlKey || e.altKey || e.target.matches("input,textarea,[contenteditable]") || document.querySelector("dialog[open], :popover-open")) return;
|
|
1173
|
+
const v = view;
|
|
1174
|
+
if (e.key === "+" || e.key === "=") zoom(v.scale * 1.25);
|
|
1175
|
+
else if (e.key === "-") zoom(v.scale / 1.25);
|
|
1176
|
+
else if (e.key === "0") fit();
|
|
1177
|
+
else if (e.key === "Escape") return;
|
|
1178
|
+
else if (e.key === "Enter") {
|
|
1179
|
+
if (e.target.closest('button,a,[role="button"]')) return;
|
|
1180
|
+
const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);if(p) inspectForm(a,p);else focusAsset(a);
|
|
1181
|
+
}
|
|
1182
|
+
else if (e.key === "1") zoom(1);
|
|
1183
|
+
else if (e.key.startsWith("Arrow"))
|
|
1184
|
+
commit({
|
|
1185
|
+
...v,
|
|
1186
|
+
x: v.x + (e.key === "ArrowLeft" ? 80 : e.key === "ArrowRight" ? -80 : 0),
|
|
1187
|
+
y: v.y + (e.key === "ArrowUp" ? 80 : e.key === "ArrowDown" ? -80 : 0),
|
|
1188
|
+
});
|
|
1189
|
+
else return;
|
|
1190
|
+
e.preventDefault();
|
|
1191
|
+
});
|
|
1192
|
+
viewport.addEventListener("dblclick", () => {
|
|
1193
|
+
const a = currentItem();
|
|
1194
|
+
const p=a?.parts.find(p=>p.id===selectedForm);
|
|
1195
|
+
if (p) inspectForm(a,p); else if(a) focusAsset(a);
|
|
1196
|
+
});
|
|
1197
|
+
for (const [id, action] of Object.entries({
|
|
1198
|
+
"zoom-fit-all": fit,
|
|
1199
|
+
"zoom-fit-group": () => frame(active === null ? world : groups[active]),
|
|
1200
|
+
"zoom-fit-selection": () =>
|
|
1201
|
+
frame(selectedBox() || currentItem() || (active === null ? world : groups[active]), currentItem() ? 24 : 0),
|
|
1202
|
+
"zoom-actual": () => zoom(1),
|
|
1203
|
+
}))
|
|
1204
|
+
$("#" + id).onclick = () => {
|
|
1205
|
+
$("#zoom-menu").hidePopover();
|
|
1206
|
+
action();
|
|
1207
|
+
};
|
|
1208
|
+
$("#back").onclick = back;
|
|
1209
|
+
$('#sidebar-toggle').onclick = () => toggleSidebar();
|
|
1210
|
+
$('#inspect').onclick = () => {
|
|
1211
|
+
inspector = !inspector;
|
|
1212
|
+
updateChrome();
|
|
1213
|
+
requestDraw(true, false);
|
|
1214
|
+
};
|
|
1215
|
+
$('#copy-path').onclick=()=>navigator.clipboard.writeText($('#source-path').textContent).catch(e=>error(e.message));
|
|
1216
|
+
$('#copy-frame').onclick=()=>navigator.clipboard.writeText($('#frame-name').textContent).catch(e=>error(e.message));
|
|
1217
|
+
$("#fullscreen").onclick = () => {
|
|
1218
|
+
$("#more-menu").hidePopover();
|
|
1219
|
+
const p = document.fullscreenElement
|
|
1220
|
+
? document.exitFullscreen()
|
|
1221
|
+
: document.documentElement.requestFullscreen();
|
|
1222
|
+
p.catch((e) => error(e.message));
|
|
1223
|
+
};
|
|
1224
|
+
document.addEventListener("fullscreenchange", () => {
|
|
1225
|
+
$("#fullscreen").textContent = document.fullscreenElement ? "Exit fullscreen" : "Fullscreen";
|
|
1226
|
+
});
|
|
1227
|
+
$("#fit-current").onclick = () =>
|
|
1228
|
+
frame(selectedBox() || currentItem() || (active !== null ? groups[active] : world), currentItem() ? 24 : 0);
|
|
1229
|
+
$("#map-toggle").onclick = () => {
|
|
1230
|
+
$("#minimap").hidden = !$("#minimap").hidden;
|
|
1231
|
+
$("#map-toggle").setAttribute("aria-pressed", String(!$("#minimap").hidden));
|
|
1232
|
+
requestDraw();
|
|
1233
|
+
};
|
|
1234
|
+
$("#minimap").onclick = e => {
|
|
1235
|
+
const {scale:s,x,y}=mapGeometry(),r=e.target.getBoundingClientRect(),area=cameraArea();
|
|
1236
|
+
remember();inspection=null;selection();
|
|
1237
|
+
commit({...view,x:area.x+area.width/2-(e.clientX-r.left-x)/s*view.scale,y:area.y+area.height/2-(e.clientY-r.top-y)/s*view.scale});
|
|
1238
|
+
};
|
|
1239
|
+
$("#shortcuts").onclick = () => {
|
|
1240
|
+
$("#more-menu").hidePopover();
|
|
1241
|
+
$("#keys").showModal();
|
|
1242
|
+
};
|
|
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;}
|
|
1250
|
+
const old = assets,
|
|
1251
|
+
oldGroups = groups;
|
|
1252
|
+
layout(manifest,false,{placed,provisional:!!data.loading});
|
|
1253
|
+
if (active !== null) {
|
|
1254
|
+
const g = groups[active],
|
|
1255
|
+
prev = oldGroups[active],
|
|
1256
|
+
dx = prev.x - g.x,
|
|
1257
|
+
dy = prev.y - g.y;
|
|
1258
|
+
for (const a of assets) {
|
|
1259
|
+
if (a.group === active) {
|
|
1260
|
+
a.x += dx;
|
|
1261
|
+
a.y += dy;
|
|
1262
|
+
} else {
|
|
1263
|
+
const before = old.find((b) => b.id === a.id);
|
|
1264
|
+
if (before)
|
|
1265
|
+
Object.assign(a, {
|
|
1266
|
+
x: before.x,
|
|
1267
|
+
y: before.y,
|
|
1268
|
+
width: before.width,
|
|
1269
|
+
height: before.height,
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
groups = groups.map((g, i) =>
|
|
1274
|
+
i === active ? { ...g, x: prev.x, y: prev.y } : oldGroups[i],
|
|
1275
|
+
);
|
|
1276
|
+
}
|
|
1277
|
+
world.width = Math.max(1, ...groups.map((g) => g.x + g.width));
|
|
1278
|
+
world.height = Math.max(1, ...groups.map((g) => g.y + g.height));
|
|
1279
|
+
$("#more-menu").hidePopover();
|
|
1280
|
+
selection();
|
|
1281
|
+
};
|
|
1282
|
+
$("#search").oninput = () => {
|
|
1283
|
+
if (tokenManifest) {
|
|
1284
|
+
$('.token-scroll').scrollTop = 0;
|
|
1285
|
+
} else if ($("#search").value.trim()) {
|
|
1286
|
+
searchReturn ??= { view: { ...view }, sidebar, active, selected, selectedId, selectedForm, selectedElement, inspection };
|
|
1287
|
+
toggleSidebar(true);
|
|
1288
|
+
} else if (searchReturn) {
|
|
1289
|
+
toggleSidebar(searchReturn.sidebar);
|
|
1290
|
+
searchReturn = null;
|
|
1291
|
+
}
|
|
1292
|
+
renderNav();
|
|
1293
|
+
};
|
|
1294
|
+
$("#search-clear").onclick=()=>{$("#search").value="";$("#search").oninput();$("#search").focus()};
|
|
1295
|
+
$("#search").onkeydown = (e) => {
|
|
1296
|
+
if (e.key === "Enter")
|
|
1297
|
+
$("#modules .search-result")?.click();
|
|
1298
|
+
};
|
|
1299
|
+
$("#minus").onclick = () => zoom(view.scale / 1.25);
|
|
1300
|
+
$("#plus").onclick = () => zoom(view.scale * 1.25);
|
|
1301
|
+
function resizeViewport() {
|
|
1302
|
+
window.__adg.ready = false;
|
|
1303
|
+
const oldW = width,
|
|
1304
|
+
oldH = height;
|
|
1305
|
+
width = viewport.clientWidth;
|
|
1306
|
+
height = viewport.clientHeight;
|
|
1307
|
+
dpr = devicePixelRatio;
|
|
1308
|
+
|
|
1309
|
+
if (oldW)
|
|
1310
|
+
view = {
|
|
1311
|
+
...view,
|
|
1312
|
+
x: view.x + (width - oldW) / 2,
|
|
1313
|
+
y: view.y + (height - oldH) / 2,
|
|
1314
|
+
};
|
|
1315
|
+
updateChrome();
|
|
1316
|
+
requestDraw();
|
|
1317
|
+
}
|
|
1318
|
+
new ResizeObserver(resizeViewport).observe(viewport);
|
|
1319
|
+
function relationshipGraph(data, measured) {
|
|
1320
|
+
const entries=new Map(Object.entries(data.sourceImports ?? {}));
|
|
1321
|
+
for (const asset of measured) entries.set(asset.path,asset.imports ?? []);
|
|
1322
|
+
for (const imports of entries.values()) for (const path of imports) if (!entries.has(path)) entries.set(path,[]);
|
|
1323
|
+
return sourceRelationships([...entries].map(([path,imports])=>({path,imports})));
|
|
1324
|
+
}
|
|
1325
|
+
function applyTokenManifest(data) {
|
|
1326
|
+
const previous = tokenManifest ?? catalog ?? manifest;
|
|
1327
|
+
const entering = !tokenManifest || tokenManifest.directory !== data.directory;
|
|
1328
|
+
tokenManifest = { ...data, tokenGroups: groupTokens(data.tokens ?? []) };
|
|
1329
|
+
scopeRequest = data.scope;
|
|
1330
|
+
catalog = null;
|
|
1331
|
+
if (entering) {
|
|
1332
|
+
tokenCategory = null;
|
|
1333
|
+
$('.token-scroll').scrollTop = 0;
|
|
1334
|
+
}
|
|
1335
|
+
if (!tokenManifest.tokenGroups.some(group => group.label === tokenCategory)) tokenCategory = null;
|
|
1336
|
+
fixtureState = data.fixture ?? null;
|
|
1337
|
+
if (previous?.directory !== data.directory) {
|
|
1338
|
+
theme = data.theme;
|
|
1339
|
+
sidebar = !!fixtureState?.sidebar;
|
|
1340
|
+
applyTheme();
|
|
1341
|
+
}
|
|
1342
|
+
for (const element of document.querySelectorAll('.directory-name')) element.textContent = data.label;
|
|
1343
|
+
$('#app-directory').title = data.directory;
|
|
1344
|
+
document.title = `${data.label} — Agent Design Gallery`;
|
|
1345
|
+
if (!fixtureState) {
|
|
1346
|
+
const url = viewURL(location.href, 'tokens');
|
|
1347
|
+
if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
|
|
1348
|
+
}
|
|
1349
|
+
updateChrome();
|
|
1350
|
+
renderNav();
|
|
1351
|
+
}
|
|
1352
|
+
async function applyManifest(data, force = false) {
|
|
1353
|
+
if (data.scope === 'tokens') {
|
|
1354
|
+
if (force || tokenManifest?.directory !== data.directory || tokenManifest?.revision !== data.revision) applyTokenManifest(data);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
const leavingTokens = !!tokenManifest;
|
|
1358
|
+
const changedRoot = initializedDirectory !== data.directory, changedScope = initializedScope !== data.scope || initializedFrame !== onlyFrame;
|
|
1359
|
+
const first = changedRoot || changedScope;
|
|
1360
|
+
if (!force && !first && !leavingTokens && manifest.revision === data.revision)
|
|
1361
|
+
return;
|
|
1362
|
+
if (leavingTokens) {
|
|
1363
|
+
initialLink = null;
|
|
1364
|
+
$('#search').value = '';
|
|
1365
|
+
}
|
|
1366
|
+
if (changedRoot) {
|
|
1367
|
+
fixtureState=data.fixture ?? null;
|
|
1368
|
+
theme = data.theme;
|
|
1369
|
+
applyTheme();
|
|
1370
|
+
if (!leavingTokens) sidebar = !!fixtureState?.sidebar;
|
|
1371
|
+
inspector = !!fixtureState && data.inspector;
|
|
1372
|
+
history = [];
|
|
1373
|
+
}
|
|
1374
|
+
if (first) {
|
|
1375
|
+
if (catalog?.directory !== data.directory || catalog?.scope !== data.scope) {
|
|
1376
|
+
expanded.clear();
|
|
1377
|
+
if (scopedUI(data) && scopeKind(data.scope)==='layer') expanded.add(0);
|
|
1378
|
+
}
|
|
1379
|
+
catalog = data;
|
|
1380
|
+
for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
|
|
1381
|
+
$("#app-directory").title=data.directory||'';
|
|
1382
|
+
document.title = `${data.label} — Agent Design Gallery`;
|
|
1383
|
+
updateChrome();
|
|
1384
|
+
renderNav();
|
|
1385
|
+
}
|
|
1386
|
+
window.__adg.ready = false;
|
|
1387
|
+
if (first) {
|
|
1388
|
+
cache.clear();
|
|
1389
|
+
labelLayer.clear();
|
|
1390
|
+
queued = [];
|
|
1391
|
+
selected = null;
|
|
1392
|
+
selectedId = null;
|
|
1393
|
+
selectedForm = null;selectedElement=null;
|
|
1394
|
+
inspection = null;
|
|
1395
|
+
active = null;
|
|
1396
|
+
assets = [];
|
|
1397
|
+
groups = [];
|
|
1398
|
+
}
|
|
1399
|
+
const versionTheme = effectiveTheme;
|
|
1400
|
+
const link = initializedDirectory === undefined && !fixtureState ? initialLink : null;
|
|
1401
|
+
const entry = !changedRoot && scopeRequest===data.scope ? scopeEntry : null;
|
|
1402
|
+
const groupTitle = groups[active]?.title;
|
|
1403
|
+
restorePacking(data.packing);
|
|
1404
|
+
const previous=manifest, results=new Array(data.assets.length), signal=refreshController?.signal;
|
|
1405
|
+
let next=0,publishFrame=0,streamView=null,streamMoved=false,publishedCount=0,nextPublish=1;
|
|
1406
|
+
const streaming=first && !leavingTokens;
|
|
1407
|
+
const publish=()=>{
|
|
1408
|
+
publishFrame=0;
|
|
1409
|
+
if(signal?.aborted||versionTheme!==effectiveTheme)return;
|
|
1410
|
+
const available=results.filter(Boolean);
|
|
1411
|
+
if(!available.length)return;
|
|
1412
|
+
publishedCount=available.length;nextPublish=Math.max(publishedCount+1,publishedCount*2);
|
|
1413
|
+
if(streamView&&view!==streamView)streamMoved=true;
|
|
1414
|
+
manifest={...data,assets:available,renderTheme:versionTheme,loading:true};
|
|
1415
|
+
layout(manifest,false,{provisional:true});
|
|
1416
|
+
if(streaming&&!streamMoved){view=entry?.view??data.view??fitWorld(cameraArea(),data);streamView=view;}
|
|
1417
|
+
requestDraw();
|
|
1418
|
+
};
|
|
1419
|
+
for(let i=0;i<data.assets.length;i++) {
|
|
1420
|
+
const a=data.assets[i],key=sourceKey(a,versionTheme,data.directory);
|
|
1421
|
+
const metadata=a.metadata?.[versionTheme]??metadataCache.get(key);
|
|
1422
|
+
if(metadata){results[i]=decorateMetadata(a,metadata);metadataCache.set(key,metadata);}
|
|
1423
|
+
}
|
|
1424
|
+
let completed=results.filter(Boolean).length;
|
|
1425
|
+
if(streaming&&completed&&completed<data.assets.length)publish();
|
|
1426
|
+
await Promise.all(Array.from({length:4},async()=>{
|
|
1427
|
+
while(next<data.assets.length) {
|
|
1428
|
+
signal?.throwIfAborted();
|
|
1429
|
+
const i=next++,a=data.assets[i];
|
|
1430
|
+
if(results[i])continue;
|
|
1431
|
+
let entry;
|
|
1432
|
+
if(a.hash&&a.metadataRefs?.[versionTheme]) {
|
|
1433
|
+
const query=new URLSearchParams({theme:versionTheme,context:metadataContext()});
|
|
1434
|
+
const response=await dataFetch(`metadata/${a.hash}?${query}`,{signal});
|
|
1435
|
+
if(response.ok){const saved=await response.json();entry=decorateMetadata({...a,previewIds:{...a.previewIds,[versionTheme]:saved.previewIds}},saved.metadata);}
|
|
1436
|
+
}
|
|
1437
|
+
if(!entry) {
|
|
1438
|
+
entry=await prepare(a,versionTheme,{signal});
|
|
1439
|
+
if (a.onlyFrame && !entry.parts.some(part => part.name === a.onlyFrame)) throw Error(`Frame ${a.onlyFrame} does not exist in ${a.path}.`);
|
|
1440
|
+
Object.assign(a,{hash:entry.hash,version:entry.version});
|
|
1441
|
+
persistSource(entry,versionTheme);
|
|
1442
|
+
keepSource(sourceKey(entry,versionTheme,data.directory),entry);
|
|
1443
|
+
}
|
|
1444
|
+
const metadata=measuredMetadata(entry);
|
|
1445
|
+
metadataCache.set(sourceKey(entry,versionTheme,data.directory),metadata);
|
|
1446
|
+
results[i]=decorateMetadata(a,metadata);completed++;
|
|
1447
|
+
if(streaming&&completed>=nextPublish&&!publishFrame)publishFrame=requestAnimationFrame(publish);
|
|
1448
|
+
}
|
|
1449
|
+
}));
|
|
1450
|
+
if(publishFrame)cancelAnimationFrame(publishFrame);
|
|
1451
|
+
if(versionTheme!==effectiveTheme){pending=true;return;}
|
|
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;
|
|
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);
|
|
1461
|
+
const live=new Set(data.assets.flatMap(a=>['light','dark'].map(t=>sourceKey(a,t,data.directory))));
|
|
1462
|
+
for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
|
|
1463
|
+
manifest = { ...data, assets: results, relationships:relationshipGraph(data,results), renderTheme: versionTheme };
|
|
1464
|
+
tokenManifest = null;
|
|
1465
|
+
// Early streamed worlds can use a much larger camera scale. Discard those
|
|
1466
|
+
// raster intermediates so the completed world starts at its exact final scale.
|
|
1467
|
+
if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
|
|
1468
|
+
catalog = null;
|
|
1469
|
+
layout(
|
|
1470
|
+
manifest,
|
|
1471
|
+
!first && !!previous &&
|
|
1472
|
+
JSON.stringify(previous.groups) === JSON.stringify(data.groups),
|
|
1473
|
+
{placed},
|
|
1474
|
+
);
|
|
1475
|
+
for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
|
|
1476
|
+
$("#app-directory").title=data.directory||'';
|
|
1477
|
+
document.title = `${data.label} — Agent Design Gallery`;
|
|
1478
|
+
if (first) {
|
|
1479
|
+
const target = entry ? entry.target : link ?? data.selection;
|
|
1480
|
+
if (!fixtureState) restoreSelection(target);
|
|
1481
|
+
const saved = data.selection;
|
|
1482
|
+
const sameSelection = link && saved && (link.path
|
|
1483
|
+
? link.path === saved.path && link.form === saved.form && link.element?.id === saved.element?.id
|
|
1484
|
+
: !saved.path && link.group === saved.group);
|
|
1485
|
+
const reload = performance.getEntriesByType('navigation')[0]?.type === 'reload';
|
|
1486
|
+
if (entry?.view) view=entry.view;
|
|
1487
|
+
else if (entry?.target || (link && (onlyFrame || !(reload && sameSelection && data.view)))) {
|
|
1488
|
+
const target = selectedBox() || currentItem() || groups[active] || world;
|
|
1489
|
+
frame(target, selected ? 24 : 0);
|
|
1490
|
+
} else if (data.view) view = data.view;
|
|
1491
|
+
else if (!streamMoved) frame(world);
|
|
1492
|
+
} else if (groupTitle) {
|
|
1493
|
+
const index = groups.findIndex(group=>group.title===groupTitle);
|
|
1494
|
+
active = index < 0 ? null : index;
|
|
1495
|
+
}
|
|
1496
|
+
if (selected && !assets.some((a) => a.path === selected)) {
|
|
1497
|
+
selected = null;
|
|
1498
|
+
selectedId = null;
|
|
1499
|
+
selectedForm = null;selectedElement=null;
|
|
1500
|
+
inspection = null;
|
|
1501
|
+
} else if (selected) {
|
|
1502
|
+
const a=currentItem(),p=a?.parts.find(p=>p.id===selectedForm);
|
|
1503
|
+
if (!a) {selectedId=assets.find(a=>a.path===selected)?.id;selectedForm=null;selectedElement=null}
|
|
1504
|
+
else if (selectedForm!==null && !p) {selectedForm=null;selectedElement=null}
|
|
1505
|
+
else if (selectedElement) {
|
|
1506
|
+
const next=p?.elements?.find(e=>e.id===selectedElement.id);
|
|
1507
|
+
selectedElement=next?.owners.some(o=>o.source===selectedElement.owner.source && o.export===selectedElement.owner.export)?{...next,owner:selectedElement.owner}:null;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
if (inspection) {
|
|
1511
|
+
const a=assets.find(a=>a.path===selected),p={...a.full,id:'full',name:'Full sheet'};
|
|
1512
|
+
inspection={...a,id:a.id+'@full',x:0,y:0,width:p.width,height:p.height,shown:[p],kind:'sheet'};
|
|
1513
|
+
}
|
|
1514
|
+
initializedDirectory=data.directory;
|
|
1515
|
+
initializedScope=scopeRequest=data.scope;
|
|
1516
|
+
initializedFrame=onlyFrame;
|
|
1517
|
+
initialLink=null;
|
|
1518
|
+
scopeEntry=null;
|
|
1519
|
+
if(data.features?.persistedMetadata && !onlyFrame)cacheWrite(`catalog?context=${encodeURIComponent(metadataContext())}`,{packing:packingSnapshot()});
|
|
1520
|
+
selection();
|
|
1521
|
+
if (pendingNavigation) {
|
|
1522
|
+
const action = pendingNavigation;
|
|
1523
|
+
pendingNavigation = null;
|
|
1524
|
+
action();
|
|
1525
|
+
}
|
|
1526
|
+
requestDraw();
|
|
1527
|
+
}
|
|
1528
|
+
function updateChoices() {
|
|
1529
|
+
for(const button of document.querySelectorAll('#themes button, #backgrounds button')) {
|
|
1530
|
+
const selected=button.dataset.theme ? button.dataset.theme===theme : button.dataset.background===backgroundChoice;
|
|
1531
|
+
button.setAttribute('aria-pressed',String(selected));button.querySelector('svg')?.remove();
|
|
1532
|
+
if(selected) button.insertAdjacentHTML('afterbegin',icon('check',14));
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
for(const button of $("#backgrounds").children) button.onclick=()=>{backgroundChoice=button.dataset.background;updateChoices();requestDraw()};
|
|
1536
|
+
for(const [id,trigger] of [['zoom-menu','zoom-options'],['more-menu','more']]) {
|
|
1537
|
+
$("#"+id).addEventListener('toggle',event=>{
|
|
1538
|
+
$("#"+trigger).setAttribute(id === "more-menu" ? "aria-expanded" : "aria-pressed", String(event.newState === "open"));
|
|
1539
|
+
if(event.newState==='open') {
|
|
1540
|
+
for(const other of document.querySelectorAll(':popover-open')) if(other.id!==id) other.hidePopover();
|
|
1541
|
+
hideTooltip();positionZoomMenu();
|
|
1542
|
+
}
|
|
1543
|
+
requestDraw();
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
let tooltipTimer;
|
|
1547
|
+
function hideTooltip() { clearTimeout(tooltipTimer);if (!$("#tooltip").hidden) { $("#tooltip").hidden=true;requestDraw(); } }
|
|
1548
|
+
function bindTooltip(button, trailing = false) {
|
|
1549
|
+
const show=()=>{clearTimeout(tooltipTimer);tooltipTimer=setTimeout(()=>{
|
|
1550
|
+
if(!button.isConnected||document.querySelector(':popover-open, dialog[open]'))return;
|
|
1551
|
+
const tip=$("#tooltip"),r=button.getBoundingClientRect();tip.textContent=button.dataset.tooltip;tip.hidden=false;
|
|
1552
|
+
const beside=trailing && r.right+16+tip.offsetWidth<=width-4;
|
|
1553
|
+
const x=beside?r.right+16:r.x+r.width/2-tip.offsetWidth/2;
|
|
1554
|
+
const y=beside?r.y+(r.height-tip.offsetHeight)/2:r.y>height/2?r.top-tip.offsetHeight-12:r.bottom+12;
|
|
1555
|
+
tip.style.left=`${Math.max(4,Math.min(width-tip.offsetWidth-4,x))}px`;
|
|
1556
|
+
tip.style.top=`${y}px`;requestDraw();
|
|
1557
|
+
},400)};
|
|
1558
|
+
button.addEventListener('pointerenter',show);button.addEventListener('focus',show);
|
|
1559
|
+
button.addEventListener('pointerleave',()=>{hideTooltip();requestDraw()});button.addEventListener('blur',hideTooltip);button.addEventListener('click',hideTooltip);
|
|
1560
|
+
}
|
|
1561
|
+
for(const button of document.querySelectorAll('[data-tooltip]')) bindTooltip(button);
|
|
1562
|
+
$("#keys-close").onclick=()=>$("#keys").close();
|
|
1563
|
+
for(const dialog of document.querySelectorAll('dialog')) {
|
|
1564
|
+
dialog.addEventListener('toggle', () => requestDraw());
|
|
1565
|
+
dialog.addEventListener('close',()=>{viewport.focus({preventScroll:true});requestDraw()});
|
|
1566
|
+
}
|
|
1567
|
+
document.addEventListener('keydown',event=>{
|
|
1568
|
+
if(event.key==='?'&&!event.target.matches('input,textarea')&&!document.querySelector('dialog[open]')) {event.preventDefault();hideTooltip();$("#keys").showModal()}
|
|
1569
|
+
});
|
|
1570
|
+
async function applyFixture() {
|
|
1571
|
+
const state=fixtureState;if(!state)return;
|
|
1572
|
+
if (tokenManifest) return;
|
|
1573
|
+
fixtureApplied=false;delete document.documentElement.dataset.fixtureReady;
|
|
1574
|
+
sidebar=state.sidebar;inspector=!!state.inspector;history=[];inspection=null;selected=null;selectedId=null;selectedForm=null;selectedElement=null;expanded.clear();
|
|
1575
|
+
active=state.group ? groups.findIndex(g=>g.title===state.group) : null;
|
|
1576
|
+
if(active===-1) throw new Error(`Fixture group not found: ${state.group}`);
|
|
1577
|
+
if(active!==null) expanded.add(active);
|
|
1578
|
+
if(state.asset) {
|
|
1579
|
+
const source=manifest.assets.find(a=>a.path===state.asset),form=state.form?source?.parts.find(p=>p.name===state.form):null;
|
|
1580
|
+
const item=assets.find(a=>a.path===state.asset && (!form || a.component || a.shown[0].id===form.id));
|
|
1581
|
+
if(!item)throw new Error(`Fixture asset/form not found: ${state.asset} ${state.form??''}`);
|
|
1582
|
+
selected=item.path;selectedId=item.id;selectedForm=form?.id ?? (state.sourceOnly ? null : item.parts[0]?.id);
|
|
1583
|
+
}
|
|
1584
|
+
$("#search").value=state.query??'';$("#minimap").hidden=!state.minimap;$("#map-toggle").setAttribute('aria-pressed',String(!!state.minimap));
|
|
1585
|
+
selection();
|
|
1586
|
+
if(state.camera==='origin') commit({scale:state.scale,x:state.origin[0]-groups[active].x*state.scale,y:state.origin[1]-groups[active].y*state.scale});
|
|
1587
|
+
else if(state.camera==='group') frame(groups[active]);
|
|
1588
|
+
else if(state.camera==='selection') frame(currentItem(),24);
|
|
1589
|
+
else frame(world);
|
|
1590
|
+
if(state.scale && state.camera!=='origin') zoom(state.scale);
|
|
1591
|
+
// Fixtures retain a useful Back button just as a user navigating from the overview would.
|
|
1592
|
+
if(state.asset){history=[{view:fitView(world,fitArea(width,height,state.sidebar,false)),active:null,selected:null,selectedId:null,selectedForm:null,inspection:null,inspector:false}];$("#back").disabled=false}
|
|
1593
|
+
if(state.menu){positionZoomMenu();$("#"+state.menu).showPopover()}
|
|
1594
|
+
if(state.dialog) $("#"+state.dialog).showModal();
|
|
1595
|
+
fixtureApplied=true;requestDraw();
|
|
1596
|
+
}
|
|
1597
|
+
let fetching = false,
|
|
1598
|
+
pending = false, refreshController=null;
|
|
1599
|
+
async function refresh(force = false) {
|
|
1600
|
+
if (fetching) {
|
|
1601
|
+
pending = true;refreshController?.abort();
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
fetching = true;refreshController=new AbortController();
|
|
1605
|
+
try {
|
|
1606
|
+
if (routeError) throw routeError;
|
|
1607
|
+
const query=new URLSearchParams({context:metadataContext(),theme:effectiveTheme,scope:scopeRequest});
|
|
1608
|
+
if (strictRoute) query.set('strict', '1');
|
|
1609
|
+
if (onlyFrame) query.set('frame', onlyFrame);
|
|
1610
|
+
if(!manifest){query.set('initial','1');query.set('metadata','1');}
|
|
1611
|
+
else if(manifest.renderTheme!==effectiveTheme || scopeRequest!==initializedScope)query.set('metadata','1');
|
|
1612
|
+
const signal=refreshController.signal, data=await api(`manifest?${query}`,null,false,signal);
|
|
1613
|
+
signal.throwIfAborted();
|
|
1614
|
+
data.scope ??= 'all';
|
|
1615
|
+
if (strictRoute && initialLink?.path && !data.assets.some(asset => asset.path === initialLink.path))
|
|
1616
|
+
throw Error(`Design link target ${initialLink.path} is outside this scope.`);
|
|
1617
|
+
if (onlyFrame) data.assets = data.assets.map(asset => ({ ...asset, onlyFrame, metadata: null, metadataRefs: null, previewIds: null }));
|
|
1618
|
+
await applyManifest(data, force);
|
|
1619
|
+
error("");
|
|
1620
|
+
} catch (e) {
|
|
1621
|
+
if(e.name!=='AbortError')error(e.message);
|
|
1622
|
+
else if(!refreshController.signal.aborted)pending=true;
|
|
1623
|
+
} finally {
|
|
1624
|
+
fetching = false;
|
|
1625
|
+
if (pending) {
|
|
1626
|
+
pending = false;
|
|
1627
|
+
await refresh(true);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
await refresh();
|
|
1632
|
+
if(fixtureState) { try { await applyFixture(); } catch(e) { error(e.message); } }
|
|
1633
|
+
if ((tokenManifest || manifest) && !isUnauthorized()) {
|
|
1634
|
+
const events = new EventSource(keyURL('events'));
|
|
1635
|
+
window.addEventListener('adg-unauthorized', () => events.close(), { once: true });
|
|
1636
|
+
events.onmessage = (e) => {
|
|
1637
|
+
const data = JSON.parse(e.data);
|
|
1638
|
+
if (data.error) error(data.error);
|
|
1639
|
+
else void refresh();
|
|
1640
|
+
};
|
|
1641
|
+
events.onerror = async () => {
|
|
1642
|
+
try {
|
|
1643
|
+
const response = await dataFetch('manifest');
|
|
1644
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
1645
|
+
error('Local server disconnected. Reconnecting…');
|
|
1646
|
+
} catch (e) { error(e.message); }
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
document.addEventListener("keydown", (e) => {
|
|
1651
|
+
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
|
|
1652
|
+
e.preventDefault();
|
|
1653
|
+
$("#search").focus();
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
if (e.key !== "Escape" || $("#keys").open) return;
|
|
1657
|
+
if (document.querySelector(":popover-open")) return;
|
|
1658
|
+
if (tokenManifest) {
|
|
1659
|
+
if ($('#search').value) $('#search-clear').click();
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
if (searchReturn) {
|
|
1663
|
+
const old = searchReturn;
|
|
1664
|
+
searchReturn = null;
|
|
1665
|
+
$("#search").value = "";
|
|
1666
|
+
toggleSidebar(old.sidebar);
|
|
1667
|
+
({ active, selected, selectedId, selectedForm, selectedElement = null, inspection } = old);
|
|
1668
|
+
selection();
|
|
1669
|
+
commit(old.view);
|
|
1670
|
+
} else clearSelection();
|
|
1671
|
+
viewport.focus({ preventScroll: true });
|
|
1672
|
+
});
|
|
1673
|
+
|
|
1674
|
+
initSwitcher();
|