-
-
Notifications
You must be signed in to change notification settings - Fork 953
Expand file tree
/
Copy pathpreview-model.tsx
More file actions
922 lines (877 loc) · 36 KB
/
preview-model.tsx
File metadata and controls
922 lines (877 loc) · 36 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
// Copyright 2026, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import { BlockNodeModel } from "@/app/block/blocktypes";
import { ContextMenuModel } from "@/app/store/contextmenu";
import { globalStore } from "@/app/store/jotaiStore";
import type { TabModel } from "@/app/store/tab-model";
import { TabRpcClient } from "@/app/store/wshrpcutil";
import { getOverrideConfigAtom, refocusNode } from "@/store/global";
import * as WOS from "@/store/wos";
import { goHistory, goHistoryBack, goHistoryForward } from "@/util/historyutil";
import { checkKeyPressed } from "@/util/keyutil";
import { addOpenMenuItems } from "@/util/previewutil";
import { base64ToString, fireAndForget, isBlank, jotaiLoadableValue, stringToBase64 } from "@/util/util";
import { formatRemoteUri } from "@/util/waveutil";
import clsx from "clsx";
import { Atom, atom, Getter, PrimitiveAtom, WritableAtom } from "jotai";
import { loadable } from "jotai/utils";
import type * as MonacoTypes from "monaco-editor";
import { createRef } from "react";
import { PreviewView } from "./preview";
import { makeDirectoryDefaultMenuItems } from "./preview-directory-utils";
import type { PreviewEnv } from "./previewenv";
// TODO drive this using config
const BOOKMARKS: { label: string; path: string }[] = [
{ label: "Home", path: "~" },
{ label: "Desktop", path: "~/Desktop" },
{ label: "Downloads", path: "~/Downloads" },
{ label: "Documents", path: "~/Documents" },
{ label: "Root", path: "/" },
];
const MaxFileSize = 1024 * 1024 * 10; // 10MB
const MaxCSVSize = 1024 * 1024 * 1; // 1MB
const textApplicationMimetypes = [
"application/sql",
"application/x-php",
"application/x-pem-file",
"application/x-httpd-php",
"application/liquid",
"application/graphql",
"application/javascript",
"application/typescript",
"application/x-javascript",
"application/x-typescript",
"application/dart",
"application/vnd.dart",
"application/x-ruby",
"application/sql",
"application/wasm",
"application/x-latex",
"application/x-sh",
"application/x-python",
"application/x-awk",
];
function isTextFile(mimeType: string): boolean {
if (mimeType == null) {
return false;
}
return (
mimeType.startsWith("text/") ||
textApplicationMimetypes.includes(mimeType) ||
(mimeType.startsWith("application/") &&
(mimeType.includes("json") || mimeType.includes("yaml") || mimeType.includes("toml"))) ||
mimeType.includes("xml")
);
}
function isStreamingType(mimeType: string): boolean {
if (mimeType == null) {
return false;
}
return (
mimeType.startsWith("application/pdf") ||
mimeType.startsWith("video/") ||
mimeType.startsWith("audio/") ||
mimeType.startsWith("image/")
);
}
function isMarkdownLike(mimeType: string): boolean {
if (mimeType == null) {
return false;
}
return mimeType.startsWith("text/markdown") || mimeType.startsWith("text/mdx");
}
function iconForFile(mimeType: string): string {
if (mimeType == null) {
mimeType = "unknown";
}
if (mimeType == "application/pdf") {
return "file-pdf";
} else if (mimeType.startsWith("image/")) {
return "image";
} else if (mimeType.startsWith("video/")) {
return "film";
} else if (mimeType.startsWith("audio/")) {
return "headphones";
} else if (isMarkdownLike(mimeType)) {
return "file-lines";
} else if (mimeType == "text/csv") {
return "file-csv";
} else if (
mimeType.startsWith("text/") ||
mimeType == "application/sql" ||
(mimeType.startsWith("application/") &&
(mimeType.includes("json") || mimeType.includes("yaml") || mimeType.includes("toml")))
) {
return "file-code";
} else {
return "file";
}
}
export class PreviewModel implements ViewModel {
viewType: string;
blockId: string;
nodeModel: BlockNodeModel;
tabModel: TabModel;
noPadding?: Atom<boolean>;
blockAtom: Atom<Block>;
viewIcon: Atom<string | IconButtonDecl>;
viewName: Atom<string>;
viewText: Atom<HeaderElem[]>;
preIconButton: Atom<IconButtonDecl>;
endIconButtons: Atom<IconButtonDecl[]>;
hideViewName: Atom<boolean>;
previewTextRef: React.RefObject<HTMLDivElement>;
editMode: Atom<boolean>;
canPreview: PrimitiveAtom<boolean>;
specializedView: Atom<Promise<{ specializedView?: string; errorStr?: string }>>;
loadableSpecializedView: Atom<Loadable<{ specializedView?: string; errorStr?: string }>>;
manageConnection: Atom<boolean>;
connStatus: Atom<ConnStatus>;
filterOutNowsh?: Atom<boolean>;
metaFilePath: Atom<string>;
statFilePath: Atom<Promise<string>>;
loadableFileInfo: Atom<Loadable<FileInfo>>;
connection: Atom<Promise<string>>;
connectionImmediate: Atom<string>;
statFile: Atom<Promise<FileInfo>>;
fullFile: Atom<Promise<FileData>>;
fileMimeType: Atom<Promise<string>>;
fileMimeTypeLoadable: Atom<Loadable<string>>;
fileContentSaved: PrimitiveAtom<string | null>;
fileContent: WritableAtom<Promise<string>, [string], void>;
newFileContent: PrimitiveAtom<string | null>;
connectionError: PrimitiveAtom<string>;
errorMsgAtom: PrimitiveAtom<ErrorMsg>;
openFileModal: PrimitiveAtom<boolean>;
openFileModalDelay: PrimitiveAtom<boolean>;
openFileError: PrimitiveAtom<string>;
openFileModalGiveFocusRef: React.RefObject<() => boolean>;
markdownShowToc: PrimitiveAtom<boolean>;
monacoRef: React.RefObject<MonacoTypes.editor.IStandaloneCodeEditor>;
showHiddenFiles: PrimitiveAtom<boolean>;
refreshVersion: PrimitiveAtom<number>;
directorySearchActive: PrimitiveAtom<boolean>;
refreshCallback: () => void;
directoryKeyDownHandler: (waveEvent: WaveKeyboardEvent) => boolean;
codeEditKeyDownHandler: (waveEvent: WaveKeyboardEvent) => boolean;
env: PreviewEnv;
followTermIdAtom: Atom<string | null>;
followTermCwdAtom: Atom<string | null>;
followTermBidirAtom: Atom<boolean>;
followTermMenuDataAtom: PrimitiveAtom<{ pos: { x: number; y: number }; terms: { blockId: string; title: string }[]; currentFollowId: string | null; bidir: boolean } | null>;
constructor({ blockId, nodeModel, tabModel, waveEnv }: ViewModelInitType) {
this.viewType = "preview";
this.blockId = blockId;
this.nodeModel = nodeModel;
this.tabModel = tabModel;
this.env = waveEnv;
let showHiddenFiles = globalStore.get(this.env.getSettingsKeyAtom("preview:showhiddenfiles")) ?? true;
this.showHiddenFiles = atom<boolean>(showHiddenFiles);
this.refreshVersion = atom(0);
this.directorySearchActive = atom(false);
this.previewTextRef = createRef();
this.openFileModal = atom(false);
this.openFileModalDelay = atom(false);
this.openFileError = atom(null) as PrimitiveAtom<string>;
this.openFileModalGiveFocusRef = createRef();
this.manageConnection = atom(true);
this.blockAtom = this.env.wos.getWaveObjectAtom<Block>(`block:${blockId}`);
this.markdownShowToc = atom(false);
this.filterOutNowsh = atom(true);
this.monacoRef = createRef();
this.connectionError = atom("");
this.errorMsgAtom = atom(null) as PrimitiveAtom<ErrorMsg | null>;
this.viewIcon = atom((get) => {
const blockData = get(this.blockAtom);
if (blockData?.meta?.icon) {
return blockData.meta.icon;
}
const connStatus = get(this.connStatus);
if (connStatus?.status != "connected") {
return null;
}
const mimeTypeLoadable = get(this.fileMimeTypeLoadable);
const mimeType = jotaiLoadableValue(mimeTypeLoadable, "");
if (mimeType == "directory") {
return {
elemtype: "iconbutton",
icon: "folder-open",
longClick: (e: React.MouseEvent<any>) => {
const menuItems: ContextMenuItem[] = BOOKMARKS.map((bookmark) => ({
label: `Go to ${bookmark.label} (${bookmark.path})`,
click: () => this.goHistory(bookmark.path),
}));
ContextMenuModel.getInstance().showContextMenu(menuItems, e);
},
};
}
return iconForFile(mimeType);
});
this.editMode = atom((get) => {
const blockData = get(this.blockAtom);
return blockData?.meta?.edit ?? false;
});
this.viewName = atom("Preview");
this.hideViewName = atom(true);
this.viewText = atom((get) => {
let headerPath = get(this.metaFilePath);
const connStatus = get(this.connStatus);
if (connStatus?.status != "connected") {
return [
{
elemtype: "text",
text: headerPath,
className: "preview-filename",
},
];
}
const loadableSV = get(this.loadableSpecializedView);
const isCeView = loadableSV.state == "hasData" && loadableSV.data.specializedView == "codeedit";
const loadableFileInfo = get(this.loadableFileInfo);
if (loadableFileInfo.state == "hasData") {
headerPath = loadableFileInfo.data?.path;
if (headerPath == "~") {
headerPath = `~ (${loadableFileInfo.data?.dir + "/" + loadableFileInfo.data?.name})`;
}
}
if (!isBlank(headerPath) && headerPath != "/" && headerPath.endsWith("/")) {
headerPath = headerPath.slice(0, -1);
}
const viewTextChildren: HeaderElem[] = [
{
elemtype: "text",
text: headerPath,
ref: this.previewTextRef,
className: "preview-filename",
onClick: () => this.toggleOpenFileModal(),
},
];
let saveClassName = "grey";
if (get(this.newFileContent) !== null) {
saveClassName = "green";
}
if (isCeView) {
const fileInfo = globalStore.get(this.loadableFileInfo);
if (fileInfo.state != "hasData") {
viewTextChildren.push({
elemtype: "textbutton",
text: "Loading ...",
className: clsx(`grey rounded-[4px] !py-[2px] !px-[10px] text-[11px] font-[500]`),
onClick: () => {},
});
} else if (fileInfo.data.readonly) {
viewTextChildren.push({
elemtype: "textbutton",
text: "Read Only",
className: clsx(`yellow rounded-[4px] !py-[2px] !px-[10px] text-[11px] font-[500]`),
onClick: () => {},
});
} else {
viewTextChildren.push({
elemtype: "textbutton",
text: "Save",
className: clsx(`${saveClassName} rounded-[4px] !py-[2px] !px-[10px] text-[11px] font-[500]`),
onClick: () => fireAndForget(this.handleFileSave.bind(this)),
});
}
if (get(this.canPreview)) {
viewTextChildren.push({
elemtype: "textbutton",
text: "Preview",
className: "grey rounded-[4px] !py-[2px] !px-[10px] text-[11px] font-[500]",
onClick: () => fireAndForget(() => this.setEditMode(false)),
});
}
} else if (get(this.canPreview)) {
viewTextChildren.push({
elemtype: "textbutton",
text: "Edit",
className: "grey rounded-[4px] !py-[2px] !px-[10px] text-[11px] font-[500]",
onClick: () => fireAndForget(() => this.setEditMode(true)),
});
}
return [
{
elemtype: "div",
children: viewTextChildren,
},
] as HeaderElem[];
});
this.preIconButton = atom((get) => {
const connStatus = get(this.connStatus);
if (connStatus?.status != "connected") {
return null;
}
const mimeType = jotaiLoadableValue(get(this.fileMimeTypeLoadable), "");
const metaPath = get(this.metaFilePath);
if (mimeType == "directory" && metaPath == "/") {
return null;
}
return {
elemtype: "iconbutton",
icon: "chevron-left",
click: this.goParentDirectory.bind(this),
};
});
this.endIconButtons = atom((get) => {
const connStatus = get(this.connStatus);
if (connStatus?.status != "connected") {
return null;
}
const mimeType = jotaiLoadableValue(get(this.fileMimeTypeLoadable), "");
const loadableSV = get(this.loadableSpecializedView);
const isCeView = loadableSV.state == "hasData" && loadableSV.data.specializedView == "codeedit";
if (mimeType == "directory") {
const showHiddenFiles = get(this.showHiddenFiles);
const followTermId = get(this.followTermIdAtom);
return [
{
elemtype: "iconbutton",
icon: showHiddenFiles ? "eye" : "eye-slash",
title: showHiddenFiles ? "Hide Hidden Files" : "Show Hidden Files",
click: () => {
globalStore.set(this.showHiddenFiles, (prev) => !prev);
},
},
{
elemtype: "iconbutton",
icon: "link",
title: followTermId ? "Following Terminal (click to change or unlink)" : "Follow a Terminal",
iconColor: followTermId ? "var(--success-color)" : undefined,
click: (e: React.MouseEvent<any>) => this.showFollowTermMenu(e),
},
{
elemtype: "iconbutton",
icon: "arrows-rotate",
click: () => this.refreshCallback?.(),
},
] as IconButtonDecl[];
} else if (!isCeView && isMarkdownLike(mimeType)) {
return [
{
elemtype: "iconbutton",
icon: "book",
title: "Table of Contents",
click: () => this.markdownShowTocToggle(),
},
{
elemtype: "iconbutton",
icon: "arrows-rotate",
title: "Refresh",
click: () => this.refreshCallback?.(),
},
] as IconButtonDecl[];
} else if (!isCeView && mimeType) {
// For all other file types (text, code, etc.), add refresh button
return [
{
elemtype: "iconbutton",
icon: "arrows-rotate",
title: "Refresh",
click: () => this.refreshCallback?.(),
},
] as IconButtonDecl[];
}
return null;
});
this.metaFilePath = atom<string>((get) => {
const file = get(this.blockAtom)?.meta?.file;
if (isBlank(file)) {
return "~";
}
return file;
});
this.statFilePath = atom<Promise<string>>(async (get) => {
const fileInfo = await get(this.statFile);
return fileInfo?.path;
});
this.connection = atom<Promise<string>>(async (get) => {
const connName = get(this.blockAtom)?.meta?.connection;
try {
await this.env.rpc.ConnEnsureCommand(TabRpcClient, { connname: connName }, { timeout: 60000 });
globalStore.set(this.connectionError, "");
} catch (e) {
globalStore.set(this.connectionError, e as string);
}
return connName;
});
this.connectionImmediate = atom<string>((get) => {
return get(this.blockAtom)?.meta?.connection;
});
this.statFile = atom<Promise<FileInfo>>(async (get) => {
const fileName = get(this.metaFilePath);
const path = await this.formatRemoteUri(fileName, get);
if (fileName == null) {
return null;
}
try {
const statFile = await this.env.rpc.FileInfoCommand(TabRpcClient, {
info: {
path,
},
});
return statFile;
} catch (e) {
const errorStatus: ErrorMsg = {
status: "File Read Failed",
text: `${e}`,
};
globalStore.set(this.errorMsgAtom, errorStatus);
}
});
this.fileMimeType = atom<Promise<string>>(async (get) => {
const fileInfo = await get(this.statFile);
return fileInfo?.mimetype;
});
this.fileMimeTypeLoadable = loadable(this.fileMimeType);
this.newFileContent = atom(null) as PrimitiveAtom<string | null>;
this.goParentDirectory = this.goParentDirectory.bind(this);
const fullFileAtom = atom<Promise<FileData>>(async (get) => {
get(this.refreshVersion); // Subscribe to refreshVersion to trigger re-fetch
const fileName = get(this.metaFilePath);
const path = await this.formatRemoteUri(fileName, get);
if (fileName == null) {
return null;
}
try {
const file = await this.env.rpc.FileReadCommand(TabRpcClient, {
info: {
path,
},
});
return file;
} catch (e) {
const errorStatus: ErrorMsg = {
status: "File Read Failed",
text: `${e}`,
};
globalStore.set(this.errorMsgAtom, errorStatus);
}
});
this.fileContentSaved = atom(null) as PrimitiveAtom<string | null>;
const fileContentAtom = atom(
async (get) => {
const newContent = get(this.newFileContent);
if (newContent != null) {
return newContent;
}
const savedContent = get(this.fileContentSaved);
if (savedContent != null) {
return savedContent;
}
const fullFile = await get(fullFileAtom);
return base64ToString(fullFile?.data64);
},
(_, set, update: string) => {
set(this.fileContentSaved, update);
}
);
this.fullFile = fullFileAtom;
this.fileContent = fileContentAtom;
this.specializedView = atom<Promise<{ specializedView?: string; errorStr?: string }>>(async (get) => {
return this.getSpecializedView(get);
});
this.loadableSpecializedView = loadable(this.specializedView);
this.canPreview = atom(false);
this.loadableFileInfo = loadable(this.statFile);
this.connStatus = atom((get) => {
const blockData = get(this.blockAtom);
const connName = blockData?.meta?.connection;
const connAtom = this.env.getConnStatusAtom(connName);
return get(connAtom);
});
this.noPadding = atom(true);
this.followTermIdAtom = atom<string | null>((get) => {
return (get(this.blockAtom)?.meta?.["preview:followtermid"] as string) ?? null;
});
this.followTermCwdAtom = atom<string | null>((get) => {
const termId = get(this.followTermIdAtom);
if (!termId) return null;
const termBlock = WOS.getObjectValue<Block>(WOS.makeORef("block", termId), get);
return (termBlock?.meta?.["cmd:cwd"] as string) ?? null;
});
this.followTermBidirAtom = atom<boolean>((get) => {
return (get(this.blockAtom)?.meta?.["preview:followterm:bidir"] as boolean) ?? false;
});
this.followTermMenuDataAtom = atom(null);
}
showFollowTermMenu(e: React.MouseEvent<any>) {
const tabData = globalStore.get(this.tabModel.tabAtom);
const blockIds = tabData?.blockids ?? [];
const termBlockIds = blockIds
.filter((bid) => {
if (bid === this.blockId) return false;
const block = WOS.getObjectValue<Block>(WOS.makeORef("block", bid), globalStore.get);
return block?.meta?.view === "term";
});
const terms = termBlockIds.map((bid) => {
const block = WOS.getObjectValue<Block>(WOS.makeORef("block", bid), globalStore.get);
const termIndex = termBlockIds.indexOf(bid) + 1;
return {
blockId: bid,
title: (block?.meta?.["frame:title"] as string) || `Terminal ${termIndex}`,
};
});
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
const currentFollowId = globalStore.get(this.followTermIdAtom);
const bidir = globalStore.get(this.followTermBidirAtom);
globalStore.set(this.followTermMenuDataAtom, {
pos: { x: rect.left, y: rect.bottom + 4 },
terms,
currentFollowId,
bidir,
});
}
markdownShowTocToggle() {
globalStore.set(this.markdownShowToc, !globalStore.get(this.markdownShowToc));
}
get viewComponent(): ViewComponent {
return PreviewView;
}
async getSpecializedView(getFn: Getter): Promise<{ specializedView?: string; errorStr?: string }> {
const mimeType = await getFn(this.fileMimeType);
const fileInfo = await getFn(this.statFile);
const fileName = fileInfo?.name;
const connErr = getFn(this.connectionError);
const editMode = getFn(this.editMode);
const genErr = getFn(this.errorMsgAtom);
if (!fileInfo) {
return { errorStr: `Load Error: ${genErr?.text}` };
}
if (connErr != "") {
return { errorStr: `Connection Error: ${connErr}` };
}
if (fileInfo?.notfound) {
return { specializedView: "codeedit" };
}
if (mimeType == null) {
return { errorStr: `Unable to determine mimetype for: ${fileInfo.path}` };
}
if (isStreamingType(mimeType)) {
return { specializedView: "streaming" };
}
if (!fileInfo) {
const fileNameStr = fileName ? " " + JSON.stringify(fileName) : "";
return { errorStr: "File Not Found" + fileNameStr };
}
if (fileInfo.size > MaxFileSize) {
return { errorStr: "File Too Large to Preview (10 MB Max)" };
}
if (mimeType == "text/csv" && fileInfo.size > MaxCSVSize) {
return { errorStr: "CSV File Too Large to Preview (1 MB Max)" };
}
if (mimeType == "directory") {
return { specializedView: "directory" };
}
if (mimeType == "text/csv") {
if (editMode) {
return { specializedView: "codeedit" };
}
return { specializedView: "csv" };
}
if (isMarkdownLike(mimeType)) {
if (editMode) {
return { specializedView: "codeedit" };
}
return { specializedView: "markdown" };
}
if (isTextFile(mimeType) || fileInfo.size == 0) {
return { specializedView: "codeedit" };
}
return { errorStr: `Preview (${mimeType})` };
}
updateOpenFileModalAndError(isOpen, errorMsg = null) {
globalStore.set(this.openFileModal, isOpen);
globalStore.set(this.openFileError, errorMsg);
if (isOpen) {
globalStore.set(this.openFileModalDelay, true);
} else {
const delayVal = globalStore.get(this.openFileModalDelay);
if (delayVal) {
setTimeout(() => {
globalStore.set(this.openFileModalDelay, false);
}, 200);
}
}
}
toggleOpenFileModal() {
const modalOpen = globalStore.get(this.openFileModal);
const delayVal = globalStore.get(this.openFileModalDelay);
if (!modalOpen && delayVal) {
return;
}
this.updateOpenFileModalAndError(!modalOpen);
}
async goHistory(newPath: string) {
let fileName = globalStore.get(this.metaFilePath);
if (fileName == null) {
fileName = "";
}
const blockMeta = globalStore.get(this.blockAtom)?.meta;
const updateMeta = goHistory("file", fileName, newPath, blockMeta);
if (updateMeta == null) {
return;
}
const blockOref = WOS.makeORef("block", this.blockId);
await this.env.services.object.UpdateObjectMeta(blockOref, updateMeta);
// Clear the saved file buffers
globalStore.set(this.fileContentSaved, null);
globalStore.set(this.newFileContent, null);
}
async goParentDirectory({ fileInfo = null }: { fileInfo?: FileInfo | null }) {
// optional parameter needed for recursive case
const defaultFileInfo = await globalStore.get(this.statFile);
if (fileInfo === null) {
fileInfo = defaultFileInfo;
}
if (fileInfo == null) {
this.updateOpenFileModalAndError(false);
return true;
}
try {
this.updateOpenFileModalAndError(false);
await this.goHistory(fileInfo.dir);
refocusNode(this.blockId);
} catch (e) {
globalStore.set(this.openFileError, e.message);
console.error("Error opening file", fileInfo.dir, e);
}
}
async goHistoryBack() {
const blockMeta = globalStore.get(this.blockAtom)?.meta;
const curPath = globalStore.get(this.metaFilePath);
const updateMeta = goHistoryBack("file", curPath, blockMeta, true);
if (updateMeta == null) {
return;
}
updateMeta.edit = false;
const blockOref = WOS.makeORef("block", this.blockId);
await this.env.services.object.UpdateObjectMeta(blockOref, updateMeta);
}
async goHistoryForward() {
const blockMeta = globalStore.get(this.blockAtom)?.meta;
const curPath = globalStore.get(this.metaFilePath);
const updateMeta = goHistoryForward("file", curPath, blockMeta);
if (updateMeta == null) {
return;
}
updateMeta.edit = false;
const blockOref = WOS.makeORef("block", this.blockId);
await this.env.services.object.UpdateObjectMeta(blockOref, updateMeta);
}
async setEditMode(edit: boolean) {
const blockMeta = globalStore.get(this.blockAtom)?.meta;
const blockOref = WOS.makeORef("block", this.blockId);
await this.env.services.object.UpdateObjectMeta(blockOref, { ...blockMeta, edit });
}
async handleFileSave() {
const filePath = await globalStore.get(this.statFilePath);
if (filePath == null) {
return;
}
const newFileContent = globalStore.get(this.newFileContent);
if (newFileContent == null) {
console.log("not saving file, newFileContent is null");
return;
}
try {
await this.env.rpc.FileWriteCommand(TabRpcClient, {
info: {
path: await this.formatRemoteUri(filePath, globalStore.get),
},
data64: stringToBase64(newFileContent),
});
globalStore.set(this.fileContent, newFileContent);
globalStore.set(this.newFileContent, null);
console.log("saved file", filePath);
} catch (e) {
const errorStatus: ErrorMsg = {
status: "Save Failed",
text: `${e}`,
};
globalStore.set(this.errorMsgAtom, errorStatus);
}
}
async handleFileRevert() {
const fileContent = await globalStore.get(this.fileContent);
this.monacoRef.current?.setValue(fileContent);
globalStore.set(this.newFileContent, null);
}
async handleOpenFile(filePath: string) {
const fileInfo = await globalStore.get(this.statFile);
this.updateOpenFileModalAndError(false);
if (fileInfo == null) {
return true;
}
try {
this.goHistory(filePath);
refocusNode(this.blockId);
} catch (e) {
globalStore.set(this.openFileError, e.message);
console.error("Error opening file", filePath, e);
}
}
isSpecializedView(sv: string): boolean {
const loadableSV = globalStore.get(this.loadableSpecializedView);
return loadableSV.state == "hasData" && loadableSV.data.specializedView == sv;
}
getSettingsMenuItems(): ContextMenuItem[] {
const defaultFontSize = globalStore.get(this.env.getSettingsKeyAtom("editor:fontsize")) ?? 12;
const blockData = globalStore.get(this.blockAtom);
const overrideFontSize = blockData?.meta?.["editor:fontsize"];
const menuItems: ContextMenuItem[] = [];
menuItems.push({
label: "Copy Full Path",
click: () =>
fireAndForget(async () => {
const filePath = await globalStore.get(this.statFilePath);
if (filePath == null) {
return;
}
const conn = await globalStore.get(this.connection);
if (conn) {
// remote path
await navigator.clipboard.writeText(formatRemoteUri(filePath, conn));
} else {
// local path
await navigator.clipboard.writeText(filePath);
}
}),
});
menuItems.push({
label: "Copy File Name",
click: () =>
fireAndForget(async () => {
const fileInfo = await globalStore.get(this.statFile);
if (fileInfo == null || fileInfo.name == null) {
return;
}
await navigator.clipboard.writeText(fileInfo.name);
}),
});
menuItems.push({ type: "separator" });
const finfo = jotaiLoadableValue(globalStore.get(this.loadableFileInfo), null);
addOpenMenuItems(menuItems, globalStore.get(this.connectionImmediate), finfo);
const loadableSV = globalStore.get(this.loadableSpecializedView);
const wordWrapAtom = getOverrideConfigAtom(this.blockId, "editor:wordwrap");
const wordWrap = globalStore.get(wordWrapAtom) ?? false;
menuItems.push({ type: "separator" });
if (loadableSV.state == "hasData" && loadableSV.data.specializedView == "codeedit") {
const fontSizeSubMenu: ContextMenuItem[] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18].map(
(fontSize: number) => {
return {
label: fontSize.toString() + "px",
type: "checkbox",
checked: overrideFontSize == fontSize,
click: () => {
this.env.rpc.SetMetaCommand(TabRpcClient, {
oref: WOS.makeORef("block", this.blockId),
meta: { "editor:fontsize": fontSize },
});
},
};
}
);
fontSizeSubMenu.unshift({
label: "Default (" + defaultFontSize + "px)",
type: "checkbox",
checked: overrideFontSize == null,
click: () => {
this.env.rpc.SetMetaCommand(TabRpcClient, {
oref: WOS.makeORef("block", this.blockId),
meta: { "editor:fontsize": null },
});
},
});
menuItems.push({
label: "Editor Font Size",
submenu: fontSizeSubMenu,
});
if (globalStore.get(this.newFileContent) != null) {
menuItems.push({ type: "separator" });
menuItems.push({
label: "Save File",
click: () => fireAndForget(this.handleFileSave.bind(this)),
});
menuItems.push({
label: "Revert File",
click: () => fireAndForget(this.handleFileRevert.bind(this)),
});
}
menuItems.push({ type: "separator" });
menuItems.push({
label: "Word Wrap",
type: "checkbox",
checked: wordWrap,
click: () =>
fireAndForget(async () => {
const blockOref = WOS.makeORef("block", this.blockId);
await this.env.services.object.UpdateObjectMeta(blockOref, {
"editor:wordwrap": !wordWrap,
});
}),
});
}
if (loadableSV.state == "hasData" && loadableSV.data.specializedView == "directory") {
menuItems.push({ type: "separator" });
menuItems.push({ label: "Default Settings", enabled: false });
menuItems.push(...makeDirectoryDefaultMenuItems(this));
}
return menuItems;
}
giveFocus(): boolean {
const openModalOpen = globalStore.get(this.openFileModal);
if (openModalOpen) {
this.openFileModalGiveFocusRef.current?.();
return true;
}
if (this.monacoRef.current) {
this.monacoRef.current.focus();
return true;
}
return false;
}
keyDownHandler(e: WaveKeyboardEvent): boolean {
if (checkKeyPressed(e, "Cmd:ArrowLeft")) {
fireAndForget(this.goHistoryBack.bind(this));
return true;
}
if (checkKeyPressed(e, "Cmd:ArrowRight")) {
fireAndForget(this.goHistoryForward.bind(this));
return true;
}
if (checkKeyPressed(e, "Cmd:ArrowUp")) {
// handle up directory
fireAndForget(() => this.goParentDirectory({}));
return true;
}
if (checkKeyPressed(e, "Cmd:o")) {
this.toggleOpenFileModal();
return true;
}
const canPreview = globalStore.get(this.canPreview);
if (canPreview) {
if (checkKeyPressed(e, "Cmd:e")) {
const editMode = globalStore.get(this.editMode);
fireAndForget(() => this.setEditMode(!editMode));
return true;
}
}
if (this.directoryKeyDownHandler) {
const handled = this.directoryKeyDownHandler(e);
if (handled) {
return true;
}
}
if (this.codeEditKeyDownHandler) {
const handled = this.codeEditKeyDownHandler(e);
if (handled) {
return true;
}
}
return false;
}
async formatRemoteUri(path: string, get: Getter): Promise<string> {
return formatRemoteUri(path, await get(this.connection));
}
}