BlueGit

timfa filemanager

pip

timfa Tim Falken · pushed by timfa

Authored 2026-05-05 · 6 months ago

Hash
aefbcaaa040c0998695c80b6c470a9e294465b82
Parent
e725ff07
11 files changed +459 −90
.github/technical-reference.md +18 −1
@@ -49,6 +49,10 @@
49 49 - GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
50 50 - GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
51 51 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
52 - splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
53 - pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
54 - removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
55 - POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
52 56
53 57 ## public/app.js
54 58 - showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -62,6 +66,11 @@
62 66 - showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
63 67 - showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
64 68 - showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
69 - splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
70 - nextAvailableName(requestedName, existingNames) - Computes `name (n).ext` for upload/move rename options.
71 - listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
72 - cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
73 - showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
65 74 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
66 75 - loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
67 76 - observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
@@ -79,6 +88,7 @@
79 88 ## tests/thumbnail-cache.test.js
80 89 - thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
81 90 - thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
91 - afterEach() cleanup - Removes temp roots with `fs.rmSync(...maxRetries...)` to tolerate transient Windows file locks.
82 92 - detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
83 93 - prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
84 94 - highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
@@ -99,6 +109,7 @@
99 109 - closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
100 110 - closePreview() - Closes expanded-tile preview and revokes active preview object URL.
101 111 - openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
112 - moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
102 113 - rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
103 114 - ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
104 115 - createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
@@ -112,13 +123,15 @@
112 123 - openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
113 124 - openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
114 125 - openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
126 - uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
115 127 - openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked.
116 128
117 129 ## public/drag-move.js
118 130 - makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
131 - makeDraggable(el, item) - Touch drag now requires a short hold before movement, uses pointer capture, and keeps drag responsive on mobile.
119 132 - (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
120 133 - (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
121 - (internal) _endDrag() - On valid target: runs drop animation on real tile then calls POST /api/files/move, refreshes dir. Otherwise snap-back.
134 - (internal) _endDrag() - On valid target: runs drop animation, calls moveWithConflictResolution() for overwrite/rename/cancel conflicts, then refreshes dir. Otherwise snap-back.
122 135 - (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
123 136
124 137 ## public/drag-move.css
@@ -134,3 +147,7 @@
134 147 ## tests/auth.routes.test.js
135 148 - session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
136 149 - session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
150
151 ## tests/page.load.test.js
152 - bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
153 - waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
@@ -49,6 +49,10 @@
49- GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
49- GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
50- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
50- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
51- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
51- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
52- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
53- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
54- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
55- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
52
56
53## public/app.js
57## public/app.js
54- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
58- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -62,6 +66,11 @@
62- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
66- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
63- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
67- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
64- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
68- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
69- splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
70- nextAvailableName(requestedName, existingNames) - Computes `name (n).ext` for upload/move rename options.
71- listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
72- cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
73- showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
65- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
74- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
66- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
75- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
67- observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
76- observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
@@ -79,6 +88,7 @@
79## tests/thumbnail-cache.test.js
88## tests/thumbnail-cache.test.js
80- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
89- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
81- thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
90- thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
91- afterEach() cleanup - Removes temp roots with `fs.rmSync(...maxRetries...)` to tolerate transient Windows file locks.
82- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
92- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
83- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
93- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
84- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
94- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
@@ -99,6 +109,7 @@
99- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
109- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
100- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
110- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
101- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
111- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
112- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
102- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
113- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
103- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
114- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
104- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
115- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
@@ -112,13 +123,15 @@
112- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
123- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
113- openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
124- openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
114- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
125- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
126- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
115- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked.
127- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked.
116
128
117## public/drag-move.js
129## public/drag-move.js
118- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
130- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
131- makeDraggable(el, item) - Touch drag now requires a short hold before movement, uses pointer capture, and keeps drag responsive on mobile.
119- (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
132- (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
120- (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
133- (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
121- (internal) _endDrag() - On valid target: runs drop animation on real tile then calls POST /api/files/move, refreshes dir. Otherwise snap-back.
134- (internal) _endDrag() - On valid target: runs drop animation, calls moveWithConflictResolution() for overwrite/rename/cancel conflicts, then refreshes dir. Otherwise snap-back.
122- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
135- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
123
136
124## public/drag-move.css
137## public/drag-move.css
@@ -134,3 +147,7 @@
134## tests/auth.routes.test.js
147## tests/auth.routes.test.js
135- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
148- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
136- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
149- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
150
151## tests/page.load.test.js
152- bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
153- waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
.github/tests.md +2 −0
@@ -38,6 +38,8 @@
38 38
39 39 ## `test/files.routes.test.js`
40 40 - `POST /api/files/move`
41 - `POST /api/files/move / overwrites an existing destination when conflict strategy is overwrite`
42 - `POST /api/files/move / renames destination when conflict strategy is rename`
41 43 - `root alias endpoints`
42 44 - `GET /api/files/thumbnail`
43 45 - `GET /api/files/root-access`
@@ -38,6 +38,8 @@
38
38
39## `test/files.routes.test.js`
39## `test/files.routes.test.js`
40- `POST /api/files/move`
40- `POST /api/files/move`
41- `POST /api/files/move / overwrites an existing destination when conflict strategy is overwrite`
42- `POST /api/files/move / renames destination when conflict strategy is rename`
41- `root alias endpoints`
43- `root alias endpoints`
42- `GET /api/files/thumbnail`
44- `GET /api/files/thumbnail`
43- `GET /api/files/root-access`
45- `GET /api/files/root-access`
package-lock.json +0 −48
@@ -786,9 +786,6 @@
786 786 "cpu": [
787 787 "arm"
788 788 ],
789 "libc": [
790 "glibc"
791 ],
792 789 "license": "LGPL-3.0-or-later",
793 790 "optional": true,
794 791 "os": [
@@ -805,9 +802,6 @@
805 802 "cpu": [
806 803 "arm64"
807 804 ],
808 "libc": [
809 "glibc"
810 ],
811 805 "license": "LGPL-3.0-or-later",
812 806 "optional": true,
813 807 "os": [
@@ -824,9 +818,6 @@
824 818 "cpu": [
825 819 "ppc64"
826 820 ],
827 "libc": [
828 "glibc"
829 ],
830 821 "license": "LGPL-3.0-or-later",
831 822 "optional": true,
832 823 "os": [
@@ -843,9 +834,6 @@
843 834 "cpu": [
844 835 "riscv64"
845 836 ],
846 "libc": [
847 "glibc"
848 ],
849 837 "license": "LGPL-3.0-or-later",
850 838 "optional": true,
851 839 "os": [
@@ -862,9 +850,6 @@
862 850 "cpu": [
863 851 "s390x"
864 852 ],
865 "libc": [
866 "glibc"
867 ],
868 853 "license": "LGPL-3.0-or-later",
869 854 "optional": true,
870 855 "os": [
@@ -881,9 +866,6 @@
881 866 "cpu": [
882 867 "x64"
883 868 ],
884 "libc": [
885 "glibc"
886 ],
887 869 "license": "LGPL-3.0-or-later",
888 870 "optional": true,
889 871 "os": [
@@ -900,9 +882,6 @@
900 882 "cpu": [
901 883 "arm64"
902 884 ],
903 "libc": [
904 "musl"
905 ],
906 885 "license": "LGPL-3.0-or-later",
907 886 "optional": true,
908 887 "os": [
@@ -919,9 +898,6 @@
919 898 "cpu": [
920 899 "x64"
921 900 ],
922 "libc": [
923 "musl"
924 ],
925 901 "license": "LGPL-3.0-or-later",
926 902 "optional": true,
927 903 "os": [
@@ -938,9 +914,6 @@
938 914 "cpu": [
939 915 "arm"
940 916 ],
941 "libc": [
942 "glibc"
943 ],
944 917 "license": "Apache-2.0",
945 918 "optional": true,
946 919 "os": [
@@ -963,9 +936,6 @@
963 936 "cpu": [
964 937 "arm64"
965 938 ],
966 "libc": [
967 "glibc"
968 ],
969 939 "license": "Apache-2.0",
970 940 "optional": true,
971 941 "os": [
@@ -988,9 +958,6 @@
988 958 "cpu": [
989 959 "ppc64"
990 960 ],
991 "libc": [
992 "glibc"
993 ],
994 961 "license": "Apache-2.0",
995 962 "optional": true,
996 963 "os": [
@@ -1013,9 +980,6 @@
1013 980 "cpu": [
1014 981 "riscv64"
1015 982 ],
1016 "libc": [
1017 "glibc"
1018 ],
1019 983 "license": "Apache-2.0",
1020 984 "optional": true,
1021 985 "os": [
@@ -1038,9 +1002,6 @@
1038 1002 "cpu": [
1039 1003 "s390x"
1040 1004 ],
1041 "libc": [
1042 "glibc"
1043 ],
1044 1005 "license": "Apache-2.0",
1045 1006 "optional": true,
1046 1007 "os": [
@@ -1063,9 +1024,6 @@
1063 1024 "cpu": [
1064 1025 "x64"
1065 1026 ],
1066 "libc": [
1067 "glibc"
1068 ],
1069 1027 "license": "Apache-2.0",
1070 1028 "optional": true,
1071 1029 "os": [
@@ -1088,9 +1046,6 @@
1088 1046 "cpu": [
1089 1047 "arm64"
1090 1048 ],
1091 "libc": [
1092 "musl"
1093 ],
1094 1049 "license": "Apache-2.0",
1095 1050 "optional": true,
1096 1051 "os": [
@@ -1113,9 +1068,6 @@
1113 1068 "cpu": [
1114 1069 "x64"
1115 1070 ],
1116 "libc": [
1117 "musl"
1118 ],
1119 1071 "license": "Apache-2.0",
1120 1072 "optional": true,
1121 1073 "os": [
@@ -786,9 +786,6 @@
786 "cpu": [
786 "cpu": [
787 "arm"
787 "arm"
788 ],
788 ],
789 "libc": [
790 "glibc"
791 ],
792 "license": "LGPL-3.0-or-later",
789 "license": "LGPL-3.0-or-later",
793 "optional": true,
790 "optional": true,
794 "os": [
791 "os": [
@@ -805,9 +802,6 @@
805 "cpu": [
802 "cpu": [
806 "arm64"
803 "arm64"
807 ],
804 ],
808 "libc": [
809 "glibc"
810 ],
811 "license": "LGPL-3.0-or-later",
805 "license": "LGPL-3.0-or-later",
812 "optional": true,
806 "optional": true,
813 "os": [
807 "os": [
@@ -824,9 +818,6 @@
824 "cpu": [
818 "cpu": [
825 "ppc64"
819 "ppc64"
826 ],
820 ],
827 "libc": [
828 "glibc"
829 ],
830 "license": "LGPL-3.0-or-later",
821 "license": "LGPL-3.0-or-later",
831 "optional": true,
822 "optional": true,
832 "os": [
823 "os": [
@@ -843,9 +834,6 @@
843 "cpu": [
834 "cpu": [
844 "riscv64"
835 "riscv64"
845 ],
836 ],
846 "libc": [
847 "glibc"
848 ],
849 "license": "LGPL-3.0-or-later",
837 "license": "LGPL-3.0-or-later",
850 "optional": true,
838 "optional": true,
851 "os": [
839 "os": [
@@ -862,9 +850,6 @@
862 "cpu": [
850 "cpu": [
863 "s390x"
851 "s390x"
864 ],
852 ],
865 "libc": [
866 "glibc"
867 ],
868 "license": "LGPL-3.0-or-later",
853 "license": "LGPL-3.0-or-later",
869 "optional": true,
854 "optional": true,
870 "os": [
855 "os": [
@@ -881,9 +866,6 @@
881 "cpu": [
866 "cpu": [
882 "x64"
867 "x64"
883 ],
868 ],
884 "libc": [
885 "glibc"
886 ],
887 "license": "LGPL-3.0-or-later",
869 "license": "LGPL-3.0-or-later",
888 "optional": true,
870 "optional": true,
889 "os": [
871 "os": [
@@ -900,9 +882,6 @@
900 "cpu": [
882 "cpu": [
901 "arm64"
883 "arm64"
902 ],
884 ],
903 "libc": [
904 "musl"
905 ],
906 "license": "LGPL-3.0-or-later",
885 "license": "LGPL-3.0-or-later",
907 "optional": true,
886 "optional": true,
908 "os": [
887 "os": [
@@ -919,9 +898,6 @@
919 "cpu": [
898 "cpu": [
920 "x64"
899 "x64"
921 ],
900 ],
922 "libc": [
923 "musl"
924 ],
925 "license": "LGPL-3.0-or-later",
901 "license": "LGPL-3.0-or-later",
926 "optional": true,
902 "optional": true,
927 "os": [
903 "os": [
@@ -938,9 +914,6 @@
938 "cpu": [
914 "cpu": [
939 "arm"
915 "arm"
940 ],
916 ],
941 "libc": [
942 "glibc"
943 ],
944 "license": "Apache-2.0",
917 "license": "Apache-2.0",
945 "optional": true,
918 "optional": true,
946 "os": [
919 "os": [
@@ -963,9 +936,6 @@
963 "cpu": [
936 "cpu": [
964 "arm64"
937 "arm64"
965 ],
938 ],
966 "libc": [
967 "glibc"
968 ],
969 "license": "Apache-2.0",
939 "license": "Apache-2.0",
970 "optional": true,
940 "optional": true,
971 "os": [
941 "os": [
@@ -988,9 +958,6 @@
988 "cpu": [
958 "cpu": [
989 "ppc64"
959 "ppc64"
990 ],
960 ],
991 "libc": [
992 "glibc"
993 ],
994 "license": "Apache-2.0",
961 "license": "Apache-2.0",
995 "optional": true,
962 "optional": true,
996 "os": [
963 "os": [
@@ -1013,9 +980,6 @@
1013 "cpu": [
980 "cpu": [
1014 "riscv64"
981 "riscv64"
1015 ],
982 ],
1016 "libc": [
1017 "glibc"
1018 ],
1019 "license": "Apache-2.0",
983 "license": "Apache-2.0",
1020 "optional": true,
984 "optional": true,
1021 "os": [
985 "os": [
@@ -1038,9 +1002,6 @@
1038 "cpu": [
1002 "cpu": [
1039 "s390x"
1003 "s390x"
1040 ],
1004 ],
1041 "libc": [
1042 "glibc"
1043 ],
1044 "license": "Apache-2.0",
1005 "license": "Apache-2.0",
1045 "optional": true,
1006 "optional": true,
1046 "os": [
1007 "os": [
@@ -1063,9 +1024,6 @@
1063 "cpu": [
1024 "cpu": [
1064 "x64"
1025 "x64"
1065 ],
1026 ],
1066 "libc": [
1067 "glibc"
1068 ],
1069 "license": "Apache-2.0",
1027 "license": "Apache-2.0",
1070 "optional": true,
1028 "optional": true,
1071 "os": [
1029 "os": [
@@ -1088,9 +1046,6 @@
1088 "cpu": [
1046 "cpu": [
1089 "arm64"
1047 "arm64"
1090 ],
1048 ],
1091 "libc": [
1092 "musl"
1093 ],
1094 "license": "Apache-2.0",
1049 "license": "Apache-2.0",
1095 "optional": true,
1050 "optional": true,
1096 "os": [
1051 "os": [
@@ -1113,9 +1068,6 @@
1113 "cpu": [
1068 "cpu": [
1114 "x64"
1069 "x64"
1115 ],
1070 ],
1116 "libc": [
1117 "musl"
1118 ],
1119 "license": "Apache-2.0",
1071 "license": "Apache-2.0",
1120 "optional": true,
1072 "optional": true,
1121 "os": [
1073 "os": [
public/app.js +175 −28
@@ -270,6 +270,49 @@ function pathInside (child, root)
270 270 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
271 271 }
272 272
273 function splitNameExt (name)
274 {
275 const dot = String(name || '').lastIndexOf('.');
276 if (dot <= 0) return { stem: String(name || ''), ext: '' };
277 return {
278 stem: String(name).slice(0, dot),
279 ext: String(name).slice(dot),
280 };
281 }
282
283 function nextAvailableName (requestedName, existingNames)
284 {
285 const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []);
286 if (!set.has(requestedName)) return requestedName;
287
288 const { stem, ext } = splitNameExt(requestedName);
289 let n = 1;
290 while (n <= 10000)
291 {
292 const candidate = `${stem || 'file'} (${n})${ext}`;
293 if (!set.has(candidate)) return candidate;
294 n++;
295 }
296
297 return requestedName;
298 }
299
300 async function listDirNameSet (dir)
301 {
302 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`);
303 const names = new Set();
304 for (const it of ((data && data.items) || [])) names.add(it.name);
305 return names;
306 }
307
308 function cloneFileWithName (file, newName)
309 {
310 return new File([file], newName, {
311 type: file.type,
312 lastModified: file.lastModified,
313 });
314 }
315
273 316 function saveSessionState ()
274 317 {
275 318 if (!STATE.token) return;
@@ -329,7 +372,14 @@ async function api (method, path, body, opts = {})
329 372 if (STATE.token)
330 373 {
331 374 headers['Authorization'] = 'Bearer ' + STATE.token;
332 headers['X-Fp'] = getFingerprint();
375 try
376 {
377 const fp = getFingerprint();
378 if (fp) headers['X-Fp'] = fp;
379 } catch
380 {
381 // Continue without a fingerprint header in constrained test/runtime contexts.
382 }
333 383 }
334 384 const fetchOpts = { ...opts };
335 385 delete fetchOpts.noAutoLogout;
@@ -494,12 +544,59 @@ function showOverwrite (filename)
494 544 });
495 545 }
496 546
547 /**
548 * Show single-file conflict options.
549 * @param {string} filename
550 * @param {string} renameTo
551 * @param {string} mode - upload|move
552 * @returns {Promise<'overwrite'|'rename'|'cancel'>}
553 */
554 function showFileConflictChoice (filename, renameTo, mode = 'upload')
555 {
556 return new Promise((resolve) =>
557 {
558 const overlay = document.getElementById('file-conflict-modal');
559 const title = document.getElementById('file-conflict-title');
560 const fileEl = document.getElementById('file-conflict-filename');
561 const renameEl = document.getElementById('file-conflict-rename');
562 const btnOverwrite = document.getElementById('file-conflict-overwrite');
563 const btnRename = document.getElementById('file-conflict-rename-btn');
564 const btnCancel = document.getElementById('file-conflict-cancel');
565
566 title.textContent = mode === 'move' ? 'Bestand verplaatsen' : 'Bestand uploaden';
567 fileEl.textContent = filename;
568 renameEl.textContent = renameTo;
569 btnRename.textContent = `Hernoemen (${renameTo})`;
570
571 overlay.classList.remove('hidden');
572
573 function finish (result)
574 {
575 overlay.classList.add('hidden');
576 btnOverwrite.removeEventListener('click', onOverwrite);
577 btnRename.removeEventListener('click', onRename);
578 btnCancel.removeEventListener('click', onCancel);
579 resolve(result);
580 }
581
582 function onOverwrite () { finish('overwrite'); }
583 function onRename () { finish('rename'); }
584 function onCancel () { finish('cancel'); }
585
586 btnOverwrite.addEventListener('click', onOverwrite);
587 btnRename.addEventListener('click', onRename);
588 btnCancel.addEventListener('click', onCancel);
589 btnCancel.focus();
590 });
591 }
592
497 593 // ───────────────────────────────────────────────────────────────────────────
498 594 // AUTH FLOW
499 595 // ───────────────────────────────────────────────────────────────────────────
500 596
501 597 function showAuthOverlay (setupMode = false)
502 598 {
599 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
503 600 document.getElementById('app').classList.add('hidden');
504 601 const overlay = document.getElementById('auth-overlay');
505 602 overlay.classList.remove('hidden');
@@ -517,6 +614,7 @@ function showAuthOverlay (setupMode = false)
517 614
518 615 function showApp ()
519 616 {
617 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
520 618 document.getElementById('auth-overlay').classList.add('hidden');
521 619 document.getElementById('app').classList.remove('hidden');
522 620 if (isMobileViewport())
@@ -532,8 +630,9 @@ function showApp ()
532 630
533 631 async function initAuth ()
534 632 {
535 // Always generate a fresh key pair so each page-load session is independent
536 await generateClientKeyPair().catch(() =>
633 // Generate a fresh key pair in the background; login falls back gracefully
634 // while this is still in progress.
635 generateClientKeyPair().catch(() =>
537 636 {
538 637 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
539 638 });
@@ -696,6 +795,7 @@ async function loadRoots (opts = {})
696 795
697 796 function renderRootsView ()
698 797 {
798 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
699 799 disconnectThumbnailObserver();
700 800 disconnectFolderIconObserver();
701 801 revokeThumbnails();
@@ -803,6 +903,7 @@ function renderBreadcrumb ()
803 903
804 904 async function refreshFolderStats ()
805 905 {
906 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
806 907 const el = document.getElementById('folder-stats');
807 908 if (!STATE.currentDir)
808 909 {
@@ -894,6 +995,7 @@ function stopAutoRefresh ()
894 995
895 996 function renderFileGrid ()
896 997 {
998 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
897 999 disconnectThumbnailObserver();
898 1000 disconnectFolderIconObserver();
899 1001 revokeThumbnails();
@@ -1231,6 +1333,7 @@ function openFolderSidebar ()
1231 1333
1232 1334 function closeSidebar ()
1233 1335 {
1336 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
1234 1337 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1235 1338 STATE.selectedItem = null;
1236 1339
@@ -1309,6 +1412,40 @@ function writableRoots ()
1309 1412 });
1310 1413 }
1311 1414
1415 async function moveWithConflictResolution (item, targetDir)
1416 {
1417 try
1418 {
1419 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
1420 }
1421 catch (err)
1422 {
1423 if (!/already exists/i.test(err.message || '')) throw err;
1424
1425 const existingNames = await listDirNameSet(targetDir);
1426 const desiredName = item.name || basenameOfPath(item.path) || 'file';
1427 const suggestedName = nextAvailableName(desiredName, existingNames);
1428 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
1429 if (decision === 'cancel') return null;
1430
1431 if (decision === 'overwrite')
1432 {
1433 return api('POST', '/files/move', {
1434 from: item.path,
1435 toDir: targetDir,
1436 conflict: 'overwrite',
1437 });
1438 }
1439
1440 return api('POST', '/files/move', {
1441 from: item.path,
1442 toDir: targetDir,
1443 conflict: 'rename',
1444 targetName: suggestedName,
1445 });
1446 }
1447 }
1448
1312 1449 function ensureMoveModal ()
1313 1450 {
1314 1451 let overlay = document.getElementById('move-modal');
@@ -1360,7 +1497,8 @@ function ensureMoveModal ()
1360 1497
1361 1498 try
1362 1499 {
1363 await api('POST', '/files/move', { from: st.item.path, toDir: st.selectedPath });
1500 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
1501 if (!moved) return;
1364 1502 }
1365 1503 catch (err)
1366 1504 {
@@ -2249,44 +2387,53 @@ async function uploadFiles (fileList)
2249 2387 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2250 2388 if (!canWrite()) { toast('No write access.', 'err'); return; }
2251 2389
2252 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
2253 const formData = new FormData();
2254 for (const f of fileList) formData.append('files', f);
2390 const files = Array.from(fileList || []);
2391 if (!files.length) return;
2255 2392
2256 2393 // Show upload bar
2257 2394 const wrap = document.createElement('div');
2258 2395 wrap.className = 'upload-bar-wrap';
2259 wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2396 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2260 2397 document.body.appendChild(wrap);
2261 2398 STATE.uploadInProgress = true;
2262 2399
2263 2400 try
2264 2401 {
2265 const xhr = new XMLHttpRequest();
2266 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
2267 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2268 xhr.setRequestHeader('X-Fp', getFingerprint());
2269 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
2270 xhr.upload.addEventListener('progress', e =>
2402 const existingNames = await listDirNameSet(STATE.currentDir);
2403 let done = 0;
2404 let uploaded = 0;
2405
2406 for (const original of files)
2271 2407 {
2272 if (e.lengthComputable)
2408 let fileToUpload = original;
2409
2410 if (existingNames.has(original.name))
2273 2411 {
2274 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
2412 const suggested = nextAvailableName(original.name, existingNames);
2413 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
2414 if (decision === 'cancel')
2415 {
2416 done++;
2417 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2418 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2419 continue;
2420 }
2421
2422 if (decision === 'rename')
2423 {
2424 fileToUpload = cloneFileWithName(original, suggested);
2425 }
2275 2426 }
2276 });
2277 2427
2278 await new Promise((resolve, reject) =>
2279 {
2280 xhr.onload = () =>
2281 {
2282 if (xhr.status === 200) resolve();
2283 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
2284 };
2285 xhr.onerror = () => reject(new Error('Network error'));
2286 xhr.send(formData);
2287 });
2428 await uploadSingleFile(fileToUpload, STATE.currentDir);
2429 existingNames.add(fileToUpload.name);
2430 done++;
2431 uploaded++;
2432 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2433 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2434 }
2288 2435
2289 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
2436 toast(`Uploaded ${uploaded} file(s).`, 'ok');
2290 2437 await navigateTo(STATE.currentDir, STATE.currentRoot);
2291 2438 } catch (err)
2292 2439 {
@@ -270,6 +270,49 @@ function pathInside (child, root)
270 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
270 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
271}
271}
272
272
273function splitNameExt (name)
274{
275 const dot = String(name || '').lastIndexOf('.');
276 if (dot <= 0) return { stem: String(name || ''), ext: '' };
277 return {
278 stem: String(name).slice(0, dot),
279 ext: String(name).slice(dot),
280 };
281}
282
283function nextAvailableName (requestedName, existingNames)
284{
285 const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []);
286 if (!set.has(requestedName)) return requestedName;
287
288 const { stem, ext } = splitNameExt(requestedName);
289 let n = 1;
290 while (n <= 10000)
291 {
292 const candidate = `${stem || 'file'} (${n})${ext}`;
293 if (!set.has(candidate)) return candidate;
294 n++;
295 }
296
297 return requestedName;
298}
299
300async function listDirNameSet (dir)
301{
302 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`);
303 const names = new Set();
304 for (const it of ((data && data.items) || [])) names.add(it.name);
305 return names;
306}
307
308function cloneFileWithName (file, newName)
309{
310 return new File([file], newName, {
311 type: file.type,
312 lastModified: file.lastModified,
313 });
314}
315
273function saveSessionState ()
316function saveSessionState ()
274{
317{
275 if (!STATE.token) return;
318 if (!STATE.token) return;
@@ -329,7 +372,14 @@ async function api (method, path, body, opts = {})
329 if (STATE.token)
372 if (STATE.token)
330 {
373 {
331 headers['Authorization'] = 'Bearer ' + STATE.token;
374 headers['Authorization'] = 'Bearer ' + STATE.token;
332 headers['X-Fp'] = getFingerprint();
375 try
376 {
377 const fp = getFingerprint();
378 if (fp) headers['X-Fp'] = fp;
379 } catch
380 {
381 // Continue without a fingerprint header in constrained test/runtime contexts.
382 }
333 }
383 }
334 const fetchOpts = { ...opts };
384 const fetchOpts = { ...opts };
335 delete fetchOpts.noAutoLogout;
385 delete fetchOpts.noAutoLogout;
@@ -494,12 +544,59 @@ function showOverwrite (filename)
494 });
544 });
495}
545}
496
546
547/**
548 * Show single-file conflict options.
549 * @param {string} filename
550 * @param {string} renameTo
551 * @param {string} mode - upload|move
552 * @returns {Promise<'overwrite'|'rename'|'cancel'>}
553 */
554function showFileConflictChoice (filename, renameTo, mode = 'upload')
555{
556 return new Promise((resolve) =>
557 {
558 const overlay = document.getElementById('file-conflict-modal');
559 const title = document.getElementById('file-conflict-title');
560 const fileEl = document.getElementById('file-conflict-filename');
561 const renameEl = document.getElementById('file-conflict-rename');
562 const btnOverwrite = document.getElementById('file-conflict-overwrite');
563 const btnRename = document.getElementById('file-conflict-rename-btn');
564 const btnCancel = document.getElementById('file-conflict-cancel');
565
566 title.textContent = mode === 'move' ? 'Bestand verplaatsen' : 'Bestand uploaden';
567 fileEl.textContent = filename;
568 renameEl.textContent = renameTo;
569 btnRename.textContent = `Hernoemen (${renameTo})`;
570
571 overlay.classList.remove('hidden');
572
573 function finish (result)
574 {
575 overlay.classList.add('hidden');
576 btnOverwrite.removeEventListener('click', onOverwrite);
577 btnRename.removeEventListener('click', onRename);
578 btnCancel.removeEventListener('click', onCancel);
579 resolve(result);
580 }
581
582 function onOverwrite () { finish('overwrite'); }
583 function onRename () { finish('rename'); }
584 function onCancel () { finish('cancel'); }
585
586 btnOverwrite.addEventListener('click', onOverwrite);
587 btnRename.addEventListener('click', onRename);
588 btnCancel.addEventListener('click', onCancel);
589 btnCancel.focus();
590 });
591}
592
497// ───────────────────────────────────────────────────────────────────────────
593// ───────────────────────────────────────────────────────────────────────────
498// AUTH FLOW
594// AUTH FLOW
499// ───────────────────────────────────────────────────────────────────────────
595// ───────────────────────────────────────────────────────────────────────────
500
596
501function showAuthOverlay (setupMode = false)
597function showAuthOverlay (setupMode = false)
502{
598{
599 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
503 document.getElementById('app').classList.add('hidden');
600 document.getElementById('app').classList.add('hidden');
504 const overlay = document.getElementById('auth-overlay');
601 const overlay = document.getElementById('auth-overlay');
505 overlay.classList.remove('hidden');
602 overlay.classList.remove('hidden');
@@ -517,6 +614,7 @@ function showAuthOverlay (setupMode = false)
517
614
518function showApp ()
615function showApp ()
519{
616{
617 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
520 document.getElementById('auth-overlay').classList.add('hidden');
618 document.getElementById('auth-overlay').classList.add('hidden');
521 document.getElementById('app').classList.remove('hidden');
619 document.getElementById('app').classList.remove('hidden');
522 if (isMobileViewport())
620 if (isMobileViewport())
@@ -532,8 +630,9 @@ function showApp ()
532
630
533async function initAuth ()
631async function initAuth ()
534{
632{
535 // Always generate a fresh key pair so each page-load session is independent
633 // Generate a fresh key pair in the background; login falls back gracefully
536 await generateClientKeyPair().catch(() =>
634 // while this is still in progress.
635 generateClientKeyPair().catch(() =>
537 {
636 {
538 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
637 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
539 });
638 });
@@ -696,6 +795,7 @@ async function loadRoots (opts = {})
696
795
697function renderRootsView ()
796function renderRootsView ()
698{
797{
798 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
699 disconnectThumbnailObserver();
799 disconnectThumbnailObserver();
700 disconnectFolderIconObserver();
800 disconnectFolderIconObserver();
701 revokeThumbnails();
801 revokeThumbnails();
@@ -803,6 +903,7 @@ function renderBreadcrumb ()
803
903
804async function refreshFolderStats ()
904async function refreshFolderStats ()
805{
905{
906 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
806 const el = document.getElementById('folder-stats');
907 const el = document.getElementById('folder-stats');
807 if (!STATE.currentDir)
908 if (!STATE.currentDir)
808 {
909 {
@@ -894,6 +995,7 @@ function stopAutoRefresh ()
894
995
895function renderFileGrid ()
996function renderFileGrid ()
896{
997{
998 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
897 disconnectThumbnailObserver();
999 disconnectThumbnailObserver();
898 disconnectFolderIconObserver();
1000 disconnectFolderIconObserver();
899 revokeThumbnails();
1001 revokeThumbnails();
@@ -1231,6 +1333,7 @@ function openFolderSidebar ()
1231
1333
1232function closeSidebar ()
1334function closeSidebar ()
1233{
1335{
1336 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
1234 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1337 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1235 STATE.selectedItem = null;
1338 STATE.selectedItem = null;
1236
1339
@@ -1309,6 +1412,40 @@ function writableRoots ()
1309 });
1412 });
1310}
1413}
1311
1414
1415async function moveWithConflictResolution (item, targetDir)
1416{
1417 try
1418 {
1419 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
1420 }
1421 catch (err)
1422 {
1423 if (!/already exists/i.test(err.message || '')) throw err;
1424
1425 const existingNames = await listDirNameSet(targetDir);
1426 const desiredName = item.name || basenameOfPath(item.path) || 'file';
1427 const suggestedName = nextAvailableName(desiredName, existingNames);
1428 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
1429 if (decision === 'cancel') return null;
1430
1431 if (decision === 'overwrite')
1432 {
1433 return api('POST', '/files/move', {
1434 from: item.path,
1435 toDir: targetDir,
1436 conflict: 'overwrite',
1437 });
1438 }
1439
1440 return api('POST', '/files/move', {
1441 from: item.path,
1442 toDir: targetDir,
1443 conflict: 'rename',
1444 targetName: suggestedName,
1445 });
1446 }
1447}
1448
1312function ensureMoveModal ()
1449function ensureMoveModal ()
1313{
1450{
1314 let overlay = document.getElementById('move-modal');
1451 let overlay = document.getElementById('move-modal');
@@ -1360,7 +1497,8 @@ function ensureMoveModal ()
1360
1497
1361 try
1498 try
1362 {
1499 {
1363 await api('POST', '/files/move', { from: st.item.path, toDir: st.selectedPath });
1500 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
1501 if (!moved) return;
1364 }
1502 }
1365 catch (err)
1503 catch (err)
1366 {
1504 {
@@ -2249,44 +2387,53 @@ async function uploadFiles (fileList)
2249 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2387 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2250 if (!canWrite()) { toast('No write access.', 'err'); return; }
2388 if (!canWrite()) { toast('No write access.', 'err'); return; }
2251
2389
2252 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
2390 const files = Array.from(fileList || []);
2253 const formData = new FormData();
2391 if (!files.length) return;
2254 for (const f of fileList) formData.append('files', f);
2255
2392
2256 // Show upload bar
2393 // Show upload bar
2257 const wrap = document.createElement('div');
2394 const wrap = document.createElement('div');
2258 wrap.className = 'upload-bar-wrap';
2395 wrap.className = 'upload-bar-wrap';
2259 wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2396 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2260 document.body.appendChild(wrap);
2397 document.body.appendChild(wrap);
2261 STATE.uploadInProgress = true;
2398 STATE.uploadInProgress = true;
2262
2399
2263 try
2400 try
2264 {
2401 {
2265 const xhr = new XMLHttpRequest();
2402 const existingNames = await listDirNameSet(STATE.currentDir);
2266 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
2403 let done = 0;
2267 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2404 let uploaded = 0;
2268 xhr.setRequestHeader('X-Fp', getFingerprint());
2405
2269 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
2406 for (const original of files)
2270 xhr.upload.addEventListener('progress', e =>
2271 {
2407 {
2272 if (e.lengthComputable)
2408 let fileToUpload = original;
2409
2410 if (existingNames.has(original.name))
2273 {
2411 {
2274 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
2412 const suggested = nextAvailableName(original.name, existingNames);
2413 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
2414 if (decision === 'cancel')
2415 {
2416 done++;
2417 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2418 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2419 continue;
2420 }
2421
2422 if (decision === 'rename')
2423 {
2424 fileToUpload = cloneFileWithName(original, suggested);
2425 }
2275 }
2426 }
2276 });
2277
2427
2278 await new Promise((resolve, reject) =>
2428 await uploadSingleFile(fileToUpload, STATE.currentDir);
2279 {
2429 existingNames.add(fileToUpload.name);
2280 xhr.onload = () =>
2430 done++;
2281 {
2431 uploaded++;
2282 if (xhr.status === 200) resolve();
2432 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2283 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
2433 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2284 };
2434 }
2285 xhr.onerror = () => reject(new Error('Network error'));
2286 xhr.send(formData);
2287 });
2288
2435
2289 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
2436 toast(`Uploaded ${uploaded} file(s).`, 'ok');
2290 await navigateTo(STATE.currentDir, STATE.currentRoot);
2437 await navigateTo(STATE.currentDir, STATE.currentRoot);
2291 } catch (err)
2438 } catch (err)
2292 {
2439 {
public/drag-move.js +60 −6
@@ -1,7 +1,7 @@
1 1 /* =========================================================
2 2 DRAG-MOVE — icon drag-into-folder behaviour
3 3 Uses the REAL .file-item element (no ghost clone).
4 Depends on: api(), canWrite(), navigateTo(), STATE,
4 Depends on: moveWithConflictResolution(), canWrite(), navigateTo(), STATE,
5 5 closeSidebar(), toast() — all defined in app.js
6 6 ========================================================= */
7 7 'use strict';
@@ -33,33 +33,82 @@ const _drag = {
33 33 };
34 34
35 35 const DRAG_THRESHOLD = 6;
36 const TOUCH_DRAG_HOLD_MS = 140;
36 37
37 38 function _dragStart (downEvent, el, item)
38 39 {
39 40 let started = false;
41 let canStart = downEvent.pointerType !== 'touch';
42 let holdTimer = null;
40 43 const startX = downEvent.clientX;
41 44 const startY = downEvent.clientY;
42 45
46 if (!canStart)
47 {
48 holdTimer = setTimeout(() =>
49 {
50 canStart = true;
51 holdTimer = null;
52 }, TOUCH_DRAG_HOLD_MS);
53 }
54
55 function cleanupListeners ()
56 {
57 if (holdTimer)
58 {
59 clearTimeout(holdTimer);
60 holdTimer = null;
61 }
62 document.removeEventListener('pointermove', onMove);
63 document.removeEventListener('pointerup', onUp);
64 document.removeEventListener('pointercancel', onCancel);
65 }
66
43 67 function onMove (e)
44 68 {
69 const moved = Math.hypot(e.clientX - startX, e.clientY - startY);
70
45 71 if (!started)
46 72 {
47 if (Math.hypot(e.clientX - startX, e.clientY - startY) < DRAG_THRESHOLD) return;
73 if (!canStart)
74 {
75 if (moved > DRAG_THRESHOLD)
76 {
77 cleanupListeners();
78 }
79 return;
80 }
81
82 if (moved < DRAG_THRESHOLD) return;
48 83 started = true;
49 84 _beginDrag(downEvent, el, item);
85 if (downEvent.pointerId != null && typeof el.setPointerCapture === 'function')
86 {
87 try { el.setPointerCapture(downEvent.pointerId); } catch { /* ignore */ }
88 }
89 }
90 if (_drag.active)
91 {
92 e.preventDefault();
93 _moveDrag(e);
50 94 }
51 if (_drag.active) _moveDrag(e);
52 95 }
53 96
54 97 function onUp ()
55 98 {
56 document.removeEventListener('pointermove', onMove);
57 document.removeEventListener('pointerup', onUp);
99 cleanupListeners();
58 100 if (started && _drag.active) _endDrag();
59 101 }
60 102
103 function onCancel ()
104 {
105 cleanupListeners();
106 if (started && _drag.active) _cleanupDrag(true);
107 }
108
61 109 document.addEventListener('pointermove', onMove);
62 110 document.addEventListener('pointerup', onUp);
111 document.addEventListener('pointercancel', onCancel);
63 112 }
64 113
65 114 function _beginDrag (e, el, item)
@@ -217,7 +266,12 @@ function _endDrag ()
217 266
218 267 try
219 268 {
220 await api('POST', '/files/move', { from: sourceItem.path, toDir: targetPath });
269 const moved = await moveWithConflictResolution(sourceItem, targetPath);
270 if (!moved)
271 {
272 _cleanupDrag(true);
273 return;
274 }
221 275 }
222 276 catch (err)
223 277 {
@@ -1,7 +1,7 @@
1/* =========================================================
1/* =========================================================
2 DRAG-MOVE — icon drag-into-folder behaviour
2 DRAG-MOVE — icon drag-into-folder behaviour
3 Uses the REAL .file-item element (no ghost clone).
3 Uses the REAL .file-item element (no ghost clone).
4 Depends on: api(), canWrite(), navigateTo(), STATE,
4 Depends on: moveWithConflictResolution(), canWrite(), navigateTo(), STATE,
5 closeSidebar(), toast() — all defined in app.js
5 closeSidebar(), toast() — all defined in app.js
6 ========================================================= */
6 ========================================================= */
7'use strict';
7'use strict';
@@ -33,33 +33,82 @@ const _drag = {
33};
33};
34
34
35const DRAG_THRESHOLD = 6;
35const DRAG_THRESHOLD = 6;
36const TOUCH_DRAG_HOLD_MS = 140;
36
37
37function _dragStart (downEvent, el, item)
38function _dragStart (downEvent, el, item)
38{
39{
39 let started = false;
40 let started = false;
41 let canStart = downEvent.pointerType !== 'touch';
42 let holdTimer = null;
40 const startX = downEvent.clientX;
43 const startX = downEvent.clientX;
41 const startY = downEvent.clientY;
44 const startY = downEvent.clientY;
42
45
46 if (!canStart)
47 {
48 holdTimer = setTimeout(() =>
49 {
50 canStart = true;
51 holdTimer = null;
52 }, TOUCH_DRAG_HOLD_MS);
53 }
54
55 function cleanupListeners ()
56 {
57 if (holdTimer)
58 {
59 clearTimeout(holdTimer);
60 holdTimer = null;
61 }
62 document.removeEventListener('pointermove', onMove);
63 document.removeEventListener('pointerup', onUp);
64 document.removeEventListener('pointercancel', onCancel);
65 }
66
43 function onMove (e)
67 function onMove (e)
44 {
68 {
69 const moved = Math.hypot(e.clientX - startX, e.clientY - startY);
70
45 if (!started)
71 if (!started)
46 {
72 {
47 if (Math.hypot(e.clientX - startX, e.clientY - startY) < DRAG_THRESHOLD) return;
73 if (!canStart)
74 {
75 if (moved > DRAG_THRESHOLD)
76 {
77 cleanupListeners();
78 }
79 return;
80 }
81
82 if (moved < DRAG_THRESHOLD) return;
48 started = true;
83 started = true;
49 _beginDrag(downEvent, el, item);
84 _beginDrag(downEvent, el, item);
85 if (downEvent.pointerId != null && typeof el.setPointerCapture === 'function')
86 {
87 try { el.setPointerCapture(downEvent.pointerId); } catch { /* ignore */ }
88 }
89 }
90 if (_drag.active)
91 {
92 e.preventDefault();
93 _moveDrag(e);
50 }
94 }
51 if (_drag.active) _moveDrag(e);
52 }
95 }
53
96
54 function onUp ()
97 function onUp ()
55 {
98 {
56 document.removeEventListener('pointermove', onMove);
99 cleanupListeners();
57 document.removeEventListener('pointerup', onUp);
58 if (started && _drag.active) _endDrag();
100 if (started && _drag.active) _endDrag();
59 }
101 }
60
102
103 function onCancel ()
104 {
105 cleanupListeners();
106 if (started && _drag.active) _cleanupDrag(true);
107 }
108
61 document.addEventListener('pointermove', onMove);
109 document.addEventListener('pointermove', onMove);
62 document.addEventListener('pointerup', onUp);
110 document.addEventListener('pointerup', onUp);
111 document.addEventListener('pointercancel', onCancel);
63}
112}
64
113
65function _beginDrag (e, el, item)
114function _beginDrag (e, el, item)
@@ -217,7 +266,12 @@ function _endDrag ()
217
266
218 try
267 try
219 {
268 {
220 await api('POST', '/files/move', { from: sourceItem.path, toDir: targetPath });
269 const moved = await moveWithConflictResolution(sourceItem, targetPath);
270 if (!moved)
271 {
272 _cleanupDrag(true);
273 return;
274 }
221 }
275 }
222 catch (err)
276 catch (err)
223 {
277 {
public/index.html +19 −0
@@ -249,6 +249,25 @@
249 249 </div>
250 250 </div>
251 251
252 <!-- FILE CONFLICT MODAL (single upload/move) -->
253 <div id="file-conflict-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
254 aria-labelledby="file-conflict-title">
255 <div class="modal small">
256 <h2 id="file-conflict-title">Bestand conflict</h2>
257 <p class="dialog-message">
258 <strong id="file-conflict-filename"></strong> bestaat al in de doelmap.
259 </p>
260 <p class="dialog-message">
261 Hernoemen naar <strong id="file-conflict-rename"></strong>?
262 </p>
263 <div class="dialog-actions">
264 <button id="file-conflict-cancel">Annuleren</button>
265 <button id="file-conflict-overwrite" class="primary">Overschrijven</button>
266 <button id="file-conflict-rename-btn" class="primary">Hernoemen</button>
267 </div>
268 </div>
269 </div>
270
252 271 <!-- FILE PREVIEW OVERLAY -->
253 272 <!-- TOAST -->
254 273 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
@@ -249,6 +249,25 @@
249 </div>
249 </div>
250 </div>
250 </div>
251
251
252 <!-- FILE CONFLICT MODAL (single upload/move) -->
253 <div id="file-conflict-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
254 aria-labelledby="file-conflict-title">
255 <div class="modal small">
256 <h2 id="file-conflict-title">Bestand conflict</h2>
257 <p class="dialog-message">
258 <strong id="file-conflict-filename"></strong> bestaat al in de doelmap.
259 </p>
260 <p class="dialog-message">
261 Hernoemen naar <strong id="file-conflict-rename"></strong>?
262 </p>
263 <div class="dialog-actions">
264 <button id="file-conflict-cancel">Annuleren</button>
265 <button id="file-conflict-overwrite" class="primary">Overschrijven</button>
266 <button id="file-conflict-rename-btn" class="primary">Hernoemen</button>
267 </div>
268 </div>
269 </div>
270
252 <!-- FILE PREVIEW OVERLAY -->
271 <!-- FILE PREVIEW OVERLAY -->
253 <!-- TOAST -->
272 <!-- TOAST -->
254 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
273 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
public/style.css +1 −0
@@ -290,6 +290,7 @@ button.danger:hover {
290 290 text-align: center;
291 291 gap: 0.4rem;
292 292 position: relative;
293 touch-action: manipulation;
293 294 }
294 295
295 296 .file-item:hover {
@@ -290,6 +290,7 @@ button.danger:hover {
290 text-align: center;
290 text-align: center;
291 gap: 0.4rem;
291 gap: 0.4rem;
292 position: relative;
292 position: relative;
293 touch-action: manipulation;
293}
294}
294
295
295.file-item:hover {
296.file-item:hover {
server/routes/files.js +92 −5
@@ -168,6 +168,46 @@ function rewriteMetaPaths (fromPath, toPath)
168 168 }
169 169 }
170 170
171 function splitNameExt (name)
172 {
173 const dot = String(name || '').lastIndexOf('.');
174 if (dot <= 0) return { stem: String(name || ''), ext: '' };
175 return {
176 stem: String(name).slice(0, dot),
177 ext: String(name).slice(dot),
178 };
179 }
180
181 function pickNumberedPath (dir, requestedName)
182 {
183 const parsed = splitNameExt(requestedName);
184 const stem = parsed.stem || 'file';
185 const ext = parsed.ext || '';
186 let index = 1;
187
188 while (index <= 10000)
189 {
190 const candidateName = `${stem} (${index})${ext}`;
191 const candidatePath = path.join(dir, candidateName);
192 if (!fs.existsSync(candidatePath)) return candidatePath;
193 index++;
194 }
195
196 throw new Error('Could not generate a free destination name.');
197 }
198
199 function removePathRecursive (targetPath)
200 {
201 const stat = fs.lstatSync(targetPath);
202 if (stat.isDirectory())
203 {
204 fs.rmSync(targetPath, { recursive: true, force: true });
205 } else
206 {
207 fs.unlinkSync(targetPath);
208 }
209 }
210
171 211 // ---------------------------------------------------------------------------
172 212 // GET /api/files/roots
173 213 // Returns the effective configured paths the user can read.
@@ -618,7 +658,20 @@ router.post('/rename', requireAuth, (req, res) =>
618 658 router.post('/move', requireAuth, (req, res) =>
619 659 {
620 660 const { from, toDir } = req.body;
661 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
662 const targetName = req.body && req.body.targetName != null
663 ? String(req.body.targetName).trim()
664 : '';
621 665 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
666 if (!['error', 'overwrite', 'rename'].includes(conflict))
667 {
668 return res.status(400).json({ error: 'Invalid conflict strategy.' });
669 }
670
671 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
672 {
673 return res.status(400).json({ error: 'Invalid targetName.' });
674 }
622 675
623 676 const roots = effectivePaths();
624 677 const fromInfo = resolveRoot(from, roots);
@@ -642,9 +695,10 @@ router.post('/move', requireAuth, (req, res) =>
642 695
643 696 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
644 697
645 const dest = path.join(toDir, path.basename(from));
646 if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
647 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
698 const requestedName = targetName || path.basename(from);
699 const requestedDest = path.join(toDir, requestedName);
700 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
701 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
648 702 {
649 703 return res.status(400).json({ error: 'Cannot move onto itself.' });
650 704 }
@@ -652,7 +706,40 @@ router.post('/move', requireAuth, (req, res) =>
652 706 {
653 707 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
654 708 }
655 if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
709
710 let dest = requestedDest;
711 let resolvedConflict = 'none';
712
713 if (fs.existsSync(requestedDest))
714 {
715 if (conflict === 'error')
716 {
717 return res.status(409).json({ error: 'Destination already exists.' });
718 }
719
720 if (conflict === 'rename')
721 {
722 dest = pickNumberedPath(toDir, requestedName);
723 resolvedConflict = 'rename';
724 }
725
726 if (conflict === 'overwrite')
727 {
728 try
729 {
730 removePathRecursive(requestedDest);
731 } catch (err)
732 {
733 return res.status(500).json({ error: err.message });
734 }
735 resolvedConflict = 'overwrite';
736 }
737 }
738
739 if (sameResolvedPath(from, dest))
740 {
741 return res.status(400).json({ error: 'Cannot move onto itself.' });
742 }
656 743
657 744 try
658 745 {
@@ -663,7 +750,7 @@ router.post('/move', requireAuth, (req, res) =>
663 750 }
664 751
665 752 rewriteMetaPaths(from, dest);
666 res.json({ ok: true, path: dest });
753 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
667 754 });
668 755
669 756 // ---------------------------------------------------------------------------
@@ -168,6 +168,46 @@ function rewriteMetaPaths (fromPath, toPath)
168 }
168 }
169}
169}
170
170
171function splitNameExt (name)
172{
173 const dot = String(name || '').lastIndexOf('.');
174 if (dot <= 0) return { stem: String(name || ''), ext: '' };
175 return {
176 stem: String(name).slice(0, dot),
177 ext: String(name).slice(dot),
178 };
179}
180
181function pickNumberedPath (dir, requestedName)
182{
183 const parsed = splitNameExt(requestedName);
184 const stem = parsed.stem || 'file';
185 const ext = parsed.ext || '';
186 let index = 1;
187
188 while (index <= 10000)
189 {
190 const candidateName = `${stem} (${index})${ext}`;
191 const candidatePath = path.join(dir, candidateName);
192 if (!fs.existsSync(candidatePath)) return candidatePath;
193 index++;
194 }
195
196 throw new Error('Could not generate a free destination name.');
197}
198
199function removePathRecursive (targetPath)
200{
201 const stat = fs.lstatSync(targetPath);
202 if (stat.isDirectory())
203 {
204 fs.rmSync(targetPath, { recursive: true, force: true });
205 } else
206 {
207 fs.unlinkSync(targetPath);
208 }
209}
210
171// ---------------------------------------------------------------------------
211// ---------------------------------------------------------------------------
172// GET /api/files/roots
212// GET /api/files/roots
173// Returns the effective configured paths the user can read.
213// Returns the effective configured paths the user can read.
@@ -618,7 +658,20 @@ router.post('/rename', requireAuth, (req, res) =>
618router.post('/move', requireAuth, (req, res) =>
658router.post('/move', requireAuth, (req, res) =>
619{
659{
620 const { from, toDir } = req.body;
660 const { from, toDir } = req.body;
661 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
662 const targetName = req.body && req.body.targetName != null
663 ? String(req.body.targetName).trim()
664 : '';
621 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
665 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
666 if (!['error', 'overwrite', 'rename'].includes(conflict))
667 {
668 return res.status(400).json({ error: 'Invalid conflict strategy.' });
669 }
670
671 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
672 {
673 return res.status(400).json({ error: 'Invalid targetName.' });
674 }
622
675
623 const roots = effectivePaths();
676 const roots = effectivePaths();
624 const fromInfo = resolveRoot(from, roots);
677 const fromInfo = resolveRoot(from, roots);
@@ -642,9 +695,10 @@ router.post('/move', requireAuth, (req, res) =>
642
695
643 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
696 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
644
697
645 const dest = path.join(toDir, path.basename(from));
698 const requestedName = targetName || path.basename(from);
646 if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
699 const requestedDest = path.join(toDir, requestedName);
647 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
700 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
701 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
648 {
702 {
649 return res.status(400).json({ error: 'Cannot move onto itself.' });
703 return res.status(400).json({ error: 'Cannot move onto itself.' });
650 }
704 }
@@ -652,7 +706,40 @@ router.post('/move', requireAuth, (req, res) =>
652 {
706 {
653 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
707 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
654 }
708 }
655 if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
709
710 let dest = requestedDest;
711 let resolvedConflict = 'none';
712
713 if (fs.existsSync(requestedDest))
714 {
715 if (conflict === 'error')
716 {
717 return res.status(409).json({ error: 'Destination already exists.' });
718 }
719
720 if (conflict === 'rename')
721 {
722 dest = pickNumberedPath(toDir, requestedName);
723 resolvedConflict = 'rename';
724 }
725
726 if (conflict === 'overwrite')
727 {
728 try
729 {
730 removePathRecursive(requestedDest);
731 } catch (err)
732 {
733 return res.status(500).json({ error: err.message });
734 }
735 resolvedConflict = 'overwrite';
736 }
737 }
738
739 if (sameResolvedPath(from, dest))
740 {
741 return res.status(400).json({ error: 'Cannot move onto itself.' });
742 }
656
743
657 try
744 try
658 {
745 {
@@ -663,7 +750,7 @@ router.post('/move', requireAuth, (req, res) =>
663 }
750 }
664
751
665 rewriteMetaPaths(from, dest);
752 rewriteMetaPaths(from, dest);
666 res.json({ ok: true, path: dest });
753 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
667});
754});
668
755
669// ---------------------------------------------------------------------------
756// ---------------------------------------------------------------------------
tests/files.routes.test.js +41 −0
@@ -228,6 +228,47 @@ describe('POST /api/files/move', () =>
228 228 expect(status).toBe(400);
229 229 expect(body.error).toMatch(/folder into itself/i);
230 230 });
231
232 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
233 {
234 const sourceFile = path.join(rootDir, 'source.txt');
235 const destinationDir = path.join(rootDir, 'dest');
236 fs.mkdirSync(destinationDir);
237 fs.writeFileSync(sourceFile, 'new-content');
238 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
239
240 const { status, body } = await req('POST', '/api/files/move', {
241 from: sourceFile,
242 toDir: destinationDir,
243 conflict: 'overwrite',
244 });
245
246 expect(status).toBe(200);
247 expect(body.conflictResolution).toBe('overwrite');
248 expect(fs.existsSync(sourceFile)).toBe(false);
249 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
250 });
251
252 test('renames destination when conflict strategy is rename', async () =>
253 {
254 const sourceFile = path.join(rootDir, 'report.txt');
255 const destinationDir = path.join(rootDir, 'dest');
256 fs.mkdirSync(destinationDir);
257 fs.writeFileSync(sourceFile, 'latest');
258 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
259
260 const { status, body } = await req('POST', '/api/files/move', {
261 from: sourceFile,
262 toDir: destinationDir,
263 conflict: 'rename',
264 });
265
266 expect(status).toBe(200);
267 expect(body.conflictResolution).toBe('rename');
268 expect(path.basename(body.path)).toBe('report (1).txt');
269 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
270 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
271 });
231 272 });
232 273
233 274 describe('root alias endpoints', () =>
@@ -228,6 +228,47 @@ describe('POST /api/files/move', () =>
228 expect(status).toBe(400);
228 expect(status).toBe(400);
229 expect(body.error).toMatch(/folder into itself/i);
229 expect(body.error).toMatch(/folder into itself/i);
230 });
230 });
231
232 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
233 {
234 const sourceFile = path.join(rootDir, 'source.txt');
235 const destinationDir = path.join(rootDir, 'dest');
236 fs.mkdirSync(destinationDir);
237 fs.writeFileSync(sourceFile, 'new-content');
238 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
239
240 const { status, body } = await req('POST', '/api/files/move', {
241 from: sourceFile,
242 toDir: destinationDir,
243 conflict: 'overwrite',
244 });
245
246 expect(status).toBe(200);
247 expect(body.conflictResolution).toBe('overwrite');
248 expect(fs.existsSync(sourceFile)).toBe(false);
249 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
250 });
251
252 test('renames destination when conflict strategy is rename', async () =>
253 {
254 const sourceFile = path.join(rootDir, 'report.txt');
255 const destinationDir = path.join(rootDir, 'dest');
256 fs.mkdirSync(destinationDir);
257 fs.writeFileSync(sourceFile, 'latest');
258 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
259
260 const { status, body } = await req('POST', '/api/files/move', {
261 from: sourceFile,
262 toDir: destinationDir,
263 conflict: 'rename',
264 });
265
266 expect(status).toBe(200);
267 expect(body.conflictResolution).toBe('rename');
268 expect(path.basename(body.path)).toBe('report (1).txt');
269 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
270 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
271 });
231});
272});
232
273
233describe('root alias endpoints', () =>
274describe('root alias endpoints', () =>
tests/page.load.test.js +39 −1
@@ -180,13 +180,48 @@ describe('page load smoke test', () =>
180 180 });
181 181
182 182 await new Promise((resolve) => dom.window.addEventListener('load', resolve, { once: true }));
183 await new Promise(resolve => dom.window.setTimeout(resolve, 100));
183 await new Promise((resolve) =>
184 {
185 const startedAt = Date.now();
186 const maxWaitMs = 2000;
187
188 function checkReady ()
189 {
190 const app = dom.window.document.getElementById('app');
191 if (app && !app.classList.contains('hidden'))
192 {
193 resolve();
194 return;
195 }
196
197 if (Date.now() - startedAt >= maxWaitMs)
198 {
199 resolve();
200 return;
201 }
202
203 dom.window.setTimeout(checkReady, 25);
204 }
205
206 checkReady();
207 });
184 208
185 209 openDoms.push(dom);
186 210
187 211 return { dom, runtimeErrors };
188 212 }
189 213
214 async function waitFor (dom, predicate, timeoutMs = 5000)
215 {
216 const startedAt = Date.now();
217 while (Date.now() - startedAt < timeoutMs)
218 {
219 if (predicate()) return true;
220 await new Promise(resolve => dom.window.setTimeout(resolve, 25));
221 }
222 return predicate();
223 }
224
190 225 test('requests / and boots the client without runtime errors', async () =>
191 226 {
192 227 const { dom, runtimeErrors } = await bootClient();
@@ -215,6 +250,8 @@ describe('page load smoke test', () =>
215 250
216 251 expect(runtimeErrors).toEqual([]);
217 252
253 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item'));
254
218 255 const tile = dom.window.document.querySelector('.file-item');
219 256 expect(tile).toBeTruthy();
220 257
@@ -331,6 +368,7 @@ describe('page load smoke test', () =>
331 368 });
332 369
333 370 expect(runtimeErrors).toEqual([]);
371 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data-a"]'));
334 372
335 373 const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]');
336 374 expect(rootTile).toBeTruthy();
@@ -180,13 +180,48 @@ describe('page load smoke test', () =>
180 });
180 });
181
181
182 await new Promise((resolve) => dom.window.addEventListener('load', resolve, { once: true }));
182 await new Promise((resolve) => dom.window.addEventListener('load', resolve, { once: true }));
183 await new Promise(resolve => dom.window.setTimeout(resolve, 100));
183 await new Promise((resolve) =>
184 {
185 const startedAt = Date.now();
186 const maxWaitMs = 2000;
187
188 function checkReady ()
189 {
190 const app = dom.window.document.getElementById('app');
191 if (app && !app.classList.contains('hidden'))
192 {
193 resolve();
194 return;
195 }
196
197 if (Date.now() - startedAt >= maxWaitMs)
198 {
199 resolve();
200 return;
201 }
202
203 dom.window.setTimeout(checkReady, 25);
204 }
205
206 checkReady();
207 });
184
208
185 openDoms.push(dom);
209 openDoms.push(dom);
186
210
187 return { dom, runtimeErrors };
211 return { dom, runtimeErrors };
188 }
212 }
189
213
214 async function waitFor (dom, predicate, timeoutMs = 5000)
215 {
216 const startedAt = Date.now();
217 while (Date.now() - startedAt < timeoutMs)
218 {
219 if (predicate()) return true;
220 await new Promise(resolve => dom.window.setTimeout(resolve, 25));
221 }
222 return predicate();
223 }
224
190 test('requests / and boots the client without runtime errors', async () =>
225 test('requests / and boots the client without runtime errors', async () =>
191 {
226 {
192 const { dom, runtimeErrors } = await bootClient();
227 const { dom, runtimeErrors } = await bootClient();
@@ -215,6 +250,8 @@ describe('page load smoke test', () =>
215
250
216 expect(runtimeErrors).toEqual([]);
251 expect(runtimeErrors).toEqual([]);
217
252
253 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item'));
254
218 const tile = dom.window.document.querySelector('.file-item');
255 const tile = dom.window.document.querySelector('.file-item');
219 expect(tile).toBeTruthy();
256 expect(tile).toBeTruthy();
220
257
@@ -331,6 +368,7 @@ describe('page load smoke test', () =>
331 });
368 });
332
369
333 expect(runtimeErrors).toEqual([]);
370 expect(runtimeErrors).toEqual([]);
371 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data-a"]'));
334
372
335 const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]');
373 const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]');
336 expect(rootTile).toBeTruthy();
374 expect(rootTile).toBeTruthy();
tests/thumbnail-cache.test.js +12 −1
@@ -5,6 +5,8 @@ const os = require('os');
5 5 const path = require('path');
6 6 const sharp = require('sharp');
7 7
8 sharp.cache(false);
9
8 10 let mockPaths = [];
9 11
10 12 jest.mock('../server/config', () => ({
@@ -68,7 +70,16 @@ describe('thumbnail cache worker', () =>
68 70 delete process.env.FILEMANAGER_PUBLIC_DIR;
69 71 delete process.env.FILEMANAGER_THUMBS_DIR;
70 72 mockPaths = [];
71 fs.rmSync(tempDir, { recursive: true, force: true });
73 try
74 {
75 fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 30 });
76 } catch (err)
77 {
78 if (!err || !/EBUSY|EPERM/i.test(String(err.code || err.message || '')))
79 {
80 throw err;
81 }
82 }
72 83 });
73 84
74 85 test('creates cached thumbnail with dimensions smaller than 100px', async () =>
@@ -5,6 +5,8 @@ const os = require('os');
5const path = require('path');
5const path = require('path');
6const sharp = require('sharp');
6const sharp = require('sharp');
7
7
8sharp.cache(false);
9
8let mockPaths = [];
10let mockPaths = [];
9
11
10jest.mock('../server/config', () => ({
12jest.mock('../server/config', () => ({
@@ -68,7 +70,16 @@ describe('thumbnail cache worker', () =>
68 delete process.env.FILEMANAGER_PUBLIC_DIR;
70 delete process.env.FILEMANAGER_PUBLIC_DIR;
69 delete process.env.FILEMANAGER_THUMBS_DIR;
71 delete process.env.FILEMANAGER_THUMBS_DIR;
70 mockPaths = [];
72 mockPaths = [];
71 fs.rmSync(tempDir, { recursive: true, force: true });
73 try
74 {
75 fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 30 });
76 } catch (err)
77 {
78 if (!err || !/EBUSY|EPERM/i.test(String(err.code || err.message || '')))
79 {
80 throw err;
81 }
82 }
72 });
83 });
73
84
74 test('creates cached thumbnail with dimensions smaller than 100px', async () =>
85 test('creates cached thumbnail with dimensions smaller than 100px', async () =>