-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.html
1610 lines (1490 loc) · 46.7 KB
/
main.html
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
<!doctype html>
<meta charset=utf-8>
<meta name="viewport" content="initial-scale=1, user-scalable=0, interactive-widget=resizes-content" />
<title>Filet Cloud</title>
<style nonce="{{.Nonce}}">
@font-face {
/* terminal font */
font-family: NotoMonoNerd;
src: url("/resources/NotoMonoNerdFontMono-Regular.ttf");
}
:root {
color-scheme: light dark;
--term-font: NotoMonoNerd;
}
* {
font-family: system-ui, NotoMonoNerd;
}
body>div>span {
/* xtermjs fix so font width calculations are correct */
font-family: var(--term-font);
}
body {
/* UI pane with no page scrolling */
position: fixed;
margin: 0px;
width: 100%;
height: 100%;
display: flex;
flex-direction: row;
overscroll-behavior: contain;
}
p,
h1 {
/* these are always clickable in the main browser page */
cursor: default;
margin: 2px;
}
.on {
/* icon of currenly selected file */
filter: contrast(0%);
}
/* horizontal storage management menu */
#menu {
display: flex;
align-items: flex-start;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
margin-bottom: 24px;
width: 100% - 48px;
}
#menu :focus-visible {
outline: 1px solid;
}
#menu>button {
all: unset;
}
#menu>button>h1 {
height: 1.1em;
margin-top: 0px;
margin-bottom: 0px;
text-align: center;
}
#menu>button>p {
font-size: 0.5em;
margin-top: 0px;
margin-bottom: 0px;
text-align: center;
}
.maxer {
width: 100%;
height: 100%;
overflow-y: auto;
}
#data {
width: calc(100% - 48px);
height: calc(100% - 48px);
margin: 24px 24px 0px 24px;
overflow-y: auto;
}
/* opened file content (fullscreen) */
body.open #data {
position: fixed;
left: 0px;
width: 100%;
height: 100%;
margin: 0px;
}
body.open #dirPane,
body.open #menu {
visibility: hidden;
}
/* selectable files and folders in the browsing pane (dir) and also the cart (data) */
#dir>button,
#data>button {
all: unset;
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
word-break: break-all;
backdrop-filter: invert(8%);
-webkit-backdrop-filter: invert(8%);
}
#dir>button:nth-child(odd),
#data>button:nth-child(odd) {
backdrop-filter: invert(4%);
-webkit-backdrop-filter: invert(4%)
}
#dir>button:nth-child(odd).highli,
#dir>button.highli,
#data>button:nth-child(odd).highli,
#data>button.highli {
backdrop-filter: invert(20%);
-webkit-backdrop-filter: invert(20%);
}
#dirPane {
display: flex;
flex-direction: column;
margin: 24px;
margin-right: 0px;
width: calc(45% - 24px);
height: calc(100% - 48px);
}
#dirPane>#path {
margin-top: 6px;
font-size: 0.7em;
filter: invert(20%);
}
#dataPane {
width: 55%;
height: 100%;
display: flex;
flex-direction: column;
}
#contenthider {
/* hide the background content when not logged in */
position: fixed;
width: 100vw;
height: 100vh;
z-index: 999998;
backdrop-filter: contrast(50%) blur(16px) brightness(130%);
-webkit-backdrop-filter: contrast(50%) blur(16px) brightness(130%);
@media (prefers-color-scheme: dark) {
backdrop-filter: contrast(50%) blur(16px) brightness(70%);
-webkit-backdrop-filter: contrast(50%) blur(16px) brightness(70%);
}
}
#uploader {
display: none;
}
p.status {
/* uploading status icon */
position: absolute;
margin: 8px;
right: 0px;
}
@media (orientation: portrait) {
#menu {
margin-bottom: 0px;
}
#dirPane {
margin-top: 0px;
}
body {
flex-direction: column-reverse;
}
#dirPane {
width: calc(100% - 48px);
height: calc(50% - 24px);
margin-right: 28px;
}
#dataPane {
width: 100%;
height: 50%;
}
}
</style>
<!-- Pane for displaying all the clickable folders and files at this level -->
<div id=dirPane>
<div id=dir class=maxer tabindex=0></div>
<div id=path></div>
</div>
<!-- Pane for displaying content or actions relevant for the selected file or folder -->
<div id=dataPane>
<div id=data></div>
<div id=menu>
<button id=reload>
<h1>🔄</h1>
<p>reload</p>
</button>
<button id=makedir>
<h1>📁</h1>
<p>new<br>folder</p>
</button>
<button id=newfile>
<h1>📄</h1>
<p>new<br>file</p>
</button>
<button id=tabopen>
<h1>📖</h1>
<p>open</p>
</button>
<button id=upload>
<h1>📤</h1>
<p>upload</p>
</button>
<button id=download>
<h1>📥</h1>
<p>down<br>load</p>
</button>
<button id=rename>
<h1>🏷</h1>
<p>rename</p>
</button>
<button id=cart>
<h1>🛒</h1>
<p>cart</p>
<p id=cartlen>0</p>
</button>
<button id=move>
<h1>🚚</h1>
<p>move</p>
</button>
<button id=del>
<h1>🗑</h1>
<p>delete</p>
</button>
<button id=close>
<h1>❌</h1>
<p>close</p>
</button>
</div>
</div>
<input id="uploader" type="file" multiple />
<a id="dwnld" target="_blank" download></a>
<div id=contenthider></div>
<div><span><!--terminal font warmer--></span></div>
<!--
-- Folder Actions Pane (including any custom actions, the terminal launcher, and logout button).
-->
<template id=-folder-actions>
<style nonce="{{.Nonce}}">
#actions {
display: flex;
flex-direction: column;
flex-wrap: wrap-reverse;
align-items: center;
align-content: end;
column-gap: 0.8em;
row-gap: 0.2em;
padding: 10px;
height: calc(100% - 20px);
overflow: auto;
}
button {
all: unset;
flex-basis: "min-content";
}
button>h1 {
cursor: default;
height: 1.1em;
margin: 0px;
text-align: center;
}
button>p {
cursor: default;
font-size: 0.5em;
margin: 0px;
text-align: center;
}
#terminal.fullit {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
font-family: var(--term-font);
}
:focus-visible {
outline: 1px solid;
}
</style>
<link rel=stylesheet href="/resources/deps/xterm.css"
integrity="sha384-LJcOxlx9IMbNXDqJ2axpfEQKkAYbFjJfhXexLfiRJhjDU81mzgkiQq8rkV0j6dVh" />
<script src="/resources/deps/xterm.js"
integrity="sha384-/nfmYPUzWMS6v2atn8hbljz7NE0EI1iGx34lJaNzyVjWGDzMv+ciUZUeJpKA3Glc"></script>
<script src="/resources/deps/xterm-addon-fit.js"
integrity="sha384-AQLWHRKAgdTxkolJcLOELg4E9rE89CPE2xMy3tIRFn08NcGKPTsELdvKomqji+DL"></script>
<div id=terminal></div>
<div id=actions>
<button id=logout>
<h1>🔐</h1>
<p>logout</p>
</button>
<button id=term-button>
<h1>🖥</h1>
<p>terminal</p>
</button>
</div>
</template>
<!--
-- Login form
--
-- Form for establishing a login connection and a storage
-- class to manage secure queries with the server.
-->
<template id=-login-form>
<style nonce="{{.Nonce}}">
:host {
position: fixed;
z-index: 999999;
}
div {
display: flex;
width: 100vw;
height: 100vh;
align-items: center;
justify-content: center;
}
ul {
list-style: none;
}
li {
margin: 3px;
}
label {
display: inline-block;
width: 80px;
text-align: right;
}
input {
padding: 5px;
}
button {
float: right;
font-size: 2em;
border-style: solid;
border-color: currentColor;
background-color: background;
}
button.loading {
filter: blur(3px);
}
</style>
<div tabindex="-1">
<form>
<h1>👤 Login</h1>
<ul>
<li>
<label for=username>Username</label>
<input type=text id=username name=username required />
</li>
<li>
<label for=password>Password</label>
<input type=password id=password name=password required />
</li>
<li>
<label for=code>(Code)</label>
<input type=text id=code name=code title="2FA access code (optional on some servers)" size=8
autocomplete="off" />
</li>
<li>
<button>Connect</button>
</li>
</ul>
<input type=hidden id=CSRFToken value="{{.CSRF}}" />
</form>
</div>
</template>
<script nonce="{{.Nonce}}">
"use strict"
let autoLogoutTimer = null
const login = () => {
clearTimeout(autoLogoutTimer)
if (!document.querySelector("login-form") && crossOriginIsolated)
document.body.appendChild(document.createElement("login-form"))
}
login()
customElements.define("login-form", class extends HTMLElement {
constructor() {
super()
if (location.protocol != 'https:') return // Ensure secure transport.
this.attachShadow({mode: "open"}).appendChild(
document.getElementById("-login-form").content.cloneNode(true))
}
connectedCallback() {
if (!this.shadowRoot) return
this.shadowRoot.querySelector("form").addEventListener("submit", e => {
this.shadowRoot.querySelector("button").classList.add("loading")
e.preventDefault()
// Establish WebSocket connection.
fetch("/preconnect").then(() => {
const ws = new WebSocket(`wss://${window.location.host}/connect`)
ws.onclose = () => login()
ws.onerror = () => ws.close()
ws.onopen = () => {
// Set up auto-logout mechanism.
document.onvisibilitychange = () => {
if (document.visibilityState === "hidden")
autoLogoutTimer = setTimeout(() => ws.close(), 300000)
else clearTimeout(autoLogoutTimer)
}
// Authenticate WebSocket connection.
ws.send(this.shadowRoot.querySelector("#CSRFToken").value)
ws.send(this.shadowRoot.querySelector("#username").value)
ws.send(this.shadowRoot.querySelector("#password").value)
ws.send(this.shadowRoot.querySelector("#code").value)
// Give connection to the storage API.
storage.connect(ws)
}
document.body.removeChild(document.querySelector("login-form"))
})
})
this.shadowRoot.querySelector("#username").focus()
}
})
/**
* Interface for all operations interacting with the storage and server.
* Securely manages server connection, with login and session management,
* and only exposes the minimum interface.
*/
class Storage {
path = () => decodeURI(window.location.hash.replace(/^#.+:\//, '/'))
mode = () => window.location.hash.split(':')[0] + ":"
// Keep raw connections private, to limit javascript access.
#ws = null; // websocket connection to the server.
#connection = [] // pending connections awaiting login.
#reqs = {} // manage requests awaiting responses (stored by msgID).
#msgID = 0 // msgID counter for generating unique message IDs.
#authRefresh = null // refresh the authentication cookie on intervals.
#actionsUpdater = null
#onTermMsg = m => { }
constructor() {
// Setup the folder actions pane.
// This is all nested inside the storage class to securly protect the terminal data streams.
const stThis = this
customElements.define("folder-actions", class extends HTMLElement {
constructor() {
super()
this.attachShadow({mode: "open"}).appendChild(
document.getElementById("-folder-actions").content.cloneNode(true))
// Setup the terminal launcher button.
const tb = this.shadowRoot.getElementById("term-button")
tb.onclick = () => {
const terminal = this.shadowRoot.getElementById("terminal")
terminal.classList.add("fullit")
const term = new Terminal({fontFamily: terminal.style.fontFamily, fontSize: 12})
const fitTerm = new window.FitAddon.FitAddon()
term.loadAddon(fitTerm)
term.open(terminal)
window.onresize = () => {
fitTerm.fit()
// Resize the terminal pty session to the new rows and columns size.
stThis.#ws.send(JSON.stringify({action: "termdata", cols: term.cols, rows: term.rows}))
}
stThis.#onTermMsg = m => {
if (m === null) {
// Close terminal.
term.dispose()
stThis.#onTermMsg = m => { }
window.onresize = null
terminal.classList.remove("fullit")
}
else term.write(m)
}
term.onData(d => stThis.#ws.send(JSON.stringify({action: "termdata", data: d})))
stThis.#ws.send(JSON.stringify({action: "termdata", rows: -1})) // Send start-session message.
window.onresize()
term.focus()
}
// Setup the active folder plugin action buttons.
stThis.listDir(stThis.path()).then(fs => fs.forEach(f => {
if (!f.startsWith("._filetCloudAction_") || [...f].length < 20) return
if (f.endsWith("_")) return // ignore default sidecar output files.
const button = document.createElement("button")
const icon = document.createElement("h1")
icon.textContent = [...f].slice(-1)
const label = document.createElement("p")
const wrap = [...f].slice(19, -1).join("").split(/(_)/).map(
i => i === '_' ? document.createElement("br") : i)
label.append(...wrap)
button.append(icon, label)
button.onclick = () => {
// Launch the action with a wait prompt that will redirect on completion (if not dismissed).
let waiting = true
prompter("Running...", new Promise(ok => {
stThis.runAction(cwd() + f).then(r => {
if (r && waiting) nav(r) // redirect if completed, and not yet dismissed
ok()
})
})).then(() => waiting = false)
}
this.shadowRoot.querySelector("#actions").appendChild(button)
}))
// Setup the logout button
this.shadowRoot.querySelector("#logout").onclick = () => location.href = "/logout"
}
})
}
/**
* Finalise the setup of the websocket connection,
* and kick off any pending requests.
*/
async connect(ws) {
ws.onclose = () => {
clearInterval(this.#authRefresh) // cancel ongoing auth refreshing.
// close terminal if open.
this.#onTermMsg(null)
this.#onTermMsg = m => { }
// Hide any open content.
document.getElementById("contenthider").style.display = 'initial'
// Requeue all pending requests.
for (const k in this.#reqs) {
const v = this.#reqs[k]
delete this.#reqs[k]
this.#req(v[0], v[1])
}
// Trigger a re-login prompt.
login()
}
window.onbeforeunload = () => ws.close() // Force logout ASAP
ws.onerror = () => ws.close()
// Setup normal message response handling.
const onmessage = async m => {
let id = null, v = null
// Handle binary, or json response mesage.
if (m.data instanceof Blob) {
id = Number(await m.data.slice(0, 20).text())
v = await m.data.slice(20)
} else {
const d = JSON.parse(m.data)
id = d.id
v = d.msg
}
// Handle terminal data.
if (id < 0) {
if (id === -1) this.#onTermMsg(new Uint8Array(await v.arrayBuffer()))
else this.#onTermMsg(null) // Close terminal.
return
}
// Activate the prepared response handler.
const ok = this.#reqs[id][1]
delete this.#reqs[id]
ok(v)
}
// Ensure all websocket responses are processed in order.
let msgQueue = Promise.resolve()
ws.onmessage = m => msgQueue = msgQueue.then(() => onmessage(m)
)
this.#ws = ws
// Setup authenticated browser access.
let nextAuthTime = Date.now()
const checkAuthenticate = async () => {
if (Date.now() < nextAuthTime) return
if (!(await fetch("/authenticate",
{method: "POST", body: await this.#req({action: "token"})})).ok) {
ws.close()
return
}
nextAuthTime = Date.now() + 4 * 60000 // Refresh every 4 minutes.
}
await checkAuthenticate()
this.#authRefresh = setInterval(checkAuthenticate, 1000) // Check auth refresh every second.
document.getElementById("contenthider").style.display = 'none'
// Handle all the waiting requests.
while (this.#connection.length) this.#connection.pop()()
}
/**
* Send a request to the storage backend,
* via the websocket connection.
*/
async #req(r, ok) {
// Ensure we have an established login connection.
if (this.#ws === null || this.#ws.readyState !== WebSocket.OPEN) await new Promise(ok => {
this.#connection.push(ok)
login()
})
if (r === undefined) return // Used by authLinks when ensuring authenticated login.
// Send request to server, after preparing the response handler.
const msgID = this.#msgID += 1 // Prepare a way to associate responses to the requests.
const resp = new Promise(ok => {
// Load up a place holder for handling the response, whenever it comes.
this.#reqs[msgID] = [r, ok]
})
if (ok) this.#reqs[msgID][1] = ok // If in a retry of a previous request, reuse promise.
// Fire off the request.
if (r instanceof Blob) {
if (msgID.toString().length > 20) throw new Error()
this.#ws.send(new Blob([msgID.toString().padEnd(20), r]))
} else {
r.id = msgID
this.#ws.send(JSON.stringify(r))
}
return resp // Return the promise that will resolve to a response.
}
// Request the mime type for a file.
mime = async (path) => await this.#req({action: "mime", path: path})
// Request the contents of a file.
readFile = async (path) => await this.#req({action: "file", path: path})
// Request to make a new dir inside an existing folder.
newDir = async (path) => await this.#req({action: "newdir", path: path})
// Request to make a new file inside an existing folder.
newFile = async (path) => await this.#req({action: "newfile", path: path})
// Request to rename or move a file or folder.
rename = async (path, to) => await this.#req({action: "rename", path: path, to: to})
// Request to delete a file or folder.
remove = async (path) => await this.#req({action: "remove", path: path})
// Request to run a custom active folder plugin, (expected to be) at the given path.
runAction = async (path) => await this.#req({action: "runaction", path: path})
// Ensure the connection is still active (for use before using a storage link).
authLinks = async () => await this.#req()
// Storage link for a file's contents retrieved for downloading.
downloadLink = (path) => `/download:${encodeURI(path)}`
// Storage link for a file's contents.
fileLink = (path) => `/file:${encodeURI(path)}`
// Storage link for a thumbnail generated for a file.
thumbLink = (path) => `/thumb:${encodeURI(path)}`
// Storage link for a generated zip archive for a list of files.
zipLink = (paths) => '/zip?' + paths.map(p => `path=${encodeURI(p)}`).join('&')
/**
* Retrieve the contents of a directory as a list of strings,
* where child directories end in (forward) slashes.
* Results are returned sorted by name but with folders first.
*/
async listDir(path) {
const r = (await this.#req({action: "dir", path: path})).sort()
return r.map(([isFile, name]) => name + (isFile ? "" : "/"))
}
/**
* Upload a file to the server into the current directory,
* potentially overwriting existing files on the server.
*/
async upload(path, content) {
const plenstr = (new TextEncoder().encode(path)).length.toString() // get byte length!
if (plenstr.length > 20) throw new Error()
await this.#req(new Blob([plenstr.padEnd(20), path, content]))
}
}
const storage = new Storage();
</script>
<script nonce="{{.Nonce}}">
/**
* Browser UI code.
*/
"use strict"
// Redirect to a valid starting URL, if a new seesion.
if (window.location.hash === "") window.history.replaceState("", "", "/#browse:/")
// Setup some basic helper functions for navigation and the cart.
const cwd = () => storage.path().replace(/[^/]+$/g, '')
const setPath = (mode, path) => {
document.getElementById('path').textContent = path
// Replace the history when navigating, but push to it when opening a file.
if (mode === storage.mode()) window.history.replaceState("", "", `${mode}${encodeURI(path)}`)
else window.location.hash = `${mode}${encodeURI(path)}`
// Adjust the UI between the open file mode, and browsing.
document.body.classList.remove('open')
if (mode === '#open:') {
document.querySelector('#data>.maxer').children[0]?.removeAttribute('preview');
document.body.classList.add('open')
}
}
const cart = []
const cartMode = () => document.getElementById('cart').classList.contains("on")
const cartRemove = c => {c ? cart.splice(cart.indexOf(c), 1) : cart.length = 0; cartSel()}
/**
* Update the dynamic storage menu,
* hiding and showing each menu botton based on the current context.
*/
function menuMode() {
const mode = (storage.path().endsWith("/") ? (
cartMode() ? (cart.length ? "cart" : "cartEmpty") :
cart.length ? "dirWithCart" : "dirEmptyCart") : "file")
menuItems.forEach(id => document.getElementById(id).style.display =
menuModes[mode].includes(id) ? 'initial' : 'none')
}
const menuModes = {
dirEmptyCart: ["reload", "makedir", "newfile", "upload", "rename", "cart"],
dirWithCart: ["reload", "download", "move", "del", "cart"],
file: ["reload", "tabopen", "download", "rename", "close"],
cart: ["download", "del", "cart"],
cartEmpty: ["cart"],
}
const menuItems = new Set(Object.values(menuModes).flat())
// All the storage menu actions.
document.getElementById("reload").onclick = () => nav(storage.path())
document.getElementById("makedir").onclick = () => makedir()
document.getElementById("newfile").onclick = () => newfile()
document.getElementById("tabopen").onclick = () => setPath('#open:', storage.path())
document.getElementById("upload").onclick = () => document.getElementById('uploader').click()
document.getElementById("download").onclick = () => download()
document.getElementById("rename").onclick = () => rename()
document.getElementById("cart").onclick = () => {
document.getElementById('cart').classList.toggle('on')
cartSel()
if (!cartMode()) open(storage.path())
}
document.getElementById("move").onclick = () => move()
document.getElementById("del").onclick = () => del()
document.getElementById("close").onclick = () => {
setPath("#browse:", cwd())
open(storage.path())
}
document.getElementById("uploader").onchange = () => send()
// Setup keyboard navigation of folders.
const dir = document.getElementById('dir')
document.querySelector('body').onkeydown = ev => {
if (ev.key != "ArrowDown" && ev.key != "ArrowUp") return
// Abort if not a parent or child of the dir pane.
if (!document.activeElement.contains(dir) && !dir.contains(document.activeElement)) return
ev.preventDefault()
// Select the first child, or if one is already selected, the previous/next child.
if (document.activeElement.parentElement != dir) {
const sel = dir.querySelector(".on")
sel ? sel.parentElement.focus() : dir.firstChild.focus()
}
else if (ev.key != "ArrowDown") document.activeElement.previousSibling?.focus()
else document.activeElement.nextSibling?.focus()
}
/**
* Navigate to, and show, a file or directory.
* For folders, path should be terminated in a "/".
* Also sets the current files or directories for future actions.
* Updates the folder area with interactive tree navigation.
* Displays file contents as best it can.
*/
async function nav(path) {
// Update the folder contents.
if (storage.mode() === "#browse:") {
// Fill the folder contents
setPath('#browse:', path)
// Refresh the contents of the directory by querying the server
const curFile = storage.path().replace(/^.*[\\/]/, '')
storage.listDir(cwd()).then(r => {
let selected = null
dir.replaceChildren(...r.map(n => {
const nibIcon = document.createElement("h1")
const nib = document.createElement("p")
nib.textContent = n.replace(/\/$/, '')
nibIcon.textContent = n.endsWith('/') ? '📂' : '📄'
const btn = document.createElement('button')
const path = cwd() // resolve here to avoid double click stacking the path
const highlight = () => { // Highlights selected file / folder.
Array.from(dir.getElementsByClassName("highli")).forEach(ni => ni.classList.remove("highli"))
btn.classList.add("highli")
if (n.endsWith('/')) return
// Highlight the icon of the open file.
Array.from(dir.getElementsByClassName("on")).forEach(ni => ni.classList.remove("on"))
nibIcon.classList.add("on")
}
btn.onclick = () => {
highlight()
if (!cartMode() || n === "../") {
// Handle when cart mode not selected (or clicking ../ which side-steps cart mode).
if (n.endsWith('/')) { // Select a folder.
nibIcon.textContent = '⏳'
nav(n === "../" ? path.replace(/[^/]+\/[^/]*$/g, '') : path + n)
} else if (storage.path() != path + n) btn.focus() // iOS 16 doesn't trigger focus.
} else cartSel(path + n) // Add to the cart.
}
btn.tabIndex = -1 // Tab should not go through each file or folder, arrow keys do that.
btn.onfocus = () => {
highlight()
if (!cartMode() && !n.endsWith('/')) {
// Open the selected file.
open(path + n)
}
}
if (curFile === n) selected = btn
btn.replaceChildren(nibIcon, nib)
return btn
}))
if (selected) selected.focus()
else open(path)
})
} else open(path)
}
/**
* Display the contents of the file, or the folder actions.
*/
async function open(path) {
const reloading = path === storage.path()
// Upate the file / details pane.
if (!path.endsWith("/")) {
// Do a fast reload of just the content, the content was already loaded (if supported).
const reloadable = document.querySelector("#data>div>.reloadable")
if (path === storage.path() && reloadable) {
reloadable.setAttribute("reload", "")
reloadable.setAttribute("preview", storage.mode() === "#browse:" ? "" : null)
return
}
// Open any file contents in the data pane.
const div = document.createElement("div")
div.classList.add("maxer")
div.textContent = '⏳'
document.getElementById('data').replaceChildren(div)
setPath(storage.mode(), path)
// Dynamically load the appropriate file loader depending on file extension and mime type.
const reg = (n) => document.getElementById(`-${n}`)?.getAttribute("loader")
const nib = document.createElement(
reg(`ext-${/(?:\.([^.]+))?$/.exec(path)[1]}`) // try file extension loader
|| reg(`mime-${(await storage.mime(path)).replace("/", "-")}`) // try mime type loader
|| reg('misc-media')) // fallback loader
// Force full window file open if the URL hash indicates that viewing mode.
if (storage.mode() === "#open:") document.getElementById("tabopen").click()
else nib.setAttribute("preview", "") // otherwise, just display as a preview.
div.replaceChildren(nib)
} else if (!cartMode()) {
// Display all the folder actions relevant to this level (including logout and terminal).
document.getElementById('data').replaceChildren(document.createElement("folder-actions"))
}
menuMode()
}
/**
* Add the given path to the cart, if provided.
* Refresh the display of the cart and count.
* Cart enties remove themselves when clicked.
*/
function cartSel(path) {
if (path && !cart.includes(path)) cart.push(path)
document.getElementById('cartlen').textContent = cart.length.toString()
document.getElementById('data').replaceChildren(...cart.map(c => {
const nibIcon = document.createElement("h1")
const nib = document.createElement("p")
nib.textContent = c
nibIcon.textContent = c.endsWith('/') ? '📂' : '📄'
const div = document.createElement('button')
div.onclick = () => cartRemove(c)
div.replaceChildren(nibIcon, nib)
return div
}))
menuMode()
}
/**
* Make a directory on the server.
* The user is prompted for the name of the new directory and
* it is made inside the current directory.
*/
async function makedir() {
const newDir = await prompter("New Folder:", "")
if (!newDir) return
storage.newDir(cwd() + newDir).then(() => nav(cwd()))
}
/**
* Make a new file on the server.
* The user is prompted for the name of the new file and
* it is made inside the current directory.
*/
async function newfile() {
const newFile = await prompter("New File:", "")
if (!newFile) return
storage.newFile(cwd() + newFile).then(() => nav(cwd() + newFile))
}
/**
* Upload selected files to the server.
* Files are uploaded into the current directory.
* This is called after the file selection popup has been loaded
* and files have been selected.
*/
function send() {
const ico = document.createElement("p")
ico.classList.add("status")
ico.textContent = '📤'
document.getElementById("dataPane").appendChild(ico) // Show upload status icon
const existing = new Set(Array.from(
document.querySelectorAll("#dir>button>p")).map(p => p.textContent))
let queue = Promise.resolve()
Array.from(document.getElementById('uploader').files).forEach(f => {
// Ensure filename for upload is unique
let filename = f.name
let n = 2
while (existing.has(filename)) filename = f.name.replace(/((?:\.|$)[^\.]*)/, `(${n++})$1`)
// Queue the upload of the file
queue = queue.then(((filename, f) => () => storage.upload(cwd() + filename, f))(filename, f))
})
queue.then(() => {
nav(cwd());
document.getElementById("dataPane").removeChild(ico) // Clear upload status icon
})
}
/**
* Rename a file or directory on the server.
* The user is prompted for the new name.
*/
async function rename() {
const suffix = storage.path().endsWith('/') ? '/' : ''
const folder = storage.path().replace(/[^/]+\/?$/g, '')
const oldName = storage.path().replace(/\/?$/g, '').split('/').pop()
const newName = await prompter("Rename:", oldName)
if (!newName || newName === oldName) return
storage.rename(folder + oldName, folder + newName).then(
() => nav(folder + newName + suffix))
}
/**
* Download a file or a zip of multiple items.
* Supports downloading the selected file (if a file),
* a single file from the cart, or zipping multiple files
* and folders in the cart.
*/
async function download() {
var paths = cart
if (!paths.length && !storage.path().endsWith('/')) paths = [storage.path()]
await fetch("/preconnect")
const dwn = document.getElementById('dwnld')
dwn.download = 'download.zip'
await storage.authLinks()
dwn.href = storage.zipLink(paths)
if (paths.length === 1 && !paths[0].endsWith('/')) {
dwn.download = paths[0].split('/').pop()
dwn.href = storage.downloadLink(paths[0])
}
dwn.click()
if (cart.length) cartRemove()
}
/**
* Moves everything in the cart to the current folder,
* after confirmation.
*/
async function move() {
const checkMsg = `Move ${cart.length} item${cart.length > 1 ? 's' : ''} to ${cwd()} ?`
if (! await prompter(checkMsg, true)) return
/* Loop through the paths in the cart sorted backwards so sub-items
are moved before parent items */
cart.sort().reverse().forEach(item => {
const dest = cwd() + item.replace(/\/?$/g, '').split('/').pop()
storage.rename(item, dest).then(() => {cartRemove(item); nav(cwd())})