@tora-editor/tora 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +5 -6
  2. package/bin/tora.mjs +255 -29
  3. package/crates/packer/trusted/native-3d-meta.json +3 -3
  4. package/crates/packer/trusted/native-3d.js +180 -180
  5. package/crates/packer/trusted/native-meta.json +3 -3
  6. package/crates/packer/trusted/native.js +5 -5
  7. package/crates/packer/trusted/release-manifest.json +17 -17
  8. package/crates/packer/trusted/review-runtime-meta.json +3 -3
  9. package/crates/packer/trusted/review-runtime.js +182 -182
  10. package/docs/MIGRATION_0_3.md +39 -0
  11. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  12. package/docs/TORA_AGENT_SETUP.md +24 -106
  13. package/docs/TORA_CREATION_API.md +63 -365
  14. package/docs/reference/CORE_AUTHORING.md +8 -2
  15. package/docs/reference/PLAYABLE_STARTERS.md +1 -1
  16. package/docs/reference/packs/3d.md +2 -0
  17. package/package.json +6 -6
  18. package/packages/creative-project/project-v21.schema.json +108 -1
  19. package/scripts/lean/editor/entry.js +11 -6
  20. package/scripts/lean/editor/project-launcher.js +116 -0
  21. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  22. package/scripts/lean/editor/review-editor.css +246 -68
  23. package/scripts/lean/editor/review-editor.js +1731 -1099
  24. package/scripts/lean/editor-state.mjs +6 -0
  25. package/scripts/lean/editor.mjs +6 -3
  26. package/scripts/lean/matrix.mjs +5 -0
  27. package/scripts/lean/native/agent-tools.mjs +35 -58
  28. package/scripts/lean/native/api.mjs +148 -134
  29. package/scripts/lean/native/audio-assets.mjs +30 -0
  30. package/scripts/lean/native/browser-pool.mjs +34 -0
  31. package/scripts/lean/native/build-cache.mjs +36 -5
  32. package/scripts/lean/native/contracts.mjs +8 -6
  33. package/scripts/lean/native/creative-qa.mjs +66 -12
  34. package/scripts/lean/native/demos.mjs +11 -20
  35. package/scripts/lean/native/document.mjs +14 -2
  36. package/scripts/lean/native/local-bundle.mjs +4 -2
  37. package/scripts/lean/native/mcp-server.mjs +16 -35
  38. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  39. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  40. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  41. package/scripts/lean/native/project-bundle.mjs +3 -2
  42. package/scripts/lean/native/project-index.mjs +0 -2
  43. package/scripts/lean/native/qa-adapters.mjs +10 -0
  44. package/scripts/lean/native/quick-edit.mjs +328 -0
  45. package/scripts/lean/native/review.mjs +203 -572
  46. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  47. package/scripts/lean/native/schema.mjs +1 -1
  48. package/scripts/lean/native/scope.mjs +45 -0
  49. package/scripts/lean/native/service.mjs +242 -70
  50. package/scripts/lean/native/starters.mjs +135 -8
  51. package/scripts/lean/native/variant-adapters.mjs +8 -0
  52. package/scripts/lean/native/variants-core.mjs +186 -0
  53. package/scripts/lean/native/variants.mjs +63 -0
  54. package/scripts/lean/native/win-cues.mjs +1 -1
  55. package/skills/tora-playables/SKILL.md +1 -1
  56. package/scripts/lean/editor/review-intake.js +0 -837
  57. package/scripts/lean/model-client.mjs +0 -119
  58. package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
  59. package/scripts/lean/native/author-fps.mjs +0 -545
  60. package/scripts/lean/native/author-games.mjs +0 -160
  61. package/scripts/lean/native/author-harvest.mjs +0 -74
  62. package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
  63. package/scripts/lean/native/author-salvage.mjs +0 -71
  64. package/scripts/lean/native/chat-compose.mjs +0 -287
  65. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
  66. package/scripts/lean/native/check-salvage.mjs +0 -200
  67. package/scripts/lean/native/compatibility.mjs +0 -34
  68. package/scripts/lean/native/concept.mjs +0 -633
  69. package/scripts/lean/native/draw-stroke.mjs +0 -26
  70. package/scripts/lean/native/erase-mask.mjs +0 -18
  71. package/scripts/lean/native/glb-loader.mjs +0 -468
  72. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  73. package/scripts/lean/native/instance-steering.mjs +0 -24
  74. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  75. package/scripts/lean/native/intake-creator-tools.mjs +0 -218
  76. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  77. package/scripts/lean/native/match-board.mjs +0 -138
  78. package/scripts/lean/native/modules/index.mjs +0 -54
  79. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  80. package/scripts/lean/native/path-network.mjs +0 -132
  81. package/scripts/lean/native/physics-2d.mjs +0 -154
  82. package/scripts/lean/native/physics-3d.mjs +0 -259
  83. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  84. package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
  85. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  86. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  87. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  88. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  89. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  90. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  91. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  92. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  93. package/scripts/lean/native/presentation.mjs +0 -335
  94. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  95. package/scripts/lean/native/review-connection.mjs +0 -303
  96. package/scripts/lean/native/review-fields.mjs +0 -24
  97. package/scripts/lean/native/review-intake.mjs +0 -385
  98. package/scripts/lean/native/review-intents.mjs +0 -217
  99. package/scripts/lean/native/review-provider.mjs +0 -580
  100. package/scripts/lean/native/review-receipts.mjs +0 -76
  101. package/scripts/lean/native/review-resolver.mjs +0 -429
  102. package/scripts/lean/native/review-targets.mjs +0 -35
  103. package/scripts/lean/native/runtime.mjs +0 -1809
  104. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  105. package/scripts/lean/native/stage-3d.mjs +0 -1121
  106. package/scripts/lean/native/verify.mjs +0 -4
  107. package/scripts/lean/scene-document.mjs +0 -48
