Repository navigation
Expand file tree
/
Copy patheditor.js
More file actions
1912 lines (1894 loc) · 154 KB
/
Copy patheditor.js
File metadata and controls
1912 lines (1894 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Dependency-free workspace UI. Source, file names, logs and engine messages are inserted as text. */
import {icon} from './icons.js';
import {createI18n} from './i18n.js';
import {DEFAULT_SETTINGS,loadSettings,saveSettings} from './settings.js';
import {createProject,basename,dirname,joinPath,isImagePath,decodeText,fileBytes,normalizePath} from './project.js';
import {openStore} from './storage.js';
import {TEMPLATES,templateProject} from './templates.js';
import {createCodeEditor} from './code-editor.js';
import {createMathPopover} from './math-popover.js';
import {createFileTree} from './file-tree.js';
import {openMenu,openDialog,openPopover,confirmDialog,createToast} from './overlays.js';
import {createInspector} from './inspector.js';
import {createThumbnails} from './thumbnails.js';
import {createTooltips} from './tooltip.js';
import {mathAt} from '../core/math-preview.js';
import {zip,unzip} from '../core/zip.js';
import {documentTitle,parseOutline} from '../core/outline.js';
import {wordCount} from '../core/word-count.js';
import {createOutline} from './outline.js';
import {createFindBar} from './find-bar.js';
import {openPalette} from './palette.js';
import {openTemplateGallery} from './template-gallery.js';
import {createCompletion} from './complete.js';
import {openSymbols,SYMBOLS} from './symbols.js';
import {openHistory} from './history.js';
import {createLabels} from './labels.js';
import {watchEdges} from './edges.js';
import {explainReason} from '../core/live-reasons.js';
import {referenceCounts,targetAt,findLabels,findReferences,findDefinition,nearest} from '../core/references.js';
import {environmentAt} from '../core/brackets.js';
import {parseBib,byline,plainField} from '../core/bib.js';
import {createBreadcrumbs} from './breadcrumbs.js';
import {createHoverCard} from './hovercard.js';
import {quickFixes,packageEdit} from '../core/quick-fix.js';
import {openTablePicker} from './table-picker.js';
import {createPdfFind} from './pdf-find.js';
const LEGACY_DRAFT='realtime-tex-web:draft:v1',LEGACY_CONSENT='realtime-tex-web:save-draft:v1',TAB_PROJECT='lightningtex:project';
const MAX_UPLOAD=20*1024*1024,ZOOMS=[0.5,0.67,0.8,0.9,1,1.1,1.25,1.5,1.75,2,2.5,3];
const ACCENTS={bolt:'#f5b800',indigo:'#6366f1',teal:'#0d9488',rose:'#e5487d'};
const mac=/Mac|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||'');
const keys=combo=>mac?combo.replace('Mod+','⌘').replace('Alt+','⌥').replace('Shift+','⇧').replace('Enter','↵').replace(/\bUp\b/,'↑').replace(/\bDown\b/,'↓'):combo.replace('Mod+','Ctrl+');
const clamp=(value,low,high)=>Math.min(high,Math.max(low,value));
// Stand-in page shown until there is a PDF: skeleton while working, blank for an empty document.
const SHEET='<div class="preview-content"><div class="sheet" data-id="sheet" data-state="loading"><div class="sheet-lines"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="load-steps" data-id="load-steps"></div><div class="sheet-note" data-id="sheet-note"></div><button type="button" class="btn" data-action="show-problems" data-i18n="preview.show" hidden></button></div></div>';
const shell=()=>`<div class="app">
<div class="load-bar" data-id="load-bar"><i></i></div>
<header class="appbar">
<div class="appbar-side">
<button type="button" class="icon-btn" data-action="toggle-sidebar" data-i18n-title="sidebar.toggle" data-keys="${keys('Mod+B')}">${icon('sidebar')}</button>
<span class="brand"><span class="brand-mark" aria-hidden="true"></span><b>Lightning<span class="tex">T<i>E</i>X</span></b></span>
<button type="button" class="project-btn" data-action="project-menu" data-i18n-title="project.menu" aria-haspopup="menu"><span data-id="project-name"></span>${icon('chevronDown',12)}</button>
<button type="button" class="icon-btn" data-action="palette" data-i18n-title="palette.open" data-keys="${keys('Mod+K')}">${icon('search')}</button>
</div>
<div class="segmented layout" data-id="layout" role="radiogroup" data-i18n-title="layout.label" data-keys="${keys('Mod+\\')}"><i class="seg-thumb"></i>${['source','split','preview'].map(value=>`<button type="button" role="radio" data-value="${value}" data-i18n="view.${value}"></button>`).join('')}</div>
<div class="appbar-side end">
<div class="capsule" data-id="preview-status" data-state="none">
<button type="button" class="cap-state" data-action="capsule" disabled data-i18n-title="compile.now" data-keys="${keys('Mod+Enter')}"><i class="dot"></i><span data-id="preview-status-text"></span><span class="cap-live" data-id="stat-live"></span><span class="cap-bars" data-id="cap-bars" aria-hidden="true">${'<i></i>'.repeat(12)}</span></button>
<button type="button" class="btn primary cap-compile" data-action="compile" disabled data-i18n-title="compile.run" data-keys="${keys('Mod+Enter')}">${icon('play',14)}<span data-i18n="compile.run"></span></button>
<button type="button" class="icon-btn cap-stop" data-action="cancel" hidden data-i18n-title="compile.stop">${icon('stop',14)}</button>
<button type="button" class="icon-btn cap-more" data-action="capsule-menu" data-i18n-title="capsule.menu" aria-haspopup="menu">${icon('chevronDown',12)}</button>
<input type="checkbox" class="sr-only" data-id="auto-compile" tabindex="-1" aria-hidden="true">
</div>
<button type="button" class="btn export-btn" data-action="export-menu" data-i18n-title="export.open" aria-haspopup="menu"><span class="export-icon">${icon('download')}${icon('check')}</span><span data-i18n="export.open"></span>${icon('chevronDown',12)}</button>
<button type="button" class="icon-btn" data-action="settings" data-i18n-title="settings.open" data-keys="${keys('Mod+,')}">${icon('settings')}</button>
</div>
</header>
<div class="main" data-id="main">
<aside class="sidebar" data-id="sidebar"><div class="sidebar-in">
<div class="side-switch" data-id="side-switch" role="tablist"><i class="seg-thumb"></i>${['files','outline','labels'].map(view=>`<button type="button" role="tab" data-side="${view}" data-i18n="side.${view}"></button>`).join('')}</div>
<div class="side-view" data-view="files" role="tabpanel">
<div class="side-head"><span class="spacer"></span>
<button type="button" class="icon-btn" data-action="new-file" data-i18n-title="file.new">${icon('fileAdd')}</button>
<button type="button" class="icon-btn" data-action="new-folder" data-i18n-title="folder.new">${icon('folderAdd')}</button>
<button type="button" class="icon-btn" data-action="upload" data-i18n-title="file.upload">${icon('upload')}</button>
</div>
<div class="side-scroll"><div class="tree" data-id="tree" role="tree"></div></div>
<div class="tree-empty" data-id="tree-empty" hidden><strong data-i18n="empty.files"></strong><p data-i18n="empty.hint"></p><button class="btn" data-action="empty-new" data-i18n="file.new"></button><button class="btn" data-action="new-project" data-i18n="project.template"></button><button class="text-btn" data-action="empty-import" data-i18n="project.import"></button></div>
<div class="side-now" data-id="side-now" hidden></div>
</div>
<div class="side-view" data-view="outline" role="tabpanel" hidden><div class="side-scroll"><nav class="outline" data-id="outline" data-i18n-title="outline.title"></nav></div></div>
<div class="side-view" data-view="labels" role="tabpanel" hidden><div class="side-scroll"><div class="labels" data-id="labels"></div></div></div>
<div class="side-foot">
<button class="text-btn" data-action="history" data-i18n-title="history.open">${icon('history',14)}<span data-i18n="history.open"></span></button>
<a class="icon-btn" href="https://github.com/CodeBoy2006/LightningTeX" target="_blank" rel="noopener noreferrer" data-i18n-title="app.repository">${icon('github')}</a>
</div>
<input data-id="file-input" type="file" multiple hidden><input data-id="zip-input" type="file" accept=".zip,application/zip" hidden>
</div></aside>
<div class="splitter" data-split="sidebar" role="separator" aria-orientation="vertical" tabindex="0" data-i18n-title="splitter.help"></div>
<section class="editor-pane">
<header class="pane-head"><div class="tabs" data-id="tabs" role="tablist"></div></header>
<nav class="crumbs" data-id="crumbs" hidden></nav>
<span class="sr-only" id="editor-keyboard-help" data-i18n="editor.help"></span>
<div class="editor-host" data-id="editor-host"><div class="editor-empty" data-id="editor-empty" hidden>${icon('file',28)}<span data-i18n="editor.empty"></span><button class="btn" data-action="editor-new" data-i18n="file.new"></button><button class="text-btn" data-action="editor-palette"><span data-i18n="palette.open"></span><kbd>${keys('Mod+K')}</kbd></button></div></div>
<section class="panel" data-id="panel" hidden>
<header class="panel-head">
<button type="button" class="panel-tab" data-panel="problems"><span data-i18n="panel.problems"></span><span class="count" data-id="problem-count"></span></button>
<button type="button" class="panel-tab" data-panel="log" data-i18n="panel.log"></button>
<button type="button" class="panel-tab" data-panel="refs" data-id="refs-tab" hidden><span data-i18n="panel.refs"></span><span class="count" data-id="refs-count"></span></button>
<span class="spacer"></span>
<button type="button" class="icon-btn" data-action="problem-filter" data-i18n-title="panel.filter">${icon('filter')}</button>
<button type="button" class="icon-btn" data-action="copy-log" data-i18n-title="panel.copy">${icon('copy')}</button>
<button type="button" class="icon-btn" data-action="clear-log" data-i18n-title="common.clear">${icon('trash')}</button>
<button type="button" class="icon-btn" data-action="close-panel" data-i18n-title="common.close">${icon('close')}</button>
</header>
<div class="panel-body"><div class="problems" data-id="problems"></div>
<pre class="logs" data-id="logs" tabindex="0" hidden></pre><div class="problems refs" data-id="refs" hidden></div></div>
</section>
</section>
<div class="splitter" data-split="preview" role="separator" aria-orientation="vertical" tabindex="0" data-i18n-title="splitter.help"></div>
<section class="preview-pane">
<button type="button" class="preview-error" data-id="preview-error" hidden></button>
<div class="preview-body"><nav class="thumbs" data-id="thumbs" data-i18n-title="thumbs.title" hidden></nav><div class="preview" data-id="preview-viewport" tabindex="0" data-i18n-title="preview.locate">${SHEET}</div></div>
<button type="button" class="marker-chip" data-id="marker-chip" hidden></button>
<span class="page-tag" data-id="page-tag" aria-hidden="true" hidden></span>
<div class="zoombar" data-id="zoombar">
<button type="button" class="icon-btn" data-action="zoom-out" data-i18n-title="zoom.out">${icon('minus')}</button>
<button type="button" class="zoom-label" data-action="zoom-menu" data-id="zoom-label" data-i18n-title="zoom.menu" aria-haspopup="menu"></button><span class="zoom-note" data-id="zoom-note" hidden></span>
<button type="button" class="icon-btn" data-action="zoom-in" data-i18n-title="zoom.in">${icon('plus')}</button>
<button type="button" class="icon-btn" data-action="zoom-fit" data-i18n-title="zoom.fit">${icon('fit')}</button>
<button type="button" class="icon-btn" data-action="toggle-thumbs" data-i18n-title="thumbs.toggle" data-keys="${keys('Mod+Alt+T')}">${icon('pages')}</button>
<button type="button" class="icon-btn" data-action="pdf-find" data-i18n-title="pdfFind.open" data-keys="${keys('Mod+F')}">${icon('search')}</button>
<label class="page-nav" data-id="page-nav" hidden><input class="page-input" data-id="page-input" type="text" inputmode="numeric" autocomplete="off" data-i18n-title="page.jump"><span data-id="page-indicator"></span></label>
</div>
</section>
</div>
<footer class="statusbar">
<button type="button" class="stat" data-action="toggle-panel" data-id="stat-problems" data-i18n-title="panel.toggle" data-keys="${keys('Mod+J')}"></button>
<span class="stat" data-id="stat-engine"></span>
<button type="button" class="stat pdf-sync" data-action="pdf-sync" data-id="pdf-sync" hidden></button>
<span class="spacer"></span>
<button type="button" class="stat" data-action="word-count" data-id="word-count" data-i18n-title="words.title"></button><span class="stat" data-id="stat-doc"></span><span class="stat" data-id="cursor-status"></span><span class="stat" data-id="save-status"></span>
</footer>
<div class="settings" data-id="settings" role="dialog" hidden></div>
<div class="toasts" data-id="toast" hidden></div>
<div class="drop-veil" data-id="drop-veil" hidden>${icon('upload',28)}</div>
</div>`;
// [label key, combo]; "Mod" is Command or Control.
const EDITOR_SHORTCUTS=[['keys.comment','Mod+/'],['keys.indent','Tab / Shift+Tab'],['keys.snippets','Tab'],['keys.stops','Tab / Shift+Tab'],
['keys.moveLine','Alt+Up / Alt+Down'],['keys.dupLine','Shift+Alt+Down'],['keys.deleteLine','Mod+Shift+K'],['keys.selectLine','Mod+L'],['keys.selectNext','Mod+D'],
['keys.follow','F12'],['keys.rename','F2'],['keys.refs','Shift+F12'],['keys.escape','Esc']];
// [category, section title, [key, kind, values?]…] — every row edits one setting, applies at once and says what it does.
const SETTINGS=[
['appearance','set.appearance',[['theme','choice',['system','light','dark']],['accent','swatch',Object.keys(ACCENTS)],['lang','choice',['auto','en','zh']],['darkPages','toggle']]],
['editor','set.editor',[['fontSize','step',[11,20]],['wrap','toggle'],['autoClose','toggle'],['tabSize','choice',[2,4]],['spellcheck','toggle']]],
['preview','set.preview',[['autoCompile','toggle'],['mathPreview','toggle'],['mathScale','choice',['s','m','l']],['follow','toggle'],['thumbs','toggle'],['spread','choice',['single','double','cover']]]],
['storage','set.storage',[['persist','toggle']]],
];
const SETTING_GROUPS=[...SETTINGS.map(([id,title])=>[id,title]),['shortcuts','keys.title']];
const choiceLabel={lang:{en:'English',zh:'中文',auto:'set.lang.auto'},theme:value=>'set.theme.'+value,mathScale:value=>'size.'+value,spread:value=>'spread.short.'+value};
/**
* mountEditor({ root, source?, project?, store?, onCompile, onPreview?, onCancel?, onSourceChange?, renderPdf?,
* typesetMath?, onCursor?, onPreviewPick?, previewIntervalMs? })
* onCompile({source, root, files, filesRev, revision, reason}) may return {pdf:Uint8Array, revision?, durationMs?},
* or {empty:true} for a document without pages; files are the project's other files as {path, data, rev}.
* Never return a fake PDF.
* onPreview(request) uses the same input, returning true, 'reflow' (settle after idle), or false (full pass).
* renderPdf({bytes, container, signal, zoom, viewport, width, dark}) renders into an offscreen container; only a
* successful render replaces the old preview. Page canvases carry data-page and data-base (CSS px at 100%).
* typesetMath({found, source, scale, maxWidth}) resolves {canvas} or {state, message} for the formula popover.
* store: {load, save, clear} persistence (default IndexedDB), or null to keep everything in memory.
*/
export function mountEditor(options={}){
const root=options.root||document.getElementById('app');
if(!root)throw new Error('LightningTeX needs a root element');
const settings=loadSettings(),i18n=createI18n(settings.lang),t=i18n.t,project=createProject();
settings.panel=false; // The problems panel opens on demand; it never starts open.
const state={revision:0,filesRev:0,pdfRevision:-1,previewRevision:-1,engine:'loading',progress:null,loaded:false,
compiling:false,previewing:false,busy:false,pdf:null,meta:null,run:0,logs:[],problems:[],problemFilter:'all',failed:false,live:null,latency:[],marker:null,dirty:false,save:'off',destroyed:false,
timeline:[],timelineId:0,livePages:[],engineInfo:{live:'off',restarts:0},lastFullMs:null};
const views=new Map(),removers=[];
let structure={headings:[],labels:[],paths:[]},wordTotal=0,wordSections=[],historyId=globalThis.crypto.randomUUID();
let tabs=[],active=null,compileTimer,settleTimer,busyTimer,zoomTimer,saveTimer,metaTimer,barTimer,hoverFrame,hoverPoint,rendererAbort,pdfSequence=0,previewRun=0,store=null,saving=null,restoring=false,storageWarned=false;
let pending=null,panelAuto=false,lastPulse=0,panelMotion=null,inkTimer;const inks=new Map();
// Projects: `store` holds every project (or is a single-project store); `scoped` is the open project's view of it.
let scoped=null,currentId=null,switching=false;
const multi=()=>!!store?.listProjects,saver=()=>multi()?scoped:store;
root.innerHTML=shell();
const app=root.firstElementChild;
const $=id=>root.querySelector(`[data-id="${id}"]`);
const action=name=>root.querySelector(`[data-action="${name}"]`);
const listen=(element,type,handler,config)=>{element.addEventListener(type,handler,config);removers.push(()=>element.removeEventListener(type,handler,config));};
const viewport=$('preview-viewport'),marker=Object.assign(document.createElement('div'),{className:'sync-marker'});
let middlePan=null;
listen(viewport,'pointerdown',event=>{
if(event.button!==1)return;
event.preventDefault();
middlePan={id:event.pointerId,x:event.clientX,y:event.clientY,left:viewport.scrollLeft,top:viewport.scrollTop};
viewport.setPointerCapture?.(event.pointerId);
viewport.classList.add('panning');
});
listen(viewport,'pointermove',event=>{
if(!middlePan||event.pointerId!==middlePan.id)return;
if(!(event.buttons&4)){stopMiddlePan(event);return;}
viewport.scrollLeft=middlePan.left-(event.clientX-middlePan.x);
viewport.scrollTop=middlePan.top-(event.clientY-middlePan.y);
});
const stopMiddlePan=event=>{
if(!middlePan||event.pointerId!==middlePan.id)return;
middlePan=null;
viewport.classList.remove('panning');
if(viewport.hasPointerCapture?.(event.pointerId))viewport.releasePointerCapture?.(event.pointerId);
};
listen(viewport,'pointerup',stopMiddlePan);
listen(viewport,'pointercancel',stopMiddlePan);
listen(viewport,'lostpointercapture',stopMiddlePan);
const thumbs=createThumbnails($('thumbs'),{t,pages:()=>[...viewport.querySelectorAll('canvas[data-page]')],goTo:number=>goToPage(number)});
const toaster=createToast($('toast')),toast=(text,undo,group)=>toaster.show(text,undo,group),tips=createTooltips(app);
const notify=(key,values)=>toast(t(key,values));
const download=(data,name,type)=>{const url=URL.createObjectURL(new Blob([data],{type})),link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),30000);};
const mainText=()=>project.get(project.main)?.text??'';
const outline=createOutline($('outline'),t,reveal),labelsView=createLabels($('labels'),t,reveal);
const motion=()=>!globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches&&app.classList.contains('ready');
for(const id of ['tree','outline','labels','problems','logs'])removers.push(watchEdges($(id),$(id).parentElement).destroy);
const activeEditor=()=>views.get(active)?.editor;
const focusEditor=()=>activeEditor()?.focus();
function commands(){return [
{label:'palette.open',key:'Mod+K',icon:'search',run:palette},
{label:'find.open',key:'Mod+F',icon:'search',run:()=>previewFocused()?openPdfFind():views.get(active)?.find?.open(),disabled:!activeEditor()&&!state.pdf},
{label:'pdfFind.open',icon:'search',run:()=>openPdfFind(),disabled:!state.pdf},
{label:'find.replaceOpen',key:'Mod+Shift+H',icon:'edit',run:()=>views.get(active)?.find?.open(true),disabled:!activeEditor()},
{label:'compile.run',key:'Mod+Enter',icon:'play',run:()=>compile(),disabled:state.engine!=='ready'},
{label:'keys.save',key:'Mod+S',icon:'check',run:()=>void flush()},
{label:'sidebar.toggle',key:'Mod+B',icon:'sidebar',run:()=>toggleSidebar()},
{label:'panel.toggle',key:'Mod+J',icon:'warning',run:()=>set('panel',!settings.panel)},
{label:'layout.label',key:'Mod+\\',icon:'sidebar',run:()=>{const order=['split','source','preview'];setLayout(order[(order.indexOf(shownLayout())+1)%3]);}},
{label:'settings.open',key:'Mod+,',icon:'settings',run:()=>toggleSettings()},
{label:'projects.open',key:'Mod+O',icon:'projects',run:()=>void openProjects()},
{label:'project.new',icon:'template',run:()=>templateGallery()},
{label:'project.import',icon:'upload',run:()=>$('zip-input').click()},
{label:'export.open',icon:'download',run:exportMenu},
{label:'compile.auto',icon:'bolt',run:()=>set('autoCompile',!settings.autoCompile)},
{label:'outline.title',icon:'outline',run:()=>showSide('outline',true)},
{label:'labels.title',icon:'hash',run:()=>showSide('labels',true)},
{label:'words.title',icon:'hash',run:wordDetails},
{label:'symbols.open',icon:'sigma',run:symbols,disabled:!activeEditor()},
{label:'table.title',icon:'table',run:()=>insertTable('table'),disabled:!activeEditor()||!isTex(active)},
{label:'matrix.title',icon:'table',run:()=>insertTable('matrix'),disabled:!activeEditor()||!isTex(active)},
{label:'fix.open',key:'Mod+.',icon:'bulb',run:()=>openFixes(),disabled:!activeEditor()},
{label:'rename.title',icon:'rename',run:()=>renameAt(active),disabled:!activeEditor()||!isTex(active)},
{label:'refs.find',icon:'hash',run:()=>referencesAt(active),disabled:!activeEditor()||!isTex(active)},
{label:'history.open',icon:'history',run:history},
{label:'insp.title',icon:'bolt',run:openInspector},
{label:'thumbs.toggle',key:'Mod+Alt+T',icon:'pages',run:()=>set('thumbs',!settings.thumbs)},
{label:'keys.title',icon:'keyboard',run:shortcutSheet},
...['source','split','preview'].map(value=>({label:'view.'+value,icon:'sidebar',run:()=>setLayout(value)})),
...['system','light','dark'].map(value=>({label:'set.theme.'+value,icon:'settings',run:()=>set('theme',value)})),
];}
function palette(){
popover?.hide();updateProject();
const lines=(text,from,count)=>text.split('\n').slice(from,from+count).join('\n');
openPalette({host:app,t,onClose:focusEditor,sources:{
files:()=>project.paths().map(path=>({id:'file:'+path,label:path,icon:isImagePath(path)?'image':'file',run:()=>openFile(path,{focus:true}),
preview:()=>{const file=project.get(path);return {title:path,text:typeof file?.text==='string'?lines(file.text,0,40):`${t('binary.note')} · ${(file.data.length/1024).toFixed(1)} KB`};}})),
sections:()=>[
...structure.headings.map(h=>({id:`section:${h.file}:${h.title}`,label:[h.number,h.title].filter(Boolean).join(' '),detail:`${h.file}:${h.line}`,icon:'outline',run:()=>reveal({path:h.file,line:h.line}),
preview:()=>({title:`${h.file}:${h.line}`,text:lines(project.get(h.file)?.text||'',h.line-1,30)})})),
...structure.labels.map(l=>({id:'label:'+l.name,label:l.name,detail:`${l.file}:${l.line}`,icon:'hash',keywords:l.text,run:()=>reveal({path:l.file,line:l.line}),
preview:()=>({title:`${l.file}:${l.line}`,text:lines(project.get(l.file)?.text||'',Math.max(0,l.line-4),24)})}))],
commands:()=>commands().filter(c=>c.label!=='palette.open').map(c=>({...c,id:'cmd:'+c.label,label:t(c.label),hint:c.key?keys(c.key):''})),
symbols:()=>activeEditor()?SYMBOLS.map(symbol=>({id:'sym:'+symbol.name,label:'\\'+symbol.name,glyph:symbol.glyph,detail:t('symbols.'+symbol.group),run:()=>{const editor=activeEditor();if(!editor)return;const at=editor.input.selectionStart;editor.edit(at,editor.input.selectionEnd,'\\'+symbol.name+(symbol.name==='sqrt'?'{}':' '),symbol.name==='sqrt'?at+6:undefined);}})):[],
line:n=>active&&views.get(active)?.editor?{label:t('palette.line',{n}),icon:'hash',run:()=>reveal({path:active,line:n})}:null,
}});
}
// ---- settings ---------------------------------------------------------------------------------
const darkQuery=globalThis.matchMedia?.('(prefers-color-scheme: dark)'),narrowQuery=globalThis.matchMedia?.('(max-width: 780px)');
// On a narrow screen the file list is a drawer over the editor: closed by default, never persisted.
let drawer=false;
const sidebarOpen=()=>narrowQuery?.matches?drawer:settings.sidebarOpen;
function toggleSidebar(open=!sidebarOpen()){
if(narrowQuery?.matches){drawer=open;applyLayout();return;}
if(open===settings.sidebarOpen)return;
settings.sidebarOpen=open;saveSettings(settings);slideSidebar(open);
}
// The panes take their new widths once, at the start; then only transforms move until the sidebar is in place.
let sidebarMotion=[];
function slideSidebar(open){
for(const animation of sidebarMotion)animation.cancel();sidebarMotion=[];
const side=$('sidebar'),width=settings.sidebar;
if(!motion()||!side.animate){applyLayout();return;}
app.dataset.sidebar=open?'open':'closing';applyLayout();
const rest=[...$('main').children].filter(node=>node!==side&&node.getClientRects().length),timing={duration:open?200:150,easing:open?'cubic-bezier(.2,0,0,1)':'cubic-bezier(.4,0,1,1)'};
const from=open?`translateX(${-width}px)`:`translateX(${width}px)`;
sidebarMotion=[side.animate(open?[{transform:from},{transform:'none'}]:[{transform:'none'},{transform:`translateX(${-width}px)`}],timing),...rest.map(node=>node.animate([{transform:from},{transform:'none'}],timing))];
if(!open)sidebarMotion[0].finished.then(()=>{if(app.dataset.sidebar==='closing'){app.dataset.sidebar='closed';}},()=>{});
}
function showSide(view,focus=false){
toggleSidebar(true);set('sideView',view);
if(focus)$(view==='files'?'tree':view).querySelector('[aria-current="true"],[aria-selected="true"],button,[tabindex="0"]')?.focus();
}
function applySide(){
const switcher=$('side-switch');
for(const button of switcher.querySelectorAll('button')){const on=button.dataset.side===settings.sideView;button.setAttribute('aria-selected',String(on));button.tabIndex=on?0:-1;}
for(const view of root.querySelectorAll('.side-view'))view.hidden=view.dataset.view!==settings.sideView;
placeThumb(switcher);
}
const darkPages=()=>settings.darkPages&&app.dataset.theme==='dark';
let pagesDark=false;
function applyAppearance(){
const theme=settings.theme==='system'?(darkQuery?.matches?'dark':'light'):settings.theme;
for(const target of [app,document.documentElement]){target.dataset.theme=theme;target.dataset.accent=settings.accent;}
app.dataset.darkPages=String(settings.darkPages);document.documentElement.lang=i18n.lang==='zh'?'zh-CN':'en';
// Dark pages are drawn into the page bitmaps, so a change redraws the pages.
if(darkPages()!==pagesDark){pagesDark=darkPages();if(state.pdf){clearTimeout(zoomTimer);zoomTimer=setTimeout(refreshPages,0);}}
}
const placeThumb=control=>{
const thumb=control.querySelector('.seg-thumb'),on=control.querySelector('[aria-checked="true"],[aria-selected="true"]');
if(thumb){thumb.style.width=(on?.offsetWidth||0)+'px';thumb.style.transform=`translateX(${on?.offsetLeft||0}px)`;}
};
const shownLayout=()=>narrowQuery?.matches?(app.dataset.view==='preview'?'preview':'source'):settings.layout;
function applyLayout(){
app.style.setProperty('--sidebar-w',settings.sidebar+'px');app.style.setProperty('--split',String(settings.split));
const side=sidebarOpen()?'open':'closed';if(!(side==='closed'&&app.dataset.sidebar==='closing'))app.dataset.sidebar=side;app.dataset.layout=settings.layout;
for(const button of $('layout').querySelectorAll('button'))button.setAttribute('aria-checked',String(button.dataset.value===shownLayout()));
placeThumb($('layout'));
}
/** 'source' | 'split' | 'preview'. A narrow screen shows one pane at a time and does not keep the choice. */
function setLayout(value){
if(narrowQuery?.matches){app.dataset.view=value==='preview'?'preview':'source';applyLayout();}else transitionLayout(()=>set('layout',value));
layoutPages();popover?.place();placeTabs();
}
// Switching layouts lays the panes out once, then moves them from where they were with transforms.
// A pane that is going away stays drawn above nothing but the background while it slides out.
let layoutMotion=[];
function transitionLayout(change){
const panes=[root.querySelector('.editor-pane'),root.querySelector('.preview-pane')];
for(const animation of layoutMotion)animation.finish();layoutMotion=[];
if(!motion()||!panes[0].animate){change();return;}
const box=$('main').getBoundingClientRect(),before=panes.map(pane=>pane.getClientRects().length?pane.getBoundingClientRect():null);
change();
const after=panes.map(pane=>pane.getClientRects().length?pane.getBoundingClientRect():null),timing={duration:300,easing:'cubic-bezier(.2,0,0,1)'};
panes.forEach((pane,index)=>{
const from=before[index],to=after[index],side=index?1:-1;
if(from&&to){
const dx=from.left-to.left;
if(Math.abs(dx)>.5)layoutMotion.push(pane.animate([{transform:`translateX(${dx}px)`},{transform:'none'}],timing));
else if(to.width-from.width>.5)layoutMotion.push(pane.animate([{clipPath:`inset(0 ${to.width-from.width}px 0 0)`},{clipPath:'inset(0)'}],timing));
}else if(to)layoutMotion.push(pane.animate([{transform:`translateX(${side*to.width}px)`},{transform:'none'}],timing));
else if(from){
pane.dataset.leaving='';Object.assign(pane.style,{left:from.left-box.left+'px',top:'0px',width:from.width+'px',height:from.height+'px'});
const animation=pane.animate([{transform:'none',opacity:1},{transform:`translateX(${side*from.width*.35}px)`,opacity:0}],{...timing,duration:240});
const done=()=>{delete pane.dataset.leaving;for(const key of ['left','top','width','height'])pane.style[key]='';};
animation.finished.then(done,done);layoutMotion.push(animation);
}
});
}
function set(key,value){
if(settings[key]===value)return;
settings[key]=value;saveSettings(settings);
if(key==='theme'||key==='accent'||key==='darkPages')applyAppearance();
else if(key==='lang'){i18n.set(value);applyAppearance();refreshText();}
else if(key==='sidebar'||key==='split'||key==='sidebarOpen'||key==='layout')applyLayout();
else if(key==='sideView')applySide();
else if(key==='thumbs'){applyThumbs();action('toggle-thumbs').setAttribute('aria-pressed',String(value));}
else if(['fontSize','wrap','autoClose','tabSize','spellcheck'].includes(key)){for(const view of views.values())view.editor?.configure(settings);popover?.place();}
else if(key==='autoCompile'){$('auto-compile').checked=value;$('preview-status').dataset.auto=String(value);clearTimeout(compileTimer);clearTimeout(settleTimer);compileTimer=null;if(value&&state.pdfRevision!==state.revision)scheduleCompile();}
else if(key==='mathPreview'||key==='mathScale'){popover?.hide();if(value)updateMath();}
else if(key==='persist')void persistChanged();
else if(key==='panel'||key==='panelTab')renderPanel();
else if(key==='follow')placeMarker(true);
syncSettings();
}
// Settings: a dialog with categories on the left and a search across every row; changes apply at once.
let settingsGroup='appearance',settingsQuery='',settingsReturn=null;
function renderSettings(){
const panel=$('settings');panel.replaceChildren();panel.setAttribute('aria-modal','true');panel.setAttribute('aria-labelledby','settings-title');
const card=make('div','settings-card'),head=make('header','settings-head'),body=make('div','settings-body'),nav=make('nav','settings-nav'),pane=make('div','settings-pane');
const title=make('h2','',t('settings.open'));title.id='settings-title';
const search=make('label','settings-search');search.innerHTML=icon('search',14);
const query=make('input');query.type='search';query.placeholder=t('set.search');query.setAttribute('aria-label',t('set.search'));query.value=settingsQuery;search.append(query);
const close=make('button','icon-btn');close.type='button';close.innerHTML=icon('close');close.setAttribute('aria-label',t('common.close'));close.dataset.tip=t('common.close');close.onclick=()=>toggleSettings(false);
head.append(title,search,close);nav.setAttribute('role','tablist');nav.setAttribute('aria-orientation','vertical');
for(const [id,key] of SETTING_GROUPS){
const tab=make('button','settings-tab',t(key));tab.type='button';tab.setAttribute('role','tab');tab.dataset.group=id;
tab.onclick=()=>{settingsGroup=id;settingsQuery='';query.value='';filterSettings();};nav.append(tab);
}
nav.addEventListener('keydown',event=>{
if(event.key!=='ArrowDown'&&event.key!=='ArrowUp')return;event.preventDefault();
const ids=SETTING_GROUPS.map(([id])=>id),next=ids[(ids.indexOf(settingsGroup)+(event.key==='ArrowDown'?1:ids.length-1))%ids.length];
settingsGroup=next;settingsQuery='';query.value='';filterSettings();nav.querySelector(`[data-group="${next}"]`).focus();
});
const reset=make('button','text-btn settings-reset');reset.type='button';reset.innerHTML=icon('history',14);reset.append(t('set.reset'));
reset.addEventListener('click',()=>{for(const key of Object.keys(DEFAULT_SETTINGS))if(!['sidebarOpen','panel','panelTab','persist'].includes(key))set(key,DEFAULT_SETTINGS[key]);layoutPages();});
nav.append(make('span','spacer'),reset);
for(const [id,heading,rows] of SETTINGS){
const section=make('section');section.dataset.group=id;section.append(make('h3','',t(heading)));
for(const [key,kind,values] of rows){
const row=make('div','setting'),text=make('div','setting-text');text.append(make('span','setting-label',t('set.'+key)),make('span','setting-desc',t('set.'+key+'.desc')));row.append(text);
row.dataset.search=(t('set.'+key)+' '+t('set.'+key+'.desc')+' '+key).toLowerCase();
const control=document.createElement(kind==='toggle'?'label':'div');control.dataset.setting=key;control.className=kind==='toggle'?'switch':kind==='step'?'stepper':'segmented';
if(kind==='choice'||kind==='swatch'){control.setAttribute('role','radiogroup');control.setAttribute('aria-label',t('set.'+key));control.append(Object.assign(document.createElement('i'),{className:'seg-thumb'}));}
if(kind==='toggle'){
const box=Object.assign(document.createElement('input'),{type:'checkbox'});box.setAttribute('aria-label',t('set.'+key));if(key==='persist')box.dataset.id='persist';
box.addEventListener('change',()=>set(key,box.checked));control.append(box,document.createElement('i'));
}else if(kind==='step'){
for(const delta of [-1,1]){
const button=Object.assign(document.createElement('button'),{type:'button',className:'icon-btn',innerHTML:icon(delta<0?'minus':'plus',14)});
button.setAttribute('aria-label',t(delta<0?'set.decrease':'set.increase'));
button.addEventListener('click',()=>set(key,clamp(settings[key]+delta,values[0],values[1])));control.append(button);
}
control.firstChild.after(document.createElement('output'));
}else for(const value of values){
const button=Object.assign(document.createElement('button'),{type:'button'});button.dataset.value=String(value);button.setAttribute('role','radio');
if(kind==='swatch'){button.className='swatch';button.style.setProperty('--swatch',ACCENTS[value]);button.setAttribute('aria-label',value);}
else{const label=choiceLabel[key];button.textContent=!label?String(value):typeof label==='function'?t(label(value)):label[value].includes('.')?t(label[value]):label[value];}
button.addEventListener('click',()=>key==='spread'?setSpread(value):set(key,value));control.append(button);
}
row.append(control);section.append(row);
}
pane.append(section);
}
// Keyboard shortcuts are a category of their own, searchable like the rest.
const keysSection=make('section');keysSection.dataset.group='shortcuts';keysSection.append(make('h3','',t('keys.title')));
const list=make('dl','keys');
for(const [label,combo] of [...commands().filter(c=>c.key).map(c=>[c.label,c.key]),...EDITOR_SHORTCUTS]){
const term=make('dt','',t(label)),cell=make('dd');term.dataset.search=cell.dataset.search=t(label).toLowerCase()+' '+combo.toLowerCase();
for(const part of combo.split(' / '))cell.append(Object.assign(document.createElement('kbd'),{textContent:keys(part)}));
list.append(term,cell);
}
keysSection.append(list);pane.append(keysSection,make('p','settings-empty',t('set.none')));
body.append(nav,pane);card.append(head,body);panel.append(card);
query.addEventListener('input',()=>{settingsQuery=query.value;filterSettings();});
query.addEventListener('keydown',event=>{if(event.key==='Escape'&&query.value){event.preventDefault();event.stopPropagation();query.value=settingsQuery='';filterSettings();}});
syncSettings();filterSettings();
}
// One category at a time; a search shows matching rows from every category under their headings.
function filterSettings(){
const panel=$('settings'),needle=settingsQuery.trim().toLowerCase();let any=false;
for(const tab of panel.querySelectorAll('.settings-tab')){const on=!needle&&tab.dataset.group===settingsGroup;tab.setAttribute('aria-selected',String(on));tab.tabIndex=on?0:-1;}
for(const section of panel.querySelectorAll('.settings-pane section')){
let shown=0;
for(const row of section.querySelectorAll('[data-search]')){const match=!needle||row.dataset.search.includes(needle);row.hidden=!match;if(match)shown++;}
section.hidden=needle?!shown:section.dataset.group!==settingsGroup;if(!section.hidden)any=true;
}
panel.querySelector('.settings-empty').hidden=any;
if(!panel.hidden)for(const control of panel.querySelectorAll('.segmented'))placeThumb(control);
}
function syncSettings(){
for(const control of $('settings').querySelectorAll('[data-setting]')){
const value=settings[control.dataset.setting],box=control.querySelector('input'),output=control.querySelector('output');
if(box)box.checked=!!value;else if(output)output.textContent=String(value);
else{for(const button of control.querySelectorAll('button'))button.setAttribute('aria-checked',String(button.dataset.value===String(value)));placeThumb(control);}
}
}
function toggleSettings(show=$('settings').hidden,group){
const panel=$('settings');if(group){settingsGroup=group;settingsQuery='';const input=panel.querySelector('.settings-search input');if(input)input.value='';}
if(show===!panel.hidden){if(group)filterSettings();return;}
if(show)settingsReturn=document.activeElement;
panel.hidden=!show;action('settings').setAttribute('aria-expanded',String(show));
// Modal while open: the rest of the workspace is inert.
for(const node of app.children)if(node!==panel&&!node.classList.contains('toasts'))node.inert=show;
if(show){filterSettings();panel.querySelector('.settings-search input')?.focus({preventScroll:true});}
else settingsReturn?.focus?.({preventScroll:true});
}
const shortcutSheet=()=>toggleSettings(true,'shortcuts');
// ---- status -----------------------------------------------------------------------------------
// ---- live inspector and PDF sync -------------------------------------------------------------
function record(kind,ms){
const last=state.timeline.at(-1);
if(kind==='waiting'&&last?.kind==='waiting'){last.at=Date.now();return;}
state.timeline.push({id:++state.timelineId,kind,ms,at:Date.now()});if(state.timeline.length>48)state.timeline.shift();
}
let inspector=null;
const lag=()=>state.pdf&&state.pdfRevision>=0?Math.max(0,state.revision-state.pdfRevision):0;
function inspectorData(){
const explain=reason=>{const found=explainReason(reason);return found&&{...found,text:describeReason(reason)};};
return {timeline:state.timeline,live:state.live,explain,pages:state.livePages,engine:state.engineInfo,lag:lag(),settling:!!settleTimer||!!viewport.querySelector('canvas.provisional'),compiling:state.compiling};
}
function openInspector(){
if(inspector){inspector.surface.close();return;}
const view=createInspector({t});view.render(inspectorData());
const anchor=$('preview-status');anchor.dataset.popoverAnchor='';
inspector={view,surface:openPopover(app,anchor.getBoundingClientRect(),view.el,{className:'inspector-pop',label:t('insp.title'),onClose:()=>{inspector=null;delete anchor.dataset.popoverAnchor;}})};
}
const renderInspector=()=>inspector?.view.render(inspectorData());
function updatePdfSync(){
const badge=$('pdf-sync'),behind=lag();badge.hidden=!state.pdf;
badge.textContent=state.compiling&&behind?t('pdf.updating'):behind?t('pdf.behind',{n:behind}):t('pdf.synced');
badge.dataset.state=state.compiling&&behind?'busy':behind?'lag':'ok';badge.dataset.tip=t(behind?'pdf.syncNow':'pdf.syncedTip');
}
function updateStatus(){
const shown=state.previewRevision>=0,stale=shown&&state.previewRevision!==state.revision,name=state.busy?'busy':!shown?'none':stale?'stale':state.previewRevision!==state.pdfRevision?'live':'ok';
const capsule=$('preview-status');capsule.dataset.state=name;capsule.dataset.failed=String(state.failed);$('preview-status-text').textContent=t('status.'+name);
updatePdfSync();renderInspector();
const error=state.problems.find(problem=>problem.severity==='error'),banner=$('preview-error');banner.hidden=!state.failed;
banner.textContent=t(state.pdf?'toast.kept':'toast.failed')+(error?' '+[error.file,error.line].filter(Boolean).join(':')+' · '+error.message:'');
}
function updateControls(){
const run=action('compile'),stop=action('cancel'),idle=state.engine!=='ready'||!state.loaded||!project.main;
run.disabled=idle||state.compiling;run.hidden=state.busy;stop.hidden=!state.busy;action('capsule').disabled=idle;
paintCapsuleTip();updateStatus();
}
function updateEngine(){
const loading=state.engine==='loading',failed=state.engine==='error',percent=Number.isFinite(state.progress)?Math.round(state.progress*100):null;
const text=loading?t('engine.loading')+(percent==null?'…':` ${percent}%`):failed?t('engine.error'):!project.main&&state.loaded?t('engine.nomain'):'';
$('stat-engine').textContent=text;$('stat-engine').dataset.state=failed?'error':'';
const bar=$('load-bar');bar.hidden=!loading;bar.dataset.mode=percent==null?'indeterminate':'determinate';bar.firstChild.style.width=percent==null?'':percent+'%';
const sheet=$('sheet');
if(sheet){
sheet.dataset.state=loading||state.busy?'loading':state.failed||failed?'failed':!state.pdf&&state.pdfRevision>=0?'empty':'idle';
$('sheet-note').textContent=text||(state.failed?t('preview.failed'):'');action('show-problems').hidden=!state.failed;
}
}
/** A fallback reason in the reader's language; reasons this build does not know are shown as written. */
function describeReason(reason){const found=explainReason(reason);return !found?'':found.code?t('reason.'+found.code,found.values):found.raw;}
// The capsule's tooltip has one source: stopping while compiling, else why the last update was not local, else compiling now.
function capsuleTip(){
if(state.compiling)return t('compile.stop');
const live=state.live,why=live?.reason&&describeReason(live.reason);
if(!why)return t('compile.now');
const head=live.state==='full'?t('live.full')+(Number.isFinite(state.meta?.durationMs)&&state.pdfRevision===state.revision?` · ${(state.meta.durationMs/1000).toFixed(2)} s`:''):live.state==='waiting'?t('live.wait'):live.state==='off'?t('live.off'):t('status.'+(live.state==='reflow'?'live':'ok'));
return head+'\n'+why;
}
function paintCapsuleTip(){const button=action('capsule');button.dataset.tip=capsuleTip();button.setAttribute('aria-label',t(state.compiling?'compile.stop':'compile.now'));}
function updateLive(){
const live=state.live,el=$('stat-live');
el.textContent=!live?'':live.state==='live'||live.state==='reflow'?t(live.state==='reflow'?'live.reflow':'live.ms',{ms:live.ms<10?live.ms.toFixed(1):Math.round(live.ms)}):live.state==='full'?t('live.full'):live.state==='waiting'?t('live.wait'):live.state==='off'?t('live.off'):'';
el.dataset.state=live?.state||'';$('preview-status').dataset.live=live?.state||'';
paintCapsuleTip();
const bars=$('cap-bars').children,offset=bars.length-state.latency.length;
for(let i=0;i<bars.length;i++)bars[i].style.setProperty('--h',String(i<offset?0.12:clamp(state.latency[i-offset]/24,0.12,1)));
}
function updateSave(){$('save-status').textContent=t('save.'+state.save);$('save-status').dataset.state=state.save;}
function updateDoc(){
const meta=state.meta;
$('stat-doc').textContent=!meta?'':[meta.pages?(meta.pages===1?t('page'):t('pages',{n:meta.pages})):null,`${(state.pdf.byteLength/1024).toFixed(1)} KB`,Number.isFinite(meta.durationMs)?`${(meta.durationMs/1000).toFixed(2)} s`:null].filter(Boolean).join(' · ');
}
function updateProject(){
$('project-name').textContent=documentTitle(mainText())||(project.main?basename(project.main):t('project.untitled'));
const files=textFiles();structure=parseOutline(files,project.main);
wordTotal=structure.paths.reduce((n,path)=>n+wordCount(files.get(path)||''),0);
wordSections=structure.headings.map((h,i)=>({heading:h,n:wordCount((files.get(h.file)||'').slice(h.offset,structure.headings.slice(i+1).find(next=>next.file===h.file)?.offset))}));
structure.references=referenceCounts(files);nowKey=null;
outline.update(structure.headings,state.problems,wordSections);labelsView.update(structure.labels,structure.references);syncCursorViews();markBroken();crumbs.reset();queueCrumbs();
$('tree-empty').hidden=project.paths().length>0;$('tree').hidden=!project.paths().length;updateWords();
}
function updateWords(){const editor=activeEditor(),selected=editor&&editor.input.selectionStart!==editor.input.selectionEnd;const n=selected?wordCount(editor.getValue().slice(editor.input.selectionStart,editor.input.selectionEnd)):wordTotal;$('word-count').textContent=t(selected?'words.selection':'words.count',{n:n.toLocaleString()});}
function wordDetails(){
const body=document.createElement('div');body.className='word-details';
body.append(Object.assign(document.createElement('p'),{textContent:t('words.note')}));
for(const {heading,n} of wordSections){const row=document.createElement('button');row.className='word-row';row.innerHTML='<span></span><b></b>';row.firstChild.textContent=[heading.number,heading.title].filter(Boolean).join(' ');row.lastChild.textContent=String(n);row.onclick=()=>{dialog.close();reveal({path:heading.file,line:heading.line});};body.append(row);}
if(!wordSections.length)body.append(Object.assign(document.createElement('p'),{textContent:t('words.count',{n:wordTotal})}));
const dialog=openDialog(app,{title:t('words.title'),content:body});
}
function refreshText(){
i18n.apply(root);renderSettings();renderTabs();tree.render();renderProblems();updateControls();updateEngine();updateLive();updateSave();updateDoc();updateZoomLabel();updateProject();applyLayout();
$('cursor-status').textContent=views.get(active)?.position?t('cursor',views.get(active).position):'';
for(const view of views.values())if(view.editor){view.editor.input.setAttribute('aria-label',t('editor.label'));view.find.destroy();view.find=createFindBar(view.editor,t);view.complete?.hide();}
for(const [i,row] of [...($('load-steps')?.children||[])].entries())row.firstChild.textContent=t('load.'+i);
}
// ---- panel: problems and log ------------------------------------------------------------------
function renderPanel(){
const panel=$('panel'),shown=panel.dataset.motion?panel.dataset.motion==='in':!panel.hidden;
if(settings.panel!==shown)slidePanel(settings.panel);
for(const tab of panel.querySelectorAll('.panel-tab'))tab.setAttribute('aria-selected',String(tab.dataset.panel===settings.panelTab));
$('problems').hidden=settings.panelTab!=='problems';$('logs').hidden=settings.panelTab!=='log';$('refs').hidden=settings.panelTab!=='refs';action('clear-log').hidden=settings.panelTab!=='log';
action('copy-log').hidden=settings.panelTab!=='log';action('problem-filter').hidden=settings.panelTab!=='problems';panel.inert=!settings.panel;
}
// The panel slides over the editor and takes its height once it is in place; leaving, it gives the height back first.
function slidePanel(open){
const panel=$('panel');panelMotion?.cancel();panelMotion=null;delete panel.dataset.motion;
if(!motion()||!panel.animate){panel.hidden=!open;return;}
panel.hidden=false;panel.dataset.motion=open?'in':'out';
const height=panel.offsetHeight,timing={duration:open?200:150,easing:open?'cubic-bezier(.2,0,0,1)':'cubic-bezier(.4,0,1,1)'};
const animation=panelMotion=panel.animate(open?[{transform:`translateY(${height}px)`},{transform:'none'}]:[{transform:'none'},{transform:`translateY(${height}px)`}],timing);
animation.finished.then(()=>{if(panelMotion!==animation)return;panelMotion=null;delete panel.dataset.motion;panel.hidden=!open;},()=>{});
}
function openPanel(tab=settings.panelTab){set('panelTab',tab);set('panel',true);}
/** Every place that refers to a label, listed in the panel's References tab. */
function findAllReferences(name){
const files=textFiles(),found=findReferences(files).filter(ref=>ref.name===name),definition=findLabels(files).find(label=>label.name===name),list=$('refs');list.replaceChildren();
const head=make('div','refs-head');head.append(make('b','',name),make('span','',found.length?t('labels.refs',{n:found.length}):t('labels.unused')));list.append(head);
for(const item of [...(definition?[{...definition,command:'label'}]:[]),...found]){
const source=files.get(item.file),from=source.lastIndexOf('\n',item.start-1)+1,to=source.indexOf('\n',item.start),line=source.slice(from,to<0?source.length:to);
const row=make('button','problem ref-row');row.type='button';row.innerHTML=icon(item.command==='label'?'target':'hash',14)+'<span class="problem-text"></span><span class="problem-where"></span>';
const textNode=row.children[1],before=line.slice(0,item.start-from).trimStart(),after=line.slice(item.end-from);
textNode.append(make('span','',before.length>48?'…'+before.slice(-48):before),make('mark','',item.name),make('span','',after.length>64?after.slice(0,64)+'…':after));
row.children[2].textContent=`${item.file}:${item.line}`;row.onclick=()=>reveal({path:item.file,offset:item.start});list.append(row);
}
$('refs-tab').hidden=false;$('refs-count').textContent=String(found.length);openPanel('refs');
}
function renderProblems(){
const list=$('problems'),counts={error:0,warning:0,info:0},marksByFile=new Map(),rank={error:3,warning:2,info:1},context=fixContext();list.replaceChildren();
for(const problem of state.problems){
counts[problem.severity]=(counts[problem.severity]||0)+1;
if(problem.line){
let marks=marksByFile.get(problem.file);
if(!marks)marksByFile.set(problem.file,marks=new Map());
// The worst problem on a line decides its gutter mark.
if((rank[marks.get(problem.line)]||0)<rank[problem.severity])marks.set(problem.line,problem.severity);
}
if(state.problemFilter!=='all'&&state.problemFilter!==problem.severity)continue;
const row=Object.assign(document.createElement('button'),{type:'button',className:'problem'});row.dataset.severity=problem.severity;
row.innerHTML=`${icon(problem.severity==='error'?'error':problem.severity==='warning'?'warning':'info',14)}<span class="problem-text"></span><span class="problem-where"></span>`;
row.children[1].textContent=problem.message;row.children[2].textContent=[problem.file,problem.line].filter(value=>value!=null).join(':');
row.disabled=!problem.file||!project.has(problem.file);
row.addEventListener('click',()=>reveal({path:problem.file,line:problem.line??1}));
list.append(row);
}
if(!list.children.length)list.append(Object.assign(document.createElement('div'),{className:'panel-empty',textContent:t('panel.none')}));
$('problem-count').textContent=state.problems.length?String(state.problems.length):'';
const stat=$('stat-problems');stat.innerHTML=`${icon('error',13)}<span></span>${icon('warning',13)}<span></span>`;
stat.children[1].textContent=String(counts.error);stat.children[3].textContent=String(counts.warning);stat.dataset.state=counts.error?'error':counts.warning?'warning':'';
for(const [path,view] of views){
if(!view.editor)continue;
view.editor.setMarkers(marksByFile.get(path)||new Map());
view.editor.setDiagnostics(state.problems.filter(problem=>problem.file===path).map(problem=>({...problem,fixable:isTex(path)&&quickFixes(problem,context).length>0})));
}
outline.update(structure.headings,state.problems,wordSections);nowKey=null;syncCursorViews();
}
// The outline, labels and the files view's "this section" summary all follow the caret.
let nowKey=null;
function syncCursorViews(){
const line=views.get(active)?.position?.line||1,heading=outline.cursor(active,line);labelsView.cursor(active,line);
const list=structure.headings,index=list.indexOf(heading),start=Math.max(0,Math.min(index-1,list.length-2)),pair=list.slice(start,start+2),key=pair.map(item=>item.offset+item.file).join()+index;
if(key===nowKey)return;nowKey=key;
const box=$('side-now');box.hidden=!pair.length;box.replaceChildren(Object.assign(document.createElement('span'),{className:'side-now-title',textContent:t('side.now')}));
for(const item of pair){
const row=document.createElement('button');row.type='button';row.setAttribute('aria-current',String(item===heading));row.innerHTML='<b></b><span></span><small></small>';
row.firstChild.textContent=item.number;row.children[1].textContent=item.title;row.lastChild.textContent=(wordSections.find(entry=>entry.heading===item)?.n??0).toLocaleString();
row.dataset.tip=`${item.file}:${item.line}`;row.onclick=()=>reveal({path:item.file,line:item.line});box.append(row);
}
}
const log=(message,level='info')=>{
state.logs.push(`${level==='error'?'ERROR · ':level==='warning'?'WARNING · ':''}${String(message)}`);if(state.logs.length>500)state.logs.shift();
const el=$('logs'),pinned=el.scrollTop+el.clientHeight>=el.scrollHeight-8;el.replaceChildren();
for(const line of state.logs){const row=document.createElement('span');row.className=/^ERROR/.test(line)?'log-error':/^WARNING/.test(line)?'log-warning':'';row.textContent=line+'\n';el.append(row);}if(pinned)el.scrollTop=el.scrollHeight;
};
// ---- editor views and tabs --------------------------------------------------------------------
const isTex=path=>/\.(tex|ltx|sty|cls)$/i.test(path);
function updateMath(){
const view=views.get(active);
if(!popover||!view?.editor)return;
const editor=view.editor,input=editor.input;
if(view.complete?.visible||!settings.mathPreview||!isTex(active)||input.selectionStart!==input.selectionEnd||document.activeElement!==input){popover.hide();return;}
const source=editor.getValue();void popover.update(editor,mathAt(source,editor.caret),source,active);
}
function createView(path){
const file=project.get(path),el=document.createElement('div'),view={el,position:null};el.className='view';el.hidden=true;
if(typeof file.text==='string'){
view.editor=createCodeEditor({value:file.text,settings,label:t('editor.label'),describedBy:'editor-keyboard-help',structure:isTex(path),
onChange:value=>project.write(path,value,'editor'),
onCursor:position=>{
view.position=position;
if(active!==path)return;
$('cursor-status').textContent=t('cursor',position);updateMath();syncCursorViews();updateWords();queueCrumbs();
options.onCursor?.({path,offset:position.offset,line:position.line,main:path===project.main});
},
onQuickFix:(line,at)=>openFixes(path,line,at),
onEscape:()=>{
if(popover?.dismiss())return;
if(state.compiling){cancel();return;}
$('tabs').querySelector('[aria-selected="true"]')?.focus();
}});
view.editor.input.addEventListener('blur',()=>popover?.hide());
view.find=createFindBar(view.editor,t);
if(isTex(path))view.complete=createCompletion(view.editor,{t,context:()=>({files:new Map(project.files().map(f=>[f.path,f.text])),labels:structure.labels,
bib:bibEntries().map(entry=>({key:entry.key,byline:byline(entry),title:plainField(entry.fields.title)}))}),onVisible:visible=>{if(visible)popover?.hide();}});
wireInsertion(view.editor,path);view.edges=watchEdges(view.editor.scroller,view.editor.el);
if(isTex(path)){
view.card=createHoverCard(view.editor,{describe:(offset,config)=>describeTarget(path,offset,config)});
// Command/Control-click or F12 follows what the source points to.
view.editor.input.addEventListener('click',event=>{if((event.metaKey||event.ctrlKey)&&!event.altKey&&follow(path,view.editor.caret))event.preventDefault();});
view.editor.input.addEventListener('keydown',event=>{
if(event.metaKey||event.ctrlKey||event.altKey)return;
if(event.key==='F12'&&event.shiftKey){event.preventDefault();referencesAt(path);}
else if(event.key==='F12'){event.preventDefault();if(!follow(path,view.editor.caret))notify('follow.none');}
else if(event.key==='F2'&&!event.shiftKey){event.preventDefault();renameAt(path);}
});
}
view.editor.scroller.addEventListener('scroll',()=>{if(active===path)queueCrumbs();},{passive:true});
el.append(view.editor.el);return view;
}
el.classList.add('viewer');
const size=`${(file.data.length/1024).toFixed(1)} KB`;
if(isImagePath(path)){
const kind=/\.([a-z]+)$/i.exec(path)[1].toLowerCase().replace('jpg','jpeg');
view.url=URL.createObjectURL(new Blob([file.data],{type:'image/'+kind}));
el.append(Object.assign(document.createElement('img'),{alt:basename(path),src:view.url}),Object.assign(document.createElement('span'),{textContent:size}));return view;
}
el.innerHTML=icon('file',28);el.append(Object.assign(document.createElement('span'),{textContent:`${t('binary.note')} · ${size}`}));return view;
}
function dropView(path){const view=views.get(path);if(!view)return;view.edges?.destroy();view.card?.destroy();view.complete?.destroy();view.find?.destroy();view.editor?.destroy();if(view.url)URL.revokeObjectURL(view.url);view.el.remove();views.delete(path);}
// Tabs are kept by path: only an opened or closed tab enters or leaves, and its neighbours slide to make room.
const tabNodes=new Map();
function renderTabs(){
const bar=$('tabs'),fresh=[];
for(const [path,tab] of tabNodes)if(!tabs.includes(path)){tabNodes.delete(path);leaveTab(tab);}
tabs.forEach((path,index)=>{
let tab=tabNodes.get(path);
if(!tab){tab=document.createElement('div');tab.className='tab';tab.draggable=true;tab.setAttribute('role','tab');tab.dataset.path=path;tabNodes.set(path,tab);fresh.push(tab);}
tab.tabIndex=0;tab.setAttribute('aria-selected',String(path===active));tab.dataset.tip=path;
// Same-named files in different folders show their folder.
const twin=tabs.some(other=>other!==path&&basename(other)===basename(path))&&dirname(path);
tab.innerHTML=(path===project.main?`<span class="tab-main">${icon('target',12)}</span>`:'')+'<span class="tab-name"></span>'+(twin?'<span class="tab-dir"></span>':'')+`<button type="button" class="icon-btn tab-close" tabindex="-1">${icon('close',12)}</button>`;
const name=tab.querySelector('.tab-name');name.textContent=basename(path);if(path===active)name.dataset.id='filename';
if(twin)tab.querySelector('.tab-dir').textContent=twin;
tab.lastChild.setAttribute('aria-label',t('tab.close'));
const placed=[...bar.children].filter(node=>!node.classList.contains('leaving'));
if(placed[index]!==tab)bar.insertBefore(tab,placed[index]||null);
});
if(motion())for(const tab of fresh){const width=tab.offsetWidth;tab.animate?.([{maxWidth:'0px',opacity:0,paddingLeft:'0px',paddingRight:'0px'},{maxWidth:width+'px',opacity:1}],{duration:200,easing:'cubic-bezier(.2,0,0,1)'})?.finished.then(placeTabs,()=>{});}
$('editor-empty').hidden=!!active;placeTabs();
}
function leaveTab(tab){
if(!motion()||!tab.animate||!tab.isConnected){tab.remove();return;}
tab.classList.add('leaving');tab.removeAttribute('role');tab.removeAttribute('aria-selected');tab.inert=true;
tab.animate([{maxWidth:tab.offsetWidth+'px',opacity:1},{maxWidth:'0px',opacity:0,paddingLeft:'0px',paddingRight:'0px'}],{duration:150,easing:'cubic-bezier(.4,0,1,1)'}).finished.then(()=>{tab.remove();placeTabs();},()=>tab.remove());
}
// The active tab's indicator is one bar that slides; the tab list itself holds nothing but tabs.
function placeTabs(){const bar=$('tabs'),on=bar.querySelector('.tab:not(.leaving)[aria-selected="true"]');bar.style.setProperty('--ind-x',(on?.offsetLeft||0)+'px');bar.style.setProperty('--ind-w',(on?.offsetWidth||0)+'px');bar.dataset.left=String(bar.scrollLeft>2);bar.dataset.right=String(bar.scrollLeft+bar.clientWidth<bar.scrollWidth-2);}
function activate(path,{focus=false}={}){
const previous=views.get(active);
if(previous&&active!==path){previous.el.hidden=true;previous.editor?.input.removeAttribute('data-id');}
popover?.hide();active=path;
if(path){
let view=views.get(path);
if(!view){view=createView(path);views.set(path,view);$('editor-host').append(view.el);renderProblems();}
view.el.hidden=false;view.editor?.input.setAttribute('data-id','source');
if(focus)view.editor?.focus();
}
$('cursor-status').textContent=views.get(path)?.position?t('cursor',views.get(path).position):'';
renderTabs();tree.setActive(path);updateWords();syncCursorViews();markBroken(path);queueCrumbs();if(state.loaded)queueSave();
}
function openFile(path,config){
if(!project.has(path))return;
if(!tabs.includes(path))tabs.push(path);
activate(path,config);
$('tabs').querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:'nearest',inline:'nearest'});
}
function closeTab(path,focus=false){
const index=tabs.indexOf(path);if(index<0)return;
tabs.splice(index,1);dropView(path);
if(active===path)activate(tabs[Math.min(index,tabs.length-1)]??null,{focus});else renderTabs();
queueSave();
}
/** Show a place in a project file: {path, line} or {path, offset}. */
function reveal({path,line,offset,flash=true}){
if(!path||!project.has(path))return;
openFile(path,{focus:true});app.dataset.view='source';
if(settings.layout==='preview'&&!narrowQuery?.matches)set('layout','split');else applyLayout();
const editor=views.get(path)?.editor;if(!editor)return;
const at=offset??editor.offsetOf(line??1);editor.select(at);
if(flash)editor.flash(editor.getValue().slice(0,at).split('\n').length);
}
// ---- where the source points: jumps, hover cards, breadcrumbs ---------------------------------
const textFiles=()=>new Map(project.files().filter(file=>typeof file.text==='string').map(file=>[file.path,file.text]));
/** A project file for \input, \includegraphics or \bibliography arguments, as TeX would look it up. */
function resolveFile(name,kind){
const clean=String(name).trim().replace(/^\.\//,''),extensions=kind==='graphics'?['','.pdf','.png','.jpg','.jpeg']:kind==='bib'?['.bib','']:['','.tex'];
for(const dir of [...new Set(['',dirname(project.main||'')])])for(const extension of extensions){
try{const path=normalizePath(joinPath(dir,clean+extension));if(project.has(path))return path;}catch{/* not a project path */}
}
return null;
}
const bibEntries=()=>project.files().filter(file=>/\.bib$/i.test(file.path)&&typeof file.text==='string').flatMap(file=>parseBib(file.text,file.path));
/** Follow what the source at offset points to. Returns false when there is nothing to follow. */
function follow(path,offset){
const text=project.get(path)?.text;if(typeof text!=='string')return false;
const target=targetAt(text,offset);if(!target)return false;
const go=place=>{if(!place)return false;reveal(place);return true;};
if(target.kind==='ref'){const label=findLabels(textFiles()).find(label=>label.name===target.name);return go(label&&{path:label.file,offset:label.start});}
if(target.kind==='label'){findAllReferences(target.name);return true;}
if(target.kind==='input'||target.kind==='graphics'||target.kind==='bib'){const file=resolveFile(target.name,target.kind);if(!file)return false;openFile(file,{focus:true});return true;}
if(target.kind==='macro'){const definition=findDefinition(textFiles(),target.name);return go(definition&&{path:definition.file,offset:definition.start});}
if(target.kind==='cite'){const entry=bibEntries().find(entry=>entry.key===target.name);return go(entry&&{path:entry.file,offset:entry.start});}
return false;
}
const make=(tag,className,text)=>{const node=document.createElement(tag);if(className)node.className=className;if(text!=null)node.textContent=text;return node;};
function cardMeta(...parts){
const meta=make('div','card-meta');
for(const part of parts.filter(Boolean)){if(meta.childNodes.length)meta.append(make('span','',' · '));meta.append(typeof part==='string'?make('span','',part):part);}
return meta;
}
function suggestions(title,options,replace){
const box=make('div');box.append(make('div','card-title'));box.firstChild.innerHTML=icon('warning',14);box.firstChild.append(title);
if(options.length){const chips=make('div','card-chips');for(const option of options){const button=make('button','',option);button.type='button';button.dataset.tip=t('follow.replace',{name:option});button.onclick=()=>replace(option);chips.append(button);}box.append(chips);}
return box;
}
const followHint=()=>{const meta=make('div','card-meta');meta.append(Object.assign(make('kbd'),{textContent:mac?'⌘':'Ctrl'}),make('span','',t('follow.hint')));return meta;};
/** The hover card for offset in path: {start, end, go, content, ready}, or null. peek skips building content. */
function describeTarget(path,offset,{peek=false}={}){
const text=project.get(path)?.text;if(typeof text!=='string')return null;
const target=targetAt(text,offset);if(!target||target.kind==='label'&&peek)return null;
const base={start:target.start,end:target.end,ready:null};
const replace=value=>{const editor=views.get(path)?.editor;if(editor&&editor.getValue().slice(target.start,target.end)===target.name){editor.edit(target.start,target.end,value);views.get(path)?.card?.hide();}};
if(target.kind==='ref'||target.kind==='label'){
const files=textFiles(),labels=findLabels(files),definition=labels.find(label=>label.name===target.name);
if(peek)return {...base,go:!!definition};
const content=make('div');
if(!definition){content.append(suggestions(t('follow.noLabel',{name:target.name}),nearest(target.name,labels.map(label=>label.name)),replace));return {...base,go:false,content};}
const info=structure.labels.find(label=>label.name===definition.name&&label.file===definition.file),count=structure.references?.get(definition.name)||0,source=files.get(definition.file);
const found=info&&/^(?:equation|align|gather|multline|flalign|alignat|eqnarray|displaymath|math)\*?$/.test(info.kind)&&mathAt(source,definition.start);
if(found&&options.typesetMath){
const formula=make('div','card-formula');content.append(formula);
base.ready=options.typesetMath({found,source,scale:'s',maxWidth:400}).then(result=>{if(result?.canvas)formula.replaceChildren(result.canvas);else formula.replaceWith(make('pre','card-code',source.slice(found.start,found.end).trim()));}).catch(()=>formula.remove());
}else if(info?.text)content.append(make('div','card-text',info.text));
content.append(cardMeta(make('b','',definition.name),info?.kind,`${definition.file}:${definition.line}`,count?t('labels.refs',{n:count}):t('labels.unused')));
if(target.kind==='ref')content.append(followHint());
return {...base,go:target.kind==='ref',content};
}
if(target.kind==='input'||target.kind==='graphics'||target.kind==='bib'){
const file=resolveFile(target.name,target.kind);if(peek)return {...base,go:!!file};
const content=make('div');
if(!file){
const wanted=target.kind==='graphics'?/\.(png|jpe?g|pdf)$/i:target.kind==='bib'?/\.bib$/i:/\.(tex|ltx)$/i,paths=project.paths().filter(path=>wanted.test(path)),stems=new Map(paths.map(path=>[path.replace(/\.[^./]+$/,''),path]));
content.append(suggestions(t('follow.noFile',{name:target.name}),nearest(target.name.replace(/\.[^./]+$/,''),[...stems.keys()],{limit:6}),replace));return {...base,go:false,content};
}
const data=project.get(file);
if(isImagePath(file)){
const image=make('img','card-image'),url=URL.createObjectURL(new Blob([data.data]));image.alt=basename(file);image.src=url;content.append(image);
const size=cardMeta(make('b','',file),`${(data.data.length/1024).toFixed(1)} KB`);content.append(size);
base.ready=new Promise(resolve=>{image.onload=()=>{size.append(make('span','',' · '),make('span','',`${image.naturalWidth} × ${image.naturalHeight} px`));URL.revokeObjectURL(url);resolve();};image.onerror=()=>{URL.revokeObjectURL(url);resolve();};});
}else if(typeof data.text==='string'){
const lines=data.text.split('\n');content.append(make('pre','card-code',lines.slice(0,4).join('\n')),cardMeta(make('b','',file),t('follow.lines',{n:lines.length})));
}else content.append(cardMeta(make('b','',file),`${(data.data.length/1024).toFixed(1)} KB`));
content.append(followHint());return {...base,go:true,content};
}
if(target.kind==='macro'){
const definition=findDefinition(textFiles(),target.name);if(!definition||definition.file===path&&definition.start<=target.start&&target.start<=definition.end)return null;
if(peek)return {...base,go:true};
const content=make('div');content.append(make('pre','card-code',definition.text.trim()),cardMeta(`${definition.file}:${definition.line}`),followHint());
return {...base,go:true,content};
}
if(target.kind==='cite'){
const entries=bibEntries(),entry=entries.find(entry=>entry.key===target.name);if(peek)return {...base,go:!!entry};
const content=make('div');
if(!entry){content.append(suggestions(t('follow.noCite',{name:target.name}),nearest(target.name,entries.map(entry=>entry.key),{limit:5}),replace));return {...base,go:false,content};}
content.append(make('div','card-title',plainField(entry.fields.title)||entry.key),make('div','card-text',byline(entry)),cardMeta(make('b','',entry.key),entry.type,`${entry.file}:${entry.line}`),followHint());
return {...base,go:true,content};
}
return null;
}
// References to labels, files or citations that do not exist get a dashed underline after a pause.
function markBroken(path=active){
const editor=views.get(path)?.editor;if(!editor||!isTex(path))return;
const text=editor.getValue(),files=textFiles(),names=new Set(findLabels(files).map(label=>label.name)),keys=bibEntries().map(entry=>entry.key),known=new Set(keys),list=[];
for(const ref of findReferences(new Map([[path,text]])))if(!names.has(ref.name))list.push({start:ref.start,end:ref.end,className:'deco-broken'});
for(const match of text.matchAll(/\\(includegraphics|input|include)\s*(?:\[[^\]]*\])?\s*\{([^{}\n]+)\}/g)){
if(/^\s*%/.test(text.slice(text.lastIndexOf('\n',match.index)+1,match.index)))continue;
if(!resolveFile(match[2],match[1]==='includegraphics'?'graphics':'input')){const start=match.index+match[0].lastIndexOf('{')+1;list.push({start,end:start+match[2].length,className:'deco-broken'});}
}
if(keys.length)for(const cite of text.matchAll(/\\(?:[a-zA-Z]*cite[a-zA-Z]*|nocite)\*?\s*(?:\[[^\]]*\]\s*){0,2}\{([^{}]*)\}/g)){
let at=cite.index+cite[0].lastIndexOf('{')+1;
for(const part of cite[1].split(',')){const key=part.trim(),start=at+part.indexOf(key);if(key&&key!=='*'&&!known.has(key))list.push({start,end:start+key.length,className:'deco-broken'});at+=part.length+1;}
}
editor.setDecorations('broken',list);
}
// Breadcrumbs follow the caret; while the caret is scrolled out of view they follow the top of the view.
const crumbs=createBreadcrumbs($('crumbs'),{t,
onPath:path=>{toggleSidebar(true);set('sideView','files');tree.reveal(path);},
onSection:(heading,at)=>{
const list=structure.headings,index=list.indexOf(heading);if(index<0)return;
let first=index;while(first>0&&list[first-1].level>=heading.level)first--;
let last=index;while(last<list.length-1&&list[last+1].level>=heading.level)last++;
const items=list.slice(first,last+1).filter(item=>item.level===heading.level||item.level===heading.level+1&&list.indexOf(item)>index&&list.slice(index+1,list.indexOf(item)+1).every(other=>other.level>heading.level));
openMenu(app,at,items.map(item=>({label:(item.level>heading.level?' ':'')+[item.number,item.title].filter(Boolean).join(' '),checked:item===heading,run:()=>reveal({path:item.file,line:item.line})})));
},
onEnvironment:environment=>{const editor=activeEditor();if(editor)editor.select(environment.from,environment.to,{center:false});}});
let crumbFrame=0;
const queueCrumbs=()=>{if(!crumbFrame)crumbFrame=(globalThis.requestAnimationFrame||setTimeout)(updateCrumbs);};
function headingAt(path,line){
const list=structure.headings,own=list.findLast(heading=>heading.file===path&&heading.line<=line);if(own)return own;
const first=list.findIndex(heading=>heading.file===path);return first>0?list[first-1]:null;
}
function updateCrumbs(){
crumbFrame=0;
const view=views.get(active);if(!view?.editor){crumbs.update(active?{path:active}:null);return;}
const editor=view.editor,scroller=editor.scroller,line=view.position?.line||1,top=editor.lineAtY(scroller.scrollTop+12),bottom=editor.lineAtY(scroller.scrollTop+scroller.clientHeight-12);
const away=line<top||line>bottom,at=away?top:line,heading=isTex(active)?headingAt(active,at):null;
let environment=null;
if(!away&&isTex(active)){
const text=editor.getValue(),caret=editor.caret,found=environmentAt(text,caret);
if(found&&found.name!=='document')environment=found;
else{const math=mathAt(text,caret);if(math&&!math.env)environment={name:math.kind,display:math.kind==='display'?'\\[ … \\]':'$ … $',from:math.start,to:math.end};}
}
crumbs.update({path:active,heading,environment,stuck:away&&!!heading&&heading.file===active&&heading.line<top});
}
// ---- edits across files, rename and quick fixes -----------------------------------------------
/** Apply [{file, start, end, text}] as one edit per file. Open editors take theirs natively (one Mod+Z);
* returns a function that restores every file that still holds what was written. */
function applyEdits(edits){
const byFile=new Map(),undo=[];
for(const edit of edits){const list=byFile.get(edit.file)||[];list.push(edit);byFile.set(edit.file,list);}
for(const [file,list] of byFile){
const source=project.get(file)?.text;if(typeof source!=='string')continue;
list.sort((a,b)=>a.start-b.start);
const from=list[0].start,to=Math.max(...list.map(edit=>edit.end));let written='',at=from;
for(const edit of list){if(edit.start<at)continue;written+=source.slice(at,edit.start)+edit.text;at=edit.end;}
written+=source.slice(at,to);
const before=source.slice(from,to);write(file,from,to,written);
undo.push(()=>{const now=project.get(file)?.text;if(typeof now==='string'&&now.slice(from,from+written.length)===written)write(file,from,from+written.length,before);});
}
return ()=>{for(const step of undo.reverse())step();};
}
function write(file,from,to,text){
const editor=views.get(file)?.editor;
// A file open in a background tab takes the edit on its own undo stack; the focus stays where it was.
if(editor&&editor.getValue()===project.get(file).text){const focused=document.activeElement;editor.edit(from,to,text);if(file!==active)focused?.focus?.({preventScroll:true});}
else{const source=project.get(file).text;project.write(file,source.slice(0,from)+text+source.slice(to));}
}
/** F2 on a \label or a reference: type the new name, see every affected line, Enter renames them all. */
function renameAt(path){
const editor=views.get(path)?.editor;if(!editor||!isTex(path))return;
const target=targetAt(editor.getValue(),editor.caret);
if(!target||target.kind!=='label'&&target.kind!=='ref'){notify('rename.none');return;}
const old=target.name,files=textFiles(),labels=findLabels(files);
const sites=[...labels.filter(label=>label.name===old).map(label=>({...label,command:'label'})),...findReferences(files).filter(ref=>ref.name===old)].sort((a,b)=>a.file.localeCompare(b.file)||a.start-b.start);
const box=make('div','rename'),head=make('div','rename-head'),input=make('input','field rename-input'),list=make('div','rename-list'),foot=make('div','rename-foot');
head.append(make('span','',t('rename.title')),make('code','',old));input.type='text';input.value=old;input.spellcheck=false;input.setAttribute('aria-label',t('rename.title'));
box.append(head,input,list,foot);
const count=new Set(sites.map(site=>site.file)).size;
function check(){
const next=input.value.trim();
if(!next)return t('rename.empty');
if(/[{}\\%#,]/.test(next))return t('rename.invalid');
if(next!==old&&labels.some(label=>label.name===next))return t('rename.taken',{name:next});
return '';
}
function paint(){
const next=input.value.trim()||old,problem=check();list.replaceChildren();
for(const site of sites.slice(0,60)){
const source=files.get(site.file),from=source.lastIndexOf('\n',site.start-1)+1,end=source.indexOf('\n',site.start),line=source.slice(from,end<0?source.length:end);
const row=make('div','rename-row'),code=make('code'),before=line.slice(0,site.start-from).trimStart(),after=line.slice(site.end-from);
code.append(make('span','',before.length>36?'…'+before.slice(-36):before),make('mark','',next),make('span','',after.length>40?after.slice(0,40)+'…':after));
row.append(make('span','rename-where',`${site.file}:${site.line}`),code);list.append(row);
}
foot.dataset.state=problem?'error':'';foot.textContent=problem||t('rename.hint',{n:sites.length,files:count});
}
const rect=editor.rectAt(target.start),origin=editor.body.getBoundingClientRect();
const at={left:origin.left+(rect?.x??0),top:origin.top+(rect?.top??0),bottom:origin.top+(rect?.bottom??0)};
const surface=openPopover(app,at,box,{className:'rename-pop',label:t('rename.title')});
input.addEventListener('input',paint);
input.addEventListener('keydown',event=>{
if(event.key!=='Enter'||event.isComposing)return;event.preventDefault();
const next=input.value.trim();if(check())return;
surface.close(false);editor.focus();
if(next===old)return;
const before=sites.filter(site=>site.file===path&&site.start<target.start).length,undo=applyEdits(sites.map(site=>({file:site.file,start:site.start,end:site.end,text:next})));
const at=target.start+before*(next.length-old.length);views.get(path)?.editor?.select(at,at+next.length,{center:false});
toast(t('rename.done',{from:old,to:next,n:sites.length}),{label:t('rename.undo'),run:undo});
});
paint();input.focus();input.select();
}
/** W3: a grid picker; the table or matrix goes in at the caret with its cells as tab stops. */
function insertTable(mode){
const editor=activeEditor(),path=active;if(!editor)return;
const start=editor.input.selectionStart,end=editor.input.selectionEnd,inMath=!!mathAt(editor.getValue(),start);
openTablePicker({host:app,t,mode,inMath,insert:(template,packages)=>{
let from=start,to=end;const added=[];
for(const pkg of packages){
const source=project.get(project.main)?.text,edit=typeof source==='string'&&packageEdit(project.main,source,pkg);if(!edit)continue;
applyEdits([edit]);added.push(pkg);if(project.main===path&&edit.start<=from){from+=edit.text.length;to+=edit.text.length;}
}
views.get(path)?.editor?.insertSnippet(from,to,template);
if(added.length)notify('table.added',{name:added.join(', ')});
}});
}
function referencesAt(path){
const editor=views.get(path)?.editor;if(!editor)return;
const target=targetAt(editor.getValue(),editor.caret);
if(target&&(target.kind==='label'||target.kind==='ref'))findAllReferences(target.name);else notify('rename.none');
}
function fixContext(){
const files=textFiles();
return {files,main:project.main,labels:findLabels(files).map(label=>label.name),bibKeys:bibEntries().map(entry=>entry.key),paths:project.paths(),
macros:[...files.values()].flatMap(text=>[...text.matchAll(/\\(?:re)?newcommand\*?\s*\{?\\([A-Za-z]+)|\\DeclareMathOperator\*?\s*\{?\\([A-Za-z]+)|\\def\s*\\([A-Za-z]+)/g)].map(match=>match[1]||match[2]||match[3]))};
}
/** Mod+. or the gutter bulb: the fixes for the problems on a line (default: the caret's), as a menu. */
function openFixes(path=active,line,at){
const editor=views.get(path)?.editor;if(!editor)return;
line??=views.get(path)?.position?.line||1;
const problems=editor.diagnosticsAt(line),context=fixContext(),items=[];
for(const problem of problems){
const fixes=quickFixes({...problem,file:path},context);if(!fixes.length)continue;
if(items.length)items.push('separator');
items.push({note:problem.message,noteIcon:problem.severity==='error'?'error':problem.severity==='warning'?'warning':'info',tone:problem.severity});
for(const fix of fixes)items.push({label:fixLabel(fix),icon:fix.kind==='package'?'plus':fix.kind==='unbalanced'?'target':fix.kind==='replace'?'edit':'bulb',
run:()=>{if(fix.go){reveal({path:fix.go.file,offset:fix.go.offset});return;}const undo=applyEdits(fix.edits);if(fix.edits.some(edit=>edit.file!==path))toast(t('fix.applied',{name:fixLabel(fix)}),{label:t('common.undo'),run:undo});}});
}
if(!items.length){notify(problems.length?'fix.unknown':'fix.none');return;}
const first=items.find(item=>item.run);if(first)first.hint='↵';
items.push('separator',{label:t('fix.panel'),icon:'warning',run:()=>openPanel('problems')});
let anchor=at;
if(!anchor){const rect=editor.rectAt(editor.offsetOf(line)),origin=editor.body.getBoundingClientRect();anchor={left:origin.left+(rect?.x??0),top:origin.top+(rect?.top??0),bottom:origin.top+(rect?.bottom??0)};}
openMenu(app,anchor,items);
}
function fixLabel(fix){
if(fix.kind==='package')return t('fix.package',{name:fix.label});