@office-kit/pptx-dev 0.9.1 → 0.13.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/dist/cli.mjs CHANGED
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { a as createDeckBuilder, i as initProject, n as exportDeck, r as inspectTemplate } from "./src-YH6kAXbA.mjs";
2
+ import { a as editorStore, i as initProject, n as exportDeck, o as sourceFingerprint, r as inspectTemplate, s as createDeckBuilder } from "./src-DASlwPDd.mjs";
3
+ import { n as renderDeck } from "./build-cpmt-r9Q.mjs";
3
4
  import { createRequire } from "node:module";
4
- import { chmod, lstat, mkdir, readFile, readdir, realpath, stat, unlink, writeFile } from "node:fs/promises";
5
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { chmod, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
7
  import { watch } from "node:fs";
7
- import { planTextEdit, verifyTextEdit } from "@office-kit/pptx-dsl/source-edit";
8
- import { randomBytes, randomUUID } from "node:crypto";
8
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
9
+ import { getGroupChildren, getShapeBounds, getShapeId, getShapeKind, getShapeRotation, getShapeXmlString, getSlideShapes, getSlideXmlString, getSlides, loadPresentation } from "@office-kit/pptx";
10
+ import { mergeDecks } from "@office-kit/pptx-editor/merge";
11
+ import { planPropEdit, planTextEdit, verifyTextEdit } from "@office-kit/pptx-dsl/source-edit";
9
12
  import { chromium } from "playwright";
10
13
  import { createServer } from "node:http";
11
14
  import MarkdownIt from "markdown-it";
@@ -112,10 +115,21 @@ async function createHistory(directory, notify = () => {}) {
112
115
  async function replace(change, expected, next) {
113
116
  if (!equal(await contents(change.file), expected)) throw new Error(`History conflict in ${change.file}. Newer changes were preserved.`);
114
117
  const file = join(root, change.file);
115
- if (next) {
116
- await mkdir(dirname(file), { recursive: true });
117
- await writeFile(file, next);
118
- } else await unlink(file);
118
+ if (!next) return unlink(file);
119
+ await mkdir(dirname(file), { recursive: true });
120
+ const temporary = `${file}.${randomUUID()}.tmp`;
121
+ try {
122
+ await writeFile(temporary, next, { flag: "wx" });
123
+ const mode = await lstat(file).then((info) => info.mode, (cause) => {
124
+ if (cause.code === "ENOENT") return void 0;
125
+ throw cause;
126
+ });
127
+ if (mode !== void 0) await chmod(temporary, mode & 4095);
128
+ if (!equal(await contents(change.file), expected)) throw new Error(`History conflict in ${change.file}. Newer changes were preserved.`);
129
+ await rename(temporary, file);
130
+ } finally {
131
+ await rm(temporary, { force: true });
132
+ }
119
133
  }
120
134
  try {
121
135
  record(await snapshot(), "Initial state");
@@ -194,6 +208,7 @@ const planErrors = {
194
208
  "not-found": "Text is computed or has multiple source matches. Use Apply with AI.",
195
209
  ambiguous: "Text is computed or has multiple source matches. Use Apply with AI."
196
210
  };
211
+ const message = (error) => error instanceof Error ? error.message : String(error);
197
212
  /** Literal edits are deliberately conservative: computed and ambiguous text goes to the agent. */
198
213
  function createTextEditor(entry, preview, verify) {
199
214
  let busy = false;
@@ -237,8 +252,299 @@ function createTextEditor(entry, preview, verify) {
237
252
  }).ok) throw new Error("This source affects other text or slides. Use Apply with AI for a local edit.");
238
253
  if (await realpath(change.path) !== change.path || await readFile(change.path, "utf8") !== change.after) throw new Error("Source changed during editing.");
239
254
  } catch (error) {
240
- await restore(change);
241
- await verify();
255
+ try {
256
+ await restore(change);
257
+ await verify();
258
+ } catch (cleanup) {
259
+ throw new Error(`${message(error)} ${message(cleanup)}`, { cause: error });
260
+ }
261
+ throw error;
262
+ }
263
+ } finally {
264
+ busy = false;
265
+ }
266
+ } };
267
+ }
268
+ //#endregion
269
+ //#region src/deck-diff.ts
270
+ const ANGLE_UNITS = 6e4;
271
+ function shapesById(shapes) {
272
+ const result = /* @__PURE__ */ new Map();
273
+ const visit = (shape, grouped) => {
274
+ result.set(getShapeId(shape), {
275
+ shape,
276
+ grouped
277
+ });
278
+ for (const child of getGroupChildren(shape)) visit(child, true);
279
+ };
280
+ for (const shape of shapes) visit(shape, false);
281
+ return result;
282
+ }
283
+ function withoutTransform(xml) {
284
+ return xml.replace(/(<a:xfrm\b[^>]*?) rot="-?\d+"/, "$1").replace(/<a:off x="-?\d+" y="-?\d+"\/>/, "").replace(/<a:ext cx="\d+" cy="\d+"\/>/, "");
285
+ }
286
+ function withoutShapes(xml) {
287
+ return xml.replace(/<p:spTree>[\s\S]*<\/p:spTree>/, "");
288
+ }
289
+ function geometryEdits(source, edited) {
290
+ const before = getShapeBounds(source);
291
+ const after = getShapeBounds(edited);
292
+ const edits = [];
293
+ if (before && after) {
294
+ const pairs = [
295
+ [
296
+ "x",
297
+ before.x,
298
+ after.x
299
+ ],
300
+ [
301
+ "y",
302
+ before.y,
303
+ after.y
304
+ ],
305
+ [
306
+ "width",
307
+ before.w,
308
+ after.w
309
+ ],
310
+ [
311
+ "height",
312
+ before.h,
313
+ after.h
314
+ ]
315
+ ];
316
+ for (const [prop, from, to] of pairs) if (from !== to) edits.push({
317
+ prop,
318
+ from,
319
+ to
320
+ });
321
+ }
322
+ const fromAngle = Math.round(getShapeRotation(source) * ANGLE_UNITS);
323
+ const toAngle = Math.round(getShapeRotation(edited) * ANGLE_UNITS);
324
+ if (fromAngle !== toAngle) edits.push({
325
+ prop: "rotation",
326
+ from: fromAngle,
327
+ to: toAngle
328
+ });
329
+ return edits;
330
+ }
331
+ /**
332
+ * What the editor changed relative to the deck built from source. Shapes are
333
+ * matched by slide index and shape id — the editor edits the deck the server
334
+ * built, so ids agree. A change this diff cannot state as typed props is
335
+ * reported as `unsupported`, never dropped.
336
+ */
337
+ function diffDecks(source, edited) {
338
+ const changes = [];
339
+ const sourceSlides = getSlides(source);
340
+ const editedSlides = getSlides(edited);
341
+ if (sourceSlides.length !== editedSlides.length) changes.push({
342
+ kind: "unsupported",
343
+ slide: null,
344
+ shapeId: null,
345
+ description: `slide count ${sourceSlides.length} → ${editedSlides.length}`
346
+ });
347
+ const count = Math.min(sourceSlides.length, editedSlides.length);
348
+ for (let slide = 0; slide < count; slide++) {
349
+ const sourceSlide = sourceSlides[slide];
350
+ const editedSlide = editedSlides[slide];
351
+ if (withoutShapes(getSlideXmlString(sourceSlide)) !== withoutShapes(getSlideXmlString(editedSlide))) changes.push({
352
+ kind: "unsupported",
353
+ slide,
354
+ shapeId: null,
355
+ description: "slide properties"
356
+ });
357
+ const before = shapesById(getSlideShapes(sourceSlide));
358
+ const after = shapesById(getSlideShapes(editedSlide));
359
+ for (const [shapeId, { shape, grouped }] of after) {
360
+ const original = before.get(shapeId)?.shape;
361
+ if (!original) {
362
+ changes.push({
363
+ kind: "unsupported",
364
+ slide,
365
+ shapeId,
366
+ description: "shape added"
367
+ });
368
+ continue;
369
+ }
370
+ if (getShapeKind(shape) === "group") {
371
+ if (geometryEdits(original, shape).length) changes.push({
372
+ kind: "unsupported",
373
+ slide,
374
+ shapeId,
375
+ description: "group transform"
376
+ });
377
+ continue;
378
+ }
379
+ if (withoutTransform(getShapeXmlString(original)) !== withoutTransform(getShapeXmlString(shape))) changes.push({
380
+ kind: "unsupported",
381
+ slide,
382
+ shapeId,
383
+ description: "properties other than position, size and rotation"
384
+ });
385
+ const edits = geometryEdits(original, shape);
386
+ if (edits.length && grouped) changes.push({
387
+ kind: "unsupported",
388
+ slide,
389
+ shapeId,
390
+ description: "grouped shape geometry"
391
+ });
392
+ else if (edits.length) changes.push({
393
+ kind: "geometry",
394
+ slide,
395
+ shapeId,
396
+ edits
397
+ });
398
+ }
399
+ for (const shapeId of before.keys()) if (!after.has(shapeId)) changes.push({
400
+ kind: "unsupported",
401
+ slide,
402
+ shapeId,
403
+ description: "shape removed"
404
+ });
405
+ }
406
+ return changes;
407
+ }
408
+ //#endregion
409
+ //#region src/source-sync.ts
410
+ const key = (change) => `${change.kind}:${change.slide}:${change.shapeId}:${change.kind === "unsupported" ? change.description : ""}`;
411
+ /**
412
+ * Writes the editor's changes back into the TSX source as typed prop edits.
413
+ * Every write is verified by rebuilding: the changes it claims must disappear
414
+ * from the diff and no other change may appear, or every file is restored.
415
+ */
416
+ function createSourceSync(entry, source, rebuild) {
417
+ let busy = false;
418
+ async function localFile(fileName) {
419
+ const root = await realpath(dirname(entry));
420
+ let path;
421
+ try {
422
+ path = await realpath(fileName);
423
+ } catch {
424
+ return null;
425
+ }
426
+ const local = relative(root, path);
427
+ if (local.startsWith("..") || isAbsolute(local) || local.split(/[\\/]/).includes("node_modules")) return null;
428
+ return path;
429
+ }
430
+ return { async sync(edited) {
431
+ if (busy) throw new Error("A source write-back is already running.");
432
+ busy = true;
433
+ try {
434
+ const built = source();
435
+ if (!built?.shapeSources) throw new Error("The source deck is not built yet.");
436
+ const shapeSources = built.shapeSources;
437
+ const editedDeck = await loadPresentation(edited);
438
+ const changes = diffDecks(await loadPresentation(built.bytes), editedDeck);
439
+ const uses = /* @__PURE__ */ new Map();
440
+ for (const bySlide of Object.values(shapeSources)) for (const chain of Object.values(bySlide)) {
441
+ const at = chain.at(-1);
442
+ if (at) {
443
+ const id = `${at.fileName}:${at.lineNumber}:${at.columnNumber}`;
444
+ uses.set(id, (uses.get(id) ?? 0) + 1);
445
+ }
446
+ }
447
+ const pending = [];
448
+ const targets = [];
449
+ for (const change of changes) {
450
+ if (change.kind !== "geometry") {
451
+ pending.push(change);
452
+ continue;
453
+ }
454
+ const anchor = shapeSources[change.slide]?.[change.shapeId]?.at(-1);
455
+ if (!anchor) {
456
+ pending.push({
457
+ ...change,
458
+ reason: "no source element"
459
+ });
460
+ continue;
461
+ }
462
+ if ((uses.get(`${anchor.fileName}:${anchor.lineNumber}:${anchor.columnNumber}`) ?? 0) > 1) {
463
+ pending.push({
464
+ ...change,
465
+ reason: "element makes several shapes"
466
+ });
467
+ continue;
468
+ }
469
+ targets.push({
470
+ change,
471
+ anchor
472
+ });
473
+ }
474
+ const byFile = /* @__PURE__ */ new Map();
475
+ for (const target of targets) {
476
+ const path = await localFile(target.anchor.fileName);
477
+ if (!path) {
478
+ pending.push({
479
+ ...target.change,
480
+ reason: "source outside the project"
481
+ });
482
+ continue;
483
+ }
484
+ byFile.set(path, [...byFile.get(path) ?? [], target]);
485
+ }
486
+ const files = [];
487
+ const written = [];
488
+ for (const [path, fileTargets] of byFile) {
489
+ const before = await readFile(path, "utf8");
490
+ let text = before;
491
+ fileTargets.sort((a, b) => b.anchor.lineNumber - a.anchor.lineNumber || b.anchor.columnNumber - a.anchor.columnNumber);
492
+ for (const { change, anchor } of fileTargets) {
493
+ const plan = planPropEdit({
494
+ file: {
495
+ path,
496
+ source: text
497
+ },
498
+ anchor: {
499
+ path,
500
+ lineNumber: anchor.lineNumber,
501
+ columnNumber: anchor.columnNumber
502
+ },
503
+ edits: change.edits
504
+ });
505
+ if (!plan.ok) {
506
+ pending.push({
507
+ ...change,
508
+ reason: plan.reason
509
+ });
510
+ continue;
511
+ }
512
+ text = plan.change.after;
513
+ written.push(change);
514
+ }
515
+ if (text !== before) files.push({
516
+ path,
517
+ before,
518
+ after: text
519
+ });
520
+ }
521
+ if (files.length === 0) return {
522
+ written: [],
523
+ pending,
524
+ complete: false
525
+ };
526
+ const restore = async () => {
527
+ for (const file of files) if (await readFile(file.path, "utf8") !== file.after) throw new Error("Source changed during write-back. Your newer changes were preserved.");
528
+ for (const file of files) await writeFile(file.path, file.before);
529
+ await rebuild();
530
+ };
531
+ for (const file of files) if (await readFile(file.path, "utf8") !== file.before) throw new Error("Source changed. Save again.");
532
+ for (const file of files) await writeFile(file.path, file.after);
533
+ try {
534
+ const error = await rebuild();
535
+ if (error) throw new Error("The written source did not build: " + error);
536
+ const rebuilt = source();
537
+ if (!rebuilt) throw new Error("The written source did not build.");
538
+ const remaining = diffDecks(await loadPresentation(rebuilt.bytes), editedDeck);
539
+ const expected = new Set(pending.map(key));
540
+ if (remaining.some((change) => !expected.has(key(change)))) throw new Error("The written source changed more than the edited shapes.");
541
+ return {
542
+ written,
543
+ pending,
544
+ complete: remaining.length === 0 && sourceFingerprint(rebuilt.bytes) === sourceFingerprint(edited)
545
+ };
546
+ } catch (error) {
547
+ await restore();
242
548
  throw error;
243
549
  }
244
550
  } finally {
@@ -316,93 +622,578 @@ function createVisualReviewer(entry, slides) {
316
622
  };
317
623
  }
318
624
  //#endregion
625
+ //#region src/preview-i18n.ts
626
+ /** Labels for the preview shell; the editor sends its active locale via editor-focus. */
627
+ const previewI18nScript = `
628
+ let previewLocale=navigator.language?.toLowerCase().startsWith('ja')?'ja':'en';
629
+ try{const stored=localStorage.getItem('ok-editor-locale');if(stored==='ja'||stored==='en')previewLocale=stored;}catch{}
630
+ let connectionLost=false;
631
+ const previewJapanese={
632
+ 'Normal':'標準','Normal (Esc)':'標準 (Esc)','Agents':'エージェント','Close Agents':'エージェントを閉じる','Presentation views':'プレゼンテーションの表示','Present':'プレゼンテーション','Presenter view':'発表者ビュー',
633
+ 'Download PPTX':'PPTXをダウンロード','Slides':'スライド','Slide viewer':'スライドビューアー','Presentation editor':'プレゼンテーション編集',
634
+ 'Chat width':'チャットの幅','Drag to resize · Double-click to reset':'ドラッグで幅を変更・ダブルクリックでリセット',
635
+ 'Previous slide':'前のスライド','Next slide':'次のスライド','Zoom':'ズーム','Fit':'画面に合わせる',
636
+ 'Exit · Esc':'終了 · Esc','Exit view · Esc':'表示を終了 · Esc','Slide position':'スライドの位置','No slides':'スライドがありません','Whole project':'プロジェクト全体',
637
+ 'Waiting for slides…':'スライドを待っています…','Building…':'ビルド中…','Updating…':'更新中…','Reconnecting…':'再接続中…',
638
+ 'Build failed · showing last successful output':'ビルドに失敗しました・最後に成功した結果を表示中',
639
+ 'Changes appear automatically · Text can be selected and copied':'変更は自動的に反映されます・文字を選択してコピーできます',
640
+ 'Skipped during presentation':'プレゼンテーションでスキップされます',
641
+ 'Allow popups to open presenter view.':'発表者ビューを開くにはポップアップを許可してください。',
642
+ 'Presentation preview':'プレゼンテーションのプレビュー'
643
+ };
644
+ const pt=key=>previewLocale==='ja'?(previewJapanese[key]??key):key;
645
+ const slideLabel=i=>previewLocale==='ja'?'スライド '+(i+1):'Slide '+(i+1);
646
+ const slideCount=()=>!state.slides.length?pt('No slides'):previewLocale==='ja'?'スライド '+(index+1)+' / '+state.slides.length:'Slide '+(index+1)+' of '+state.slides.length;
647
+ function updatePreviewStatus(){
648
+ byId('status').textContent=connectionLost?pt('Reconnecting…'):state.error?pt('Build failed · showing last successful output'):state.building?pt('Updating…'):previewLocale==='ja'?state.slides.length+' スライド・ライブ':state.slides.length+' slides · Live';
649
+ }
650
+ function updatePreviewLabels(){
651
+ document.documentElement.lang=previewLocale;document.title=pt('Presentation preview');
652
+ const labels={'#present':'Present','#presenter':'Presenter view','.download':'Download PPTX','#toggle-chat span':'Agents','#agents-title':'Agents','.filmstrip h2':'Slides','#empty':'Waiting for slides…','footer .hint':'Changes appear automatically · Text can be selected and copied','label[for="zoom"]':'Zoom','#zoom option[value="fit"]':'Fit'};
653
+ for(const [selector,key] of Object.entries(labels))document.querySelector(selector).textContent=pt(key);
654
+ for(const [selector,key] of Object.entries({'.filmstrip':'Slides','main':'Slide viewer','#chat-resizer':'Chat width','#close-chat':'Close Agents','#toggle-editor':'Normal','.status-views':'Presentation views','#prev':'Previous slide','#present-prev':'Previous slide','#next':'Next slide','#present-next':'Next slide'}))document.querySelector(selector).setAttribute('aria-label',pt(key));
655
+ byId('editor-frame').title=pt('Presentation editor');byId('chat-resizer').title=pt('Drag to resize · Double-click to reset');
656
+ byId('exit-present').textContent=pt('Exit · Esc');
657
+ byId('close-chat').title=pt('Close Agents');byId('toggle-editor').title=pt('Normal (Esc)');
658
+ byId('count').textContent=slideCount();byId('present-count').textContent=slideCount();
659
+ updateAnimationNotice();
660
+ slide.setAttribute('aria-label',slideLabel(index));
661
+ for(const [i,item] of Array.from(thumbnails.children).entries()){
662
+ item.firstElementChild.setAttribute('aria-label',slideLabel(i));
663
+ item.firstElementChild.title=state.hiddenSlides?.[i]?pt('Skipped during presentation'):'';
664
+ }
665
+ updateChatWidthAria();updatePreviewStatus();
666
+ }
667
+ `;
668
+ //#endregion
669
+ //#region src/transition-script.ts
670
+ /** Presentation-only visual transitions. All layers stay inside the clipped slide. */
671
+ const transitionScript = `
672
+ let transitionAnimations=[],transitionCleanup;
673
+ const reducedMotion=matchMedia('(prefers-reduced-motion: reduce)');
674
+ function cancelTransition(){
675
+ const cleanup=transitionCleanup;transitionCleanup=undefined;
676
+ for(const animation of transitionAnimations)animation.cancel();
677
+ transitionAnimations=[];cleanup?.();
678
+ }
679
+ reducedMotion.addEventListener('change',()=>{if(reducedMotion.matches){cancelTransition();scheduleAdvance();}});
680
+ function renderSlide(svg,options){
681
+ const previous=displayedSvg;
682
+ cancelTransition();
683
+ // What the viewer last saw, not the drawing the slide started as: leaving a
684
+ // slide part-way through its build must not flash the effects still to come.
685
+ const previousMarkup=canvas.innerHTML;
686
+ displayedSvg=svg;
687
+ const style='<style>svg{display:block;width:100%;height:100%}.transition-layer{position:absolute;inset:0;background:white;overflow:hidden}.transition-old{pointer-events:none}</style>';
688
+ canvas.innerHTML=svg?style+svg:'';
689
+ const playableEffects=['fade','push','wipe','cover','pull','zoom','split','circle','diamond','plus','blinds','comb','checker','strips','randomBar','dissolve','wedge','newsflash','wheel'];
690
+ // The reference desktop app (2010+) effects (p14 / p15 / p159) play as the nearest flat
691
+ // effect above: their 3-D turns, particles and page curls are not drawn.
692
+ const approximations={morph:'fade',flash:'fade',reveal:'fade',prstTrans:'fade',honeycomb:'dissolve',glitter:'dissolve',vortex:'dissolve',shred:'dissolve',ripple:'circle',switch:'push',flip:'push',gallery:'push',conveyor:'push',ferris:'push',pan:'push',prism:'push',doors:'split',window:'split',warp:'zoom',flythrough:'zoom',wheelReverse:'wheel'};
693
+ const alias=Object.hasOwn(approximations,options?.effect??'')?approximations[options.effect]:undefined;
694
+ if(alias)options=alias==='split'
695
+ ?{...options,effect:alias,orientation:options.direction==='horz'?'horz':'vert',direction:'out'}
696
+ :{...options,effect:alias};
697
+ // Choose per visit without replacing the persisted random transition or its timing.
698
+ const effect=options?.effect==='random'?playableEffects[Math.floor(Math.random()*playableEffects.length)]:options?.effect;
699
+ if(!previous||!svg||reducedMotion.matches||(effect==='cut'&&!options.thruBlack)||!(effect==='cut'||playableEffects.includes(effect)))return;
700
+ const incoming=document.createElement('div'),outgoing=document.createElement('div');
701
+ incoming.className='transition-layer';incoming.innerHTML=svg;
702
+ outgoing.className='transition-layer transition-old';outgoing.innerHTML=previousMarkup;
703
+ outgoing.setAttribute('aria-hidden','true');outgoing.inert=true;
704
+ canvas.innerHTML=style;canvas.append(outgoing,incoming);
705
+ // The reference desktop app plays fast/med/slow as 0.5/0.75/1 s; p14:dur overrides them.
706
+ // No spd is the schema default, fast.
707
+ const duration=options.durationMs??(options.speed==='slow'?1000:options.speed==='med'?750:500);
708
+ const timing={duration,easing:'ease-in-out',fill:'both'};
709
+ const animate=(node,frames,easing=timing.easing)=>transitionAnimations.push(node.animate(frames,{...timing,easing}));
710
+ const vectors={l:[-100,0],r:[100,0],u:[0,-100],d:[0,100],lu:[-100,-100],ru:[100,-100],ld:[-100,100],rd:[100,100]};
711
+ const [x,y]=vectors[options.direction]??vectors.l;
712
+ const shift=(a,b)=>'translate('+a+'%,'+b+'%)';
713
+ if(effect==='cut'){
714
+ slide.style.background='black';outgoing.style.visibility='hidden';
715
+ animate(incoming,[{opacity:0},{opacity:1}],'steps(1,end)');
716
+ }else if(effect==='fade'){
717
+ if(options.thruBlack){
718
+ outgoing.style.background='black';incoming.style.background='black';slide.style.background='black';
719
+ animate(outgoing,[{opacity:1,offset:0},{opacity:0,offset:.5},{opacity:0,offset:1}]);
720
+ animate(incoming,[{opacity:0,offset:0},{opacity:0,offset:.5},{opacity:1,offset:1}]);
721
+ }else animate(incoming,[{opacity:0},{opacity:1}]);
722
+ }else if(effect==='push'||effect==='cover'){
723
+ animate(incoming,[{transform:shift(-x,-y)},{transform:shift(0,0)}]);
724
+ if(effect==='push')animate(outgoing,[{transform:shift(0,0)},{transform:shift(x,y)}]);
725
+ }else if(effect==='pull'){
726
+ canvas.append(outgoing);
727
+ animate(outgoing,[{transform:shift(0,0)},{transform:shift(x,y)}]);
728
+ }else if(effect==='wipe'){
729
+ const clips={l:'inset(0 0 0 100%)',r:'inset(0 100% 0 0)',u:'inset(100% 0 0 0)',d:'inset(0 0 100% 0)'};
730
+ animate(incoming,[{clipPath:clips[options.direction]??clips.l},{clipPath:'inset(0 0 0 0)'}]);
731
+ }else if(effect==='blinds'||effect==='comb'){
732
+ const vertical=options.direction==='vert';
733
+ const bands=(progress)=>{
734
+ const points=[];
735
+ for(let band=0;band<8;band++){
736
+ const start=band*12.5,end=start+12.5;
737
+ const left=effect==='comb'&&band%2?100*(1-progress):0;
738
+ const right=effect==='comb'&&band%2?100:100*progress;
739
+ const rect=effect==='blinds'
740
+ ?[[start,0],[start+12.5*progress,0],[start+12.5*progress,100],[start,100]]
741
+ :[[left,start],[right,start],[right,end],[left,end]];
742
+ // Return along the same bridge so disconnected bands share one clip polygon.
743
+ points.push([0,0],...rect,rect[0],[0,0]);
744
+ }
745
+ return 'polygon('+points.map(([x,y])=>vertical?y+'% '+x+'%':x+'% '+y+'%').join(',')+')';
746
+ };
747
+ animate(incoming,[{clipPath:bands(0)},{clipPath:bands(1)}]);
748
+ }else if(effect==='checker'){
749
+ const cells=(progress)=>{
750
+ const points=[];
751
+ for(let row=0;row<6;row++)for(let col=0;col<8;col++){
752
+ const amount=Math.max(0,Math.min(1,2*progress-(row+col)%2));
753
+ const left=col*100/8,top=row*100/6;
754
+ const right=(col+(options.direction==='vert'?1:amount))*100/8;
755
+ const bottom=(row+(options.direction==='vert'?amount:1))*100/6;
756
+ // Keep zero-area bridges on cell boundaries to avoid diagonal antialiasing artifacts.
757
+ points.push([0,0],[left,0],[left,top],[right,top],[right,bottom],[left,bottom],[left,top],[left,0],[0,0]);
758
+ }
759
+ return 'polygon('+points.map(([x,y])=>x+'% '+y+'%').join(',')+')';
760
+ };
761
+ animate(incoming,[{clipPath:cells(0)},{clipPath:cells(.5)},{clipPath:cells(1)}]);
762
+ }else if(effect==='newsflash'){
763
+ animate(incoming,[{transform:'rotate(720deg) scale(0)'},{transform:'rotate(0deg) scale(1)'}]);
764
+ }else if(effect==='wheel'){
765
+ const spokes=options.spokes??4;
766
+ if(spokes===0)animate(incoming,[{opacity:0},{opacity:1}]);
767
+ else{
768
+ const stages=64,sector=360/spokes;
769
+ // A repeating mask keeps memory bounded even for the schema's maximum unsigned integer.
770
+ const mask=(progress)=>'repeating-conic-gradient(#000 0deg '+sector*progress+'deg,transparent '+sector*progress+'deg '+sector+'deg)';
771
+ // Gradient images are discrete values; explicit stages avoid a halfway-only image swap.
772
+ animate(incoming,Array.from({length:stages+1},(_,step)=>({maskImage:mask(step/stages),offset:step/stages,easing:'steps(1,end)'})),'linear');
773
+ }
774
+ }else if(effect==='wedge'){
775
+ const segments=32;
776
+ const wedge=(progress)=>{
777
+ const points=['50% 50%'];
778
+ for(let point=0;point<=segments;point++){
779
+ const angle=-Math.PI/2+Math.PI*progress*(2*point/segments-1);
780
+ points.push((50+100*Math.cos(angle))+'% '+(50+100*Math.sin(angle))+'%');
781
+ }
782
+ return 'polygon('+points.join(',')+')';
783
+ };
784
+ // Intermediate angles keep the radial boundaries rotating instead of shrinking across the slide.
785
+ animate(incoming,Array.from({length:segments+1},(_,step)=>({clipPath:wedge(step/segments),offset:step/segments})));
786
+ }else if(effect==='dissolve'){
787
+ const columns=32,stages=16,bounds=incoming.getBoundingClientRect();
788
+ const rows=Math.max(1,Math.round(columns*bounds.height/bounds.width)),count=columns*rows;
789
+ const order=Array.from({length:count},(_,i)=>i);
790
+ for(let i=count-1;i>0;i--){
791
+ const j=Math.floor(Math.random()*(i+1));
792
+ [order[i],order[j]]=[order[j],order[i]];
793
+ }
794
+ const cells=(step)=>{
795
+ const points=['0% 0%'];
796
+ for(let i=0;i<Math.floor(count*step/stages);i++){
797
+ const cell=order[i],col=cell%columns,row=Math.floor(cell/columns);
798
+ const left=100*col/columns,right=100*(col+1)/columns,top=100*row/rows,bottom=100*(row+1)/rows;
799
+ // Retrace bridges along cell boundaries to avoid diagonal clipping artifacts.
800
+ for(const [x,y] of [[left,0],[left,top],[right,top],[right,bottom],[left,bottom],[left,top],[left,0],[0,0]])
801
+ points.push(x+'% '+y+'%');
802
+ }
803
+ return step===0?'polygon(0% 0%,0% 0%,0% 0%)':'polygon('+points.join(',')+')';
804
+ };
805
+ // Discrete masks add whole squares instead of morphing unrelated polygon vertices.
806
+ animate(incoming,Array.from({length:stages+1},(_,step)=>({clipPath:cells(step),offset:step/stages,easing:'steps(1,end)'})),'linear');
807
+ }else if(effect==='randomBar'){
808
+ const bands=16,vertical=options.direction==='vert';
809
+ const ranks=Array.from({length:bands},(_,i)=>i);
810
+ for(let i=bands-1;i>0;i--){
811
+ const j=Math.floor(Math.random()*(i+1));
812
+ [ranks[i],ranks[j]]=[ranks[j],ranks[i]];
813
+ }
814
+ const bars=(step)=>{
815
+ const points=[];
816
+ for(let band=0;band<bands;band++){
817
+ const top=100*band/bands,bottom=top+100/bands*Math.max(0,Math.min(1,step-ranks[band]));
818
+ // Retrace the edge bridge so disconnected bars do not clip diagonal slivers.
819
+ for(const [x,y] of [[0,0],[0,top],[100,top],[100,bottom],[0,bottom],[0,top],[0,0]])
820
+ points.push((vertical?y:x)+'% '+(vertical?x:y)+'%');
821
+ }
822
+ return 'polygon('+points.join(',')+')';
823
+ };
824
+ animate(incoming,Array.from({length:bands+1},(_,step)=>({clipPath:bars(step),offset:step/bands})));
825
+ }else if(effect==='strips'){
826
+ const direction=options.direction??'lu';
827
+ const strips=(progress)=>{
828
+ const points=[];
829
+ for(let band=0;band<8;band++){
830
+ const top=band*12.5,bottom=(band+1)*12.5;
831
+ const right=100*Math.max(0,Math.min(1,(15*progress-band)/8));
832
+ points.push([0,0],[0,top],[right,top],[right,bottom],[0,bottom],[0,top],[0,0]);
833
+ }
834
+ return 'polygon('+points.map(([x,y])=>(direction.startsWith('l')?100-x:x)+'% '+(direction.endsWith('u')?100-y:y)+'%').join(',')+')';
835
+ };
836
+ // Include every band's start/end so interpolation preserves the staggered wipe.
837
+ animate(incoming,Array.from({length:16},(_,step)=>({clipPath:strips(step/15),offset:step/15})));
838
+ }else if(effect==='split'){
839
+ const collapsed=options.orientation==='vert'?'inset(0 50%)':'inset(50% 0)';
840
+ const expanded='inset(0 0)';
841
+ if(options.direction==='in'){
842
+ canvas.append(outgoing);
843
+ animate(outgoing,[{clipPath:expanded},{clipPath:collapsed}]);
844
+ }else animate(incoming,[{clipPath:collapsed},{clipPath:expanded}]);
845
+ }else if(effect==='circle'){
846
+ animate(incoming,[{clipPath:'circle(0% at 50% 50%)'},{clipPath:'circle(100% at 50% 50%)'}]);
847
+ }else if(effect==='diamond'){
848
+ animate(incoming,[{clipPath:'polygon(50% 50%,50% 50%,50% 50%,50% 50%)'},{clipPath:'polygon(50% -50%,150% 50%,50% 150%,-50% 50%)'}]);
849
+ }else if(effect==='plus'){
850
+ const cross=(low,high)=>'polygon('+low+'% 0%,'+high+'% 0%,'+high+'% '+low+'%,100% '+low+'%,100% '+high+'%,'+high+'% '+high+'%,'+high+'% 100%,'+low+'% 100%,'+low+'% '+high+'%,0% '+high+'%,0% '+low+'%,'+low+'% '+low+'%)';
851
+ animate(incoming,[{clipPath:cross(50,50)},{clipPath:cross(0,100)}]);
852
+ }else if(effect==='zoom'){
853
+ animate(incoming,[{transform:options.direction==='out'?'scale(2)':'scale(0.1)',opacity:0},{transform:'scale(1)',opacity:1}]);
854
+ }
855
+ clearTimeout(advanceTimer);advanceKey=null;
856
+ const cleanup=()=>{
857
+ outgoing.remove();
858
+ // The incoming layer keeps its own nodes rather than being re-parsed into
859
+ // the canvas: the slide's build may already be running on them — a leading
860
+ // 'with previous' effect starts as the slide appears — and new nodes would
861
+ // lose both the animation and what it was hiding. Dropping the class is
862
+ // enough to leave no transition layer behind.
863
+ incoming.className='';incoming.style.cssText='position:absolute;inset:0';
864
+ slide.style.background='';
865
+ };
866
+ transitionCleanup=cleanup;
867
+ Promise.all(transitionAnimations.map(animation=>animation.finished)).then(()=>{
868
+ if(transitionCleanup!==cleanup)return;
869
+ cancelTransition();scheduleAdvance();
870
+ },()=>{});
871
+ }
872
+ `;
873
+ //#endregion
319
874
  //#region src/styles.ts
320
- const previewStyles = `*{box-sizing:border-box}
321
- body{margin:0;height:100dvh;overflow:hidden;background:#e9eaf4;color:#dce1f1;font:13px system-ui;display:grid;grid-template-rows:60px minmax(0,1fr) 42px}
322
- button,a,select{font:inherit;color:inherit}button,select,.download{border:1px solid #30364d;border-radius:9px;background:#191e30;padding:7px 12px;text-decoration:none;cursor:pointer}
323
- button:hover:not(:disabled),.download:hover{background:#292f48}button:disabled{opacity:.4;cursor:default}
324
- :focus-visible{outline:2px solid #9b87ff;outline-offset:3px}
325
- header{display:flex;align-items:center;gap:16px;padding:0 20px;background:linear-gradient(110deg,#171b2f,#211c38 60%,#171b2f);border-bottom:1px solid #38304d;min-width:0}
326
- .brand{font-weight:700;font-size:17px;white-space:nowrap}.badge{font-size:11px;color:#b2a4fb;background:#342c54;border-radius:4px;padding:3px 6px}
327
- #status{flex:1;color:#9ba5be;min-width:0}#present{background:#7154e8;color:#191e30;border-color:#7154e8}
875
+ const tokenStyles = `:root{
876
+ --ok-accent:#b4235a;--ok-accent-2:#d6336c;--ok-bg:#f4f5f7;--ok-panel:#ffffff;--ok-panel-2:#f9fafb;--ok-ribbon:#f7f8fa;--ok-ribbon-active:#ffffff;
877
+ --ok-border:#dfe2e7;--ok-border-strong:#c9cdd6;--ok-text:#15171c;--ok-text-2:#545b69;--ok-text-3:#8a909c;--ok-hover:#eef0f3;--ok-selected:#fdebf1;--ok-selected-border:#b4235a;
878
+ --ok-canvas-bg:#d3d6dc;--ok-danger:#c92a2a;--ok-radius:3px;--ok-radius-lg:6px;
879
+ --ok-shadow:0 1px 2px rgba(16, 18, 23, 0.08), 0 0 0 1px rgba(16, 18, 23, 0.04);--ok-shadow-lg:0 12px 32px -8px rgba(16, 18, 23, 0.22), 0 2px 6px rgba(16, 18, 23, 0.08);
880
+ --ok-font:system-ui, -apple-system, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;--ok-mono:ui-monospace, 'SF Mono', 'Cascadia Code', 'Consolas', monospace;
881
+ --shell-alert-bg:#fff0cd;--shell-alert-text:#583b00;
882
+ color-scheme:light;
883
+ }
884
+ @media (prefers-color-scheme: dark){:root{
885
+ color-scheme:dark;
886
+ --ok-accent:#e85a90;--ok-accent-2:#ff9cbf;--ok-bg:#1f1f1f;--ok-panel:#2b2b2b;--ok-panel-2:#252525;--ok-ribbon:#2a2a2a;--ok-ribbon-active:#333333;
887
+ --ok-border:#3d3d3d;--ok-border-strong:#555555;--ok-text:#f0f0f0;--ok-text-2:#c4c4c4;--ok-text-3:#8f8f8f;--ok-hover:#3a3a3a;--ok-selected:#3a2230;--ok-selected-border:#ff7aa8;
888
+ --ok-canvas-bg:#1b1b1b;--ok-danger:#f1707a;
889
+ --ok-shadow:0 1px 2px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(255, 255, 255, 0.04);--ok-shadow-lg:0 12px 32px -8px rgba(0, 0, 0, 0.6), 0 2px 6px rgba(0, 0, 0, 0.35);
890
+ --shell-alert-bg:#4a3a12;--shell-alert-text:#ffe2a3;
891
+ }}
892
+ *{box-sizing:border-box}
893
+ body{margin:0;background:var(--ok-bg);color:var(--ok-text);font:13px var(--ok-font);-webkit-font-smoothing:antialiased}
894
+ button,a,select,textarea{font:inherit;color:inherit}
895
+ button,select,.download{border:1px solid transparent;border-radius:var(--ok-radius);background:transparent;padding:3px 8px;text-decoration:none;cursor:pointer;white-space:nowrap}
896
+ button:hover:not(:disabled),.download:hover{background:var(--ok-hover);border-color:var(--ok-border)}
897
+ button:active:not(:disabled){background:var(--ok-selected)}
898
+ button[aria-pressed="true"]{background:var(--ok-selected);border-color:var(--ok-selected-border)}
899
+ button:disabled{color:var(--ok-text-3);cursor:default}
900
+ select{border-color:var(--ok-border-strong);background:var(--ok-panel);padding:2px 6px}
901
+ select:hover:not(:disabled){border-color:var(--ok-border-strong)}
902
+ :focus-visible{outline:2px solid var(--ok-selected-border);outline-offset:1px}
903
+ .primary{background:var(--ok-accent);border-color:var(--ok-accent);color:#fff}
904
+ .primary:hover:not(:disabled){background:var(--ok-accent-2);border-color:var(--ok-accent-2)}
905
+ .primary:disabled{background:var(--ok-hover);border-color:var(--ok-border);color:var(--ok-text-3)}
906
+ [hidden]{display:none!important}
907
+ @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
908
+ `;
909
+ const previewStyles = `${tokenStyles}
910
+ body{height:100dvh;overflow:hidden;display:grid;grid-template-rows:minmax(0,1fr) 26px}
328
911
  .workspace{--filmstrip-width:190px;--chat-width:38vw;display:grid;grid-template-columns:var(--filmstrip-width) minmax(0,1fr) clamp(280px,var(--chat-width),calc(100vw - var(--filmstrip-width) - 240px));min-height:0}
329
- .filmstrip{background:#111625;border-right:1px solid #30364d;overflow:auto;overscroll-behavior:contain;padding:16px 12px}
330
- .filmstrip h2{margin:0 0 12px 26px;text-transform:uppercase;letter-spacing:.1em;font-size:10px;color:#8490ac;font-weight:600}
331
- #thumbnails{display:flex;flex-direction:column;gap:12px;margin:0;padding:0;list-style:none}
332
- .thumbnail{display:flex;align-items:flex-start;gap:8px;width:100%;padding:4px 3px;border:0;background:transparent;border-radius:5px;text-align:left}
333
- .slide-number{width:18px;flex:none;text-align:right;font-size:11px;color:#8995b0;padding-top:5px}
334
- .thumbnail img{display:block;min-width:0;width:calc(100% - 26px);background:white;box-shadow:0 1px 4px #080b1933;border:2px solid transparent;border-radius:3px;aspect-ratio:var(--slide-ratio,16/9);object-fit:contain}
335
- .thumbnail[aria-current="true"]{background:#31274e}.thumbnail[aria-current="true"] img{border-color:#9b87ff}.thumbnail[aria-current="true"] .slide-number{color:#b6a5ff;font-weight:700}
912
+ .filmstrip{background:var(--ok-panel-2);border-right:1px solid var(--ok-border);overflow:auto;overscroll-behavior:contain;padding:8px}
913
+ .filmstrip h2{margin:4px 0 8px 26px;font-size:11px;font-weight:600;color:var(--ok-text-2)}
914
+ #thumbnails{display:flex;flex-direction:column;gap:6px;margin:0;padding:0;list-style:none}
915
+ .thumbnail{display:flex;align-items:flex-start;gap:6px;width:100%;padding:6px 6px 8px 4px;border:0;background:transparent;border-radius:0;text-align:left}
916
+ .thumbnail:hover:not(:disabled){background:transparent;border-color:transparent}
917
+ .slide-number{width:16px;flex:none;text-align:right;font-size:11px;color:var(--ok-text-2);padding-top:2px}
918
+ .thumbnail img{display:block;min-width:0;width:calc(100% - 22px);background:white;border:1px solid var(--ok-border);border-radius:4px;aspect-ratio:var(--slide-ratio,16/9);object-fit:contain}
919
+ .thumbnail:hover img{outline:3px solid var(--ok-border-strong);outline-offset:2px}
920
+ .thumbnail[aria-current="true"] img{outline:3px solid var(--ok-accent);outline-offset:2px}.thumbnail[aria-current="true"] .slide-number{color:var(--ok-accent);font-weight:600}
921
+ .thumbnail[data-skipped="true"] .slide-number{text-decoration:line-through}
922
+ .thumbnail[data-skipped="true"] img{opacity:.6}
336
923
  main{min-width:0;min-height:0;display:flex;flex-direction:column}
337
- #error{flex:none;max-height:30%;overflow:auto;background:#fff0ef;color:#922e25;margin:0;padding:16px 20px;white-space:pre-wrap;border-bottom:1px solid #e8bbb7}
338
- #error[hidden]{display:none}
339
- #stage{background:radial-gradient(ellipse at 20% 15%,#ddd8f6aa,transparent 65%),radial-gradient(#a0a4bf33 1px,transparent 1px),#edeef6;background-size:auto,18px 18px,auto;flex:1;min-height:0;overflow:auto;display:flex;padding:32px;overscroll-behavior:contain}
340
- #slide{position:relative;flex:none;margin:auto;background:white;box-shadow:0 20px 70px #28234825,0 2px 8px #28234815;overflow:hidden}
341
- #slide{user-select:text;-webkit-user-select:text}
342
- #empty{margin:auto;color:#8995b0}
343
- footer{display:flex;align-items:center;gap:14px;padding:0 16px;background:#191e30;border-top:1px solid #30364d;font-size:12px}
344
- #count{min-width:90px}footer .hint{flex:1;color:#8995b0}footer button{padding:3px 10px}footer select{padding:3px 8px}
924
+ #error{flex:none;max-height:30%;overflow:auto;background:var(--shell-alert-bg);color:var(--shell-alert-text);margin:0;padding:8px 12px;font:12px var(--ok-mono);white-space:pre-wrap;border-bottom:1px solid var(--ok-border)}
925
+ #stage{background:var(--ok-canvas-bg);flex:1;min-height:0;overflow:auto;display:flex;padding:32px;overscroll-behavior:contain}
926
+ #slide{position:relative;flex:none;margin:auto;background:white;box-shadow:var(--ok-shadow-lg);overflow:hidden;user-select:text;-webkit-user-select:text}
927
+ #empty{margin:auto;color:var(--ok-text-2)}
928
+ footer{display:flex;align-items:center;gap:6px;padding:0 12px;background:var(--ok-ribbon);border-top:1px solid var(--ok-border);color:var(--ok-text-2);font-size:11px;min-width:0;white-space:nowrap}
929
+ footer button,footer .download,footer select{font-size:11px;padding:1px 6px;line-height:16px}
930
+ footer .hint{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;color:var(--ok-text-3)}
931
+ #status{min-width:0;overflow:hidden;text-overflow:ellipsis}
932
+ .status-views{display:flex;gap:2px}
933
+ footer svg{display:block;fill:none;stroke:currentColor;stroke-width:1.1}
934
+ #toggle-editor{padding:2px 6px}
935
+ #toggle-chat svg{width:13px;height:13px}#toggle-chat[aria-pressed="true"] svg{fill:var(--ok-accent);stroke:var(--ok-accent)}#toggle-chat{display:inline-flex;align-items:center;gap:4px}
936
+ #notice{position:fixed;z-index:40;left:50%;bottom:36px;transform:translateX(-50%);max-width:min(480px,calc(100vw - 32px));padding:8px 12px;border:1px solid var(--ok-border);border-radius:var(--ok-radius-lg);background:var(--ok-panel);color:var(--ok-text);box-shadow:var(--ok-shadow-lg);font-size:12px}
345
937
  #presentation-controls{display:none}
346
938
  body.presenting{grid-template-rows:minmax(0,1fr);background:#111}
347
- .presenting header,.presenting footer,.presenting .filmstrip,.presenting #chat{display:none}
939
+ .presenting footer,.presenting .filmstrip,.presenting #chat{display:none}
348
940
  .presenting .workspace{grid-template-columns:minmax(0,1fr)}.presenting #stage{padding:0;background:#111}.presenting #slide{box-shadow:none}
349
941
  .presenting #presentation-controls{display:flex;position:fixed;bottom:16px;left:50%;transform:translateX(-50%);align-items:center;gap:12px;background:#202735e8;color:white;padding:6px;border-radius:8px;opacity:0;transition:opacity .15s}
350
942
  .presenting #presentation-controls:hover,.presenting #presentation-controls:focus-within{opacity:1}
351
- #presentation-controls button{background:transparent;color:white;border-color:#5d6575}
352
- @media(max-width:700px){.workspace{grid-template-columns:140px minmax(0,1fr)}.filmstrip{padding:12px 5px}header{padding:0 12px;gap:10px}.badge,footer .hint{display:none}#stage{padding:16px}footer{gap:8px}#status{font-size:11px}.download{padding:7px 8px}}
353
- #chat{position:relative;min-width:0;min-height:0;display:flex;flex-direction:column;background:#191e30;border-left:1px solid #30364d}
354
- #chat-resizer{position:absolute;left:-5px;top:0;bottom:0;width:10px;z-index:3;cursor:col-resize;touch-action:none}#chat-resizer::after{content:"";position:absolute;left:4px;top:0;bottom:0;width:2px}#chat-resizer:hover::after,#chat-resizer:focus-visible::after,.resizing-chat #chat-resizer::after{background:#9b87ff}body.resizing-chat,body.resizing-chat *{cursor:col-resize!important;user-select:none!important}
355
- .chat-heading{display:flex;align-items:center;gap:8px;padding:16px;border-bottom:1px solid #2a3046}.chat-heading strong{flex:1}.chat-heading button{padding:5px 8px}
356
- #messages{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:16px;overscroll-behavior:contain}
357
- .chat-message{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}.chat-message.user{background:#302752;border-radius:8px;padding:10px 12px}.chat-message small{display:block;color:#a4afc6;font-size:11px;margin-bottom:4px}.chat-intro{color:#8995b0;line-height:1.7}
358
- #chat-form{padding:14px;border-top:1px solid #2a3046}#chat-context{font-size:11px;color:#9b87ff;margin-bottom:8px}#chat-input{font:inherit;resize:vertical;min-height:90px;max-height:200px;width:100%;padding:10px;border:1px solid #30364d;border-radius:8px} .chat-actions{display:flex;gap:8px;margin-top:8px;align-items:center}.chat-actions select{min-width:0;flex:1}#chat-send{background:#7154e8;color:white}#chat-status{padding:0 14px 12px;color:#9ba5be;font-size:11px;white-space:pre-wrap;max-height:90px;overflow:auto}
359
- body.chat-hidden .workspace{grid-template-columns:190px minmax(0,1fr)}body.chat-hidden #chat{display:none}
943
+ .presenting.browse-scrollbar #stage{padding-right:18px}
944
+ #presentation-scrollbar{position:fixed;z-index:4;top:0;bottom:0;right:0;width:16px;touch-action:none;border:1px solid #5d6575;background:#202735e8;cursor:pointer}
945
+ #presentation-scrollbar span{position:absolute;left:3px;right:3px;min-height:8px;border-radius:5px;background:#c4c4c4;pointer-events:none}
946
+ .kiosk-presenting #present-prev,.kiosk-presenting #present-next{display:none}
947
+ #presentation-controls button{background:transparent;color:white;border-color:#5d6575;padding:5px 10px}
948
+ #presentation-controls button:hover:not(:disabled){background:#ffffff1f}
949
+ #present-note{max-width:38ch;color:#ffd9a8;font-size:11px;line-height:1.35}
950
+ #chat{position:relative;min-width:0;min-height:0;display:flex;flex-direction:column;background:var(--ok-panel);color:var(--ok-text);border-left:1px solid var(--ok-border)}
951
+ #chat-resizer{position:absolute;left:-4px;top:0;bottom:0;width:7px;z-index:3;cursor:col-resize;touch-action:none}#chat-resizer::after{content:"";position:absolute;left:3px;top:0;bottom:0;width:1px}#chat-resizer:hover::after,#chat-resizer:focus-visible::after,.resizing-chat #chat-resizer::after{background:var(--ok-selected-border)}#chat-resizer:focus-visible{outline:none}
952
+ body.resizing-chat,body.resizing-chat *{cursor:col-resize!important;user-select:none!important}
953
+ .pane-head{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--ok-border);background:var(--ok-panel);flex:none}
954
+ .pane-head strong{font-size:13px;font-weight:600}
955
+ .pane-close{margin-left:auto;padding:0 4px;border:none;background:none;color:var(--ok-text-2);font-size:20px;line-height:20px}
956
+ .pane-close:hover:not(:disabled){background:var(--ok-hover);border-color:transparent;color:var(--ok-text)}
957
+ body.chat-hidden .workspace{grid-template-columns:var(--filmstrip-width) minmax(0,1fr)}body.chat-hidden #chat{display:none}
360
958
  body.presenting .workspace{grid-template-columns:minmax(0,1fr)}
361
- @media(max-width:1000px){.workspace{--filmstrip-width:120px;--chat-width:380px}.filmstrip{padding:12px 5px}#stage{padding:16px}}
362
- @media(max-width:700px){#chat-resizer{display:none}.workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(160px,1fr) minmax(200px,1fr)}.filmstrip{display:none}#chat{border-top:1px solid #30364d}.chat-heading{padding:8px 12px}#chat-form{padding:8px 12px}#chat-input{min-height:50px}body.chat-hidden .workspace,.presenting .workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}.brand{font-size:14px}header{gap:6px}.download{font-size:11px}}
363
- @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
364
-
365
- [hidden]{display:none!important}
366
- .chat-heading{padding:10px 14px}.chat-heading select{flex:1;min-width:0;font-weight:600;border:0;padding-left:0}
367
- #chat-context{margin:0;padding:8px 14px;border-bottom:1px solid #2a3046;color:#9ba5be;font-size:11px}
959
+ @media(max-width:1000px){.workspace{--filmstrip-width:120px;--chat-width:380px}#stage{padding:16px}}
960
+ @media(max-width:700px){#chat-resizer{display:none}.workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(160px,1fr) minmax(200px,1fr)}.filmstrip{display:none}#chat{border-left:0;border-top:1px solid var(--ok-border)}body.chat-hidden .workspace,.presenting .workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}footer .hint,#status,.download{display:none}#stage{padding:16px}}
961
+ `;
962
+ /** The agent page renders inside one agent pane of the docked Agents task pane. */
963
+ const agentStyles = `${tokenStyles}
964
+ body{display:flex;flex-direction:column;background:var(--ok-panel);height:100dvh;min-width:0;overflow:auto;overflow-x:hidden}
965
+ .chat-heading{display:flex;align-items:center;flex-wrap:wrap;gap:6px;padding:6px 12px 2px;flex-shrink:0}
966
+ .chat-heading select{flex:1;min-width:100px;font-size:12px}
967
+ #chat-context{flex-shrink:0;margin:0;padding:4px 12px 6px;color:var(--ok-text-2);font-size:11px;border-bottom:1px solid var(--ok-border)}
368
968
  #claude-panel,#codex-panel{display:flex;flex-direction:column;flex:1;min-height:0}
369
- #claude-panel{background:#171b24;color:#e4e8f0}
370
- .terminal-toolbar{display:flex;align-items:center;gap:8px;padding:8px 12px;font-size:11px;min-height:40px}.terminal-toolbar span{flex:1;overflow-wrap:anywhere}.terminal-toolbar button{font-size:11px;padding:5px 8px;background:#262d3b;border-color:#45516a;color:#e4e8f0}
371
- .terminal-toolbar button:hover:not(:disabled){background:#35415a}
372
- #terminal{flex:1;min-height:0;overflow:hidden;padding:0}.xterm{height:100%}
373
- #chat-input{min-height:70px;resize:vertical}.chat-shortcut{flex:1;color:#9098a7;font-size:10px}
374
- .markdown{white-space:normal;line-height:1.65}.markdown>:first-child{margin-top:0}.markdown>:last-child{margin-bottom:0}.markdown p{margin:0 0 .8em}.markdown pre{overflow:auto;padding:10px;background:#22283b;border:1px solid #2a3046;border-radius:6px;white-space:pre}.markdown code{font-size:.9em;background:#22283b;border-radius:3px;padding:1px 4px}.markdown pre code{padding:0}.markdown ul,.markdown ol{padding-left:22px}.markdown blockquote{margin-left:0;padding-left:12px;border-left:3px solid #30364d;color:#9ba5be}.markdown table{display:block;overflow:auto;border-collapse:collapse}.markdown th,.markdown td{padding:6px 8px;border:1px solid #30364d}.markdown h1,.markdown h2,.markdown h3{font-size:1.1em}.markdown a{color:#b6a5ff;text-decoration:underline}
375
-
376
- .brand{display:flex;align-items:center;gap:10px;letter-spacing:-.5px}.brand svg{width:32px;height:32px;flex:none}.brand em{font-style:normal;font-weight:400;color:#aca4ce}.badge{text-transform:uppercase;letter-spacing:.14em;font-size:9px;border:1px solid #61508866;border-radius:5px}#status{font-size:11px}#present,#chat-send{color:#fff;background:linear-gradient(120deg,#8061ed,#634de0);border-color:#a38aef55;box-shadow:0 3px 15px #7455e82a}#toggle-chat[aria-expanded="true"]{background:#35294f;border-color:#6f528b;color:#d6c5ff}.download{background:transparent;color:#bcc5dc}header button,header .download{font-size:12px}.filmstrip{background:linear-gradient(180deg,#161b2c,#111625)}.thumbnail{transition:background .15s}.thumbnail[aria-current="true"]{box-shadow:inset 0 0 0 1px #9980ef33}.thumbnail[aria-current="true"] img{box-shadow:0 0 16px #9567ed22}footer{background:#141929;color:#b9c2d8}footer .hint{font-size:10px}#count{font-size:11px;font-weight:600}#chat{background:#101422}.workspace-heading{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;color:#c7bee5;font-size:10px;font-weight:600;letter-spacing:.12em}.workspace-heading b{font-size:9px;color:#89cdbc;font-weight:500;letter-spacing:.08em}.workspace-heading b::before{content:"";display:inline-block;width:5px;height:5px;background:#86d5bb;border-radius:50%;margin-right:6px;box-shadow:0 0 8px #86d5bb66}.chat-heading{background:#191e30}.chat-heading select{background:transparent;color:#e4e5f3;font-size:12px}.chat-heading option{background:#191e30}#chat-context{background:#1a1e30;color:#a59abb;font-size:10px}.terminal-toolbar{gap:6px;padding:8px;font-size:10px}.terminal-toolbar button{white-space:nowrap}#terminal-start{background:#6c52c9;border-color:#9678e9}.terminal-frame{display:flex;flex:1;min-height:0;min-width:0;padding:4px 8px 8px;overflow:hidden}#terminal{width:100%;min-width:0}#chat-input{color:#e2e5f3;background:#131827;border-color:#3b3f58}#chat-input:focus{outline:none;border-color:#9b87ff;box-shadow:0 0 0 3px #9b87ff18}.chat-message.user{border:1px solid #67509655}.chat-intro{font-size:12px}.markdown pre{border-color:#3a4059}.markdown code{color:#d2c6fa}#error{background:#38242b;color:#ffb8b0}
377
- @media(max-width:700px){.brand svg{width:26px;height:26px}.brand{gap:6px}.workspace-heading{padding:7px 12px}header .download{font-size:10px;padding:7px}.badge{display:none}}
969
+ #claude-panel{min-height:100px}#codex-panel{min-height:240px}
970
+ .terminal-toolbar{display:flex;align-items:center;gap:6px;padding:6px 12px;min-height:34px;font-size:11px;color:var(--ok-text-2)}
971
+ .terminal-toolbar span{flex:1;overflow-wrap:anywhere}
972
+ .terminal-toolbar button{font-size:11px;padding:2px 8px;border-color:var(--ok-border-strong)}
973
+ .terminal-frame{display:flex;flex:1;min-height:0;min-width:0;padding:2px 4px 4px 12px;overflow:hidden}
974
+ #terminal{flex:1;width:100%;min-width:0;min-height:0;overflow:hidden;padding:0}.xterm{height:100%}
975
+ /* xterm's stylesheet paints the viewport black; the rows below the last full line show it. */
976
+ #terminal .xterm-viewport{background-color:var(--ok-panel)!important}
977
+ #messages{flex:1;overflow:auto;padding:12px;display:flex;flex-direction:column;gap:12px;overscroll-behavior:contain}
978
+ .chat-message{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.55}.chat-message.user{background:var(--ok-panel-2);border:1px solid var(--ok-border);border-radius:var(--ok-radius-lg);padding:8px 10px}
979
+ .chat-message small{display:block;color:var(--ok-text-2);font-size:11px;margin-bottom:4px}.chat-intro{color:var(--ok-text-2);line-height:1.6;font-size:12px}
980
+ #chat-form{padding:8px 12px;border-top:1px solid var(--ok-border)}
981
+ #chat-input{resize:vertical;min-height:70px;max-height:200px;width:100%;padding:6px 8px;border:1px solid var(--ok-border-strong);border-radius:var(--ok-radius);background:var(--ok-panel);color:var(--ok-text)}
982
+ #chat-input:focus{outline:2px solid var(--ok-selected-border);outline-offset:-1px}
983
+ .chat-actions{display:flex;gap:6px;margin-top:6px;align-items:center}.chat-actions button{border-color:var(--ok-border-strong)}.chat-actions .primary{border-color:var(--ok-accent)}
984
+ .chat-shortcut{flex:1;color:var(--ok-text-3);font-size:10px}
985
+ #chat-status{padding:0 12px 8px;color:var(--ok-text-2);font-size:11px;white-space:pre-wrap;max-height:90px;overflow:auto}
986
+ .markdown{white-space:normal;line-height:1.6}.markdown>:first-child{margin-top:0}.markdown>:last-child{margin-bottom:0}.markdown p{margin:0 0 .8em}
987
+ .markdown pre{overflow:auto;padding:8px;background:var(--ok-panel-2);border:1px solid var(--ok-border);border-radius:var(--ok-radius);white-space:pre;font-family:var(--ok-mono)}
988
+ .markdown code{font:.9em var(--ok-mono);background:var(--ok-panel-2);border-radius:3px;padding:1px 4px}.markdown pre code{padding:0}
989
+ .markdown ul,.markdown ol{padding-left:22px}.markdown blockquote{margin-left:0;padding-left:12px;border-left:3px solid var(--ok-border);color:var(--ok-text-2)}
990
+ .markdown table{display:block;overflow:auto;border-collapse:collapse}.markdown th,.markdown td{padding:6px 8px;border:1px solid var(--ok-border)}
991
+ .markdown h1,.markdown h2,.markdown h3{font-size:1.1em}.markdown a{color:var(--ok-accent);text-decoration:underline}
378
992
  `;
379
993
  //#endregion
380
994
  //#region src/page.ts
381
995
  const page = `<!doctype html>
382
996
  <html lang="en">
383
997
  <meta charset="utf-8"><meta name="viewport" content="width=device-width">
384
- <title>Office Kit — PowerPoint preview</title>
998
+ <title>Presentation preview</title>
385
999
  <link rel="stylesheet" href="/terminal.css">
386
1000
  <style>
387
1001
  ${previewStyles}
388
- .slide-edit-tools{display:flex;gap:6px;padding:8px 14px;flex-shrink:0}.slide-edit-tools{align-items:center;flex-wrap:wrap}.slide-edit-tools [data-undo],.slide-edit-tools [data-redo]{width:32px;height:32px;padding:0;display:grid;place-items:center;border:1px solid transparent;border-radius:8px;background:transparent;color:#625873;box-shadow:none}.slide-edit-tools [data-undo]:hover:not(:disabled),.slide-edit-tools [data-redo]:hover:not(:disabled){background:#ede7fa;border-color:#d6cbea;color:#513399}.slide-edit-tools button:disabled{opacity:.35}.slide-edit-tools button:focus-visible{outline:2px solid #8966df;outline-offset:2px}.slide-edit-tools [hidden]{display:none}.slide-edit-tools span{font-size:11px;color:#625873;flex:1}.slide-edit-tools small{font-size:11px;color:#634396}.slide-hover{position:fixed;border:1px solid #b094ff;pointer-events:none;z-index:19;border-radius:2px}.slide-text-input{position:fixed;z-index:22;resize:none;background:#202438;color:#fff;border:2px solid #b094ff;border-radius:3px;padding:0;box-shadow:0 0 0 3px #b094ff30;line-height:1.15}.slide-text-input[hidden],.slide-hover[hidden]{display:none}.slide-selection{position:fixed;border:2px solid #b094ff;background:#a080ff18;pointer-events:none;z-index:20;box-shadow:0 0 0 1px #201632}.slide-edit-panel{position:fixed;z-index:21;width:min(380px,calc(100vw - 16px));padding:14px;background:#202438;border:1px solid #776591;border-radius:14px;box-shadow:0 16px 50px #0008;display:flex;flex-direction:column;gap:12px}.slide-edit-panel[hidden],.slide-selection[hidden]{display:none}.selection-heading,.selection-actions{display:flex;align-items:center;gap:8px}.selection-heading strong{flex:1}.slide-edit-panel textarea{width:100%;min-height:90px;max-height:35vh;resize:vertical;background:#141a2b;color:#f4efff;border:1px solid #514969;border-radius:8px;padding:10px;font:inherit}.selection-actions{flex-wrap:wrap}.selection-actions select{min-width:80px;flex:1}.slide-edit-panel small{color:#d1c9e3;line-height:1.5}.presenting .slide-edit-tools{display:none}
1002
+ .slide-edit-tools{display:flex;align-items:center;flex-wrap:wrap;gap:4px;padding:4px 12px;flex-shrink:0;background:var(--ok-ribbon);border-bottom:1px solid var(--ok-border)}.slide-edit-tools [data-undo],.slide-edit-tools [data-redo]{width:26px;height:26px;padding:0;display:grid;place-items:center;color:var(--ok-text-2)}.slide-edit-tools [data-undo]:hover:not(:disabled),.slide-edit-tools [data-redo]:hover:not(:disabled){color:var(--ok-text)}.slide-edit-tools span{font-size:11px;color:var(--ok-text-2);flex:1}.slide-edit-tools small{font-size:11px;color:var(--ok-accent)}.slide-hover{position:fixed;border:1px solid var(--ok-selected-border);pointer-events:none;z-index:19;border-radius:2px}.slide-text-input{position:fixed;z-index:22;resize:none;background:var(--ok-panel);color:var(--ok-text);border:2px solid var(--ok-selected-border);border-radius:var(--ok-radius);padding:0;line-height:1.15}.slide-selection{position:fixed;border:2px solid var(--ok-selected-border);background:color-mix(in srgb,var(--ok-selected-border) 10%,transparent);pointer-events:none;z-index:20}.slide-edit-panel{position:fixed;z-index:21;width:min(380px,calc(100vw - 16px));padding:12px;background:var(--ok-panel);color:var(--ok-text);border:1px solid var(--ok-border);border-radius:var(--ok-radius-lg);box-shadow:var(--ok-shadow-lg);display:flex;flex-direction:column;gap:10px}.selection-heading,.selection-actions{display:flex;align-items:center;gap:6px}.selection-heading strong{flex:1}.slide-edit-panel textarea{width:100%;min-height:90px;max-height:35vh;resize:vertical;background:var(--ok-panel);color:var(--ok-text);border:1px solid var(--ok-border-strong);border-radius:var(--ok-radius);padding:6px 8px}.slide-edit-panel textarea:focus{outline:2px solid var(--ok-selected-border);outline-offset:-1px}.selection-actions{flex-wrap:wrap}.selection-actions select{min-width:80px;flex:1}.selection-actions button{border-color:var(--ok-border-strong)}.slide-edit-panel small{color:var(--ok-text-2);line-height:1.5}.presenting .slide-edit-tools{display:none}
1003
+ .editing:not(.presenting) .slide-edit-tools{display:none}
389
1004
 
390
- #agent-workspace{position:relative;flex:1;min-height:0;min-width:0;display:flex;overflow:auto}.agent-pane{position:absolute;padding:3px 5px;display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.agent-pane iframe{border:0;width:100%;flex:1;min-height:0;border-radius:0 0 9px 9px}.agent-tools{display:flex;gap:4px;align-items:center;flex-wrap:wrap;padding:6px;background:#20253a;border:1px solid #34334e;border-radius:9px 9px 0 0}.agent-tools span{flex:1;font-size:10px;letter-spacing:.04em;color:#b3abc9}.agent-tools svg{width:14px;height:14px}.agent-pane:focus-within .agent-tools{border-color:#8b6ed577;background:#29243e}.agent-tools button{font-size:11px;padding:5px;background:transparent;border:0;display:grid;place-items:center}.agent-divider{position:absolute;z-index:2;background:#101422;cursor:col-resize;touch-action:none}.agent-divider.vertical{cursor:row-resize}.agent-divider:hover,.agent-divider:focus-visible{background:#9b87ff}.splitting-agents iframe,.resizing-chat iframe{pointer-events:none}
1005
+ #agent-workspace{position:relative;flex:1;min-height:0;min-width:0;display:flex;overflow:auto}.agent-pane{position:absolute;display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.agent-pane iframe{border:0;width:100%;flex:1;min-height:0;background:var(--ok-panel)}.agent-tools{display:flex;gap:2px;align-items:center;padding:3px 6px 3px 12px;min-height:30px;background:var(--ok-panel-2);border-bottom:1px solid var(--ok-border)}.agent-tools span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;font-weight:600;color:var(--ok-text-2)}.agent-pane:focus-within .agent-tools span{color:var(--ok-text)}.agent-tools button{width:24px;height:24px;padding:0;display:grid;place-items:center;color:var(--ok-text-2)}.agent-tools button:hover:not(:disabled){color:var(--ok-text)}.agent-tools svg{width:14px;height:14px}.agent-divider{position:absolute;z-index:2;background:transparent;cursor:col-resize;touch-action:none}.agent-divider.vertical{cursor:row-resize}.agent-divider::after{content:"";position:absolute;background:var(--ok-border)}.agent-divider.horizontal::after{top:0;bottom:0;left:50%;width:1px}.agent-divider.vertical::after{left:0;right:0;top:50%;height:1px}.agent-divider:hover::after,.agent-divider:focus-visible::after{background:var(--ok-selected-border)}.agent-divider.horizontal:hover::after,.agent-divider.horizontal:focus-visible::after{width:2px}.agent-divider.vertical:hover::after,.agent-divider.vertical:focus-visible::after{height:2px}.agent-divider:focus-visible{outline:none}.splitting-agents iframe,.resizing-chat iframe{pointer-events:none}
1006
+ #editor-frame{display:none;border:0;width:100%;height:100%;flex:1;min-height:0}
1007
+ body.editing:not(.presenting){grid-template-rows:minmax(0,1fr)}
1008
+ .editing:not(.presenting) .workspace{--filmstrip-width:0px;grid-template-columns:minmax(0,1fr) clamp(280px,var(--chat-width),calc(100vw - 500px))}
1009
+ .editing.chat-hidden:not(.presenting) .workspace{grid-template-columns:minmax(0,1fr)}
1010
+ .editing:not(.presenting) .filmstrip,.editing:not(.presenting) footer,.editing:not(.presenting) #stage{display:none}
1011
+ .editing:not(.presenting) #editor-frame{display:block}
1012
+ /* Too narrow to dock beside the editor: the pane floats over its right edge. */
1013
+ @media(max-width:900px){.editing:not(.presenting) .workspace{grid-template-columns:minmax(0,1fr)}.editing:not(.presenting) #chat{position:fixed;z-index:30;top:0;right:0;bottom:0;width:min(380px,100vw);box-shadow:var(--ok-shadow-lg)}.editing:not(.presenting) #chat-resizer{display:none}}
391
1014
  </style>
392
- <header><span class="brand"><svg viewBox="0 0 36 36" aria-hidden="true"><defs><linearGradient id="brand-gradient" x2="1" y2="1"><stop stop-color="#c39aff"/><stop offset="1" stop-color="#7165f4"/></linearGradient></defs><rect x="2" y="2" width="32" height="32" rx="10" fill="url(#brand-gradient)"/><path d="M11 10h9l6 6v10H11z" fill="none" stroke="white" stroke-width="1.8" stroke-linejoin="round"/><path d="M20 10v7h6M15 21h7M15 25h4" fill="none" stroke="white" stroke-width="1.8" stroke-linecap="round"/><path d="m28 3 1.2 3.8L33 8l-3.8 1.2L28 13l-1.2-3.8L23 8l3.8-1.2z" fill="#e7dbff"/></svg>Office <em>Kit</em></span><span class="badge">Studio</span><span id="status" role="status">Building…</span><button id="toggle-chat" aria-expanded="true" aria-controls="chat">✦ Agents</button><button id="present" disabled>Present</button><a class="download" href="/deck.pptx">Download PPTX</a></header>
1015
+ <body class="editing chat-hidden">
393
1016
  <div class="workspace">
394
1017
  <nav class="filmstrip" aria-label="Slides"><h2>Slides</h2><ol id="thumbnails"></ol></nav>
395
- <main aria-label="Slide viewer"><pre id="error" role="alert" hidden></pre><div id="stage" tabindex="-1"><div id="empty">Waiting for slides…</div><div id="slide" hidden></div></div></main>
396
- <aside id="chat" aria-label="Slide chat">
1018
+ <main aria-label="Slide viewer"><iframe id="editor-frame" title="Presentation editor"></iframe><pre id="error" role="alert" hidden></pre><div id="stage" tabindex="-1"><div id="empty">Waiting for slides…</div><div id="slide" hidden></div></div></main>
1019
+ <aside id="chat" aria-labelledby="agents-title">
397
1020
  <div id="chat-resizer" role="separator" tabindex="0" aria-label="Chat width" aria-orientation="vertical" aria-controls="chat" title="Drag to resize · Double-click to reset"></div>
398
- <div class="workspace-heading"><span>✦ AI WORKSPACE</span><b>LOCAL</b></div><div id="agent-workspace"></div><div id="chat-context" hidden></div></aside>
1021
+ <div class="pane-head"><strong id="agents-title">Agents</strong><button id="close-chat" class="pane-close" aria-label="Close Agents" title="Close Agents">×</button></div><div id="agent-workspace"></div><div id="chat-context" hidden></div></aside>
399
1022
  </div>
400
- <footer><span id="count" aria-live="polite">No slides</span><span class="hint">Select an area to ask AI · Edit text directly</span><button id="prev" aria-label="Previous slide" disabled>‹</button><button id="next" aria-label="Next slide" disabled>›</button><label for="zoom">Zoom</label><select id="zoom"><option value="fit">Fit</option><option value="0.5">50%</option><option value="0.75">75%</option><option value="1">100%</option><option value="1.25">125%</option><option value="1.5">150%</option><option value="2">200%</option></select></footer>
401
- <div id="presentation-controls"><button id="present-prev" aria-label="Previous slide">‹</button><span id="present-count"></span><button id="present-next" aria-label="Next slide">›</button><button id="exit-present">Exit · Esc</button></div>
1023
+ <footer><span id="count" aria-live="polite">No slides</span><span id="status" role="status">Building…</span><span class="hint">Select an area to ask AI · Edit text directly</span><button id="prev" aria-label="Previous slide" disabled>‹</button><button id="next" aria-label="Next slide" disabled>›</button><button id="present" disabled>Present</button><button id="presenter" disabled>Presenter view</button><a class="download" href="/deck.pptx">Download PPTX</a><button id="toggle-chat" aria-pressed="false" aria-controls="chat"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5 9.4 6.6 14.5 8 9.4 9.4 8 14.5 6.6 9.4 1.5 8 6.6 6.6Z" stroke-linejoin="round"/></svg><span>Agents</span></button><span class="status-views" role="group" aria-label="Presentation views"><button id="toggle-editor" aria-label="Normal" title="Normal (Esc)"><svg width="16" height="12" viewBox="0 0 16 12" aria-hidden="true"><rect x=".5" y=".5" width="15" height="11" rx="1"/><path d="M5 1v10"/></svg></button></span><label for="zoom">Zoom</label><select id="zoom"><option value="fit">Fit</option><option value="0.5">50%</option><option value="0.75">75%</option><option value="1">100%</option><option value="1.25">125%</option><option value="1.5">150%</option><option value="2">200%</option></select></footer><div id="notice" role="alert" hidden></div>
1024
+ <div id="presentation-scrollbar" role="scrollbar" aria-label="Slide position" aria-controls="slide" aria-orientation="vertical" aria-valuemin="0" aria-valuemax="0" aria-valuenow="0" tabindex="0" hidden><span></span></div><div id="presentation-controls"><button id="present-prev" aria-label="Previous slide">‹</button><span id="present-count"></span><span id="rehearsal-timer" role="timer" aria-label="Rehearsal time" hidden></span><span id="present-note" role="status" hidden></span><button id="animation-retry" hidden></button><button id="present-next" aria-label="Next slide">›</button><button id="exit-present">Exit · Esc</button></div>
402
1025
  <script>
403
- let state={slides:[],error:null,aspectRatio:16/9},index=0,urls=[],presenting=false;
1026
+ let state={slides:[],error:null,aspectRatio:16/9,showProperties:null,customShows:[]},index=0,urls=[],presenting=false;
1027
+ let showOrder=[],showCursor=0,lastViewed=null,linkedShowId=null;
1028
+ let showReturns=[];
1029
+ // The fullscreen request of the show now starting. Starting or ending any show
1030
+ // (Present, presenter view, Escape) drops it, so a grant arriving after that
1031
+ // belongs to no show and is released instead of adopted.
1032
+ let presentationFullscreen=false,fullscreenRequest=null;
1033
+ function loopShow(){return showReturns.length===0&&(state.showProperties?.loop||state.showProperties?.mode?.kind==='kiosk');}
404
1034
  let displayedSvg;
1035
+ let presenterWindow;
1036
+ ${previewI18nScript}
1037
+ function rebuildShowOrder(){
1038
+ const previousSlide=showOrder[showCursor];
1039
+ const settings=state.showProperties;
1040
+ let order;
1041
+ if(linkedShowId!==null){
1042
+ order=state.customShows?.find(show=>show.id===linkedShowId)?.slideIndices??[];
1043
+ }else if(settings?.slides?.kind==='range'){
1044
+ const start=Math.max(1,settings.slides.start),end=Math.min(state.slides.length,settings.slides.end);
1045
+ order=Array.from({length:Math.max(0,end-start+1)},(_,offset)=>start-1+offset);
1046
+ }else if(settings?.slides?.kind==='customShow'){
1047
+ order=state.customShows?.find(show=>show.id===settings.slides.id)?.slideIndices??[];
1048
+ }else order=Array.from({length:state.slides.length},(_,slide)=>slide);
1049
+ showOrder=order.filter(slide=>slide>=0&&slide<state.slides.length);
1050
+ if(previousSlide!==undefined){
1051
+ if(showOrder[showCursor]===previousSlide)return;
1052
+ const candidates=showOrder.map((slide,position)=>slide===previousSlide?position:-1).filter(position=>position>=0);
1053
+ if(candidates.length){showCursor=candidates.reduce((best,position)=>Math.abs(position-showCursor)<Math.abs(best-showCursor)?position:best,candidates[0]);return;}
1054
+ }
1055
+ const current=showOrder.indexOf(index);
1056
+ if(current>=0)showCursor=current;
1057
+ else showCursor=Math.min(showCursor,Math.max(0,showOrder.length-1));
1058
+ }
1059
+ function showSlideAt(position,step=1,skipHidden=presenting){
1060
+ if(!showOrder.length)return -1;
1061
+ let cursor=position;
1062
+ for(let n=0;n<showOrder.length;n++){
1063
+ if(cursor<0||cursor>=showOrder.length){
1064
+ if(loopShow())cursor=(cursor+showOrder.length)%showOrder.length;
1065
+ else return -1;
1066
+ }
1067
+ const candidate=showOrder[cursor];
1068
+ if(!skipHidden||!state.hiddenSlides?.[candidate])return candidate;
1069
+ cursor+=step;
1070
+ }
1071
+ return -1;
1072
+ }
1073
+ function firstShowSlide(){return showSlideAt(0,1,true);}
1074
+ function nextShowPosition(step){
1075
+ if(!showOrder.length)return -1;
1076
+ let cursor=showCursor+step;
1077
+ for(let n=0;n<showOrder.length;n++){
1078
+ if(cursor<0||cursor>=showOrder.length){
1079
+ if(loopShow())cursor=(cursor+showOrder.length)%showOrder.length;
1080
+ else return -1;
1081
+ }
1082
+ if(!presenting||!state.hiddenSlides?.[showOrder[cursor]])return cursor;
1083
+ cursor+=step;
1084
+ }
1085
+ return -1;
1086
+ }
1087
+ function nextShowSlide(step){
1088
+ const position=nextShowPosition(step);
1089
+ return position<0?-1:showOrder[position];
1090
+ }
1091
+ function browsePositions(){
1092
+ return showOrder.map((slide,position)=>({slide,position})).filter(({slide})=>!state.hiddenSlides?.[slide]);
1093
+ }
1094
+ function syncBrowseScrollbar(){
1095
+ const scrollbar=byId('presentation-scrollbar');
1096
+ const enabled=presenting&&state.showProperties?.mode?.kind==='browse'&&state.showProperties?.mode?.showScrollbar===true;
1097
+ scrollbar.setAttribute('aria-label',pt('Slide position'));
1098
+ scrollbar.hidden=!enabled;
1099
+ document.body.classList.toggle('browse-scrollbar',enabled);
1100
+ if(!enabled)return;
1101
+ const positions=browsePositions();
1102
+ const max=Math.max(0,positions.length-1);
1103
+ scrollbar.setAttribute('aria-valuemax',String(max));
1104
+ const current=positions.findIndex(({position})=>position===showCursor);
1105
+ const value=Math.max(0,current);
1106
+ scrollbar.setAttribute('aria-valuenow',String(value));
1107
+ const thumbPercent=positions.length?Math.max(8,100/positions.length):100;
1108
+ scrollbar.firstElementChild.style.height=thumbPercent+'%';
1109
+ scrollbar.firstElementChild.style.top=(max?(value/max)*(100-thumbPercent):0)+'%';
1110
+ scrollbar.setAttribute('aria-valuetext',positions.length?slideLabel(positions[value].slide):pt('No slides'));
1111
+ }
1112
+ function findSlide(start,step,skipHidden=presenting){
1113
+ if(skipHidden&&presenting)return showSlideAt(showCursor+step,step);
1114
+ for(let i=start;i>=0&&i<state.slides.length;i+=step)if(!skipHidden||!state.hiddenSlides?.[i])return i;
1115
+ return -1;
1116
+ }
1117
+ function moveSlide(step,skipHidden=presenting,focusThumbnail=false){
1118
+ // The slide has effects and the player is still on its way: moving on now
1119
+ // would skip them, so the click waits rather than costing the viewer content.
1120
+ if(animationsWaiting())return;
1121
+ // A build comes before the slide: the click that would move on first plays
1122
+ // whatever the current slide still has to show, in either direction.
1123
+ if(animationPlayer&&(step>0?animationPlayer.advance():animationPlayer.back()))return;
1124
+ const previousShowCursor=showCursor;
1125
+ const nextPosition=skipHidden&&presenting?nextShowPosition(step):-1;
1126
+ const next=skipHidden&&presenting?(nextPosition<0?-1:showOrder[nextPosition]):findSlide(index+step,step,skipHidden);
1127
+ // Arriving backwards lands on a slide that has already played out, the way
1128
+ // the reference desktop app shows it; arriving forwards starts its build from the top.
1129
+ if(next>=0){
1130
+ selectSlide(next,focusThumbnail,true,step<0?'end':'start',nextPosition);
1131
+ if(presenting&&step>0&&nextPosition>=0&&nextPosition<=previousShowCursor&&loopShow())scheduleKioskRestart();
1132
+ }
1133
+ else if(presenting&&step>0&&linkedShowId!==null)void exitPresentation();
1134
+ }
1135
+ let advanceTimer,advanceKey;
1136
+ let kioskRestartTimer,kioskRestartKey;
1137
+ function clearKioskRestart(){
1138
+ clearTimeout(kioskRestartTimer);kioskRestartTimer=undefined;kioskRestartKey=null;
1139
+ }
1140
+ function scheduleKioskRestart(){
1141
+ clearKioskRestart();
1142
+ const restart=state.showProperties?.mode?.kind==='kiosk'?Number(state.showProperties.mode.restart):NaN;
1143
+ // The OOXML attribute is an unsigned duration, but the schema does not
1144
+ // define a special meaning for zero. Do not turn an unconfigured/zero value
1145
+ // into a busy immediate restart loop; only a positive duration schedules it.
1146
+ if(!presenting||!Number.isFinite(restart)||restart<=0)return;
1147
+ const key={};kioskRestartKey=key;
1148
+ const deadline=performance.now()+restart;
1149
+ function tick(){
1150
+ if(kioskRestartKey!==key||!presenting)return;
1151
+ const remaining=deadline-performance.now();
1152
+ if(remaining>0){kioskRestartTimer=setTimeout(tick,Math.min(remaining,2147483647));return;}
1153
+ const first=firstShowSlide();
1154
+ if(first>=0){
1155
+ const position=showOrder.indexOf(first);
1156
+ clearTimeout(advanceTimer);advanceTimer=undefined;advanceKey=null;
1157
+ selectSlide(first,false,true,'start',position);
1158
+ scheduleKioskRestart();
1159
+ }else clearKioskRestart();
1160
+ }
1161
+ kioskRestartTimer=setTimeout(tick,Math.min(restart,2147483647));
1162
+ }
1163
+ function scheduleAdvance(){
1164
+ const delay=state.transitions?.[index]?.advanceAfterMs;
1165
+ // A slide that still has effects to play — or one whose last click is still
1166
+ // playing out — is not finished, whatever its transition says about
1167
+ // advancing itself.
1168
+ const settled=!animationsWaiting()&&(!animationPlayer||!(animationPlayer.pending||animationPlayer.running));
1169
+ const key=presenting&&state.showProperties?.useTimings!==false&&settled&&(nextShowSlide(1)>=0||linkedShowId!==null)&&Number.isFinite(delay)&&delay>=0?index+':'+showCursor+':'+delay:null;
1170
+ if(key===advanceKey)return;
1171
+ clearTimeout(advanceTimer);advanceKey=key;
1172
+ if(key===null)return;
1173
+ // OOXML unsigned milliseconds can exceed the browser's signed timer limit.
1174
+ const deadline=performance.now()+delay;
1175
+ function tick(){
1176
+ const remaining=deadline-performance.now();
1177
+ if(remaining>0)advanceTimer=setTimeout(tick,Math.min(remaining,2147483647));
1178
+ else {advanceKey=null;moveSlide(1);}
1179
+ }
1180
+ advanceTimer=setTimeout(tick,Math.min(delay,2147483647));
1181
+ }
405
1182
  const byId=id=>document.getElementById(id);
1183
+ // Next and previous move through the slide's own build before they move
1184
+ // through the deck, so the last slide's remaining effects are still reachable
1185
+ // and the first step back is the one inside this slide.
1186
+ // True while this slide has effects but the player has not arrived yet. Its
1187
+ // clicks belong to the build, so they are held rather than spent on the deck.
1188
+ function animationsWaiting(){return state.showProperties?.showAnimation!==false&&animationLoad==='loading'&&presenting&&animationStepsAt(index).length>0;}
1189
+ function animationsPending(){return state.showProperties?.showAnimation!==false&&(animationsWaiting()||Boolean(animationPlayer&&animationPlayer.pending));}
1190
+ function animationsBehind(){return Boolean(animationPlayer&&animationPlayer.cursor>0);}
1191
+ function updateNavigationButtons(){
1192
+ for(const id of ['prev','present-prev'])byId(id).disabled=presenting?nextShowSlide(-1)<0&&!animationsBehind():findSlide(index-1,-1)<0&&!animationsBehind();
1193
+ for(const id of ['next','present-next'])byId(id).disabled=presenting?nextShowSlide(1)<0&&linkedShowId===null&&!animationsPending():findSlide(index+1,1)<0&&!animationsPending();
1194
+ byId('present').disabled=firstShowSlide()<0;
1195
+ byId('presenter').disabled=byId('present').disabled;
1196
+ }
406
1197
  const stage=byId('stage'),slide=byId('slide'),thumbnails=byId('thumbnails');
407
1198
  const workspace=document.querySelector('.workspace'),chatResizer=byId('chat-resizer');
408
1199
  const chatWidthKey='office-kit-chat-width',minChatWidth=280,minStageWidth=240;
@@ -411,7 +1202,7 @@ function updateChatWidthAria(){
411
1202
  const {min,max}=chatWidthLimits();
412
1203
  chatResizer.setAttribute('aria-valuemin',String(min));chatResizer.setAttribute('aria-valuemax',String(Math.round(max)));
413
1204
  const width=Math.round(byId('chat').getBoundingClientRect().width);
414
- chatResizer.setAttribute('aria-valuenow',String(width));chatResizer.setAttribute('aria-valuetext',width+' pixels');
1205
+ chatResizer.setAttribute('aria-valuenow',String(width));chatResizer.setAttribute('aria-valuetext',width+(previewLocale==='ja'?' ピクセル':' pixels'));
415
1206
  }
416
1207
  function setChatWidth(width){const {min,max}=chatWidthLimits();workspace.style.setProperty('--chat-width',Math.min(max,Math.max(min,width))+'px');}
417
1208
  function saveChatWidth(){try{const width=workspace.style.getPropertyValue('--chat-width');if(width)localStorage.setItem(chatWidthKey,String(parseFloat(width)));else localStorage.removeItem(chatWidthKey);}catch(error){console.warn('Could not save chat width',error);}}
@@ -439,6 +1230,153 @@ new ResizeObserver(updateChatWidthAria).observe(byId('chat'));
439
1230
  // SVG stays out of the viewer's own DOM and CSS. Keyboard events still reach the
440
1231
  // document, so arrow-key navigation keeps working after clicking into a slide.
441
1232
  const canvas=slide.attachShadow({mode:'open'});
1233
+ ${transitionScript}
1234
+ // The slide's object animations. One player per slide, kept while the slide and
1235
+ // its timing stay as they are: an unrelated rebuild (new speaker notes, say)
1236
+ // must not throw away how far the viewer has clicked through a build.
1237
+ //
1238
+ // The player is the editor's module, served as one build, so the show, the
1239
+ // presenter window and the editor panel cannot disagree about a timing tree.
1240
+ let animationPlayer,animationPlayerKey,createAnimationPlayer,pendingAnimationPosition;
1241
+ // 'loading' | 'ready' | 'failed'. A slide show holds its clicks while the
1242
+ // player is on its way; if it never arrives, the viewer is told so and can ask
1243
+ // for it again rather than watching a deck quietly skip its animations.
1244
+ let animationLoad='loading',animationLoadAttempt=0;
1245
+ function loadAnimationPlayer(){
1246
+ if(animationLoad==='ready')return;
1247
+ animationLoad='loading';updateAnimationNotice();
1248
+ // A module that failed to load stays failed in the browser's module map, so
1249
+ // asking again means asking for a different URL.
1250
+ const url='/animation-player.js'+(animationLoadAttempt++?'?retry='+animationLoadAttempt:'');
1251
+ import(url).then(module=>{
1252
+ createAnimationPlayer=module.createAnimationPlayer;animationLoad='ready';
1253
+ const position=pendingAnimationPosition;pendingAnimationPosition=undefined;
1254
+ if(position!==undefined)syncAnimationPlayer(position);
1255
+ updateNavigationButtons();updateAnimationNotice();scheduleAdvance();
1256
+ },error=>{
1257
+ animationLoad='failed';console.warn('Could not load the animation player',error);
1258
+ updateNavigationButtons();updateAnimationNotice();scheduleAdvance();
1259
+ });
1260
+ }
1261
+ const animationStepsAt=i=>state.animations?.[i]??[];
1262
+ const animationKeyAt=i=>i+'\u0000'+(state.slides[i]??'')+'\u0000'+JSON.stringify(animationStepsAt(i));
1263
+ // A transition draws the arriving slide into a layer of its own, beside a layer
1264
+ // holding the slide being left — whose shapes carry ids of their own, from a
1265
+ // different slide's id space. Only the arriving one is this slide.
1266
+ const slideRoot=()=>canvas.querySelector('.transition-layer:not(.transition-old)')??canvas;
1267
+ let mediaPlayer,mediaPlayerKey,mediaPlayerConfigKey,createMediaPlayer,mediaLoading=false,mediaGeneration=0;
1268
+ const backgroundMedia=[];
1269
+ const backgroundMediaRoot=document.createElement('div');
1270
+ backgroundMediaRoot.hidden=true;
1271
+ stage.append(backgroundMediaRoot);
1272
+ const mediaRetry=document.createElement('button');
1273
+ mediaRetry.hidden=true;
1274
+ byId('presentation-controls').append(mediaRetry);
1275
+ mediaRetry.onclick=()=>syncMediaPlayer();
1276
+ function disposeCurrentMediaPlayer(){
1277
+ mediaPlayer?.dispose();mediaPlayer=undefined;mediaPlayerKey=undefined;mediaPlayerConfigKey=undefined;
1278
+ }
1279
+ function disposeMediaPlayer(){
1280
+ disposeCurrentMediaPlayer();
1281
+ for(const retained of backgroundMedia)retained.player.dispose();
1282
+ backgroundMedia.length=0;
1283
+ }
1284
+ function leaveMediaSlide(previousIndex,previousCursor){
1285
+ if(!presenting){disposeMediaPlayer();return;}
1286
+ if(mediaPlayer){backgroundMedia.push({player:mediaPlayer,index:previousIndex,cursor:previousCursor});mediaPlayer=undefined;mediaPlayerKey=undefined;mediaPlayerConfigKey=undefined;}
1287
+ for(let i=backgroundMedia.length-1;i>=0;i--){
1288
+ const retained=backgroundMedia[i];
1289
+ if(index===retained.index||!retained.player.retainAcrossSlides(showCursor-retained.cursor,backgroundMediaRoot)){
1290
+ retained.player.dispose();backgroundMedia.splice(i,1);
1291
+ }
1292
+ }
1293
+ }
1294
+ function syncMediaPlayer(){
1295
+ const clips=(state.media??[]).filter(clip=>clip.slideIndex===index&&clip.kind!=='online');
1296
+ if(!presenting){disposeMediaPlayer();mediaRetry.hidden=true;return;}
1297
+ if(!clips.length){disposeCurrentMediaPlayer();mediaRetry.hidden=true;return;}
1298
+ if(!createMediaPlayer){
1299
+ if(mediaLoading)return;
1300
+ mediaLoading=true;mediaRetry.hidden=true;
1301
+ import('/media-player.js?attempt='+Date.now()).then(module=>{
1302
+ createMediaPlayer=module.createMediaPlayer;mediaLoading=false;syncMediaPlayer();
1303
+ },error=>{
1304
+ mediaLoading=false;console.warn('Could not load the media player',error);
1305
+ mediaRetry.textContent=previewLocale==='ja'?'メディアを読み込めませんでした · 再試行':'Media could not load · Retry';
1306
+ mediaRetry.hidden=!presenting;
1307
+ });
1308
+ return;
1309
+ }
1310
+ const key=JSON.stringify([index,clips]);
1311
+ if(mediaPlayerConfigKey===key)return;
1312
+ disposeCurrentMediaPlayer();
1313
+ mediaPlayer=createMediaPlayer({root:slideRoot(),overlayRoot:stage,clips,locale:previewLocale});
1314
+ mediaPlayerConfigKey=key;
1315
+ mediaPlayerKey=String(++mediaGeneration)+':'+key;
1316
+ updatePresenter();
1317
+ }
1318
+ function updateAnimationNotice(){
1319
+ const note=byId('present-note'),retry=byId('animation-retry');
1320
+ const slideHasEffects=presenting&&state.showProperties?.showAnimation!==false&&animationStepsAt(index).length>0;
1321
+ retry.hidden=!(slideHasEffects&&animationLoad==='failed');
1322
+ retry.textContent=previewLocale==='ja'?'再試行':'Try again';
1323
+ if(slideHasEffects&&animationLoad==='failed'){
1324
+ note.hidden=false;
1325
+ note.textContent=previewLocale==='ja'
1326
+ ?'アニメーションを読み込めませんでした。このスライドの効果は再生されません。'
1327
+ :'The animations could not be loaded, so this slide’s effects are not played.';
1328
+ return;
1329
+ }
1330
+ if(animationsWaiting()){
1331
+ note.hidden=false;
1332
+ note.textContent=previewLocale==='ja'?'アニメーションを準備中…':'Preparing animations…';
1333
+ return;
1334
+ }
1335
+ const skipped=animationPlayer?animationPlayer.unsupported:[];
1336
+ note.hidden=skipped.length===0;
1337
+ note.textContent=skipped.length===0?'':previewLocale==='ja'
1338
+ ?'このスライドの '+skipped.length+' 件のアニメーションは未対応のため再生されません'
1339
+ :skipped.length===1
1340
+ ?'1 animation on this slide is not supported yet, so it is not played'
1341
+ :skipped.length+' animations on this slide are not supported yet, so they are not played';
1342
+ }
1343
+ function syncAnimationPlayer(position){
1344
+ // Animations belong to the slide show. The still preview shows the slide as
1345
+ // it ends, which is what the renderer drew.
1346
+ const wanted=presenting&&state.showProperties?.showAnimation!==false&&animationStepsAt(index).length>0;
1347
+ if(!wanted){
1348
+ if(animationPlayer){animationPlayer.dispose();animationPlayer=undefined;animationPlayerKey=undefined;}
1349
+ updateAnimationNotice();
1350
+ return;
1351
+ }
1352
+ if(!createAnimationPlayer){
1353
+ // Still on its way, or it never arrived. The slide keeps the picture the
1354
+ // renderer drew; this position is applied the moment the player is there.
1355
+ pendingAnimationPosition=position;
1356
+ updateAnimationNotice();
1357
+ return;
1358
+ }
1359
+ const key=animationKeyAt(index);
1360
+ if(!animationPlayer||animationPlayerKey!==key){
1361
+ // A changed timing makes the old cursor meaningless — the effects it
1362
+ // counted are not the effects there are now.
1363
+ animationPlayer?.dispose();
1364
+ animationPlayer=createAnimationPlayer({
1365
+ root:slideRoot,
1366
+ steps:animationStepsAt(index),
1367
+ reducedMotion:()=>reducedMotion.matches,
1368
+ onChange:()=>{updateNavigationButtons();updatePresenter();scheduleAdvance();},
1369
+ });
1370
+ animationPlayerKey=key;
1371
+ position==='end'?animationPlayer.finish():animationPlayer.reset();
1372
+ updateAnimationNotice();
1373
+ return;
1374
+ }
1375
+ if(position==='end')animationPlayer.finish();
1376
+ else if(position==='start')animationPlayer.reset();
1377
+ // 'keep' leaves the cursor where the viewer left it.
1378
+ updateAnimationNotice();
1379
+ }
442
1380
  function resize(){
443
1381
  if(!state.slides.length)return;
444
1382
  const style=getComputedStyle(stage);
@@ -449,36 +1387,56 @@ function resize(){
449
1387
  const slideWidth=presenting||zoom==='fit'?Math.min(width,height*ratio):1280*Number(zoom);
450
1388
  slide.style.width=slideWidth+'px';slide.style.height=slideWidth/ratio+'px';
451
1389
  }
452
- function selectSlide(next,focusThumbnail=false,reveal=true){
453
- index=Math.max(0,Math.min(next,state.slides.length-1));
454
- const count=state.slides.length?'Slide '+(index+1)+' of '+state.slides.length:'No slides';
455
- byId('chat-context').textContent=state.slides.length?count:'Whole project';
1390
+ function selectSlide(next,focusThumbnail=false,reveal=true,position='start',showPosition=-1){
1391
+ const previousIndex=index,previousCursor=showCursor;
1392
+ index=Math.max(0,Math.min(next,state.slides.length-1));
1393
+ if(showPosition>=0)showCursor=showPosition;
1394
+ else if(presenting){if(showOrder[showCursor]!==index){const naturalPosition=showOrder.indexOf(index);if(naturalPosition>=0)showCursor=naturalPosition;}}
1395
+ else {const naturalPosition=showOrder.indexOf(index);if(naturalPosition>=0)showCursor=naturalPosition;}
1396
+ if(presenting&&state.hiddenSlides?.[index]){
1397
+ const forwardPosition=nextShowPosition(1),backwardPosition=forwardPosition<0?nextShowPosition(-1):-1;
1398
+ const position=forwardPosition>=0?forwardPosition:backwardPosition;
1399
+ if(position>=0){showCursor=position;index=showOrder[position];}
1400
+ }
1401
+ if(presenting&&(previousIndex!==index||previousCursor!==showCursor))lastViewed={index:previousIndex,cursor:previousCursor};
1402
+ const count=slideCount();
1403
+ byId('chat-context').textContent=state.slides.length?count:pt('Whole project');
456
1404
  byId('chat-context').dataset.focus=JSON.stringify({slide:state.slides.length?index:null,revision:state.revision??0});
457
1405
  window.dispatchEvent(new Event('agent-focus'));
1406
+ if(document.body.classList.contains('editing')&&editorFocus)applyEditorFocus();
458
1407
  byId('count').textContent=count;byId('present-count').textContent=count;
459
- for(const id of ['prev','present-prev'])byId(id).disabled=index===0;
460
- for(const id of ['next','present-next'])byId(id).disabled=index>=state.slides.length-1;
461
- byId('present').disabled=!state.slides.length;
1408
+ document.body.classList.toggle('kiosk-presenting',presenting&&state.showProperties?.mode?.kind==='kiosk');
462
1409
  byId('zoom').disabled=!state.slides.length;
463
1410
  slide.hidden=!state.slides.length;byId('empty').hidden=!!state.slides.length;
464
1411
  const svg=state.slides[index];
465
- if(svg!==displayedSvg){
466
- displayedSvg=svg;
467
- canvas.innerHTML=svg?'<style>svg{display:block;width:100%;height:100%}</style>'+svg:'';
1412
+ if(previousIndex!==index||previousCursor!==showCursor)leaveMediaSlide(previousIndex,previousCursor);
1413
+ else if(svg!==displayedSvg||position!=='keep')disposeMediaPlayer();
1414
+ if(svg!==displayedSvg||previousIndex!==index){
1415
+ renderSlide(svg,presenting&&previousIndex!==index?state.transitions?.[index]:null);
468
1416
  }
469
- slide.setAttribute('aria-label','Slide '+(index+1));
1417
+ syncAnimationPlayer(position);
1418
+ syncMediaPlayer();
1419
+ updateNavigationButtons();
1420
+ slide.setAttribute('aria-label',slideLabel(index));
470
1421
  for(const [position,item] of Array.from(thumbnails.children).entries()){
471
1422
  const button=item.firstElementChild,selected=position===index;
472
1423
  button.setAttribute('aria-current',String(selected));button.tabIndex=selected?0:-1;
1424
+ button.dataset.skipped=String(!!state.hiddenSlides?.[position]);
1425
+ button.title=state.hiddenSlides?.[position]?pt('Skipped during presentation'):'';
473
1426
  if(selected){if(reveal)button.scrollIntoView({block:'nearest'});if(focusThumbnail)button.focus({preventScroll:true});}
474
1427
  }
1428
+ syncBrowseScrollbar();
475
1429
  resize();
1430
+ if(!transitionCleanup)scheduleAdvance();
1431
+ updatePresenter();
476
1432
  }
477
1433
  function update(updated){
478
1434
  const focusedThumbnail=thumbnails.contains(document.activeElement);
479
1435
  const previous=state;
1436
+ if(JSON.stringify(previous.media)!==JSON.stringify(updated.media))disposeMediaPlayer();
480
1437
  state=updated;
481
- byId('status').textContent=state.error?'Build failed · showing last successful output':state.building?'Updating…':state.slides.length+' slides · Live';
1438
+ rebuildShowOrder();
1439
+ connectionLost=false;updatePreviewStatus();
482
1440
  byId('error').textContent=state.error||'';byId('error').hidden=!state.error;
483
1441
  document.documentElement.style.setProperty('--slide-ratio',String(state.aspectRatio));
484
1442
  for(let i=state.slides.length;i<urls.length;i++){
@@ -493,7 +1451,7 @@ function update(updated){
493
1451
  if(!item){
494
1452
  item=document.createElement('li');
495
1453
  const button=document.createElement('button'),number=document.createElement('span'),image=document.createElement('img');
496
- button.className='thumbnail';button.setAttribute('aria-label','Slide '+(i+1));button.onclick=()=>selectSlide(i,true);
1454
+ button.className='thumbnail';button.setAttribute('aria-label',slideLabel(i));button.onclick=()=>selectSlide(i,true);
497
1455
  number.className='slide-number';number.textContent=String(i+1);
498
1456
  image.alt='';image.draggable=false;image.loading='lazy';
499
1457
  button.append(number,image);item.append(button);thumbnails.append(item);
@@ -501,63 +1459,495 @@ function update(updated){
501
1459
  item.querySelector('img').src=urls[i];
502
1460
  if(oldUrl)URL.revokeObjectURL(oldUrl);
503
1461
  });
504
- selectSlide(index,focusedThumbnail,false);
505
- if(!state.slides.length&&presenting)void exitPresentation();
1462
+ if(presenting&&firstShowSlide()<0)void exitPresentation();
1463
+ selectSlide(index,focusedThumbnail,false,'keep');
1464
+ if(presenting&&(previous.showProperties?.mode?.kind!==state.showProperties?.mode?.kind||previous.showProperties?.mode?.restart!==state.showProperties?.mode?.restart))scheduleKioskRestart();
506
1465
  }
507
- function setPresenting(value){
508
- presenting=value;document.body.classList.toggle('presenting',value);resize();
509
- if(value)stage.focus();else{
1466
+ function setPresenting(value,from){
1467
+ if(!value){presentationFullscreen=false;finishRehearsal();}
1468
+ fullscreenRequest=null;
1469
+ clearKioskRestart();
1470
+ linkedShowId=null;showReturns=[];
1471
+ lastViewed=null;
1472
+ cancelTransition();
1473
+ rebuildShowOrder();
1474
+ presenting=value&&firstShowSlide()>=0;document.body.classList.toggle('presenting',presenting);
1475
+ if(presenting){const first=from??firstShowSlide();if(first>=0){index=first;showCursor=showOrder.findIndex(slide=>slide===first);}}
1476
+ selectSlide(index);
1477
+ if(presenting)scheduleKioskRestart();
1478
+ if(presenting)stage.focus();else{
510
1479
  byId('present').focus();
511
1480
  thumbnails.children[index]?.firstElementChild.scrollIntoView({block:'nearest'});
512
1481
  }
513
1482
  }
1483
+ function returnToLastViewed(){
1484
+ if(!presenting||!lastViewed||lastViewed.index>=state.slides.length)return;
1485
+ const target=lastViewed;
1486
+ selectSlide(target.index,false,true,'start',showOrder[target.cursor]===target.index?target.cursor:-1);
1487
+ }
1488
+ function followNavigationLink(href){
1489
+ const directions={'#pptx-next-slide':1,'#pptx-prev-slide':-1,'#pptx-first-slide':0,'#pptx-last-slide':0};
1490
+ if(!Object.hasOwn(directions,href))return false;
1491
+ const step=directions[href];
1492
+ let position=-1,target=-1;
1493
+ if(step){
1494
+ position=presenting?nextShowPosition(step):-1;
1495
+ target=presenting?(position>=0?showOrder[position]:-1):findSlide(index+step,step,true);
1496
+ }else{
1497
+ const first=href==='#pptx-first-slide';
1498
+ target=presenting?showSlideAt(first?0:showOrder.length-1,first?1:-1):findSlide(first?0:state.slides.length-1,first?1:-1,true);
1499
+ if(presenting)position=first?showOrder.indexOf(target):showOrder.lastIndexOf(target);
1500
+ }
1501
+ if(target>=0)selectSlide(target,false,true,'start',position);
1502
+ else if(presenting&&step>0)void exitPresentation();
1503
+ return true;
1504
+ }
1505
+ function launchCustomShow(id,returnToShow){
1506
+ if(!presenting)return;
1507
+ const show=state.customShows?.find(show=>show.id===id);
1508
+ const first=show?.slideIndices.find(slide=>slide>=0&&slide<state.slides.length&&!state.hiddenSlides?.[slide]);
1509
+ if(first===undefined)return;
1510
+ const caller={id:linkedShowId,index,cursor:showCursor,lastViewed,animation:animationPlayer?.progress};
1511
+ if(returnToShow)showReturns.push(caller);else showReturns=[];
1512
+ linkedShowId=id;showCursor=0;lastViewed=null;
1513
+ rebuildShowOrder();
1514
+ selectSlide(first,false,true,'start',showOrder.indexOf(first));
1515
+ lastViewed=null;
1516
+ }
1517
+ function followCustomShowLink(href){
1518
+ if(!href.startsWith('#pptx-custom-show?'))return false;
1519
+ const params=new URLSearchParams(href.slice('#pptx-custom-show?'.length));
1520
+ const id=params.get('id');
1521
+ if(id!==null&&/^[0-9]+$/.test(id))launchCustomShow(Number(id),params.get('return')==='true');
1522
+ return true;
1523
+ }
1524
+ // Slide Show ▸ Rehearse Timings: time each slide while presenting, then hand
1525
+ // the times to the editor, which asks whether to keep them as slide timings.
1526
+ let rehearsal=null;
1527
+ const clock=ms=>{const total=Math.floor(ms/1000),two=n=>String(n).padStart(2,'0');return Math.floor(total/3600)+':'+two(Math.floor(total/60)%60)+':'+two(total%60);};
1528
+ function rehearsalTick(){
1529
+ if(!rehearsal)return;
1530
+ const now=performance.now();
1531
+ // The show's cursor names the slide on screen; a custom show can repeat one.
1532
+ const showing=showOrder[showCursor]??index;
1533
+ if(showing!==rehearsal.slide){rehearsal.times.set(rehearsal.slide,(rehearsal.times.get(rehearsal.slide)??0)+now-rehearsal.since);rehearsal.slide=showing;rehearsal.since=now;}
1534
+ byId('rehearsal-timer').textContent=clock(now-rehearsal.since)+' · '+clock(now-rehearsal.started);
1535
+ }
1536
+ function startRehearsal(){
1537
+ const now=performance.now();
1538
+ rehearsal={times:new Map(),slide:showOrder[showCursor]??index,since:now,started:now,timer:setInterval(rehearsalTick,200)};
1539
+ byId('rehearsal-timer').hidden=false;rehearsalTick();
1540
+ }
1541
+ function finishRehearsal(){
1542
+ if(!rehearsal)return;
1543
+ rehearsalTick();
1544
+ const now=performance.now();
1545
+ rehearsal.times.set(rehearsal.slide,(rehearsal.times.get(rehearsal.slide)??0)+now-rehearsal.since);
1546
+ clearInterval(rehearsal.timer);byId('rehearsal-timer').hidden=true;
1547
+ const timings=[...rehearsal.times].map(([slide,ms])=>({slide,ms:Math.round(ms)}));
1548
+ rehearsal=null;
1549
+ editorFrame.contentWindow?.postMessage({type:'rehearsal-timings',timings},location.origin);
1550
+ }
514
1551
  async function exitPresentation(){
1552
+ if(presenting&&showReturns.length){
1553
+ const caller=showReturns.pop();
1554
+ linkedShowId=caller.id;showCursor=caller.cursor;
1555
+ rebuildShowOrder();
1556
+ selectSlide(caller.index,false,true,'start',caller.cursor);
1557
+ lastViewed=caller.lastViewed;
1558
+ if(caller.animation&&animationPlayer)animationPlayer.resume(caller.animation.cursor,caller.animation.elapsed);
1559
+ return;
1560
+ }
515
1561
  setPresenting(false);
516
1562
  if(document.fullscreenElement)await document.exitFullscreen();
517
1563
  }
518
- byId('present').onclick=async()=>{
519
- setPresenting(true);
1564
+ async function startPresentation(from){
1565
+ setPresenting(true,from);
1566
+ if(state.showProperties?.mode?.kind==='browse')return;
1567
+ const request=fullscreenRequest={};
520
1568
  try{await document.documentElement.requestFullscreen();}
521
- catch{byId('exit-present').textContent='Exit view · Esc';}
1569
+ catch{if(fullscreenRequest===request){fullscreenRequest=null;byId('exit-present').textContent=pt('Exit view · Esc');}}
1570
+ }
1571
+ byId('present').onclick=()=>startPresentation();
1572
+ // Messages that used to sit in the shell's header now float over whichever
1573
+ // view is showing, so they are not lost while the editor fills the window.
1574
+ const NOTICE_MS=6000;
1575
+ let noticeTimer;
1576
+ function showNotice(text){const notice=byId('notice');notice.textContent=text;notice.hidden=false;clearTimeout(noticeTimer);noticeTimer=setTimeout(()=>{notice.hidden=true;},NOTICE_MS);}
1577
+ function updatePresenter(){
1578
+ if(!presenterWindow||presenterWindow.closed)return;
1579
+ // The presenter runs the same player over its own copy of the slide, from the
1580
+ // same cursor and the same moment within the stop in hand, so what it shows
1581
+ // is what the audience sees — including an effect still fading in.
1582
+ const progress=animationPlayer?animationPlayer.progress:null;
1583
+ const animationSteps=animationPlayer?animationStepsAt(index):null;
1584
+ presenterWindow.postMessage({type:'presenter-state',index,count:state.slides.length,animationSteps,current:state.slides[index]??null,next:state.slides[nextShowSlide(1)]??null,hasPrevious:nextShowSlide(-1)>=0||animationsBehind(),hasNext:nextShowSlide(1)>=0||linkedShowId!==null||animationsPending(),animation:progress,notes:state.notes?.[index]??'',aspectRatio:state.aspectRatio,locale:previewLocale,presenting,media:presenting?(state.media??[]).filter(clip=>clip.slideIndex===index):[],mediaKey:mediaPlayerKey,mediaProgress:mediaPlayer?.progress??[]},location.origin);
1585
+ }
1586
+ setInterval(()=>{
1587
+ if(!presenterWindow||presenterWindow.closed||!mediaPlayer)return;
1588
+ presenterWindow.postMessage({type:'presenter-media-state',index,mediaKey:mediaPlayerKey,mediaProgress:mediaPlayer.progress},location.origin);
1589
+ },250);
1590
+ byId('presenter').onclick=()=>{
1591
+ if(presenterWindow&&!presenterWindow.closed){setPresenting(true);presenterWindow.focus();return;}
1592
+ presenterWindow=window.open('/presenter','office-kit-presenter','popup,width=1100,height=800');
1593
+ if(presenterWindow)setPresenting(true);
1594
+ else showNotice(pt('Allow popups to open presenter view.'));
522
1595
  };
1596
+ window.addEventListener('message',event=>{
1597
+ if(event.origin!==location.origin||event.source!==presenterWindow||event.data?.type!=='presenter-command')return;
1598
+ if(event.data.action==='ready')updatePresenter();
1599
+ else if(event.data.action==='media'){
1600
+ const command=event.data.index;
1601
+ if(!presenting||!mediaPlayer||event.data.mediaKey!==mediaPlayerKey||!command||!Number.isInteger(command.shapeId)||!['play','pause','seek'].includes(command.action))return;
1602
+ if(command.action==='seek'&&(!Number.isFinite(command.time)||command.time<0))return;
1603
+ mediaPlayer.command(command);updatePresenter();
1604
+ }
1605
+ else if(event.data.action==='next')moveSlide(1,true);
1606
+ else if(event.data.action==='previous')moveSlide(-1,true);
1607
+ else if(event.data.action==='exit')void exitPresentation();
1608
+ else if(event.data.action==='lastViewed')returnToLastViewed();
1609
+ else if(event.data.action==='navigation'&&typeof event.data.index==='string')followNavigationLink(event.data.index);
1610
+ else if(event.data.action==='customShow'&&typeof event.data.index==='string')followCustomShowLink(event.data.index);
1611
+ else if(event.data.action==='jump'&&Number.isInteger(event.data.index)&&event.data.index>=0&&event.data.index<state.slides.length)selectSlide(event.data.index);
1612
+ });
523
1613
  byId('exit-present').onclick=exitPresentation;
524
- document.addEventListener('fullscreenchange',()=>{if(!document.fullscreenElement&&presenting)setPresenting(false);});
525
- for(const id of ['prev','present-prev'])byId(id).onclick=()=>selectSlide(index-1);
526
- for(const id of ['next','present-next'])byId(id).onclick=()=>selectSlide(index+1);
1614
+ function scrollToBrowsePosition(value){
1615
+ const positions=browsePositions();
1616
+ const position=positions[Math.max(0,Math.min(positions.length-1,value))];
1617
+ if(position&&position.position!==showCursor)selectSlide(position.slide,false,true,'start',position.position);
1618
+ }
1619
+ const browseScrollbar=byId('presentation-scrollbar');
1620
+ let scrollbarDragOffset;
1621
+ function dragBrowseScrollbar(event){
1622
+ const rect=browseScrollbar.getBoundingClientRect();
1623
+ const thumb=browseScrollbar.firstElementChild.getBoundingClientRect();
1624
+ const travel=rect.height-thumb.height;
1625
+ if(travel<=0)return;
1626
+ const max=Number(browseScrollbar.getAttribute('aria-valuemax'));
1627
+ scrollToBrowsePosition(Math.round(((event.clientY-rect.top-scrollbarDragOffset)/travel)*max));
1628
+ }
1629
+ browseScrollbar.onpointerdown=event=>{
1630
+ if(event.button!==0)return;
1631
+ event.preventDefault();browseScrollbar.focus();
1632
+ const thumb=browseScrollbar.firstElementChild.getBoundingClientRect();
1633
+ scrollbarDragOffset=event.clientY>=thumb.top&&event.clientY<=thumb.bottom?event.clientY-thumb.top:thumb.height/2;
1634
+ browseScrollbar.setPointerCapture(event.pointerId);
1635
+ dragBrowseScrollbar(event);
1636
+ };
1637
+ browseScrollbar.onpointermove=event=>{
1638
+ if(browseScrollbar.hasPointerCapture(event.pointerId))dragBrowseScrollbar(event);
1639
+ };
1640
+ browseScrollbar.onpointerup=event=>{
1641
+ if(browseScrollbar.hasPointerCapture(event.pointerId))browseScrollbar.releasePointerCapture(event.pointerId);
1642
+ };
1643
+ browseScrollbar.onkeydown=event=>{
1644
+ const current=Number(browseScrollbar.getAttribute('aria-valuenow'));
1645
+ const max=Number(browseScrollbar.getAttribute('aria-valuemax'));
1646
+ let next;
1647
+ if(event.key==='ArrowDown'||event.key==='PageDown')next=current+1;
1648
+ else if(event.key==='ArrowUp'||event.key==='PageUp')next=current-1;
1649
+ else if(event.key==='Home')next=0;
1650
+ else if(event.key==='End')next=max;
1651
+ else return;
1652
+ event.preventDefault();event.stopPropagation();scrollToBrowsePosition(next);
1653
+ };
1654
+ byId('animation-retry').onclick=()=>{loadAnimationPlayer();};
1655
+ loadAnimationPlayer();
1656
+ document.addEventListener('fullscreenchange',()=>{
1657
+ // Only the page itself is ever requested here. A native video control can put
1658
+ // its <video> into fullscreen (and return to the page) on its own; that is the
1659
+ // viewer's choice, not a stale grant.
1660
+ if(document.fullscreenElement){
1661
+ if(document.fullscreenElement!==document.documentElement||presentationFullscreen)return;
1662
+ if(fullscreenRequest){fullscreenRequest=null;presentationFullscreen=true;}
1663
+ else void document.exitFullscreen();
1664
+ }
1665
+ else if(presentationFullscreen){presentationFullscreen=false;if(presenting)setPresenting(false);}
1666
+ });
1667
+ for(const id of ['prev','present-prev'])byId(id).onclick=()=>{if(!presenting||state.showProperties?.mode?.kind!=='kiosk')moveSlide(-1);};
1668
+ for(const id of ['next','present-next'])byId(id).onclick=()=>{if(!presenting||state.showProperties?.mode?.kind!=='kiosk')moveSlide(1);};
527
1669
  byId('zoom').onchange=resize;
528
- stage.onclick=()=>{if(presenting&&!getSelection().toString())selectSlide(index+1);};
1670
+ stage.onclick=event=>{
1671
+ const link=event.composedPath().find(node=>node instanceof Element&&node.localName==='a');
1672
+ if(link){
1673
+ const href=link.getAttribute('href')??link.getAttributeNS('http://www.w3.org/1999/xlink','href')??'';
1674
+ if(followNavigationLink(href)||followCustomShowLink(href)){event.preventDefault();return;}
1675
+ if(href==='#pptx-end-show'||href==='#pptx-last-slide-viewed'){
1676
+ event.preventDefault();
1677
+ if(!presenting)return;
1678
+ if(href==='#pptx-end-show'){void exitPresentation();return;}
1679
+ returnToLastViewed();
1680
+ return;
1681
+ }
1682
+ if(href.startsWith('#slide-')){
1683
+ event.preventDefault();
1684
+ const number=Number(href.slice(7));
1685
+ if(Number.isInteger(number)&&number>=1&&number<=state.slides.length)selectSlide(number-1);
1686
+ }
1687
+ return;
1688
+ }
1689
+ if(!presenting||state.showProperties?.mode?.kind==='kiosk'||getSelection().toString())return;
1690
+ // 'advClick' says whether a click moves to the next *slide*. A build still
1691
+ // belongs to this one, so its remaining effects play either way.
1692
+ if(animationsPending()||state.transitions?.[index]?.advanceOnClick!==false)moveSlide(1);
1693
+ };
529
1694
  document.addEventListener('keydown',event=>{
530
1695
  if(event.key==='Escape'&&presenting){event.preventDefault();void exitPresentation();return;}
1696
+ // As in the reference desktop app's Reading View, Esc goes back to Normal view, unless it
1697
+ // is closing the viewer's own text field or area selection first.
1698
+ if(event.key==='Escape'&&!document.body.classList.contains('editing')&&!event.target.closest('select,input,textarea,[contenteditable]')&&document.querySelector('.slide-edit-panel')?.hidden!==false){event.preventDefault();chooseView(true);return;}
1699
+ if(presenting&&state.showProperties?.mode?.kind==='kiosk')return;
531
1700
  if(event.altKey||event.ctrlKey||event.metaKey||event.target.closest('select,input,textarea,[contenteditable]'))return;
532
- let next=index;
533
- if(['ArrowLeft','ArrowUp','PageUp'].includes(event.key))next--;
534
- else if(['ArrowRight','ArrowDown','PageDown'].includes(event.key))next++;
535
- else if(event.key==='Home')next=0;
536
- else if(event.key==='End')next=state.slides.length-1;
537
- else if(event.key===' '&&presenting&&!event.target.closest('button,a'))next+=event.shiftKey?-1:1;
1701
+ const focusThumbnail=thumbnails.contains(document.activeElement);
1702
+ let step=0,jump=-1,jumpPosition=-1;
1703
+ if(['ArrowLeft','ArrowUp','PageUp'].includes(event.key))step=-1;
1704
+ else if(['ArrowRight','ArrowDown','PageDown'].includes(event.key))step=1;
1705
+ else if(event.key==='Home'){
1706
+ jump=presenting?firstShowSlide():findSlide(0,1);
1707
+ if(presenting)jumpPosition=showOrder.findIndex(slide=>slide===jump&&!state.hiddenSlides?.[slide]);
1708
+ }
1709
+ else if(event.key==='End'){
1710
+ jump=presenting?showSlideAt(showOrder.length-1,-1):findSlide(state.slides.length-1,-1);
1711
+ if(presenting)jumpPosition=showOrder.findLastIndex(slide=>slide===jump&&!state.hiddenSlides?.[slide]);
1712
+ }
1713
+ else if(event.key===' '&&presenting&&!event.target.closest('button,a'))step=event.shiftKey?-1:1;
538
1714
  else return;
539
- event.preventDefault();selectSlide(next,thumbnails.contains(document.activeElement));
1715
+ event.preventDefault();
1716
+ // Home and End are a jump, not a step: they land on a slide with its build
1717
+ // at the start rather than walking through the one in hand.
1718
+ if(step!==0)moveSlide(step,presenting,focusThumbnail);
1719
+ else if(jump>=0)selectSlide(jump,focusThumbnail,true,'start',jumpPosition);
540
1720
  });
541
1721
  new ResizeObserver(resize).observe(stage);
542
1722
  let refreshId=0;
543
1723
  async function refresh(){
544
1724
  const id=++refreshId;
545
1725
  try{const response=await fetch('/state'+(state.revision===undefined?'':'?since='+state.revision));if(!response.ok)throw new Error('Preview unavailable');const updated=await response.json();if(id===refreshId){if(updated.changes){updated.slides=state.slides.slice(0,updated.count);updated.slides.length=updated.count;for(const [position,svg] of Object.entries(updated.changes))updated.slides[Number(position)]=svg;}update(updated);}}
546
- catch{if(id===refreshId)byId('status').textContent='Reconnecting…';}
1726
+ catch{if(id===refreshId){connectionLost=true;updatePreviewStatus();}}
1727
+ }
1728
+ const editorFrame=byId('editor-frame');
1729
+ let editorFocus;
1730
+ // The preview revision the editor last saw; it reports this apart from its focus.
1731
+ let editorRevision=0;
1732
+ // The Agents task pane opens on demand, like the reference desktop app's panes; the editor's
1733
+ // Agents button (in its tab row) mirrors that state, so every change is reported back.
1734
+ const agentsKey='office-kit-agents-open';
1735
+ function agentsOpen(){return !document.body.classList.contains('chat-hidden');}
1736
+ function postAgentsState(focusButton=false){editorFrame.contentWindow?.postMessage({type:'host-panes',agents:agentsOpen(),focus:focusButton},location.origin);}
1737
+ function setAgentsOpen(open,{focusPane=false,returnFocus=false}={}){
1738
+ document.body.classList.toggle('chat-hidden',!open);
1739
+ byId('toggle-chat').setAttribute('aria-pressed',String(open));
1740
+ try{sessionStorage.setItem(agentsKey,open?'1':'0');}catch(error){console.warn('Could not save the Agents pane state',error);}
1741
+ postAgentsState(returnFocus&&document.body.classList.contains('editing'));
1742
+ resize();
1743
+ if(open&&focusPane)byId('close-chat').focus();
1744
+ else if(returnFocus){if(document.body.classList.contains('editing'))editorFrame.focus();else byId('toggle-chat').focus();}
1745
+ }
1746
+ byId('toggle-chat').onclick=()=>setAgentsOpen(!agentsOpen());
1747
+ byId('close-chat').onclick=()=>setAgentsOpen(false,{returnFocus:true});
1748
+ try{if(sessionStorage.getItem(agentsKey)==='1')setAgentsOpen(true);}catch(error){console.warn('Could not restore the Agents pane state',error);}
1749
+ function setEditorMode(editing){
1750
+ document.body.classList.toggle('editing',editing);
1751
+ if(editing&&!editorFrame.getAttribute('src'))editorFrame.src='/editor';
1752
+ if(editing&&editorFocus)applyEditorFocus();else selectSlide(index);
1753
+ resize();
547
1754
  }
548
- byId('toggle-chat').onclick=()=>{const hidden=document.body.classList.toggle('chat-hidden');byId('toggle-chat').setAttribute('aria-expanded',String(!hidden));resize();};
549
- const events=new EventSource('/events');events.onmessage=event=>{if(event.data==='history'){window.dispatchEvent(new Event('agent-history'));return;}if(event.data==='chat'){window.dispatchEvent(new Event('agent-chat'));return;}if(event.data==='ready'){delete state.revision;}void refresh();};events.onerror=()=>{byId('status').textContent='Reconnecting…'};refresh();
1755
+ // The rendered viewer is the editor's Reading View; Normal (or Esc) returns.
1756
+ function chooseView(editing){
1757
+ setEditorMode(editing);
1758
+ try{sessionStorage.setItem('office-kit-view',editing?'editor':'preview');}catch(error){console.warn('Could not save view preference',error);}
1759
+ if(editing)editorFrame.focus();else stage.focus();
1760
+ }
1761
+ byId('toggle-editor').onclick=()=>chooseView(true);
1762
+ try{setEditorMode(sessionStorage.getItem('office-kit-view')!=='preview');}catch(error){console.warn('Could not restore view preference',error);setEditorMode(true);}
1763
+ function applyEditorFocus(){
1764
+ if(!editorFocus)return;
1765
+ index=Math.max(0,editorFocus.slide);
1766
+ byId('chat-context').textContent=(editorFocus.locale==='ja'?'スライド ':'Slide ')+(index+1)+' / '+editorFocus.count+(editorFocus.dirty?' · '+(editorFocus.locale==='ja'?'未保存':'Unsaved'):'');
1767
+ byId('chat-context').dataset.focus=JSON.stringify({slide:editorFocus.count?index:null,revision:editorFocus.dirty?-1:editorRevision});
1768
+ window.dispatchEvent(new Event('agent-focus'));
1769
+ }
1770
+ window.addEventListener('message',event=>{
1771
+ if(event.origin!==location.origin||event.source!==editorFrame.contentWindow||event.data?.type!=='editor-command')return;
1772
+ const slide=event.data.slide;
1773
+ if(event.data.action==='agents'){setAgentsOpen(!agentsOpen(),{focusPane:true});return;}
1774
+ if(event.data.action==='reading'){
1775
+ if(Number.isInteger(slide)&&slide>=0&&slide<state.slides.length)index=slide;
1776
+ chooseView(false);
1777
+ return;
1778
+ }
1779
+ // The editor's Slide Show tab; the click's user activation reaches this page,
1780
+ // so fullscreen and the presenter popup are still allowed.
1781
+ if(byId('present').disabled)return;
1782
+ if(event.data.action==='start')void startPresentation();
1783
+ else if(event.data.action==='current'&&Number.isInteger(slide)&&slide>=0&&slide<state.slides.length)void startPresentation(slide);
1784
+ else if(event.data.action==='presenter')byId('presenter').click();
1785
+ else if(event.data.action==='rehearse'){void startPresentation();if(presenting)startRehearsal();}
1786
+ });
1787
+ window.addEventListener('message',event=>{
1788
+ if(event.origin!==location.origin||event.source!==editorFrame.contentWindow||event.data?.type!=='editor-revision'||!Number.isInteger(event.data.revision))return;
1789
+ editorRevision=event.data.revision;
1790
+ if(document.body.classList.contains('editing'))applyEditorFocus();
1791
+ });
1792
+ window.addEventListener('message',event=>{
1793
+ if(event.origin!==location.origin||event.source!==editorFrame.contentWindow||event.data?.type!=='editor-focus')return;
1794
+ editorFocus=event.data;
1795
+ if(previewLocale!==editorFocus.locale&&(editorFocus.locale==='ja'||editorFocus.locale==='en')){previewLocale=editorFocus.locale;updatePreviewLabels();}
1796
+ updatePresenter();
1797
+ if(document.body.classList.contains('editing'))applyEditorFocus();
1798
+ postAgentsState();
1799
+ });
1800
+ updatePreviewLabels();
1801
+ const events=new EventSource('/events');events.onmessage=event=>{if(event.data==='history'){window.dispatchEvent(new Event('agent-history'));return;}if(event.data==='chat'){window.dispatchEvent(new Event('agent-chat'));return;}if(event.data==='ready'){delete state.revision;}void refresh();};events.onerror=()=>{connectionLost=true;updatePreviewStatus()};refresh();
550
1802
  <\/script><script type="module" src="/terminal.js"><\/script></html>`;
551
1803
  //#endregion
1804
+ //#region src/presenter-page.ts
1805
+ /** Separate window so speaker notes never appear on the audience surface. */
1806
+ const presenterPage = `<!doctype html>
1807
+ <html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
1808
+ <title>Presenter view</title>
1809
+ <style>
1810
+ *{box-sizing:border-box}body{margin:0;background:#141929;color:#e4e8f0;font:15px system-ui,sans-serif;height:100vh;display:flex;flex-direction:column}header,footer{display:flex;align-items:center;gap:14px;padding:16px;flex-wrap:wrap}h1{font-size:18px;margin:0;flex:1}h2{font-size:13px;color:#b9c2d8;margin:0 0 10px}button{font:inherit;color:inherit;background:#29243e;border:1px solid #675487;border-radius:6px;padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}button:focus-visible{outline:2px solid #bca3ff;outline-offset:3px}main{display:grid;grid-template-columns:minmax(0,3fr) minmax(240px,2fr);gap:20px;padding:0 20px;flex:1;min-height:0;overflow:auto}section{min-width:0}#current{position:relative}#current [hidden]{display:none!important}#current,#next{background:#090c14;aspect-ratio:16/9}#current svg,#next svg{width:100%;height:100%}#notes{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6;max-height:40vh;overflow:auto;padding:14px;background:#1e2538;border-radius:8px}#notes-title{margin-top:20px}#count{flex:1}#message{padding:0 20px;color:#ffc9bd}#elapsed{font-variant-numeric:tabular-nums}footer{justify-content:flex-end}@media(max-width:640px){main{grid-template-columns:1fr}#notes{max-height:none}}
1811
+ </style>
1812
+ <header><h1 id="title">Presenter view</h1><span id="timer-label">Elapsed</span><output id="elapsed">00:00</output><button id="reset">Reset timer</button></header>
1813
+ <p id="message" role="status">Connecting to presentation…</p>
1814
+ <main><section><h2 id="current-title">Current slide</h2><div id="current"></div><button id="media-retry" hidden></button><h2 id="notes-title">Speaker notes</h2><div id="notes" tabindex="0"></div></section><section><h2 id="next-title">Next slide</h2><div id="next"></div><p id="end" hidden></p></section></main>
1815
+ <footer><span id="count" aria-live="polite"></span><button id="prev" disabled>Previous</button><button id="next-button" disabled>Next</button><button id="exit">Exit presentation</button></footer>
1816
+ <script>
1817
+ const byId=id=>document.getElementById(id);
1818
+ const canvases={current:byId('current').attachShadow({mode:'open'}),next:byId('next').attachShadow({mode:'open'})};
1819
+ const displayed={};
1820
+ let locale='en',started=performance.now(),connected=false;
1821
+ const text=(en,ja)=>locale==='ja'?ja:en;
1822
+ // The presenter shows the slide the audience is looking at, so it runs the very
1823
+ // same player over its own copy, resumed at the same point in the same stop,
1824
+ // rather than being told after the fact what is on screen.
1825
+ let makePlayer,animationPlayer,animationKey,animationGeneration,lastState;
1826
+ const presenterReducedMotion=matchMedia('(prefers-reduced-motion: reduce)');
1827
+ import('/animation-player.js').then(module=>{makePlayer=module.createAnimationPlayer;if(lastState)syncAnimation(lastState);},()=>{});
1828
+ function syncAnimation(data){
1829
+ const steps=data.presenting?data.animationSteps:null;
1830
+ if(!steps||!steps.length||!makePlayer){
1831
+ if(animationPlayer){animationPlayer.dispose();animationPlayer=undefined;animationKey=undefined;animationGeneration=undefined;}
1832
+ return;
1833
+ }
1834
+ const key=data.index+'\\u0000'+(data.current??'')+'\\u0000'+JSON.stringify(steps);
1835
+ if(key!==animationKey){
1836
+ animationPlayer?.dispose();
1837
+ animationPlayer=makePlayer({root:canvases.current,steps,reducedMotion:()=>presenterReducedMotion.matches});
1838
+ animationKey=key;animationGeneration=undefined;
1839
+ }
1840
+ const progress=data.animation;
1841
+ if(!progress)return;
1842
+ // Follow the audience only when it actually moved. The effects inside a stop
1843
+ // run on the same clock here, so re-running them on every passing report would
1844
+ // restart a fade; a seek that lands on the cursor it is already on — jumping
1845
+ // to the end of the stop in hand, say — still has to be followed, which is
1846
+ // what the generation says and the cursor alone does not.
1847
+ if(progress.generation===animationGeneration)return;
1848
+ animationGeneration=progress.generation;
1849
+ animationPlayer.resume(progress.cursor,progress.elapsed);
1850
+ }
1851
+ let makeMediaPlayer,mediaPlayer,mediaOverlay,mediaKey,mediaLoading=false;
1852
+ function disposeMedia(){mediaPlayer?.dispose();mediaOverlay?.remove();mediaPlayer=undefined;mediaOverlay=undefined;mediaKey=undefined;}
1853
+ function syncMedia(data){
1854
+ const clips=(data.media??[]).filter(clip=>clip.kind!=='online');
1855
+ if(!data.presenting||!data.mediaKey||!clips.length){disposeMedia();byId('media-retry').hidden=true;return;}
1856
+ if(!makeMediaPlayer){
1857
+ if(mediaLoading)return;
1858
+ mediaLoading=true;byId('media-retry').hidden=true;
1859
+ import('/media-player.js?attempt='+Date.now()).then(module=>{
1860
+ makeMediaPlayer=module.createMediaPlayer;mediaLoading=false;if(lastState)syncMedia(lastState);
1861
+ },error=>{
1862
+ mediaLoading=false;console.warn('Could not load presenter media',error);
1863
+ byId('media-retry').textContent=text('Media could not load · Retry','メディアを読み込めませんでした · 再試行');
1864
+ byId('media-retry').hidden=!lastState?.presenting;
1865
+ });
1866
+ return;
1867
+ }
1868
+ const key=data.mediaKey+'\\u0000'+data.current;
1869
+ if(key!==mediaKey){
1870
+ disposeMedia();
1871
+ // Overlays must live inside the canvas shadow tree; the host has no slot
1872
+ // and would not render children appended to its light DOM.
1873
+ mediaOverlay=document.createElement('div');canvases.current.append(mediaOverlay);
1874
+ mediaPlayer=makeMediaPlayer({root:canvases.current,overlayRoot:mediaOverlay,clips,locale,
1875
+ onCommand:command=>{
1876
+ if(window.opener&&!window.opener.closed)window.opener.postMessage({type:'presenter-command',action:'media',index:command,mediaKey:data.mediaKey},location.origin);
1877
+ }});
1878
+ mediaKey=key;
1879
+ }
1880
+ mediaPlayer.sync(data.mediaProgress??[]);
1881
+ }
1882
+ byId('media-retry').onclick=()=>{if(lastState)syncMedia(lastState);};
1883
+ function send(action,index){if(window.opener&&!window.opener.closed)window.opener.postMessage({type:'presenter-command',action,index},location.origin);}
1884
+ for(const canvas of Object.values(canvases))canvas.addEventListener('click',event=>{
1885
+ const link=event.composedPath().find(node=>node instanceof Element&&node.localName==='a');
1886
+ const href=link?.getAttribute('href')??link?.getAttributeNS('http://www.w3.org/1999/xlink','href')??'';
1887
+ if(['#pptx-next-slide','#pptx-prev-slide','#pptx-first-slide','#pptx-last-slide'].includes(href)){
1888
+ event.preventDefault();send('navigation',href);
1889
+ }else if(href.startsWith('#pptx-custom-show?')){
1890
+ event.preventDefault();send('customShow',href);
1891
+ }else if(href==='#pptx-end-show'||href==='#pptx-last-slide-viewed'){
1892
+ event.preventDefault();send(href==='#pptx-end-show'?'exit':'lastViewed');
1893
+ }else if(href.startsWith('#slide-')){
1894
+ event.preventDefault();
1895
+ const number=Number(href.slice(7));
1896
+ if(Number.isInteger(number)&&number>=1)send('jump',number-1);
1897
+ }
1898
+ });
1899
+ function update(data){
1900
+ connected=true;locale=data.locale;document.documentElement.lang=locale;
1901
+ for(const [id,en,ja] of [['title','Presenter view','発表者ビュー'],['timer-label','Elapsed','経過時間'],['reset','Reset timer','タイマーをリセット'],['current-title','Current slide','現在のスライド'],['notes-title','Speaker notes','発表者ノート'],['next-title','Next slide','次のスライド'],['prev','Previous','前へ'],['next-button','Next','次へ'],['exit','Exit presentation','プレゼンテーションを終了']])byId(id).textContent=text(en,ja);
1902
+ document.title=text('Presenter view','発表者ビュー');
1903
+ byId('message').textContent=data.presenting?'':text('Presentation is stopped.','プレゼンテーションは停止中です。');
1904
+ const animation=data.animation&&data.animation.stops>0
1905
+ ? ' · '+text('Click '+data.animation.cursor+' of '+data.animation.stops,'クリック '+data.animation.cursor+' / '+data.animation.stops)
1906
+ : '';
1907
+ byId('count').textContent=data.count?text('Slide '+(data.index+1)+' of '+data.count,'スライド '+(data.index+1)+' / '+data.count)+animation:text('No slides','スライドがありません');
1908
+ for(const name of ['current','next']){
1909
+ const svg=data[name];
1910
+ if(displayed[name]!==svg){if(name==='current')disposeMedia();displayed[name]=svg;canvases[name].innerHTML=svg?'<style>svg{display:block;width:100%;height:100%}</style>'+svg:'';}
1911
+ byId(name).style.aspectRatio=String(data.aspectRatio);byId(name).hidden=!svg;
1912
+ }
1913
+ byId('notes').textContent=data.notes||text('No speaker notes.','発表者ノートはありません。');
1914
+ byId('prev').disabled=!data.hasPrevious;
1915
+ // The next click may be an effect on this slide rather than the next slide.
1916
+ byId('next-button').disabled=!(data.hasNext??data.next);
1917
+ byId('exit').disabled=!data.presenting;
1918
+ byId('end').hidden=!!(data.hasNext??data.next);byId('end').textContent=text('End of presentation','プレゼンテーションの最後です');
1919
+ lastState=data;syncAnimation(data);syncMedia(data);
1920
+ }
1921
+ window.addEventListener('message',event=>{
1922
+ if(event.origin!==location.origin||event.source!==window.opener)return;
1923
+ if(event.data?.type==='presenter-state')update(event.data);
1924
+ else if(event.data?.type==='presenter-media-state'&&lastState&&event.data.index===lastState.index&&event.data.mediaKey===lastState.mediaKey){
1925
+ lastState.mediaProgress=event.data.mediaProgress;mediaPlayer?.sync(lastState.mediaProgress);
1926
+ }
1927
+ });
1928
+ byId('prev').onclick=()=>send('previous');byId('next-button').onclick=()=>send('next');byId('exit').onclick=()=>send('exit');
1929
+ byId('reset').onclick=()=>{started=performance.now();byId('elapsed').textContent='00:00';};
1930
+ document.addEventListener('keydown',event=>{
1931
+ if(event.altKey||event.ctrlKey||event.metaKey||(event.key!=='Escape'&&event.target.closest('button')))return;
1932
+ const action=['ArrowRight','ArrowDown','PageDown',' '].includes(event.key)?'next':['ArrowLeft','ArrowUp','PageUp'].includes(event.key)?'previous':event.key==='Escape'?'exit':null;
1933
+ if(action){event.preventDefault();send(action);}
1934
+ });
1935
+ setInterval(()=>{
1936
+ const seconds=Math.floor((performance.now()-started)/1000);byId('elapsed').textContent=String(Math.floor(seconds/60)).padStart(2,'0')+':'+String(seconds%60).padStart(2,'0');
1937
+ if(!window.opener||window.opener.closed){disposeMedia();byId('message').textContent=text('The presentation window is closed.','プレゼンテーションのウィンドウは閉じられています。');for(const id of ['prev','next-button','exit'])byId(id).disabled=true;}
1938
+ else if(!connected)send('ready');
1939
+ },250);
1940
+ send('ready');
1941
+ <\/script></html>`;
1942
+ //#endregion
552
1943
  //#region src/agent-page.ts
553
- const agentPage = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/terminal.css"><style>${previewStyles}
554
- body{display:flex;flex-direction:column;background:#191e30;height:100dvh;min-width:0;overflow:auto;overflow-x:hidden} .chat-heading{flex-wrap:wrap} .chat-heading select{min-width:100px}.chat-heading,#chat-context{flex-shrink:0}#claude-panel{min-height:100px}#codex-panel{min-height:240px}
1944
+ const agentPage = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/terminal.css"><style>${agentStyles}
555
1945
  </style><div class="chat-heading"><select id="chat-provider" aria-label="AI provider"><option value="claude">Claude Code</option><option value="codex">Codex</option></select><button id="chat-reset" hidden>New chat</button></div>
556
1946
  <div id="chat-context">No slide selected</div>
557
- <section id="claude-panel" aria-label="Claude Code terminal"><div class="terminal-toolbar"><span id="terminal-status" role="status">Start Claude Code to edit your slides.</span><button id="terminal-start">Start</button><button id="terminal-stop" hidden>End session</button></div><div class="terminal-frame"><div id="terminal"></div></div></section>
1947
+ <section id="claude-panel" aria-label="Claude Code terminal"><div class="terminal-toolbar"><span id="terminal-status" role="status">Start Claude Code to edit your slides.</span><button id="terminal-start" class="primary">Start</button><button id="terminal-stop" hidden>End session</button></div><div class="terminal-frame"><div id="terminal"></div></div></section>
558
1948
  <div id="codex-panel" hidden>
559
1949
  <div id="messages" role="log" aria-label="Conversation"><p class="chat-intro">Describe what you want to change. The current slide is included automatically. You can also ask about other slides or the whole deck.<br><br>Uses your locally installed Codex. Sign in through its CLI first. Sending a message allows it to edit this project.</p></div>
560
- <form id="chat-form"><textarea id="chat-input" aria-label="Message" maxlength="16000" placeholder="Ask for a change…" required></textarea><div class="chat-actions"><span class="chat-shortcut">⌘ / Ctrl + Enter</span><button id="chat-stop" type="button" hidden>Stop</button><button id="chat-send" type="submit">Send</button></div></form>
1950
+ <form id="chat-form"><textarea id="chat-input" aria-label="Message" maxlength="16000" placeholder="Ask for a change…" required></textarea><div class="chat-actions"><span class="chat-shortcut">⌘ / Ctrl + Enter</span><button id="chat-stop" type="button" hidden>Stop</button><button id="chat-send" class="primary" type="submit">Send</button></div></form>
561
1951
  <div id="chat-status" role="status">Ready</div>
562
1952
  </div>
563
1953
  <script>
@@ -743,7 +2133,7 @@ function createTerminal(entry, busy = () => false, base = "", verify = async ()
743
2133
  review?.begin();
744
2134
  json(200, { hookSpecificOutput: {
745
2135
  hookEventName: "UserPromptSubmit",
746
- additionalContext: `You are editing the local PowerPoint TSX project at ${resolve(entry)}.
2136
+ additionalContext: `You are editing the local presentation TSX project at ${resolve(entry)}.
747
2137
  Read the project's authoring instructions. Make focused source patches and preserve unrelated work.
748
2138
  The preview rebuilds on save; do not start another dev server. A Stop hook checks the actual build and returns errors for repair.
749
2139
  ${authoringGuidance}
@@ -971,7 +2361,7 @@ function createChat(entry, notify, busy = () => false, verify = async () => null
971
2361
  ...message,
972
2362
  text: message.text.slice(-12e3)
973
2363
  }));
974
- const prompt = `You are editing a local PowerPoint TSX project in ${dirname(resolve(entry))}.
2364
+ const prompt = `You are editing a local presentation TSX project in ${dirname(resolve(entry))}.
975
2365
  Read the project's authoring instructions. Make focused patches to the TSX source, preserving unrelated work.
976
2366
  The preview rebuilds automatically on save; do not start another dev server.
977
2367
  ${authoringGuidance}
@@ -1188,8 +2578,88 @@ Current request and preview context (JSON): ${JSON.stringify(user)}`;
1188
2578
  }
1189
2579
  //#endregion
1190
2580
  //#region src/server.ts
2581
+ const embeddedMediaUrl = /^data:([^;,]+);base64,(.*)$/s;
2582
+ function cacheEmbeddedMedia(media) {
2583
+ const cache = /* @__PURE__ */ new Map();
2584
+ return {
2585
+ cache,
2586
+ published: media.map((item) => {
2587
+ if (item.kind === "online") return item;
2588
+ const match = embeddedMediaUrl.exec(item.src);
2589
+ if (!match) return item;
2590
+ const bytes = Buffer.from(match[2], "base64");
2591
+ const hash = createHash("sha256").update(bytes).digest("hex");
2592
+ if (!cache.has(hash)) cache.set(hash, {
2593
+ bytes,
2594
+ contentType: item.contentType ?? match[1]
2595
+ });
2596
+ return {
2597
+ ...item,
2598
+ src: `/media/${hash}`
2599
+ };
2600
+ })
2601
+ };
2602
+ }
2603
+ function mediaRange(value, length) {
2604
+ if (!value) return {
2605
+ start: 0,
2606
+ end: length - 1,
2607
+ partial: false
2608
+ };
2609
+ const match = /^bytes=(\d*)-(\d*)$/.exec(value);
2610
+ if (!match || !match[1] && !match[2] || length === 0) return null;
2611
+ let start;
2612
+ let end;
2613
+ if (!match[1]) {
2614
+ const suffix = Number(match[2]);
2615
+ if (!Number.isSafeInteger(suffix) || suffix <= 0) return null;
2616
+ start = Math.max(0, length - suffix);
2617
+ end = length - 1;
2618
+ } else {
2619
+ start = Number(match[1]);
2620
+ end = match[2] ? Number(match[2]) : length - 1;
2621
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= length) return null;
2622
+ end = Math.min(end, length - 1);
2623
+ }
2624
+ return {
2625
+ start,
2626
+ end,
2627
+ partial: true
2628
+ };
2629
+ }
2630
+ const REMEMBERED_DOCUMENTS = 32;
2631
+ const EDITOR_CHUNK = /^\/editor-chunks\/[\w-]+\.js$/;
2632
+ const BUNDLED_ASSETS = {
2633
+ "/terminal.js": "terminal-client.js",
2634
+ "/terminal.css": "terminal-client.css",
2635
+ "/editor.js": "editor.js",
2636
+ "/animation-player.js": "animation-player.js",
2637
+ "/media-player.js": "media-player.js"
2638
+ };
1191
2639
  async function serveDeck(entry, port = 4173) {
1192
2640
  let latest;
2641
+ let source;
2642
+ let sourceHash;
2643
+ let documentHash;
2644
+ let mediaCache = /* @__PURE__ */ new Map();
2645
+ let publishedMedia = [];
2646
+ const store = editorStore(entry);
2647
+ let saved = await store.read();
2648
+ let conflicts = [];
2649
+ const documents = /* @__PURE__ */ new Map();
2650
+ let uploads = 0;
2651
+ function remember(id, bytes) {
2652
+ documents.set(id, bytes);
2653
+ if (documents.size > REMEMBERED_DOCUMENTS) documents.delete(documents.keys().next().value);
2654
+ }
2655
+ const serverId = randomUUID();
2656
+ const projectId = createHash("sha256").update(resolve(entry)).digest("hex");
2657
+ let publishing = Promise.resolve();
2658
+ function publish(fn) {
2659
+ const result = publishing.then(fn);
2660
+ publishing = result.then(() => {}, () => {});
2661
+ return result;
2662
+ }
1193
2663
  let error = null;
1194
2664
  let building = false;
1195
2665
  let revision = 0;
@@ -1225,6 +2695,240 @@ async function serveDeck(entry, port = 4173) {
1225
2695
  }
1226
2696
  return result;
1227
2697
  }
2698
+ function editorState() {
2699
+ const conflict = !!saved && !!sourceHash && saved.sourceHash !== sourceHash;
2700
+ return {
2701
+ projectId,
2702
+ revision: `${serverId}:${revision}`,
2703
+ previewRevision: revision,
2704
+ documentHash,
2705
+ sourceHash,
2706
+ fileName: basename(entry).replace(/\.[^.]+$/, "") + ".pptx",
2707
+ hasEdits: !!saved,
2708
+ conflict,
2709
+ conflicts: conflict ? conflicts : [],
2710
+ building,
2711
+ error,
2712
+ available: !!latest
2713
+ };
2714
+ }
2715
+ function update(result) {
2716
+ patch = {};
2717
+ result.slides.forEach((svg, index) => {
2718
+ if (svg !== latest?.slides[index]) patch[index] = svg;
2719
+ });
2720
+ latest = result;
2721
+ ({cache: mediaCache, published: publishedMedia} = cacheEmbeddedMedia(result.media));
2722
+ documentHash = sourceFingerprint(result.bytes);
2723
+ revision++;
2724
+ remember(`${serverId}:${revision}`, result.bytes);
2725
+ }
2726
+ function notify() {
2727
+ for (const client of clients) client.write("data: updated\n\n");
2728
+ }
2729
+ /**
2730
+ * Accepts an editor upload. An upload based on an older document the editor
2731
+ * loaded (the source rebuilt meanwhile) is merged with the current one.
2732
+ */
2733
+ function acceptUpload(bytes, basis, keepEdits) {
2734
+ if (!source || !sourceHash || !latest || building || error || closed) return {
2735
+ ok: false,
2736
+ refused: "busy",
2737
+ conflicts: []
2738
+ };
2739
+ const state = editorState();
2740
+ if (state.conflict && !keepEdits) return {
2741
+ ok: false,
2742
+ refused: "conflict",
2743
+ conflicts: state.conflicts
2744
+ };
2745
+ const accepted = {
2746
+ ok: true,
2747
+ source,
2748
+ sourceHash
2749
+ };
2750
+ if (basis === state.revision) return {
2751
+ ...accepted,
2752
+ bytes,
2753
+ merged: false
2754
+ };
2755
+ const based = basis !== void 0 && !keepEdits ? documents.get(basis) : void 0;
2756
+ if (!based) return {
2757
+ ok: false,
2758
+ refused: "stale",
2759
+ conflicts: []
2760
+ };
2761
+ const merged = mergeDecks(based, bytes, latest.bytes);
2762
+ return merged.ok ? {
2763
+ ...accepted,
2764
+ bytes: merged.bytes,
2765
+ merged: true
2766
+ } : {
2767
+ ok: false,
2768
+ refused: "conflict",
2769
+ conflicts: merged.conflicts
2770
+ };
2771
+ }
2772
+ async function edit(request, response) {
2773
+ const json = (status, message, extra = {}) => {
2774
+ response.writeHead(status, { "Content-Type": "application/json" });
2775
+ response.end(JSON.stringify({
2776
+ ...editorState(),
2777
+ ...message ? { message } : {},
2778
+ ...extra
2779
+ }));
2780
+ };
2781
+ const refuse = (upload) => json(409, upload.refused === "conflict" ? "These edits conflict with changes in the source." : "The preview changed. Review the current source before saving.", {
2782
+ refused: upload.refused,
2783
+ mergeConflicts: upload.conflicts
2784
+ });
2785
+ if (request.headers.origin !== `http://${request.headers.host}` || request.headers["sec-fetch-site"] === "cross-site") {
2786
+ request.resume();
2787
+ json(403, "Editor requests must come from this preview.");
2788
+ return;
2789
+ }
2790
+ const useSource = request.url === "/editor/resolve" && request.method === "POST";
2791
+ const save = request.url === "/editor/document" && request.method === "PUT";
2792
+ if (!useSource && !save) {
2793
+ request.resume();
2794
+ json(405);
2795
+ return;
2796
+ }
2797
+ if (save && request.headers["content-type"] !== "application/octet-stream") {
2798
+ request.resume();
2799
+ json(415);
2800
+ return;
2801
+ }
2802
+ const chunks = [];
2803
+ let length = 0;
2804
+ const MAX_EDITOR_BYTES = 64 * 1024 * 1024;
2805
+ const basis = request.headers["if-match"];
2806
+ const keepEdits = request.headers["x-editor-resolve"] === "edits";
2807
+ const uploaded = (bytes, upload) => {
2808
+ if (!upload.merged) return {};
2809
+ const id = `${serverId}:upload:${++uploads}`;
2810
+ remember(id, bytes);
2811
+ return {
2812
+ merged: true,
2813
+ uploadRevision: id
2814
+ };
2815
+ };
2816
+ try {
2817
+ for await (const chunk of request) {
2818
+ length += chunk.length;
2819
+ if (length > MAX_EDITOR_BYTES) {
2820
+ json(413, "The editor upload exceeds 64 MiB.");
2821
+ return;
2822
+ }
2823
+ chunks.push(chunk);
2824
+ }
2825
+ if (save && sourceSync) {
2826
+ const received = new Uint8Array(Buffer.concat(chunks));
2827
+ const upload = acceptUpload(received, basis, keepEdits);
2828
+ if (!upload.ok) {
2829
+ refuse(upload);
2830
+ return;
2831
+ }
2832
+ const bytes = upload.bytes;
2833
+ let synced;
2834
+ try {
2835
+ synced = await sourceSync.sync(bytes);
2836
+ } catch (cause) {
2837
+ synced = {
2838
+ written: [],
2839
+ pending: [{
2840
+ kind: "unsupported",
2841
+ slide: null,
2842
+ shapeId: null,
2843
+ description: cause instanceof Error ? cause.message : String(cause)
2844
+ }],
2845
+ complete: false
2846
+ };
2847
+ }
2848
+ await publish(async () => {
2849
+ if (!source || !sourceHash || closed) {
2850
+ json(409, "The preview changed. Review the current source before saving.", { refused: "busy" });
2851
+ return;
2852
+ }
2853
+ if (synced.complete) {
2854
+ await store.clear();
2855
+ saved = void 0;
2856
+ update(source);
2857
+ } else {
2858
+ let result;
2859
+ try {
2860
+ result = (await renderDeck(bytes, source.dependencies)).result;
2861
+ } catch (cause) {
2862
+ json(400, cause instanceof Error ? cause.message : String(cause));
2863
+ return;
2864
+ }
2865
+ const edits = {
2866
+ sourceHash,
2867
+ base: source.bytes,
2868
+ bytes
2869
+ };
2870
+ await store.write(edits);
2871
+ saved = edits;
2872
+ update(result);
2873
+ }
2874
+ json(200, void 0, {
2875
+ ...uploaded(received, upload),
2876
+ writeBack: {
2877
+ written: synced.written.length,
2878
+ pending: synced.pending
2879
+ }
2880
+ });
2881
+ notify();
2882
+ });
2883
+ return;
2884
+ }
2885
+ await publish(async () => {
2886
+ if (useSource) {
2887
+ if (!source || !sourceHash || building || error || closed || basis !== editorState().revision) {
2888
+ json(409, "The preview changed. Review the current source before saving.", { refused: "busy" });
2889
+ return;
2890
+ }
2891
+ await store.clear();
2892
+ saved = void 0;
2893
+ update(source);
2894
+ json(200);
2895
+ notify();
2896
+ return;
2897
+ }
2898
+ const received = new Uint8Array(Buffer.concat(chunks));
2899
+ const upload = acceptUpload(received, basis, keepEdits);
2900
+ if (!upload.ok) {
2901
+ refuse(upload);
2902
+ return;
2903
+ }
2904
+ const started = generation;
2905
+ let result;
2906
+ try {
2907
+ result = (await renderDeck(upload.bytes, upload.source.dependencies)).result;
2908
+ } catch (cause) {
2909
+ json(400, cause instanceof Error ? cause.message : String(cause));
2910
+ return;
2911
+ }
2912
+ if (started !== generation) {
2913
+ json(409, "Source changed during save.", { refused: "busy" });
2914
+ return;
2915
+ }
2916
+ const edits = {
2917
+ sourceHash: upload.sourceHash,
2918
+ base: upload.source.bytes,
2919
+ bytes: upload.bytes
2920
+ };
2921
+ await store.write(edits);
2922
+ saved = edits;
2923
+ update(result);
2924
+ json(200, void 0, uploaded(received, upload));
2925
+ notify();
2926
+ });
2927
+ } catch (cause) {
2928
+ if (!response.headersSent) json(500, cause instanceof Error ? cause.message : String(cause));
2929
+ }
2930
+ }
2931
+ const sourceSync = process.env.OFFICE_KIT_TSX_WRITE_BACK === "1" ? createSourceSync(resolve(entry), () => source, verify) : void 0;
1228
2932
  const textEditor = createTextEditor(resolve(entry), () => {
1229
2933
  if (!latest || building || pending || timer || error) throw new Error("Wait for a successful preview build.");
1230
2934
  return {
@@ -1244,6 +2948,39 @@ async function serveDeck(entry, port = 4173) {
1244
2948
  response.writeHead(404).end();
1245
2949
  return;
1246
2950
  }
2951
+ const mediaMatch = request.url?.match(/^\/media\/([a-f0-9]{64})(?:\?.*)?$/);
2952
+ if (mediaMatch) {
2953
+ if (request.method !== "GET") {
2954
+ response.writeHead(405).end();
2955
+ return;
2956
+ }
2957
+ const cached = mediaCache.get(mediaMatch[1]);
2958
+ if (!cached) {
2959
+ response.writeHead(404).end();
2960
+ return;
2961
+ }
2962
+ const range = mediaRange(request.headers.range, cached.bytes.length);
2963
+ const immutableHeaders = {
2964
+ "Accept-Ranges": "bytes",
2965
+ "Cache-Control": "public, max-age=31536000, immutable",
2966
+ "Content-Type": cached.contentType
2967
+ };
2968
+ if (!range) {
2969
+ response.writeHead(416, {
2970
+ ...immutableHeaders,
2971
+ "Content-Range": `bytes */${cached.bytes.length}`
2972
+ }).end();
2973
+ return;
2974
+ }
2975
+ const bytes = cached.bytes.subarray(range.start, range.end + 1);
2976
+ response.writeHead(range.partial ? 206 : 200, {
2977
+ ...immutableHeaders,
2978
+ "Content-Length": bytes.length,
2979
+ ...range.partial ? { "Content-Range": `bytes ${range.start}-${range.end}/${cached.bytes.length}` } : {}
2980
+ });
2981
+ response.end(bytes);
2982
+ return;
2983
+ }
1247
2984
  if (request.url === "/history" && request.method === "GET") {
1248
2985
  response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(history.state()));
1249
2986
  return;
@@ -1357,12 +3094,34 @@ async function serveDeck(entry, port = 4173) {
1357
3094
  buildError: error
1358
3095
  };
1359
3096
  });
1360
- } else if (request.method === "GET" && ["/terminal.js", "/terminal.css"].includes(request.url ?? "")) {
1361
- const asset = request.url === "/terminal.js" ? "terminal-client.js" : "terminal-client.css";
3097
+ } else if (request.method === "GET" && BUNDLED_ASSETS[(request.url ?? "").split("?")[0]] !== void 0) {
3098
+ const asset = BUNDLED_ASSETS[(request.url ?? "").split("?")[0]];
1362
3099
  readFile(new URL(asset, import.meta.url)).then((bytes) => {
1363
3100
  response.writeHead(200, { "Content-Type": asset.endsWith(".css") ? "text/css" : "text/javascript" });
1364
3101
  response.end(bytes);
1365
- }, () => response.writeHead(500).end("Terminal assets unavailable. Rebuild pptx-dev."));
3102
+ }, () => response.writeHead(500).end("Preview assets unavailable. Rebuild pptx-dev."));
3103
+ } else if (request.method === "GET" && EDITOR_CHUNK.test(request.url ?? "")) readFile(new URL(`.${request.url}`, import.meta.url)).then((bytes) => response.writeHead(200, { "Content-Type": "text/javascript" }).end(bytes), () => response.writeHead(404).end());
3104
+ else if (request.url?.startsWith("/editor/") && request.method !== "GET") edit(request, response);
3105
+ else if (request.method === "GET" && request.url === "/editor/state") response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(editorState()));
3106
+ else if (request.method === "GET" && (request.url === "/editor/base" || request.url?.startsWith("/editor/document?revision="))) {
3107
+ const bytes = request.url === "/editor/base" ? saved?.base : documents.get(new URL(request.url, "http://localhost").searchParams.get("revision") ?? "");
3108
+ if (!bytes) {
3109
+ response.writeHead(404).end();
3110
+ return;
3111
+ }
3112
+ response.writeHead(200, { "Content-Type": "application/octet-stream" });
3113
+ response.end(bytes);
3114
+ } else if (request.method === "GET" && ["/editor/document", "/editor/source"].includes(request.url ?? "")) {
3115
+ const result = request.url === "/editor/source" ? source : latest;
3116
+ if (!result) {
3117
+ response.writeHead(503).end();
3118
+ return;
3119
+ }
3120
+ response.writeHead(200, {
3121
+ "Content-Type": "application/octet-stream",
3122
+ ETag: editorState().revision
3123
+ });
3124
+ response.end(result.bytes);
1366
3125
  } else if (request.method !== "GET") response.writeHead(405).end();
1367
3126
  else if (request.url === "/events") {
1368
3127
  response.writeHead(200, { "Content-Type": "text/event-stream" });
@@ -1381,6 +3140,13 @@ async function serveDeck(entry, port = 4173) {
1381
3140
  count: latest?.slides.length ?? 0
1382
3141
  } : { slides: latest?.slides ?? [] },
1383
3142
  aspectRatio: latest?.aspectRatio ?? 16 / 9,
3143
+ transitions: latest?.transitions ?? [],
3144
+ animations: latest?.animations ?? [],
3145
+ media: publishedMedia,
3146
+ showProperties: latest?.showProperties ?? null,
3147
+ customShows: latest?.customShows ?? [],
3148
+ notes: latest?.notes ?? [],
3149
+ hiddenSlides: latest?.hiddenSlides ?? [],
1384
3150
  error,
1385
3151
  diagnostics: latest?.diagnostics ?? []
1386
3152
  }));
@@ -1390,6 +3156,12 @@ async function serveDeck(entry, port = 4173) {
1390
3156
  "Content-Disposition": "attachment; filename=\"deck.pptx\""
1391
3157
  });
1392
3158
  response.end(latest.bytes);
3159
+ } else if (request.url === "/editor") {
3160
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
3161
+ response.end("<!doctype html><html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>Presentation editor</title><body><script type=\"module\" src=\"/editor.js\"><\/script></body></html>");
3162
+ } else if (request.url === "/presenter") {
3163
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
3164
+ response.end(presenterPage);
1393
3165
  } else if (request.url === "/") {
1394
3166
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1395
3167
  response.end(page);
@@ -1415,15 +3187,33 @@ async function serveDeck(entry, port = 4173) {
1415
3187
  for (const client of clients) client.write("data: building\n\n");
1416
3188
  try {
1417
3189
  const result = await builder.build();
1418
- if (started === generation && !closed) {
1419
- patch = {};
1420
- result.slides.forEach((svg, index) => {
1421
- if (svg !== latest?.slides[index]) patch[index] = svg;
1422
- });
1423
- latest = result;
1424
- revision++;
3190
+ await publish(async () => {
3191
+ if (started !== generation || closed) return;
3192
+ const nextHash = sourceFingerprint(result.bytes);
3193
+ let unmerged = [];
3194
+ let merged;
3195
+ if (saved?.base && saved.sourceHash !== nextHash) {
3196
+ const merge = mergeDecks(saved.base, saved.bytes, result.bytes);
3197
+ if (!merge.ok) unmerged = merge.conflicts;
3198
+ else if (sourceFingerprint(merge.bytes) === nextHash) merged = null;
3199
+ else merged = {
3200
+ sourceHash: nextHash,
3201
+ base: result.bytes,
3202
+ bytes: merge.bytes
3203
+ };
3204
+ }
3205
+ const edits = merged === void 0 ? saved : merged ?? void 0;
3206
+ const edited = edits ? (await renderDeck(edits.bytes, result.dependencies)).result : result;
3207
+ if (started !== generation || closed) return;
3208
+ if (merged) await store.write(merged);
3209
+ else if (merged === null) await store.clear();
3210
+ saved = edits;
3211
+ source = result;
3212
+ sourceHash = nextHash;
3213
+ conflicts = unmerged;
3214
+ update(edited);
1425
3215
  error = null;
1426
- }
3216
+ });
1427
3217
  } catch (cause) {
1428
3218
  if (started === generation) error = cause instanceof Error ? cause.stack ?? cause.message : String(cause);
1429
3219
  } finally {
@@ -1480,6 +3270,7 @@ async function serveDeck(entry, port = 4173) {
1480
3270
  watcher.close();
1481
3271
  await Promise.all([...sessions.values()].flatMap(({ terminal, chat }) => [terminal.close(), chat.close()]));
1482
3272
  await builder.close();
3273
+ await publishing;
1483
3274
  for (const client of clients) client.end();
1484
3275
  await new Promise((done, reject) => server.close((cause) => cause ? reject(cause) : done()));
1485
3276
  }