@@ -0,0 +1,479 @@
1
+ /* global document,Audio */
2
+
3
+ function toSixDigitHex(color) {
4
+ if (typeof color !== 'string') return '#ffffff';
5
+ const match = /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(color.trim());
6
+ return match ? '#' + match[1].toLowerCase() : '#ffffff';
7
+ }
8
+
9
+ function alphaSuffix(color) {
10
+ if (typeof color !== 'string') return '';
11
+ const match = /^#[0-9a-f]{6}([0-9a-f]{2})$/i.exec(color.trim());
12
+ return match ? match[1].toLowerCase() : '';
13
+ }
14
+
15
+ function shiftHexColor(hex, delta) {
16
+ if (typeof hex !== 'string' || !/^#[0-9a-f]{6}$/i.test(hex)) return hex;
17
+ const clamp = v => Math.max(0, Math.min(255, Math.round(v)));
18
+ const r = clamp(parseInt(hex.slice(1, 3), 16) + delta);
19
+ const g = clamp(parseInt(hex.slice(3, 5), 16) + delta);
20
+ const b = clamp(parseInt(hex.slice(5, 7), 16) + delta);
21
+ return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
22
+ }
23
+
24
+ function applyEditsToVariant(variant, edits) {
25
+ const next = globalThis.structuredClone(variant);
26
+ for (const edit of edits) {
27
+ if (edit.kind === 'text') {
28
+ next.texts = {...(next.texts ?? {})};
29
+ const prev = {...(next.texts[edit.componentId] ?? {})};
30
+ if (edit.text !== undefined) prev.text = edit.text;
31
+ if (edit.color !== undefined) prev.color = edit.color;
32
+ if (edit.fontSize !== undefined) prev.fontSize = edit.fontSize;
33
+ next.texts[edit.componentId] = prev;
34
+ } else if (edit.kind === 'color') {
35
+ next.colors = {...(next.colors ?? {})};
36
+ const prev = {...(next.colors[edit.componentId] ?? {})};
37
+ prev[edit.key] = edit.value;
38
+ if (edit.key === 'fill' && edit.syncButtonStates && /^#[0-9a-f]{6}$/i.test(edit.value)) {
39
+ prev.hoverFill = shiftHexColor(edit.value, 18);
40
+ prev.pressedFill = shiftHexColor(edit.value, -20);
41
+ }
42
+ next.colors[edit.componentId] = prev;
43
+ } else if (edit.kind === 'timing') {
44
+ next.behaviors = {...(next.behaviors ?? {})};
45
+ next.behaviors[edit.behaviorId] = {...(next.behaviors[edit.behaviorId] ?? {}), seconds: edit.seconds};
46
+ } else if (edit.kind === 'replaceAsset') {
47
+ next.assets = {...(next.assets ?? {})};
48
+ const ids = Array.isArray(edit.componentIds) ? edit.componentIds : [edit.componentId];
49
+ for (const componentId of ids) {
50
+ next.assets[componentId] = {slotId: edit.slotId ?? 'source', assetId: edit.assetId};
51
+ }
52
+ }
53
+ }
54
+ return next;
55
+ }
56
+
57
+ export function createQuickEditPanel({
58
+ container,
59
+ projectId,
60
+ api,
61
+ getMetadata,
62
+ getAssetDataUrl,
63
+ isCandidateActive,
64
+ getActiveVariant,
65
+ getActiveVariantLabel,
66
+ onUpdated,
67
+ onSelectMoment,
68
+ onHighlight,
69
+ onStatus,
70
+ onError,
71
+ prepareImageFile,
72
+ prepareAudioFile,
73
+ formatBytes,
74
+ reviewElement,
75
+ isHosted = false,
76
+ }) {
77
+ let activeAudio = null;
78
+ let activeAudioBtn = null;
79
+ let lastSignature = '';
80
+ let focusedComponentId = null;
81
+
82
+ function stopAudio() {
83
+ if (activeAudio) {
84
+ activeAudio.pause();
85
+ activeAudio = null;
86
+ }
87
+ if (activeAudioBtn) {
88
+ activeAudioBtn.textContent = '▶ Play';
89
+ activeAudioBtn = null;
90
+ }
91
+ }
92
+
93
+ async function commitQuickEdit(edits, successMessage) {
94
+ if (isCandidateActive?.()) {
95
+ onError('Choose Use this version or Discard before making Quick Edit changes.');
96
+ return false;
97
+ }
98
+ const metadata = getMetadata();
99
+ const variant = getActiveVariant?.() ?? null;
100
+ onError('');
101
+ onStatus(variant ? `Saving to ${variant.label}…` : 'Saving change…');
102
+ try {
103
+ if (variant) {
104
+ const nextVariant = applyEditsToVariant(variant, edits);
105
+ await api('/variants', {
106
+ action: 'upsert',
107
+ variant: nextVariant,
108
+ expectedVariantRevision: metadata.variants?.revision,
109
+ });
110
+ } else {
111
+ await api('/quick-edit', {expected: metadata.expected, edits});
112
+ }
113
+ await onUpdated();
114
+ onStatus(successMessage ? (variant ? `${successMessage.replace(/\.$/, '')} in ${variant.label}.` : successMessage) : 'Change saved.');
115
+ return true;
116
+ } catch (error) {
117
+ onStatus('');
118
+ onError(error);
119
+ return false;
120
+ }
121
+ }
122
+
123
+ function makeSection(title, subtitle) {
124
+ const section = reviewElement('section', '', 'tora-qe-section');
125
+ const head = reviewElement('div', '', 'tora-qe-section-head');
126
+ head.append(reviewElement('h3', title));
127
+ if (subtitle) head.append(reviewElement('span', subtitle));
128
+ section.append(head);
129
+ return section;
130
+ }
131
+
132
+ function render(force = false) {
133
+ const metadata = getMetadata();
134
+ const qe = metadata?.quickEdit;
135
+ const variant = getActiveVariant?.() ?? null;
136
+ const activeVariantLabel = variant?.label ?? getActiveVariantLabel?.() ?? '';
137
+ const signature = JSON.stringify([metadata?.expected?.revisionId, metadata?.variants?.hash, qe, isHosted, variant ?? activeVariantLabel]);
138
+ if (!force && signature === lastSignature) return;
139
+ lastSignature = signature;
140
+ stopAudio();
141
+
142
+ if (!qe) {
143
+ container.replaceChildren(reviewElement('p', 'Loading Quick Edit controls…', 'tora-qe-empty'));
144
+ return;
145
+ }
146
+
147
+ const fragment = document.createDocumentFragment();
148
+
149
+ const tip = reviewElement('p', 'Click any element in the preview or edit directly below — changes apply instantly at $0 AI cost and support Undo.', 'tora-qe-intro');
150
+ fragment.append(tip);
151
+
152
+ if (activeVariantLabel) {
153
+ const notice = reviewElement('div', '', 'tora-qe-variant-notice');
154
+ notice.append(
155
+ reviewElement('strong', `Editing variant: ${activeVariantLabel}`),
156
+ reviewElement('span', `Changes below save only to "${activeVariantLabel}" and leave your Base playable untouched.`),
157
+ );
158
+ fragment.append(notice);
159
+ }
160
+
161
+ // 1. Copy & Buttons
162
+ if (qe.texts?.length) {
163
+ const section = makeSection('Copy & Buttons', `${qe.texts.length} text ${qe.texts.length === 1 ? 'field' : 'fields'}`);
164
+ for (const item of qe.texts) {
165
+ const textOverride = variant?.texts?.[item.id];
166
+ const currentText = typeof textOverride?.text === 'string' ? textOverride.text : item.text;
167
+ const currentColor = typeof textOverride?.color === 'string' ? textOverride.color : item.color;
168
+ const card = reviewElement('div', '', 'tora-qe-card');
169
+ card.dataset.componentId = item.id;
170
+ if (item.parentId) card.dataset.parentId = item.parentId;
171
+ if (focusedComponentId && (focusedComponentId === item.id || focusedComponentId === item.parentId)) {
172
+ card.dataset.focused = 'true';
173
+ }
174
+ const top = reviewElement('div', '', 'tora-qe-card-top');
175
+ top.append(reviewElement('strong', item.roleLabel));
176
+ const sceneBtn = reviewElement('button', item.sceneLabel, 'tora-qe-scene-pill');
177
+ sceneBtn.type = 'button';
178
+ sceneBtn.title = `Jump preview to ${item.sceneLabel}`;
179
+ sceneBtn.onclick = () => {
180
+ onSelectMoment?.(item.moment);
181
+ onHighlight?.(item.componentIds);
182
+ };
183
+ top.append(sceneBtn);
184
+
185
+ const row = reviewElement('div', '', 'tora-qe-input-row');
186
+ const input = reviewElement('input');
187
+ input.type = 'text';
188
+ input.value = currentText;
189
+ input.maxLength = item.maxLength ?? 120;
190
+ input.setAttribute('aria-label', item.roleLabel);
191
+ input.onfocus = () => onHighlight?.(item.componentIds);
192
+
193
+ const colorInput = reviewElement('input');
194
+ colorInput.type = 'color';
195
+ colorInput.className = 'tora-qe-color-swatch';
196
+ colorInput.value = toSixDigitHex(currentColor);
197
+ colorInput.title = `${item.roleLabel} text color`;
198
+ colorInput.setAttribute('aria-label', `${item.roleLabel} text color`);
199
+
200
+ const applyBtn = reviewElement('button', 'Apply', 'tora-qe-apply');
201
+ applyBtn.type = 'button';
202
+ applyBtn.disabled = true;
203
+
204
+ const syncDirty = () => {
205
+ const textChanged = input.value !== currentText;
206
+ const colorChanged = colorInput.value.toLowerCase() !== toSixDigitHex(currentColor).toLowerCase();
207
+ applyBtn.disabled = !textChanged && !colorChanged;
208
+ };
209
+ input.oninput = syncDirty;
210
+ colorInput.oninput = syncDirty;
211
+
212
+ const submitItem = async () => {
213
+ const edit = {kind: 'text', componentId: item.id, autoFallbackFont: true};
214
+ if (input.value !== currentText) edit.text = input.value;
215
+ if (colorInput.value.toLowerCase() !== toSixDigitHex(currentColor).toLowerCase()) {
216
+ edit.color = colorInput.value + alphaSuffix(currentColor);
217
+ }
218
+ if (edit.text === undefined && edit.color === undefined) return;
219
+ applyBtn.disabled = true;
220
+ const ok = await commitQuickEdit([edit], `Updated ${item.roleLabel}.`);
221
+ if (!ok) syncDirty();
222
+ };
223
+ applyBtn.onclick = submitItem;
224
+ input.addEventListener('keydown', event => {
225
+ if (event.key === 'Enter') {
226
+ event.preventDefault();
227
+ void submitItem();
228
+ }
229
+ });
230
+
231
+ row.append(input, colorInput, applyBtn);
232
+ card.append(top, row);
233
+ if (item.hasPlaceholder) {
234
+ card.append(reviewElement('span', 'Tip: Keep {{...}} placeholders so live counters keep updating.', 'tora-qe-hint'));
235
+ }
236
+ section.append(card);
237
+ }
238
+ fragment.append(section);
239
+ }
240
+
241
+ // 2. Colors & Theme
242
+ if (qe.colors?.length) {
243
+ const section = makeSection('Colors & Theme', 'Buttons & background');
244
+ for (const item of qe.colors) {
245
+ const currentValue = typeof variant?.colors?.[item.componentId]?.[item.key] === 'string'
246
+ ? variant.colors[item.componentId][item.key]
247
+ : item.value;
248
+ const card = reviewElement('div', '', 'tora-qe-card tora-qe-color-card');
249
+ card.dataset.componentId = item.componentId;
250
+ const left = reviewElement('div', '', 'tora-qe-color-info');
251
+ left.append(reviewElement('strong', item.roleLabel), reviewElement('span', currentValue.toUpperCase(), 'tora-qe-hex'));
252
+ const right = reviewElement('div', '', 'tora-qe-color-actions');
253
+ const picker = reviewElement('input');
254
+ picker.type = 'color';
255
+ picker.className = 'tora-qe-color-swatch';
256
+ picker.value = toSixDigitHex(currentValue);
257
+ picker.setAttribute('aria-label', item.roleLabel);
258
+ const applyBtn = reviewElement('button', 'Apply', 'tora-qe-apply');
259
+ applyBtn.type = 'button';
260
+ applyBtn.disabled = true;
261
+ picker.oninput = () => {
262
+ left.lastChild.textContent = picker.value.toUpperCase();
263
+ applyBtn.disabled = picker.value.toLowerCase() === toSixDigitHex(currentValue).toLowerCase();
264
+ onHighlight?.([item.componentId]);
265
+ };
266
+ applyBtn.onclick = async () => {
267
+ applyBtn.disabled = true;
268
+ const nextValue = picker.value + alphaSuffix(currentValue);
269
+ const ok = await commitQuickEdit([{
270
+ kind: 'color',
271
+ componentId: item.componentId,
272
+ key: item.key,
273
+ value: nextValue,
274
+ syncButtonStates: Boolean(item.syncButtonStates),
275
+ }], `Updated ${item.roleLabel}.`);
276
+ if (!ok) applyBtn.disabled = picker.value.toLowerCase() === toSixDigitHex(currentValue).toLowerCase();
277
+ };
278
+ right.append(picker, applyBtn);
279
+ card.append(left, right);
280
+ section.append(card);
281
+ }
282
+ fragment.append(section);
283
+ }
284
+
285
+ // 3. Timing & Pacing
286
+ if (qe.timings?.length) {
287
+ const section = makeSection('Timing & Pacing', 'Round length');
288
+ for (const item of qe.timings) {
289
+ const currentSeconds = Number.isFinite(variant?.behaviors?.[item.behaviorId]?.seconds)
290
+ ? Number(variant.behaviors[item.behaviorId].seconds)
291
+ : Number(item.seconds);
292
+ const card = reviewElement('div', '', 'tora-qe-card');
293
+ const top = reviewElement('div', '', 'tora-qe-card-top');
294
+ const readout = reviewElement('span', `${currentSeconds}s`, 'tora-pill');
295
+ top.append(reviewElement('strong', item.roleLabel), readout);
296
+ const row = reviewElement('div', '', 'tora-qe-input-row');
297
+ const range = reviewElement('input');
298
+ range.type = 'range';
299
+ range.min = String(item.min);
300
+ range.max = String(item.max);
301
+ range.step = String(item.step);
302
+ range.value = String(currentSeconds);
303
+ range.setAttribute('aria-label', item.roleLabel);
304
+ const applyBtn = reviewElement('button', 'Apply', 'tora-qe-apply');
305
+ applyBtn.type = 'button';
306
+ applyBtn.disabled = true;
307
+ range.oninput = () => {
308
+ readout.textContent = `${range.value}s`;
309
+ applyBtn.disabled = Number(range.value) === currentSeconds;
310
+ };
311
+ applyBtn.onclick = async () => {
312
+ applyBtn.disabled = true;
313
+ const ok = await commitQuickEdit([{kind: 'timing', behaviorId: item.behaviorId, seconds: Number(range.value)}], `Set ${item.roleLabel} to ${range.value}s.`);
314
+ if (!ok) applyBtn.disabled = Number(range.value) === currentSeconds;
315
+ };
316
+ row.append(range, applyBtn);
317
+ card.append(top, row);
318
+ section.append(card);
319
+ }
320
+ fragment.append(section);
321
+ }
322
+
323
+ // 4. Images & Audio
324
+ const swappableMedia = (qe.media ?? []).filter(item => item.kind === 'image' || item.kind === 'audio');
325
+ if (swappableMedia.length) {
326
+ const section = makeSection('Images & Audio', isHosted ? 'Preview assets' : 'Click Replace to swap files');
327
+ for (const item of swappableMedia) {
328
+ const overrideAssetId = variant ? (item.componentIds?.map(cid => variant.assets?.[cid]?.assetId).find(Boolean) ?? null) : null;
329
+ const currentAssetId = overrideAssetId ?? item.assetId;
330
+ const card = reviewElement('div', '', 'tora-qe-card tora-qe-media-card');
331
+ if (item.componentIds?.length) card.dataset.componentId = item.componentIds[0];
332
+ const rawUrl = isHosted
333
+ ? getAssetDataUrl?.(currentAssetId)
334
+ : `/api/projects/${encodeURIComponent(projectId)}/assets/${encodeURIComponent(currentAssetId)}/raw`;
335
+
336
+ if (item.kind === 'image' && rawUrl) {
337
+ const thumb = reviewElement('img', '', 'tora-qe-thumb');
338
+ thumb.src = rawUrl;
339
+ thumb.alt = item.roleLabel;
340
+ card.append(thumb);
341
+ } else {
342
+ card.append(reviewElement('span', item.kind === 'audio' ? '🔊' : '🖼️', 'tora-qe-media-icon'));
343
+ }
344
+
345
+ const info = reviewElement('div', '', 'tora-qe-media-info');
346
+ info.append(
347
+ reviewElement('strong', item.roleLabel),
348
+ reviewElement('span', `${item.kind === 'audio' ? 'Audio' : 'Image'} · ${overrideAssetId ? 'Variant override' : formatBytes(item.bytes)}`),
349
+ );
350
+ card.append(info);
351
+
352
+ const actions = reviewElement('div', '', 'tora-qe-media-actions');
353
+ if (item.kind === 'audio' && rawUrl) {
354
+ const playBtn = reviewElement('button', '▶ Play', 'tora-qe-apply');
355
+ playBtn.type = 'button';
356
+ playBtn.onclick = () => {
357
+ if (activeAudioBtn === playBtn) {
358
+ stopAudio();
359
+ return;
360
+ }
361
+ stopAudio();
362
+ const player = new Audio(rawUrl);
363
+ activeAudio = player;
364
+ activeAudioBtn = playBtn;
365
+ playBtn.textContent = '■ Stop';
366
+ player.onended = () => stopAudio();
367
+ player.onerror = () => {
368
+ stopAudio();
369
+ onStatus('Could not preview this audio file.');
370
+ };
371
+ void player.play().catch(() => stopAudio());
372
+ };
373
+ actions.append(playBtn);
374
+ }
375
+ if (!isHosted) {
376
+ const picker = reviewElement('input');
377
+ picker.type = 'file';
378
+ picker.hidden = true;
379
+ picker.accept = item.kind === 'audio' ? '.wav,.mp3,.ogg,.m4a,.aac' : '.png,.jpg,.jpeg,.webp';
380
+ const replaceBtn = reviewElement('button', 'Replace', 'tora-qe-apply');
381
+ replaceBtn.type = 'button';
382
+ replaceBtn.onclick = () => picker.click();
383
+ picker.onchange = async event => {
384
+ const file = event.target.files?.[0];
385
+ event.target.value = '';
386
+ if (!file) return;
387
+ if (isCandidateActive?.()) {
388
+ onError('Choose Use this version or Discard before replacing files.');
389
+ return;
390
+ }
391
+ replaceBtn.disabled = true;
392
+ onError('');
393
+ let assetUploaded = false;
394
+ try {
395
+ const activeVar = getActiveVariant?.() ?? null;
396
+ onStatus(`Preparing ${file.name}…`);
397
+ const prepared = item.kind === 'audio'
398
+ ? await prepareAudioFile(file)
399
+ : await prepareImageFile(file, {asReference: false});
400
+ const baseId = file.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z]+/, 'asset-').slice(0, 48);
401
+ const newAssetId = `${baseId || 'asset'}-${Date.now().toString(36).slice(-4)}`;
402
+ onStatus(`Uploading & optimizing ${prepared.name}…`);
403
+ const uploaded = await api('/assets', {
404
+ expected: getMetadata().expected,
405
+ asset: {
406
+ id: newAssetId,
407
+ mime: prepared.mime,
408
+ data: prepared.data,
409
+ rights: 'Creator replaced asset directly in Tora Studio Quick Edit and confirmed commercial rights.',
410
+ },
411
+ });
412
+ assetUploaded = true;
413
+ onStatus(`Swapping ${item.roleLabel}…`);
414
+ if (activeVar) {
415
+ const nextVariant = applyEditsToVariant(activeVar, [{kind: 'replaceAsset', componentIds: item.componentIds, slotId: item.slotId, assetId: newAssetId}]);
416
+ await api('/variants', {
417
+ action: 'upsert',
418
+ variant: nextVariant,
419
+ expectedVariantRevision: getMetadata().variants?.revision,
420
+ });
421
+ } else {
422
+ await api('/quick-edit', {
423
+ expected: {revisionId: uploaded.revisionId, contentHash: uploaded.contentHash},
424
+ edits: [{kind: 'replaceAsset', componentIds: item.componentIds, slotId: item.slotId, assetId: newAssetId}],
425
+ });
426
+ }
427
+ await onUpdated();
428
+ onStatus(activeVar
429
+ ? `Replaced ${item.roleLabel} with "${prepared.name}" in ${activeVar.label}.`
430
+ : `Replaced ${item.roleLabel} with "${prepared.name}".`);
431
+ } catch (error) {
432
+ if (assetUploaded) await onUpdated().catch(() => {});
433
+ onStatus('');
434
+ onError(error);
435
+ } finally {
436
+ replaceBtn.disabled = false;
437
+ }
438
+ };
439
+ actions.append(replaceBtn, picker);
440
+ }
441
+ card.append(actions);
442
+ section.append(card);
443
+ }
444
+ fragment.append(section);
445
+ }
446
+
447
+ if (!qe.texts?.length && !qe.colors?.length && !qe.timings?.length && !swappableMedia.length) {
448
+ fragment.append(reviewElement('p', 'This project has no editable elements yet. Use your connected AI client or open a starter to add gameplay.', 'tora-qe-empty'));
449
+ }
450
+
451
+ container.replaceChildren(fragment);
452
+ }
453
+
454
+ function focusFromHit(hitIds = []) {
455
+ if (!hitIds.length) return false;
456
+ const cards = [...container.querySelectorAll('.tora-qe-card')];
457
+ for (const id of hitIds) {
458
+ const card = cards.find(el => el.dataset.componentId === id || el.dataset.parentId === id);
459
+ if (card) {
460
+ for (const el of container.querySelectorAll('.tora-qe-card[data-focused="true"]')) {
461
+ el.dataset.focused = 'false';
462
+ }
463
+ focusedComponentId = id;
464
+ card.dataset.focused = 'true';
465
+ card.scrollIntoView({behavior: 'smooth', block: 'nearest'});
466
+ const field = card.querySelector('input[type="text"], input[type="color"], input[type="range"]');
467
+ field?.focus();
468
+ return true;
469
+ }
470
+ }
471
+ return false;
472
+ }
473
+
474
+ return {
475
+ render,
476
+ focusFromHit,
477
+ destroy: stopAudio,
478
+ };
479
+ }