@putkoff/abstract-securefiles 0.0.47 → 0.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/ConfirmButton.d.ts +5 -0
  2. package/dist/CopyButton.d.ts +4 -0
  3. package/dist/FolderSelect.d.ts +6 -0
  4. package/dist/SecureFiles.d.ts +3 -0
  5. package/dist/ServerFiles.d.ts +6 -0
  6. package/dist/ShareDialog.d.ts +6 -0
  7. package/dist/UploadPanel.d.ts +6 -0
  8. package/dist/api.d.ts +46 -0
  9. package/dist/index.cjs +539 -956
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +4 -8
  12. package/dist/index.js +531 -902
  13. package/dist/index.js.map +1 -1
  14. package/dist/types.d.ts +54 -0
  15. package/package.json +15 -11
  16. package/src/ConfirmButton.tsx +35 -0
  17. package/src/CopyButton.tsx +24 -0
  18. package/src/FolderSelect.tsx +68 -0
  19. package/src/SecureFiles.tsx +344 -0
  20. package/src/ServerFiles.tsx +324 -0
  21. package/src/ShareDialog.tsx +148 -0
  22. package/src/UploadPanel.tsx +217 -0
  23. package/src/api.ts +119 -0
  24. package/src/index.ts +4 -8
  25. package/src/styles.css +432 -0
  26. package/src/types.ts +54 -0
  27. package/css.d.ts +0 -2
  28. package/dist/App/SecureFiles.d.ts +0 -4
  29. package/dist/App/index.d.ts +0 -1
  30. package/dist/FileHandlers/FileRow/imports.d.ts +0 -2
  31. package/dist/FileHandlers/FileRow/index.d.ts +0 -1
  32. package/dist/FileHandlers/FileRow/src/index.d.ts +0 -1
  33. package/dist/FileHandlers/FileRow/src/row_utils.d.ts +0 -2
  34. package/dist/FileHandlers/FileTable/imports.d.ts +0 -4
  35. package/dist/FileHandlers/FileTable/index.d.ts +0 -1
  36. package/dist/FileHandlers/FileTable/src/index.d.ts +0 -1
  37. package/dist/FileHandlers/FileTable/src/table_utils.d.ts +0 -2
  38. package/dist/FileHandlers/ShareModal/imports.d.ts +0 -2
  39. package/dist/FileHandlers/ShareModal/index.d.ts +0 -1
  40. package/dist/FileHandlers/ShareModal/src/index.d.ts +0 -1
  41. package/dist/FileHandlers/ShareModal/src/share_utils.d.ts +0 -2
  42. package/dist/FileHandlers/Upload/imports.d.ts +0 -2
  43. package/dist/FileHandlers/Upload/index.d.ts +0 -1
  44. package/dist/FileHandlers/Upload/src/index.d.ts +0 -2
  45. package/dist/FileHandlers/Upload/src/upload_utils.d.ts +0 -2
  46. package/dist/FileHandlers/imports.d.ts +0 -4
  47. package/dist/FileHandlers/index.d.ts +0 -4
  48. package/dist/UI/index.d.ts +0 -28
  49. package/dist/file_utils/imports.d.ts +0 -2
  50. package/dist/file_utils/index.d.ts +0 -1
  51. package/dist/file_utils/src/cookieFetch.d.ts +0 -33
  52. package/dist/file_utils/src/delete_utils/imports.d.ts +0 -1
  53. package/dist/file_utils/src/delete_utils/index.d.ts +0 -1
  54. package/dist/file_utils/src/delete_utils/src/delete_row.d.ts +0 -2
  55. package/dist/file_utils/src/delete_utils/src/delete_select.d.ts +0 -4
  56. package/dist/file_utils/src/delete_utils/src/delete_selected.d.ts +0 -2
  57. package/dist/file_utils/src/delete_utils/src/index.d.ts +0 -3
  58. package/dist/file_utils/src/download_utils/imports.d.ts +0 -2
  59. package/dist/file_utils/src/download_utils/index.d.ts +0 -1
  60. package/dist/file_utils/src/download_utils/src/direct_download.d.ts +0 -3
  61. package/dist/file_utils/src/download_utils/src/download_file.d.ts +0 -6
  62. package/dist/file_utils/src/download_utils/src/download_select.d.ts +0 -2
  63. package/dist/file_utils/src/download_utils/src/index.d.ts +0 -5
  64. package/dist/file_utils/src/download_utils/src/target_downloads.d.ts +0 -4
  65. package/dist/file_utils/src/download_utils/src/trigger_download.d.ts +0 -2
  66. package/dist/file_utils/src/imports.d.ts +0 -2
  67. package/dist/file_utils/src/index.d.ts +0 -6
  68. package/dist/file_utils/src/list_utils/imports.d.ts +0 -1
  69. package/dist/file_utils/src/list_utils/index.d.ts +0 -1
  70. package/dist/file_utils/src/list_utils/src/index.d.ts +0 -1
  71. package/dist/file_utils/src/list_utils/src/list_utils.d.ts +0 -2
  72. package/dist/file_utils/src/select_utils/index.d.ts +0 -1
  73. package/dist/file_utils/src/select_utils/src/index.d.ts +0 -3
  74. package/dist/file_utils/src/select_utils/src/init_select_all.d.ts +0 -2
  75. package/dist/file_utils/src/select_utils/src/sync_header_checkbox.d.ts +0 -5
  76. package/dist/file_utils/src/select_utils/src/toggle_checkboxes.d.ts +0 -2
  77. package/dist/file_utils/src/share_utils/imports.d.ts +0 -1
  78. package/dist/file_utils/src/share_utils/index.d.ts +0 -1
  79. package/dist/file_utils/src/share_utils/src/index.d.ts +0 -1
  80. package/dist/file_utils/src/share_utils/src/share_utils.d.ts +0 -7
  81. package/dist/file_utils/src/upload_utils/imports.d.ts +0 -0
  82. package/dist/file_utils/src/upload_utils/index.d.ts +0 -1
  83. package/dist/file_utils/src/upload_utils/src/index.d.ts +0 -3
  84. package/dist/file_utils/src/upload_utils/src/patch_file_settings.d.ts +0 -2
  85. package/dist/file_utils/src/upload_utils/src/upload_file.d.ts +0 -2
  86. package/dist/file_utils/src/upload_utils/src/upload_files.d.ts +0 -5
  87. package/dist/hooks/imports.d.ts +0 -3
  88. package/dist/hooks/index.d.ts +0 -1
  89. package/dist/hooks/useFiles/imports.d.ts +0 -2
  90. package/dist/hooks/useFiles/index.d.ts +0 -1
  91. package/dist/hooks/useFiles/src/deleteFile.d.ts +0 -3
  92. package/dist/hooks/useFiles/src/index.d.ts +0 -6
  93. package/dist/hooks/useFiles/src/load.d.ts +0 -3
  94. package/dist/hooks/useFiles/src/patchShareSettings.d.ts +0 -3
  95. package/dist/hooks/useFiles/src/toggleShare.d.ts +0 -3
  96. package/dist/hooks/useFiles/src/useFiles.d.ts +0 -13
  97. package/dist/hooks/useFiles/src/useSaveShareSettings.d.ts +0 -7
  98. package/dist/imports.d.ts +0 -6
  99. package/dist/index.css +0 -1
  100. package/dist/styles/index.d.ts +0 -1
  101. package/dist/types/index.d.ts +0 -1
  102. package/dist/types/src/index.d.ts +0 -1
  103. package/dist/types/src/types.d.ts +0 -75
  104. package/index.ts +0 -1
  105. package/postcss.config.cjs +0 -8
  106. package/rollup.config.js +0 -38
  107. package/rollup.config.mjs +0 -35
  108. package/src/App/SecureFiles.tsx +0 -45
  109. package/src/App/index.ts +0 -1
  110. package/src/FileHandlers/FileRow/imports.ts +0 -2
  111. package/src/FileHandlers/FileRow/index.ts +0 -1
  112. package/src/FileHandlers/FileRow/src/index.ts +0 -1
  113. package/src/FileHandlers/FileRow/src/row_utils.tsx +0 -143
  114. package/src/FileHandlers/FileTable/imports.ts +0 -15
  115. package/src/FileHandlers/FileTable/index.ts +0 -1
  116. package/src/FileHandlers/FileTable/src/index.ts +0 -1
  117. package/src/FileHandlers/FileTable/src/table_utils.tsx +0 -251
  118. package/src/FileHandlers/ShareModal/imports.ts +0 -2
  119. package/src/FileHandlers/ShareModal/index.ts +0 -1
  120. package/src/FileHandlers/ShareModal/src/index.ts +0 -1
  121. package/src/FileHandlers/ShareModal/src/share_utils.tsx +0 -155
  122. package/src/FileHandlers/Upload/imports.ts +0 -3
  123. package/src/FileHandlers/Upload/index.ts +0 -1
  124. package/src/FileHandlers/Upload/src/index.ts +0 -2
  125. package/src/FileHandlers/Upload/src/upload_utils.tsx +0 -267
  126. package/src/FileHandlers/imports.ts +0 -17
  127. package/src/FileHandlers/index.ts +0 -4
  128. package/src/UI/index.tsx +0 -122
  129. package/src/custom.d.ts +0 -7
  130. package/src/file_utils/imports.ts +0 -2
  131. package/src/file_utils/index.ts +0 -1
  132. package/src/file_utils/src/cookieFetch.ts +0 -109
  133. package/src/file_utils/src/delete_utils/imports.ts +0 -1
  134. package/src/file_utils/src/delete_utils/index.ts +0 -1
  135. package/src/file_utils/src/delete_utils/src/delete_row.ts +0 -11
  136. package/src/file_utils/src/delete_utils/src/delete_select.ts +0 -10
  137. package/src/file_utils/src/delete_utils/src/delete_selected.ts +0 -15
  138. package/src/file_utils/src/delete_utils/src/index.ts +0 -3
  139. package/src/file_utils/src/download_utils/imports.ts +0 -3
  140. package/src/file_utils/src/download_utils/index.ts +0 -1
  141. package/src/file_utils/src/download_utils/src/direct_download.ts +0 -22
  142. package/src/file_utils/src/download_utils/src/download_file.ts +0 -25
  143. package/src/file_utils/src/download_utils/src/download_select.ts +0 -25
  144. package/src/file_utils/src/download_utils/src/index.ts +0 -5
  145. package/src/file_utils/src/download_utils/src/target_downloads.ts +0 -21
  146. package/src/file_utils/src/download_utils/src/trigger_download.ts +0 -14
  147. package/src/file_utils/src/imports.ts +0 -3
  148. package/src/file_utils/src/index.ts +0 -6
  149. package/src/file_utils/src/list_utils/imports.ts +0 -2
  150. package/src/file_utils/src/list_utils/index.ts +0 -1
  151. package/src/file_utils/src/list_utils/src/index.ts +0 -1
  152. package/src/file_utils/src/list_utils/src/list_utils.ts +0 -28
  153. package/src/file_utils/src/select_utils/index.ts +0 -1
  154. package/src/file_utils/src/select_utils/src/index.ts +0 -3
  155. package/src/file_utils/src/select_utils/src/init_select_all.ts +0 -37
  156. package/src/file_utils/src/select_utils/src/sync_header_checkbox.ts +0 -18
  157. package/src/file_utils/src/select_utils/src/toggle_checkboxes.ts +0 -11
  158. package/src/file_utils/src/share_utils/imports.ts +0 -1
  159. package/src/file_utils/src/share_utils/index.ts +0 -1
  160. package/src/file_utils/src/share_utils/src/index.ts +0 -1
  161. package/src/file_utils/src/share_utils/src/share_utils.ts +0 -20
  162. package/src/file_utils/src/upload_utils/imports.ts +0 -1
  163. package/src/file_utils/src/upload_utils/index.ts +0 -1
  164. package/src/file_utils/src/upload_utils/src/index.ts +0 -3
  165. package/src/file_utils/src/upload_utils/src/patch_file_settings.ts +0 -20
  166. package/src/file_utils/src/upload_utils/src/upload_file.ts +0 -27
  167. package/src/file_utils/src/upload_utils/src/upload_files.ts +0 -19
  168. package/src/hooks/imports.ts +0 -3
  169. package/src/hooks/index.ts +0 -1
  170. package/src/hooks/useFiles/imports.ts +0 -3
  171. package/src/hooks/useFiles/index.ts +0 -1
  172. package/src/hooks/useFiles/src/deleteFile.ts +0 -23
  173. package/src/hooks/useFiles/src/index.ts +0 -6
  174. package/src/hooks/useFiles/src/load.ts +0 -39
  175. package/src/hooks/useFiles/src/logs/clipit_logs.log +0 -0
  176. package/src/hooks/useFiles/src/logs/routes_bp.log +0 -0
  177. package/src/hooks/useFiles/src/patchShareSettings.ts +0 -27
  178. package/src/hooks/useFiles/src/toggleShare.ts +0 -28
  179. package/src/hooks/useFiles/src/useFiles.ts +0 -35
  180. package/src/hooks/useFiles/src/useSaveShareSettings.ts +0 -31
  181. package/src/imports.ts +0 -18
  182. package/src/styles/SecureFiles/App.css +0 -42
  183. package/src/styles/SecureFiles/index.css +0 -10
  184. package/src/styles/SecureFiles/logs/clipit_logs.log +0 -0
  185. package/src/styles/SecureFiles/logs/routes_bp.log +0 -0
  186. package/src/styles/SecureFiles/tailwind.css +0 -3
  187. package/src/styles/SecureFiles/window-manager.css +0 -283
  188. package/src/styles/SecureFilesStyles.module.css +0 -287
  189. package/src/styles/index.ts +0 -1
  190. package/src/types/index.ts +0 -1
  191. package/src/types/src/index.ts +0 -1
  192. package/src/types/src/types.ts +0 -88
  193. package/tailwind.config.cjs +0 -7
  194. package/testit.mjs +0 -11
  195. package/testit.ts +0 -3
  196. package/tsconfig.json +0 -27
  197. /package/src/{global.d.ts → css.d.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,990 +1,619 @@
1
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
- import { createPortal } from 'react-dom';
3
- import * as React from 'react';
4
- import { useCallback, useState, useEffect, useRef, useMemo } from 'react';
5
- import { alertit, currentUsername } from '@putkoff/abstract-utilities';
6
-
7
- function ClipboardIcon({
8
- title,
9
- titleId,
10
- ...props
11
- }, svgRef) {
12
- return /*#__PURE__*/React.createElement("svg", Object.assign({
13
- xmlns: "http://www.w3.org/2000/svg",
14
- fill: "none",
15
- viewBox: "0 0 24 24",
16
- strokeWidth: 1.5,
17
- stroke: "currentColor",
18
- "aria-hidden": "true",
19
- "data-slot": "icon",
20
- ref: svgRef,
21
- "aria-labelledby": titleId
22
- }, props), title ? /*#__PURE__*/React.createElement("title", {
23
- id: titleId
24
- }, title) : null, /*#__PURE__*/React.createElement("path", {
25
- strokeLinecap: "round",
26
- strokeLinejoin: "round",
27
- d: "M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184"
28
- }));
29
- }
30
- const ForwardRef$1 = /*#__PURE__*/ React.forwardRef(ClipboardIcon);
31
-
32
- function CloudArrowUpIcon({
33
- title,
34
- titleId,
35
- ...props
36
- }, svgRef) {
37
- return /*#__PURE__*/React.createElement("svg", Object.assign({
38
- xmlns: "http://www.w3.org/2000/svg",
39
- fill: "none",
40
- viewBox: "0 0 24 24",
41
- strokeWidth: 1.5,
42
- stroke: "currentColor",
43
- "aria-hidden": "true",
44
- "data-slot": "icon",
45
- ref: svgRef,
46
- "aria-labelledby": titleId
47
- }, props), title ? /*#__PURE__*/React.createElement("title", {
48
- id: titleId
49
- }, title) : null, /*#__PURE__*/React.createElement("path", {
50
- strokeLinecap: "round",
51
- strokeLinejoin: "round",
52
- d: "M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z"
53
- }));
54
- }
55
- const ForwardRef = /*#__PURE__*/ React.forwardRef(CloudArrowUpIcon);
56
-
57
- // Utility to convert input to array
58
- function ensure_list(obj) {
59
- if (Array.isArray(obj))
60
- return obj.filter(Boolean);
61
- if (typeof obj === 'string')
62
- return obj.split(' ').filter(Boolean);
63
- return [];
64
- }
65
- // Get list and length safely
66
- function getListAndLen(obj) {
67
- const return_obj = ensure_list(obj);
68
- const ob_len = return_obj.length;
69
- return { return_obj, ob_len };
70
- }
71
- // Combine class names with defaults
72
- function combineClassNames(classNames = [], defaultClasses = ['form-group', 'form-label', 'flex', 'gap-2']) {
73
- const { return_obj: inputClasses } = getListAndLen(classNames);
74
- const { return_obj: defaultClassList } = getListAndLen(defaultClasses);
75
- // Combine and remove duplicates
76
- const combined = [...new Set([...defaultClassList, ...inputClasses])];
77
- console.log(`Combined classes (length: ${combined.length}): ${combined.join(' ')}`);
78
- return combined;
79
- }
80
- function Button({ children, color = 'gray', variant = 'default', className = '', ...rest }) {
81
- const variantClasses = {
82
- default: 'btn',
83
- icon: 'btn-icon',
84
- primary: 'btn-primary',
85
- secondary: 'btn-secondary',
86
- };
87
- const colorClasses = {
88
- gray: '',
89
- green: variant === 'primary' ? 'btn-success' : 'btn-secondary',
90
- blue: variant === 'primary' ? 'btn-primary' : 'btn-secondary',
91
- };
92
- const classes = combineClassNames([variantClasses[variant], colorClasses[color], className]);
93
- return (jsx("button", { className: classes.join(' '), ...rest, children: children }));
94
- }
95
- function Checkbox({ label, className = '', classNames = [], ...rest }) {
96
- const classes = combineClassNames(classNames, ['checkbox', 'wm-checkbox']);
97
- return (jsxs("label", { className: classes.join(' '), children: [jsx("input", { type: "checkbox", className: "wm-checkbox", ...rest }), label && jsx("span", { children: label })] }));
98
- }
99
- function Input({ label, trailing, className = '', classNames = [], ...rest }) {
100
- const classes = combineClassNames(classNames, ['form-group', 'flex', 'gap-2']);
101
- const inputClasses = combineClassNames(className, ['form-input']);
102
- return (jsxs("label", { className: classes.join(' '), children: [label && jsx("span", { className: "form-label", children: label }), jsxs("div", { className: "flex gap-2", children: [jsx("input", { className: inputClasses.join(' '), ...rest }), trailing] })] }));
103
- }
104
- function Spinner() {
105
- const classes = combineClassNames('animate-pulse');
106
- return jsx("p", { className: classes.join(' '), children: "Loading\u2026" });
107
- }
108
-
109
- /** Helper function to trigger file download */
110
- function triggerDownload(blob, filename) {
111
- const url = URL.createObjectURL(blob);
112
- const a = Object.assign(document.createElement("a"), {
113
- href: url,
114
- download: filename,
115
- });
116
- document.body.appendChild(a);
117
- a.click();
118
- a.remove();
119
- URL.revokeObjectURL(url);
120
- console.log(`✅ Successfully downloaded: ${filename}`);
121
- }
122
-
123
- /** Non-React “direct download” used by some old links (kept for parity) */
124
- async function directDownload(item) {
125
- const token = localStorage.getItem("token");
126
- if (!token)
127
- throw new Error("No auth token found");
128
- const res = await fetch("https://abstractendeavors.com/api/secure-files/secure-download/", {
129
- method: "POST",
130
- headers: {
131
- Authorization: `Bearer ${token}`,
132
- "Content-Type": "application/json",
133
- Accept: "application/octet-stream",
134
- },
135
- body: JSON.stringify(item),
136
- });
137
- if (!res.ok)
138
- throw new Error(`Download failed: ${res.status}`);
139
- const blob = await res.blob();
140
- triggerDownload(blob, item.filename);
141
- }
142
-
143
- /**
144
- * Download a file using the current session cookie.
145
- * No JWT / localStorage token required.
146
- */
147
- async function downloadFile(item) {
148
- const res = await fetch("/api/secure-files/download", {
149
- method: "POST",
150
- credentials: "include",
151
- headers: { "Content-Type": "application/json" },
152
- body: JSON.stringify({
153
- id: item.id,
154
- filepath: item.filepath,
155
- filename: item.filename,
156
- }),
157
- });
158
- if (res.status === 401)
159
- throw new Error("Not authenticated – please log in.");
160
- if (!res.ok)
161
- throw new Error(`Download failed: HTTP ${res.status}`);
162
- const blob = await res.blob();
163
- triggerDownload(blob, item.filename || "download");
164
- }
165
-
166
- /**
167
- * Cookie-authenticated API helpers.
168
- * All requests include credentials: 'include' so the browser sends the
169
- * session cookie (auth_session) automatically. No JWT tokens are used.
170
- *
171
- * API base URL resolution order (first truthy value wins):
172
- * 1. window.__SECURE_FILES_API_BASE__ – runtime override (any bundler)
173
- * 2. VITE_SECURE_FILES_API_BASE – Vite env var
174
- * 3. REACT_APP_SECURE_FILES_API_BASE – Create React App env var
175
- * 4. /api/secure-files – same-origin default
176
- *
177
- * Subdomain API example (set one of the above to the full origin + path):
178
- * VITE_SECURE_FILES_API_BASE=https://api.example.com/secure-files
179
- */
180
- function resolveApiBase() {
181
- // 1. Runtime window config — works regardless of bundler
182
- if (typeof window !== "undefined" && window.__SECURE_FILES_API_BASE__) {
183
- return String(window.__SECURE_FILES_API_BASE__).replace(/\/+$/, "");
1
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
2
+ import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
3
+
4
+ const DEFAULT_API_BASE = "https://api.abstractendeavors.com";
5
+ class ApiError extends Error {
6
+ constructor(message, status) {
7
+ super(message);
8
+ this.status = status;
184
9
  }
185
- // 2. Vite (import.meta.env is replaced at build time; guard with try for non-Vite builds)
186
- try {
187
- const v = import.meta.env?.VITE_SECURE_FILES_API_BASE;
188
- if (v)
189
- return String(v).replace(/\/+$/, "");
190
- }
191
- catch { /* not a Vite build */ }
192
- // 3. Create React App / plain Node
10
+ }
11
+ async function errorFrom(res) {
12
+ let message = `${res.status} ${res.statusText}`;
193
13
  try {
194
- const v = process.env?.REACT_APP_SECURE_FILES_API_BASE;
195
- if (v)
196
- return String(v).replace(/\/+$/, "");
14
+ const body = await res.json();
15
+ message = body?.message || body?.error || message;
197
16
  }
198
- catch { /* process not defined */ }
199
- // 4. Same-origin default
200
- return "/api/secure-files";
201
- }
202
- const API_BASE$1 = resolveApiBase();
203
- function apiUrl(path) {
204
- const p = path.startsWith("/") ? path : `/${path}`;
205
- return `${API_BASE$1}${p}`;
206
- }
207
- /**
208
- * Generic JSON fetch with session-cookie auth.
209
- * Throws Error("UNAUTHENTICATED") on 401 so callers can redirect to login.
210
- */
211
- async function cookieFetch(path, body, method) {
212
- const m = method ?? (body !== undefined ? "POST" : "GET");
213
- const init = { method: m, credentials: "include" };
214
- if (body !== undefined && body !== null) {
215
- init.headers = { "Content-Type": "application/json" };
216
- init.body = JSON.stringify(body);
17
+ catch {
18
+ /* non-JSON error body */
217
19
  }
218
- const res = await fetch(apiUrl(path), init);
219
20
  if (res.status === 401)
220
- throw new Error("UNAUTHENTICATED");
221
- if (!res.ok) {
222
- const msg = await res.text().catch(() => res.statusText);
223
- throw new Error(`HTTP ${res.status}: ${msg}`);
224
- }
225
- const ct = res.headers.get("Content-Type") ?? "";
226
- return (ct.includes("application/json") ? res.json() : res.text());
21
+ message = "Please log in to use Secure Files.";
22
+ return new ApiError(message, res.status);
227
23
  }
228
- /**
229
- * Check whether the current session is valid.
230
- * Calls /userInfo which requires authentication; returns true if the user
231
- * is logged in, false otherwise (no exception thrown).
232
- */
233
- async function checkAuth() {
234
- try {
235
- const res = await fetch(apiUrl("/userInfo"), {
236
- method: "GET",
24
+ function createApi(apiBase = DEFAULT_API_BASE) {
25
+ const root = `${apiBase.replace(/\/+$/, "")}/secure-files`;
26
+ async function json(path, init = {}) {
27
+ const res = await fetch(`${root}${path}`, {
237
28
  credentials: "include",
29
+ ...init,
30
+ headers: { Accept: "application/json", ...(init.body ? { "Content-Type": "application/json" } : {}) },
238
31
  });
239
- return res.ok;
32
+ if (!res.ok)
33
+ throw await errorFrom(res);
34
+ return res.json();
240
35
  }
241
- catch {
242
- return false;
243
- }
244
- }
245
- /**
246
- * Upload a single file using multipart/form-data with session-cookie auth.
247
- * @param file The File object to upload.
248
- * @param relPath Optional relative path within the user's directory.
249
- */
250
- async function cookieUpload(file, relPath = "") {
251
- const form = new FormData();
252
- form.append("file", file);
253
- if (relPath)
254
- form.append("rel_path", relPath);
255
- const res = await fetch(apiUrl("/upload"), {
256
- method: "POST",
257
- credentials: "include",
258
- body: form,
259
- });
260
- if (res.status === 401)
261
- throw new Error("UNAUTHENTICATED");
262
- if (!res.ok)
263
- throw new Error(`Upload failed: HTTP ${res.status}`);
264
- return res.json();
265
- }
266
- /** The resolved API base URL, exported for debugging / display purposes. */
267
- const SECURE_FILES_API_BASE = API_BASE$1;
268
-
269
- async function downloadSelect(item) {
270
- const res = await fetch(`${SECURE_FILES_API_BASE}/download`, {
271
- method: "POST",
272
- credentials: "include",
273
- headers: {
274
- "Content-Type": "application/json",
275
- Accept: "application/octet-stream",
36
+ return {
37
+ list: () => json("/userInfo"),
38
+ roots: () => json("/admin/roots"),
39
+ requestRoot: (path) => json("/admin/roots", { method: "POST", body: JSON.stringify({ path }) }),
40
+ confirmRoot: (nonce, signature, label) => json("/admin/roots/confirm", {
41
+ method: "POST",
42
+ body: JSON.stringify({ nonce, signature, label }),
43
+ }),
44
+ removeRoot: (id) => json(`/admin/roots/${id}`, { method: "DELETE" }),
45
+ browse: (path) => json(`/admin/browse?path=${encodeURIComponent(path)}`),
46
+ link: (paths, folder) => json("/admin/link", {
47
+ method: "POST",
48
+ body: JSON.stringify({ paths, folder }),
49
+ }),
50
+ updateShare: (update) => json("/files/share", { method: "PATCH", body: JSON.stringify(update) }),
51
+ remove: (ids) => json("/remove", {
52
+ method: "POST",
53
+ body: JSON.stringify({ ids }),
54
+ }),
55
+ async download(ids, fallbackName) {
56
+ const res = await fetch(`${root}/download`, {
57
+ method: "POST",
58
+ credentials: "include",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify({ ids }),
61
+ });
62
+ if (!res.ok)
63
+ throw await errorFrom(res);
64
+ const disposition = res.headers.get("Content-Disposition") || "";
65
+ const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition);
66
+ const name = match ? decodeURIComponent(match[1]) : fallbackName;
67
+ const url = URL.createObjectURL(await res.blob());
68
+ const a = document.createElement("a");
69
+ a.href = url;
70
+ a.download = name;
71
+ document.body.appendChild(a);
72
+ a.click();
73
+ a.remove();
74
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
276
75
  },
277
- body: JSON.stringify(item),
278
- });
279
- if (res.status === 401)
280
- throw new Error("Not authenticated – please log in.");
281
- if (!res.ok)
282
- throw new Error(`Download failed: HTTP ${res.status}`);
283
- const blob = await res.blob();
284
- if (!blob || blob.size === 0) {
285
- throw new Error(`Received empty file data for "${item.filename}"`);
286
- }
287
- triggerDownload(blob, item.filename);
288
- }
289
-
290
- /** Given a checkbox inside a table-row → download that row’s file. */
291
- async function downloadRow(cb) {
292
- const row = cb.closest("tr");
293
- const filepath = cb.value;
294
- const filename = row?.children[1]?.textContent?.trim() || "downloaded_file";
295
- if (filepath)
296
- await downloadSelect({ filepath, filename });
297
- }
298
- /** Bulk download: pass a NodeList or array of checkboxes. */
299
- async function downloadSelected(checkboxes) {
300
- const list = Array.from(checkboxes);
301
- if (!list.length) {
302
- alert("No files selected.");
303
- return;
304
- }
305
- for (const cb of list) {
306
- await downloadRow(cb);
307
- }
308
- }
309
-
310
- /**
311
- * Classic “select all rows” logic (still handy in non-React views
312
- * such as the admin dashboard).
313
- */
314
- function syncHeaderCheckbox() {
315
- const all = document.querySelectorAll(".file-checkbox");
316
- const checked = document.querySelectorAll(".file-checkbox:checked");
317
- const header = document.getElementById("select-all-checkbox");
318
- header.indeterminate =
319
- checked.length > 0 && checked.length < all.length;
320
- header.checked = checked.length === all.length;
76
+ upload(file, relPath, onProgress) {
77
+ return new Promise((resolve, reject) => {
78
+ const form = new FormData();
79
+ form.append("file", file);
80
+ form.append("rel_path", relPath);
81
+ const xhr = new XMLHttpRequest();
82
+ xhr.open("POST", `${root}/upload`);
83
+ xhr.withCredentials = true;
84
+ xhr.upload.onprogress = (e) => {
85
+ if (e.lengthComputable)
86
+ onProgress?.(e.loaded / e.total);
87
+ };
88
+ xhr.onload = () => {
89
+ if (xhr.status >= 200 && xhr.status < 300)
90
+ return resolve();
91
+ let message = `Upload failed (${xhr.status})`;
92
+ try {
93
+ message = JSON.parse(xhr.responseText)?.message || message;
94
+ }
95
+ catch {
96
+ /* non-JSON */
97
+ }
98
+ if (xhr.status === 401)
99
+ message = "Please log in to use Secure Files.";
100
+ reject(new ApiError(message, xhr.status));
101
+ };
102
+ xhr.onerror = () => reject(new ApiError("Network error during upload", 0));
103
+ xhr.send(form);
104
+ });
105
+ },
106
+ };
321
107
  }
322
108
 
323
- /** Wire up header + row checkboxes once the table is in the DOM. */
324
- function initSelectAll() {
325
- const header = document.getElementById("select-all-checkbox");
326
- const btn = document.getElementById("select-all");
327
- // 1) header → toggle all
328
- header.addEventListener("change", (e) => {
329
- const on = e.target.checked;
330
- document
331
- .querySelectorAll(".file-checkbox")
332
- .forEach((cb) => (cb.checked = on));
333
- });
334
- // 2) button → toggle all
335
- btn.addEventListener("click", () => {
336
- const cbs = Array.from(document.querySelectorAll(".file-checkbox"));
337
- if (!cbs.length) {
338
- alert("No files to select.");
339
- return;
109
+ const NEW_FOLDER = "__new__";
110
+ function FolderSelect({ label, folders, value, onChange, }) {
111
+ const [creating, setCreating] = useState(false);
112
+ const [draft, setDraft] = useState("");
113
+ const [extra, setExtra] = useState([]);
114
+ const options = [...new Set([...folders, ...extra, ...(value ? [value] : [])])].sort();
115
+ const accept = () => {
116
+ const clean = draft.trim().replace(/^\/+|\/+$/g, "");
117
+ if (clean) {
118
+ setExtra((e) => (e.includes(clean) ? e : [...e, clean]));
119
+ onChange(clean);
340
120
  }
341
- const anyUnchecked = cbs.some((cb) => !cb.checked);
342
- cbs.forEach((cb) => (cb.checked = anyUnchecked));
343
- syncHeaderCheckbox();
344
- });
345
- // 3) row boxes → keep header state
346
- document
347
- .querySelectorAll(".file-checkbox")
348
- .forEach((cb) => cb.addEventListener("change", syncHeaderCheckbox));
349
- syncHeaderCheckbox();
350
- }
351
-
352
- /** Utility for other screens: toggle a list of checkboxes on/off. */
353
- function toggleCheckboxes(cbs) {
354
- if (!cbs.length) {
355
- alert("No files to select.");
356
- return;
357
- }
358
- const anyUnchecked = cbs.some((cb) => !cb.checked);
359
- cbs.forEach((cb) => (cb.checked = anyUnchecked));
360
- syncHeaderCheckbox();
121
+ setCreating(false);
122
+ setDraft("");
123
+ };
124
+ return (jsxs("div", { className: "sf-field", children: [jsx("span", { children: label }), creating ? (jsxs("div", { className: "sf-row", children: [jsx("input", { className: "sf-input", autoFocus: true, value: draft, placeholder: "new-folder-name (use / for subfolders)", onChange: (e) => setDraft(e.target.value), onKeyDown: (e) => {
125
+ if (e.key === "Enter")
126
+ accept();
127
+ if (e.key === "Escape")
128
+ setCreating(false);
129
+ } }), jsx("button", { type: "button", className: "sf-btn", onClick: accept, children: "OK" })] })) : (jsxs("select", { className: "sf-input", value: value, onChange: (e) => (e.target.value === NEW_FOLDER ? setCreating(true) : onChange(e.target.value)), children: [jsx("option", { value: "", children: "/ (top level)" }), options.map((d) => (jsxs("option", { value: d, children: [d, "/"] }, d))), jsx("option", { value: NEW_FOLDER, children: "+ Create new directory\u2026" })] }))] }));
361
130
  }
362
131
 
363
- const API_BASE = '/api/secure-files';
364
- /** Generic PATCH helper for file-level admin settings. */
365
- async function patchFileSetting(fileId, field, value) {
366
- const res = await fetch(`${API_BASE}/files/${fileId}/settings/${field}`, {
367
- method: 'PATCH',
368
- credentials: 'include',
369
- headers: { 'Content-Type': 'application/json' },
370
- body: JSON.stringify({ value }),
371
- });
372
- if (!res.ok) {
373
- const err = await res.json().catch(() => ({}));
374
- throw new Error(err.error || res.statusText);
375
- }
376
- return (await res.json());
132
+ function readEntries(reader) {
133
+ return new Promise((resolve, reject) => reader.readEntries(resolve, reject));
377
134
  }
378
-
379
- /** File-upload helper (used by non-React fallback pages). */
380
- async function uploadFile(file, subdir) {
381
- const fileInput = file || document.getElementById('file-browser');
382
- const subdirInput = subdir || document.getElementById('subdir');
383
- const banner = document.getElementById('banner');
384
- if (!fileInput.files?.length) {
385
- alert('No file selected.');
386
- return;
135
+ async function walkEntry(entry, prefix, out) {
136
+ if (entry.isFile) {
137
+ const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
138
+ out.push({ file, relPath: prefix + file.name });
387
139
  }
388
- const f = fileInput.files[0];
389
- const dir = (subdirInput?.value ?? '').trim();
390
- const relPath = dir ? `${dir}/${f.name}` : f.name;
391
- try {
392
- const json = await cookieUpload(f, relPath);
393
- if (banner)
394
- banner.textContent = `Uploaded: ${json.filepath}`;
395
- fileInput.value = '';
396
- if (subdirInput)
397
- subdirInput.value = '';
398
- window.location.reload();
399
- }
400
- catch (err) {
401
- console.error('Upload failed', err);
402
- }
403
- }
404
-
405
- async function uploadFiles(file, subdir = '') {
406
- if (!(file instanceof File))
407
- throw new Error('Invalid file: must be a File object.');
408
- if (typeof subdir !== 'string')
409
- throw new Error('Invalid subdir: must be a string.');
410
- const relPath = subdir.trim() ? `${subdir.trim()}/${file.name}` : file.name;
411
- const json = await cookieUpload(file, relPath);
412
- if (!json?.filepath)
413
- throw new Error('Server response missing filepath.');
414
- return { filepath: json.filepath };
415
- }
416
-
417
- async function removeFile(item) {
418
- const resp = await cookieFetch("remove", { id: item.id }, "POST");
419
- if (!resp || resp === false || resp?.result === false) {
420
- throw new Error(`Could not delete "${item.filename ?? item.id}"`);
140
+ else if (entry.isDirectory) {
141
+ const reader = entry.createReader();
142
+ let batch;
143
+ do {
144
+ batch = await readEntries(reader);
145
+ for (const child of batch)
146
+ await walkEntry(child, `${prefix}${entry.name}/`, out);
147
+ } while (batch.length > 0);
421
148
  }
422
149
  }
423
-
424
- /** Bulk download: pass a NodeList or array of checkboxes. */
425
- async function removeSelected(checkboxes) {
426
- const list = Array.from(checkboxes);
427
- if (!list.length) {
428
- alert("No files selected.");
429
- return;
150
+ async function filesFromDrop(dt) {
151
+ const out = [];
152
+ const entries = Array.from(dt.items || [])
153
+ .map((item) => item.webkitGetAsEntry?.())
154
+ .filter(Boolean);
155
+ if (entries.length) {
156
+ for (const entry of entries)
157
+ await walkEntry(entry, "", out);
430
158
  }
431
- for (const cb of list) {
432
- alert(cb);
433
- await removeFile(cb);
159
+ else {
160
+ for (const file of Array.from(dt.files))
161
+ out.push({ file, relPath: file.name });
434
162
  }
163
+ return out;
435
164
  }
436
-
437
- /** Given a checkbox inside a table-row → download that row’s file. */
438
- async function removeRow(cb) {
439
- const row = cb.closest("tr");
440
- alertit(row);
441
- if (row && row?.id)
442
- await removeFile(row);
443
- }
444
-
445
- async function listFiles(setFiles = null) {
446
- const result = await cookieFetch("list", undefined, "GET");
447
- const apiRows = Array.isArray(result)
448
- ? result
449
- : (result?.result ?? []);
450
- const rows = apiRows.map((r) => ({
451
- id: r.id,
452
- filename: r.filename,
453
- uploader_id: r.uploader_id,
454
- filepath: r.filepath,
455
- created_at: r.created_at,
456
- download_count: r.download_count,
457
- download_limit: r.download_limit,
458
- shareable: Boolean(r.shareable),
459
- needsPassword: !!r.share_password,
460
- share_password: r.share_password,
461
- password_str: r.password_str,
462
- }));
463
- if (setFiles)
464
- setFiles(rows);
465
- return rows;
165
+ function joinTarget(target, relPath) {
166
+ const clean = target.trim().replace(/^\/+|\/+$/g, "");
167
+ return clean ? `${clean}/${relPath}` : relPath;
466
168
  }
467
-
468
- /**
469
- * Toggle sharing on a file.
470
- * Sends the updated settings to /api/secure-files/files/share.
471
- * Does NOT update local state – the caller is responsible for that.
472
- */
473
- async function toggleShare(file) {
474
- const updated = { ...file, shareable: !file.shareable };
475
- if (!updated.shareable)
476
- updated.needsPassword = false;
477
- await cookieFetch("files/share", {
478
- id: updated.id,
479
- shareable: updated.shareable,
480
- share_password: updated.share_password ?? null,
481
- password_str: updated.password_str ?? null,
482
- download_limit: updated.download_limit ?? null,
483
- }, "POST");
169
+ function CloudIcon() {
170
+ return (jsx("svg", { className: "sf-drop__icon", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.5, "aria-hidden": "true", children: jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" }) }));
484
171
  }
485
-
486
- const useLoadFiles = (setLoading, setError, setFiles) => {
487
- return useCallback(async () => {
488
- setLoading(true);
489
- setError(null);
490
- try {
491
- const result = await cookieFetch("list", undefined, "GET");
492
- const apiRows = Array.isArray(result)
493
- ? result
494
- : (result?.result ?? []);
495
- setFiles(apiRows.map((r) => ({
496
- id: r.id,
497
- filename: r.filename,
498
- uploader_id: r.uploader_id,
499
- filepath: r.filepath,
500
- created_at: r.created_at,
501
- download_count: r.download_count,
502
- download_limit: r.download_limit,
503
- shareable: Boolean(r.shareable),
504
- needsPassword: !!r.share_password,
505
- share_password: r.share_password,
506
- password_str: r.password_str,
507
- })));
508
- }
509
- catch (err) {
510
- setError(err instanceof Error ? err : new Error('Failed to load files'));
511
- }
512
- finally {
513
- setLoading(false);
172
+ function UploadPanel({ api, folders, onUploaded, }) {
173
+ const [queue, setQueue] = useState([]);
174
+ const [mode, setMode] = useState("files");
175
+ const [target, setTarget] = useState("");
176
+ const [dragging, setDragging] = useState(false);
177
+ const [busy, setBusy] = useState(false);
178
+ const [message, setMessage] = useState(null);
179
+ const fileInput = useRef(null);
180
+ const folderInput = useRef(null);
181
+ const enqueue = (items) => {
182
+ setMessage(null);
183
+ setQueue((q) => {
184
+ const kept = q.filter((x) => !x.done);
185
+ const seen = new Set(kept.map((x) => x.relPath));
186
+ return [...kept, ...items.filter((i) => !seen.has(i.relPath)).map((i) => ({ ...i, progress: 0 }))];
187
+ });
188
+ };
189
+ const openPicker = () => (mode === "folder" ? folderInput : fileInput).current?.click();
190
+ const fromInput = (e) => {
191
+ const files = Array.from(e.target.files || []);
192
+ enqueue(files.map((file) => ({ file, relPath: file.webkitRelativePath || file.name })));
193
+ e.target.value = "";
194
+ };
195
+ const uploadAll = async () => {
196
+ setBusy(true);
197
+ setMessage(null);
198
+ let failed = 0;
199
+ for (let i = 0; i < queue.length; i++) {
200
+ const item = queue[i];
201
+ if (item.done)
202
+ continue;
203
+ const set = (patch) => setQueue((q) => q.map((x, idx) => (idx === i ? { ...x, ...patch } : x)));
204
+ try {
205
+ await api.upload(item.file, joinTarget(target, item.relPath), (p) => set({ progress: p }));
206
+ set({ progress: 1, done: true, error: undefined });
207
+ }
208
+ catch (err) {
209
+ failed++;
210
+ set({ error: err instanceof Error ? err.message : String(err) });
211
+ }
514
212
  }
515
- }, [setLoading, setError, setFiles]);
516
- };
517
-
518
- const useToggleShare = (setFiles) => {
519
- return useCallback(async (file) => {
520
- const updated = { ...file, shareable: !file.shareable };
521
- if (!updated.shareable)
522
- updated.needsPassword = false;
213
+ setBusy(false);
214
+ setMessage(failed ? `${failed} upload(s) failed` : "Upload complete");
215
+ if (!failed)
216
+ setQueue([]);
217
+ onUploaded();
218
+ };
219
+ const pending = queue.filter((q) => !q.done);
220
+ return (jsxs("section", { className: "sf-upload", children: [jsxs("div", { className: "sf-row sf-mode", role: "radiogroup", "aria-label": "Choose what clicking the upload area picks", children: [jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "radio", checked: mode === "files", onChange: () => setMode("files") }), " Files"] }), jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "radio", checked: mode === "folder", onChange: () => setMode("folder") }), " Folder"] }), jsx("span", { className: "sf-muted", children: "(drag-and-drop accepts either)" })] }), jsxs("div", { className: `sf-drop${dragging ? " sf-drop--active" : ""}`, role: "button", tabIndex: 0, "aria-label": `Upload area: click to choose ${mode === "folder" ? "a folder" : "files"}, or drop files or folders`, onClick: openPicker, onKeyDown: (e) => {
221
+ if (e.key === "Enter" || e.key === " ") {
222
+ e.preventDefault();
223
+ openPicker();
224
+ }
225
+ }, onDragEnter: (e) => {
226
+ e.preventDefault();
227
+ setDragging(true);
228
+ }, onDragOver: (e) => e.preventDefault(), onDragLeave: (e) => {
229
+ if (!e.currentTarget.contains(e.relatedTarget))
230
+ setDragging(false);
231
+ }, onDrop: async (e) => {
232
+ e.preventDefault();
233
+ setDragging(false);
234
+ enqueue(await filesFromDrop(e.dataTransfer));
235
+ }, children: [jsx(CloudIcon, {}), jsxs("div", { children: [jsx("p", { className: "sf-drop__title", children: "Drag & drop files or folders here" }), jsxs("p", { className: "sf-muted", children: ["Click anywhere to choose ", mode === "folder" ? "a folder" : "files"] }), pending.length > 0 && (jsxs("p", { className: "sf-drop__count", children: [pending.length, " item", pending.length === 1 ? "" : "s", " queued"] }))] })] }), jsx("input", { ref: fileInput, type: "file", multiple: true, hidden: true, onChange: fromInput }), jsx("input", { ref: folderInput, type: "file", multiple: true, hidden: true, onChange: fromInput, ...{ webkitdirectory: "", directory: "" } }), jsxs("div", { className: "sf-row", children: [jsx(FolderSelect, { label: "Upload into", folders: folders, value: target, onChange: setTarget }), jsx("button", { type: "button", className: "sf-btn sf-btn--primary", disabled: busy || !pending.length, onClick: uploadAll, children: busy ? "Uploading…" : `Upload ${pending.length}` }), queue.length > 0 && !busy && (jsx("button", { type: "button", className: "sf-btn", onClick: () => setQueue([]), children: "Clear" }))] }), message && (jsx("p", { className: message.includes("failed") ? "sf-error" : "sf-muted", role: "status", children: message })), queue.length > 0 && (jsx("ul", { className: "sf-queue", children: queue.map((q, i) => (jsxs("li", { children: [jsx("span", { className: "sf-queue__name", children: joinTarget(target, q.relPath) }), q.error ? (jsx("span", { className: "sf-error", children: q.error })) : (jsxs("span", { className: "sf-row", children: [jsx("progress", { max: 1, value: q.progress }), jsxs("span", { className: "sf-muted", children: [Math.round(q.progress * 100), "%"] })] }))] }, `${q.relPath}-${i}`))) }))] }));
236
+ }
237
+
238
+ function CopyButton({ text, label = "Copy link" }) {
239
+ const [copied, setCopied] = useState(false);
240
+ const copy = async () => {
523
241
  try {
524
- await cookieFetch("files/share", {
525
- id: updated.id,
526
- shareable: updated.shareable,
527
- share_password: updated.share_password ?? null,
528
- password_str: updated.password_str ?? null,
529
- download_limit: updated.download_limit ?? null,
530
- }, "POST");
531
- setFiles(curr => curr.map(f => f.id === file.id ? updated : f));
242
+ await navigator.clipboard.writeText(text);
532
243
  }
533
- catch (err) {
534
- console.error('Failed to toggle share:', err);
244
+ catch {
245
+ const ta = document.createElement("textarea");
246
+ ta.value = text;
247
+ document.body.appendChild(ta);
248
+ ta.select();
249
+ document.execCommand("copy");
250
+ ta.remove();
535
251
  }
536
- }, [setFiles]);
537
- };
252
+ setCopied(true);
253
+ setTimeout(() => setCopied(false), 1500);
254
+ };
255
+ return (jsx("button", { type: "button", className: "sf-btn", onClick: copy, children: copied ? "Copied" : label }));
256
+ }
538
257
 
539
- const usePatchShareSettings = (setFiles) => {
540
- return useCallback(async (file) => {
541
- const body = {
542
- id: file.id,
543
- shareable: file.shareable,
544
- share_password: file.share_password ?? null,
545
- password_str: file.password_str ?? null,
546
- download_limit: file.download_limit ?? null,
547
- };
258
+ function ShareDialog({ file, onClose, onSave, }) {
259
+ const [shareable, setShareable] = useState(file.shareable);
260
+ const [limit, setLimit] = useState(file.download_limit ? String(file.download_limit) : "");
261
+ const [pwMode, setPwMode] = useState(file.has_password ? "keep" : "remove");
262
+ const [password, setPassword] = useState("");
263
+ const [resetCount, setResetCount] = useState(false);
264
+ const [saving, setSaving] = useState(false);
265
+ const [error, setError] = useState(null);
266
+ useEffect(() => {
267
+ const onKey = (e) => e.key === "Escape" && onClose();
268
+ window.addEventListener("keydown", onKey);
269
+ return () => window.removeEventListener("keydown", onKey);
270
+ }, [onClose]);
271
+ const limitValid = limit === "" || /^\d+$/.test(limit);
272
+ const passwordValid = pwMode !== "set" || password.length > 0;
273
+ const save = async () => {
274
+ setSaving(true);
275
+ setError(null);
548
276
  try {
549
- await cookieFetch("files/share", body, "POST");
550
- setFiles(curr => curr.map(f => f.id === body.id ? { ...f, ...body } : f));
277
+ const update = { id: file.id, shareable };
278
+ if (shareable) {
279
+ update.download_limit = limit === "" ? null : Number(limit);
280
+ if (pwMode === "set")
281
+ update.password = password;
282
+ else if (pwMode === "remove" && file.has_password)
283
+ update.password = "";
284
+ if (resetCount)
285
+ update.reset_count = true;
286
+ }
287
+ await onSave(update);
288
+ onClose();
551
289
  }
552
290
  catch (err) {
553
- console.error('Failed to update share settings:', err);
291
+ setError(err instanceof Error ? err.message : String(err));
554
292
  }
555
- }, [setFiles]);
556
- };
557
-
558
- /**
559
- * Hook alias used by useFiles.ts. Patches share settings via the session-cookie
560
- * authenticated /files/share endpoint.
561
- */
562
- const useSaveShareSettings = (setFiles) => {
563
- return useCallback(async (file) => {
564
- const body = {
565
- id: file.id,
566
- shareable: file.shareable,
567
- share_password: file.share_password ?? null,
568
- password_str: file.password_str ?? null,
569
- download_limit: file.download_limit ?? null,
570
- };
571
- try {
572
- await cookieFetch("files/share", body, "POST");
573
- setFiles(curr => curr.map(f => f.id === body.id ? { ...f, ...body } : f));
574
- }
575
- catch (err) {
576
- console.error('Failed to save share settings:', err);
293
+ finally {
294
+ setSaving(false);
577
295
  }
578
- }, [setFiles]);
579
- };
296
+ };
297
+ return (jsx("div", { className: "sf-overlay", onMouseDown: (e) => e.target === e.currentTarget && onClose(), children: jsxs("div", { className: "sf-dialog", role: "dialog", "aria-modal": "true", "aria-label": `Share settings for ${file.filename}`, children: [jsxs("header", { className: "sf-dialog__head", children: [jsx("h3", { children: "Share settings" }), jsx("button", { type: "button", className: "sf-icon-btn", "aria-label": "Close", onClick: onClose, children: "\u2715" })] }), jsx("p", { className: "sf-muted", children: file.filepath }), jsxs("label", { className: "sf-check", children: [jsx("input", { type: "checkbox", checked: shareable, onChange: (e) => setShareable(e.target.checked) }), "Anyone with the link can download"] }), jsxs("fieldset", { disabled: !shareable, className: "sf-fieldset", children: [jsxs("label", { className: "sf-field", children: [jsx("span", { children: "Download limit (blank = unlimited)" }), jsx("input", { className: "sf-input", inputMode: "numeric", value: limit, onChange: (e) => setLimit(e.target.value.trim()), placeholder: "unlimited" }), !limitValid && jsx("span", { className: "sf-error", children: "Enter a whole number" })] }), jsxs("p", { className: "sf-muted", children: ["Downloaded ", file.download_count, " time", file.download_count === 1 ? "" : "s", file.download_limit ? ` of ${file.download_limit}` : "", ".", " ", jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "checkbox", checked: resetCount, onChange: (e) => setResetCount(e.target.checked) }), "reset count"] })] }), jsxs("div", { className: "sf-field", children: [jsx("span", { children: "Password" }), jsxs("div", { className: "sf-row", children: [file.has_password && (jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "radio", checked: pwMode === "keep", onChange: () => setPwMode("keep") }), "keep current"] })), jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "radio", checked: pwMode === "set", onChange: () => setPwMode("set") }), file.has_password ? "change" : "require password"] }), jsxs("label", { className: "sf-check sf-check--inline", children: [jsx("input", { type: "radio", checked: pwMode === "remove", onChange: () => setPwMode("remove") }), file.has_password ? "remove" : "none"] })] }), pwMode === "set" && (jsx("input", { className: "sf-input", type: "password", autoComplete: "new-password", value: password, onChange: (e) => setPassword(e.target.value), placeholder: "New password" }))] }), jsxs("div", { className: "sf-field", children: [jsx("span", { children: "Share link" }), jsxs("div", { className: "sf-row", children: [jsx("input", { className: "sf-input", readOnly: true, value: file.share_url, onFocus: (e) => e.target.select() }), jsx(CopyButton, { text: file.share_url })] }), !file.shareable && jsx("span", { className: "sf-muted", children: "The link works once you save with sharing on." })] })] }), error && jsx("p", { className: "sf-error", children: error }), jsxs("footer", { className: "sf-row sf-dialog__foot", children: [jsx("button", { type: "button", className: "sf-btn", onClick: onClose, children: "Cancel" }), jsx("button", { type: "button", className: "sf-btn sf-btn--primary", disabled: saving || !limitValid || !passwordValid, onClick: save, children: saving ? "Saving…" : "Save" })] })] }) }));
298
+ }
580
299
 
581
- const useDeleteFile = (setFiles) => {
582
- return useCallback(async (file) => {
583
- const targets = Array.isArray(file) ? file : [file];
584
- for (const f of targets) {
585
- try {
586
- await cookieFetch("remove", { id: f.id }, "POST");
587
- setFiles(curr => curr.filter(item => item.id !== f.id));
300
+ function ConfirmButton({ label, onConfirm, disabled, }) {
301
+ const [armed, setArmed] = useState(false);
302
+ useEffect(() => {
303
+ if (!armed)
304
+ return;
305
+ const t = setTimeout(() => setArmed(false), 3000);
306
+ return () => clearTimeout(t);
307
+ }, [armed]);
308
+ return (jsx("button", { type: "button", className: `sf-btn sf-btn--danger${armed ? " sf-btn--armed" : ""}`, disabled: disabled, onClick: () => {
309
+ if (armed) {
310
+ setArmed(false);
311
+ onConfirm();
588
312
  }
589
- catch (err) {
590
- console.error(`Failed to delete "${f.filename}":`, err);
313
+ else {
314
+ setArmed(true);
591
315
  }
592
- }
593
- }, [setFiles]);
594
- };
595
-
596
- function useFiles() {
597
- const [files, setFiles] = useState([]);
598
- const [loading, setLoading] = useState(false);
599
- const [error, setError] = useState(null);
600
- const loadCallback = useLoadFiles(setLoading, setError, setFiles);
601
- const toggleShareCallback = useToggleShare(setFiles);
602
- const patchShareSettingsCallback = useSaveShareSettings(setFiles);
603
- const deleteFileCallback = useDeleteFile(setFiles);
604
- useEffect(() => {
605
- loadCallback();
606
- }, [loadCallback]);
607
- return {
608
- files,
609
- loading,
610
- error,
611
- load: loadCallback,
612
- toggleShare: toggleShareCallback,
613
- patchShareSettings: patchShareSettingsCallback,
614
- deleteFile: deleteFileCallback,
615
- setFiles,
616
- setLoading,
617
- setError,
618
- };
316
+ }, children: armed ? "Confirm" : label }));
619
317
  }
620
318
 
621
- function FileRow({ file, onDownload, onSettings, onToggleShare, onDelete, }) {
622
- const isOwner = file.uploader_id?.toLowerCase() === (currentUsername() ?? '').toLowerCase();
623
- const downloadAllowed = isOwner || file.shareable;
624
- const [isDownloading, setIsDownloading] = useState(false);
625
- const [isTogglingShare, setIsTogglingShare] = useState(false);
626
- const [isDeleting, setIsDeleting] = useState(false);
627
- // Mimic WindowManagerApp's unsaved heuristic
628
- const looksUnsaved = file.filename.toLowerCase().startsWith('untitled') ||
629
- file.filename.includes('*');
630
- const handleDownload = async () => {
631
- setIsDownloading(true);
319
+ function formatSize(bytes) {
320
+ const units = ["B", "KB", "MB", "GB", "TB"];
321
+ let n = bytes;
322
+ let i = 0;
323
+ while (n >= 1024 && i < units.length - 1) {
324
+ n /= 1024;
325
+ i++;
326
+ }
327
+ return `${n.toFixed(i ? 1 : 0)} ${units[i]}`;
328
+ }
329
+ const errText = (err) => (err instanceof Error ? err.message : String(err));
330
+ function AddRoot({ api, onAdded }) {
331
+ const [path, setPath] = useState("");
332
+ const [label, setLabel] = useState("");
333
+ const [challenge, setChallenge] = useState(null);
334
+ const [signature, setSignature] = useState("");
335
+ const [error, setError] = useState(null);
336
+ const [busy, setBusy] = useState(false);
337
+ const request = async () => {
338
+ setBusy(true);
339
+ setError(null);
632
340
  try {
633
- await onDownload();
634
- }
635
- finally {
636
- setIsDownloading(false);
341
+ setChallenge((await api.requestRoot(path.trim())).challenge);
342
+ setSignature("");
637
343
  }
638
- };
639
- const handleToggleShare = async () => {
640
- setIsTogglingShare(true);
641
- try {
642
- await onToggleShare();
344
+ catch (err) {
345
+ setError(errText(err));
643
346
  }
644
347
  finally {
645
- setIsTogglingShare(false);
348
+ setBusy(false);
646
349
  }
647
350
  };
648
- const handleDeleteFile = async () => {
649
- setIsDeleting(true);
351
+ const confirm = async () => {
352
+ if (!challenge)
353
+ return;
354
+ setBusy(true);
355
+ setError(null);
650
356
  try {
651
- await onDelete();
357
+ onAdded((await api.confirmRoot(challenge.nonce, signature, label)).roots);
358
+ setChallenge(null);
359
+ setPath("");
360
+ setLabel("");
361
+ setSignature("");
362
+ }
363
+ catch (err) {
364
+ setError(errText(err));
652
365
  }
653
366
  finally {
654
- setIsDeleting(false);
367
+ setBusy(false);
655
368
  }
656
369
  };
657
- return (jsxs("tr", { className: "wm-row transition-colors duration-75", children: [jsx("td", { className: "wm-cell w-12 align-middle", children: jsx("input", { type: "checkbox", className: "wm-checkbox", "aria-label": `Select ${file.filename}` }) }), jsx("td", { className: `wm-cell ${looksUnsaved ? 'unsaved' : ''}`, children: file.filename }), jsx("td", { className: "wm-cell w-12 align-middle", children: downloadAllowed ? (jsx(Button, { color: "blue", variant: "secondary", onClick: handleDownload, disabled: isDownloading, "aria-label": `Download ${file.filename}`, className: "wm-btn-link", children: isDownloading ? 'Downloading...' : 'Download' })) : (jsx("span", { className: "text-gray-500 text-lg", "aria-label": "Download restricted", children: "\uD83D\uDD12" })) }), jsx("td", { className: "wm-cell w-12 align-middle", children: isOwner && (jsx(Button, { color: "gray", variant: "icon", onClick: () => {
658
- console.log('⚙︎ clicked', file.id);
659
- onSettings();
660
- }, "aria-label": "Open share settings", className: "wm-btn-icon text-lg", children: "\u2699\uFE0F" })) }), jsx("td", { className: "wm-cell w-12 align-middle", children: isOwner && (jsx(Button, { color: file.shareable ? 'blue' : 'gray', variant: file.shareable ? 'primary' : 'secondary', onClick: handleToggleShare, disabled: isTogglingShare, className: "btn", children: isTogglingShare
661
- ? 'Toggling...'
662
- : file.shareable
663
- ? 'Sharing'
664
- : 'Share' })) }), jsx("td", { className: "wm-cell w-12 align-middle", children: isOwner && (jsx(Button, { color: "gray", variant: "icon", onClick: handleDeleteFile, disabled: isDeleting, className: "wm-btn-icon text-lg", children: "\uD83D\uDDD1" })) }), jsxs("td", { className: "wm-cell", children: [file.download_count, " / ", file.download_limit ?? "∞"] })] }));
370
+ const minutesLeft = challenge ? Math.max(0, Math.round((challenge.expires * 1000 - Date.now()) / 60000)) : 0;
371
+ return (jsxs("div", { className: "sf-card", children: [jsx("h4", { children: "Allow a directory" }), !challenge ? (jsxs("div", { className: "sf-row sf-row--bottom", children: [jsxs("label", { className: "sf-field", children: [jsx("span", { children: "Absolute path on the server" }), jsx("input", { className: "sf-input", value: path, onChange: (e) => setPath(e.target.value), placeholder: "/srv/shared/docs", onKeyDown: (e) => e.key === "Enter" && path.trim() && request() })] }), jsxs("label", { className: "sf-field sf-field--narrow", children: [jsx("span", { children: "Label (optional)" }), jsx("input", { className: "sf-input", value: label, onChange: (e) => setLabel(e.target.value) })] }), jsx("button", { type: "button", className: "sf-btn sf-btn--primary", disabled: busy || !path.trim(), onClick: request, children: "Request" })] })) : (jsxs("div", { className: "sf-stack", children: [jsxs("p", { children: ["Allowing ", jsx("code", { children: challenge.message.split("|")[3] }), " requires a signature from a trusted SSH key. Run this where that key lives (expires in about ", minutesLeft, " min):"] }), jsxs("div", { className: "sf-row", children: [jsx("textarea", { className: "sf-input sf-code", readOnly: true, rows: 3, value: challenge.command }), jsx(CopyButton, { text: challenge.command, label: "Copy command" })] }), jsxs("label", { className: "sf-field", children: [jsx("span", { children: "Paste the full output (BEGIN \u2026 END SSH SIGNATURE)" }), jsx("textarea", { className: "sf-input sf-code", rows: 6, value: signature, onChange: (e) => setSignature(e.target.value), placeholder: "-----BEGIN SSH SIGNATURE-----" })] }), jsxs("div", { className: "sf-row", children: [jsx("button", { type: "button", className: "sf-btn sf-btn--primary", disabled: busy || !signature.includes("END SSH SIGNATURE"), onClick: confirm, children: "Verify & allow" }), jsx("button", { type: "button", className: "sf-btn", onClick: () => setChallenge(null), children: "Cancel" })] })] })), error && jsx("p", { className: "sf-error", children: error })] }));
665
372
  }
666
-
667
- function ShareModal({ file, onClose, onSave }) {
668
- const [fileId, setFileId] = useState("");
669
- const [enabled, setEnabled] = useState(false);
670
- const [password, setPassword] = useState(undefined);
671
- const [strPassword, setStrPassword] = useState("");
672
- const [download_limit, setDownloadLimit] = useState(0);
673
- const [error, setError] = useState("");
373
+ function Browser({ api, roots, folders, onLinked, }) {
374
+ const [listing, setListing] = useState(null);
375
+ const [picked, setPicked] = useState(new Set());
376
+ const [target, setTarget] = useState("");
377
+ const [error, setError] = useState(null);
378
+ const [result, setResult] = useState(null);
674
379
  const [busy, setBusy] = useState(false);
675
- const modalRef = useRef(null);
676
- const shareLink = file && enabled
677
- ? `/api/secure-files/secure-download/${file.id}`
678
- : "";
679
- useEffect(() => {
680
- if (!file)
681
- return;
682
- setFileId(file.id);
683
- setEnabled(file.shareable);
684
- setPassword(file.share_password);
685
- setStrPassword(file.password_str ?? "");
686
- setDownloadLimit(file.download_limit ?? 0);
687
- setError("");
688
- modalRef.current?.focus();
689
- }, [file]);
690
- useEffect(() => {
691
- const h = (e) => e.key === "Escape" && onClose();
692
- window.addEventListener("keydown", h);
693
- return () => window.removeEventListener("keydown", h);
694
- }, [onClose]);
695
- if (!file)
696
- return null;
697
- async function handleSave() {
698
- if (strPassword && strPassword.length < 4) {
699
- setError("Password must be at least 4 characters");
700
- return;
380
+ const open = useCallback(async (path) => {
381
+ setError(null);
382
+ try {
383
+ setListing(await api.browse(path));
384
+ setPicked(new Set());
385
+ }
386
+ catch (err) {
387
+ setError(errText(err));
701
388
  }
389
+ }, [api]);
390
+ useEffect(() => {
391
+ if (!listing && roots.length)
392
+ open(roots[0].path);
393
+ if (listing && !roots.some((r) => listing.path.startsWith(r.path)))
394
+ setListing(null);
395
+ }, [roots, listing, open]);
396
+ const link = async () => {
702
397
  setBusy(true);
703
- const save_dict = {
704
- id: fileId,
705
- shareable: enabled,
706
- needsPassword: !!strPassword,
707
- share_password: strPassword || null,
708
- password_str: strPassword || null,
709
- download_limit: download_limit === "" ? null : Number(download_limit),
710
- };
398
+ setResult(null);
711
399
  try {
712
- const resp = await onSave(save_dict);
713
- onClose();
400
+ const res = await api.link([...picked], target);
401
+ const parts = [`Linked ${res.linked.length} file(s)`];
402
+ if (res.errors.length)
403
+ parts.push(`${res.errors.length} skipped: ${res.errors.map((e) => e.error).join("; ")}`);
404
+ setResult(parts.join(". "));
405
+ onLinked();
406
+ if (listing)
407
+ await open(listing.path);
714
408
  }
715
409
  catch (err) {
716
- setError(`${err} Failed to save settings. Please try again.`);
410
+ setResult(errText(err));
717
411
  }
718
412
  finally {
719
413
  setBusy(false);
720
414
  }
415
+ };
416
+ if (!roots.length)
417
+ return jsx("p", { className: "sf-muted", children: "Allow a directory above to browse and link its files." });
418
+ const linkable = listing?.files.filter((f) => !f.linked_id) ?? [];
419
+ const relative = listing ? listing.path.slice(listing.root.length) || "/" : "";
420
+ return (jsxs("div", { className: "sf-card", children: [jsx("h4", { children: "Link files" }), jsxs("div", { className: "sf-row", children: [jsx("select", { className: "sf-input sf-root-select", value: listing?.root ?? "", onChange: (e) => open(e.target.value), children: roots.map((r) => (jsx("option", { value: r.path, children: r.label ? `${r.label} (${r.path})` : r.path }, r.id))) }), listing && jsx("code", { className: "sf-muted", children: relative })] }), error && jsx("p", { className: "sf-error", children: error }), listing && (jsxs("div", { className: "sf-browser", children: [listing.parent && (jsx("button", { type: "button", className: "sf-browser__dir", onClick: () => open(listing.parent), children: "\u21A9 .." })), listing.dirs.map((d) => (jsxs("button", { type: "button", className: "sf-browser__dir", onClick: () => open(`${listing.path}/${d}`), children: ["\uD83D\uDCC1 ", d] }, d))), listing.files.length > 0 && (jsxs("label", { className: "sf-check sf-browser__all", children: [jsx("input", { type: "checkbox", checked: linkable.length > 0 && linkable.every((f) => picked.has(f.path)), disabled: !linkable.length, onChange: (e) => setPicked(e.target.checked ? new Set(linkable.map((f) => f.path)) : new Set()) }), "Select all files here"] })), listing.files.map((f) => (jsxs("label", { className: `sf-check sf-browser__file${f.linked_id ? " sf-muted" : ""}`, children: [jsx("input", { type: "checkbox", disabled: !!f.linked_id, checked: picked.has(f.path), onChange: (e) => setPicked((p) => {
421
+ const next = new Set(p);
422
+ e.target.checked ? next.add(f.path) : next.delete(f.path);
423
+ return next;
424
+ }) }), jsx("span", { className: "sf-browser__name", children: f.name }), jsx("span", { className: "sf-muted", children: f.linked_id ? "already linked" : formatSize(f.size) })] }, f.path))), !listing.dirs.length && !listing.files.length && jsx("p", { className: "sf-muted", children: "Empty directory" }), listing.truncated && jsx("p", { className: "sf-muted", children: "Showing the first 5000 entries." })] })), jsxs("div", { className: "sf-row sf-row--bottom", children: [jsx(FolderSelect, { label: "Show in Secure Files under", folders: folders, value: target, onChange: setTarget }), jsx("button", { type: "button", className: "sf-btn sf-btn--primary", disabled: busy || !picked.size, onClick: link, children: busy ? "Linking…" : `Link ${picked.size || ""}`.trim() })] }), result && jsx("p", { className: result.includes("skipped") ? "sf-error" : "sf-muted", children: result })] }));
425
+ }
426
+ function ServerFiles({ api, folders, onLinked, }) {
427
+ const [roots, setRoots] = useState(null);
428
+ const [error, setError] = useState(null);
429
+ const load = useCallback(async () => {
430
+ try {
431
+ setRoots((await api.roots()).roots);
432
+ setError(null);
433
+ }
434
+ catch (err) {
435
+ setError(errText(err));
436
+ }
437
+ }, [api]);
438
+ return (jsxs("details", { className: "sf-admin", onToggle: (e) => e.currentTarget.open && !roots && load(), children: [jsx("summary", { children: "Server files (admin)" }), jsxs("div", { className: "sf-stack", children: [jsx("p", { className: "sf-muted", children: "Link files that already live on the server instead of uploading copies. Only files inside allowed directories can be linked; removing a directory immediately disables its links. Deleting a linked entry never touches the original file. Available from the local network only." }), error && jsx("p", { className: "sf-error", children: error }), roots && (jsxs(Fragment, { children: [jsxs("div", { className: "sf-card", children: [jsx("h4", { children: "Allowed directories" }), roots.length === 0 ? (jsx("p", { className: "sf-muted", children: "None yet." })) : (jsx("ul", { className: "sf-roots", children: roots.map((r) => (jsxs("li", { children: [jsxs("span", { children: [jsx("code", { children: r.path }), " ", r.label && jsxs("span", { className: "sf-muted", children: ["\u2014 ", r.label] }), !r.exists && jsx("span", { className: "sf-error", children: " (missing)" })] }), jsx(ConfirmButton, { label: "Remove", onConfirm: async () => {
439
+ try {
440
+ setRoots((await api.removeRoot(r.id)).roots);
441
+ onLinked();
442
+ }
443
+ catch (err) {
444
+ setError(errText(err));
445
+ }
446
+ } })] }, r.id))) }))] }), jsx(AddRoot, { api: api, onAdded: setRoots }), jsx(Browser, { api: api, roots: roots, folders: folders, onLinked: onLinked })] }))] })] }));
447
+ }
448
+
449
+ function styleInject(css, ref) {
450
+ if ( ref === void 0 ) ref = {};
451
+ var insertAt = ref.insertAt;
452
+
453
+ if (typeof document === 'undefined') { return; }
454
+
455
+ var head = document.head || document.getElementsByTagName('head')[0];
456
+ var style = document.createElement('style');
457
+ style.type = 'text/css';
458
+
459
+ if (insertAt === 'top') {
460
+ if (head.firstChild) {
461
+ head.insertBefore(style, head.firstChild);
462
+ } else {
463
+ head.appendChild(style);
721
464
  }
722
- return createPortal(jsxs(Fragment, { children: [jsx("div", { className: "modal-backdrop z-100", onClick: (e) => e.target === e.currentTarget && onClose() }), jsx("div", { className: "modal-wrapper z-110", children: jsxs("div", { ref: modalRef, role: "dialog", "aria-modal": "true", tabIndex: -1, className: "modal-panel", children: [jsxs("h3", { className: "form-title", children: ["Share settings for ", jsx("span", { className: "font-mono", children: file.filename })] }), error && jsx("p", { className: "form-error", children: error }), jsx(Checkbox, { label: "Enable sharing", checked: enabled, onChange: (e) => setEnabled(e.target.checked), className: "checkbox" }), jsx(Input, { label: "Password (optional)", type: "text", value: strPassword, onChange: (e) => setStrPassword(e.target.value), disabled: !enabled, className: "form-input" }), jsx(Input, { label: "Download limit (0 = \u221E)", type: "number", min: 0, value: download_limit, onChange: (e) => setDownloadLimit(e.target.value === "" ? "" : Number(e.target.value)), disabled: !enabled, className: "form-input" }), enabled && shareLink && (jsx(Input, { label: "Share link", readOnly: true, value: shareLink, className: "form-input", trailing: jsx(Button, { variant: "icon", className: "btn-icon", onClick: () => navigator.clipboard.writeText(shareLink), children: jsx(ForwardRef$1, { className: "h-5 w-5" }) }) })), jsxs("div", { className: "mt-6 flex justify-end gap-2", children: [jsx(Button, { color: "green", variant: "primary", onClick: handleSave, disabled: busy, className: "btn-primary", children: busy ? "Saving…" : "Save" }), jsx(Button, { variant: "secondary", onClick: onClose, disabled: busy, className: "btn-secondary", children: "Cancel" })] })] }) })] }), document.body);
465
+ } else {
466
+ head.appendChild(style);
467
+ }
468
+
469
+ if (style.styleSheet) {
470
+ style.styleSheet.cssText = css;
471
+ } else {
472
+ style.appendChild(document.createTextNode(css));
473
+ }
723
474
  }
724
475
 
725
- // Build a directory tree from a flat file list
476
+ var css_248z = ".sf-root{--sf-border:color-mix(in srgb,currentColor 22%,transparent);--sf-subtle:color-mix(in srgb,currentColor 6%,transparent);--sf-accent:#2563eb;--sf-danger:#dc2626;display:flex;flex-direction:column;font-size:14px;gap:16px;margin:0 auto;max-width:1100px;padding:16px;text-align:left}.sf-root *,.sf-root :after,.sf-root :before{box-sizing:border-box}.sf-head{align-items:baseline;display:flex;gap:12px;justify-content:space-between}.sf-head h2{font-size:1.4em;margin:0}.sf-muted{opacity:.7}.sf-error{color:var(--sf-danger)}.sf-row{align-items:center;display:flex;flex-wrap:wrap;gap:8px}.sf-row--end{justify-content:flex-end}.sf-field{display:flex;flex:1;flex-direction:column;gap:4px;min-width:200px}.sf-input{background:var(--sf-subtle);border:1px solid var(--sf-border);border-radius:6px;color:inherit;font:inherit;min-width:0;padding:6px 10px;width:100%}.sf-row .sf-input{flex:1;width:auto}.sf-btn{background:var(--sf-subtle);border:1px solid var(--sf-border);border-radius:6px;color:inherit;cursor:pointer;font:inherit;padding:5px 12px;white-space:nowrap}.sf-btn:hover:not(:disabled){border-color:var(--sf-accent)}.sf-btn:disabled{cursor:default;opacity:.45}.sf-btn--primary{background:var(--sf-accent);border-color:var(--sf-accent);color:#fff}.sf-btn--armed,.sf-btn--danger:hover:not(:disabled){border-color:var(--sf-danger);color:var(--sf-danger)}.sf-btn--armed{background:color-mix(in srgb,var(--sf-danger) 12%,transparent)}.sf-icon-btn{background:none;border:1px solid transparent;border-radius:6px;color:inherit;cursor:pointer;font:inherit;padding:3px 6px}.sf-icon-btn:hover{border-color:var(--sf-border)}.sf-upload{display:flex;flex-direction:column;gap:10px}.sf-drop{align-items:center;border:2px dashed var(--sf-border);border-radius:12px;cursor:pointer;display:flex;gap:20px;padding:28px 24px;transition:border-color .15s,background .15s,box-shadow .15s;-webkit-user-select:none;-moz-user-select:none;user-select:none}.sf-drop:focus-visible,.sf-drop:hover{border-color:var(--sf-accent);box-shadow:0 4px 14px color-mix(in srgb,currentColor 10%,transparent);outline:none}.sf-drop p{margin:0}.sf-drop__icon{flex-shrink:0;height:72px;opacity:.6;width:72px}.sf-drop__title{font-size:1.1em;font-weight:600;margin-bottom:4px!important}.sf-drop__count{color:var(--sf-accent);font-weight:600;margin-top:6px!important}.sf-drop--active{background:color-mix(in srgb,var(--sf-accent) 8%,transparent);border-color:var(--sf-accent)}.sf-drop--active .sf-drop__icon{color:var(--sf-accent);opacity:1}.sf-mode{gap:14px}.sf-queue progress{width:120px}.sf-upload>.sf-row{align-items:flex-end}.sf-queue{display:flex;flex-direction:column;gap:4px;list-style:none;margin:0;max-height:200px;overflow:auto;padding:0}.sf-queue li{display:flex;gap:12px;justify-content:space-between}.sf-queue__name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sf-toolbar{display:flex;flex-wrap:wrap;gap:12px;justify-content:space-between}.sf-search{max-width:320px}.sf-table-wrap{border:1px solid var(--sf-border);border-radius:8px;overflow-x:auto}.sf-table{border-collapse:collapse;width:100%}.sf-table td,.sf-table th{border-bottom:1px solid var(--sf-border);padding:8px 10px;text-align:left;vertical-align:middle}.sf-table tbody tr:last-child td{border-bottom:none}.sf-table th{background:var(--sf-subtle);font-weight:600}.sf-col-check{width:36px}.sf-col-actions{text-align:right!important}.sf-dir td{background:var(--sf-subtle)}.sf-dir__toggle{background:none;border:none;color:inherit;cursor:pointer;font:inherit;font-weight:600;padding:0}.sf-busy{opacity:.55}.sf-pill{background:var(--sf-subtle);border:1px solid var(--sf-border);border-radius:999px;color:inherit;cursor:pointer;font:inherit;font-size:12px;padding:2px 10px}.sf-pill--on{background:color-mix(in srgb,#16a34a 18%,transparent);border-color:#16a34a}.sf-overlay{align-items:center;background:rgba(0,0,0,.5);display:flex;inset:0;justify-content:center;padding:16px;position:fixed;z-index:1000}.sf-dialog{--sf-border:color-mix(in srgb,CanvasText 22%,transparent);--sf-subtle:color-mix(in srgb,CanvasText 6%,transparent);background:Canvas;border-radius:10px;color:CanvasText;display:flex;flex-direction:column;gap:12px;max-height:90vh;overflow:auto;padding:18px 20px;text-align:left;width:min(520px,100%)}.sf-dialog__head{align-items:center;display:flex;justify-content:space-between}.sf-dialog__head h3{margin:0}.sf-dialog>.sf-muted{margin:0;word-break:break-all}.sf-dialog__foot{justify-content:flex-end}.sf-fieldset{border:none;display:flex;flex-direction:column;gap:12px;margin:0;padding:0}.sf-fieldset:disabled{opacity:.5}.sf-fieldset p{margin:0}.sf-check{align-items:center;cursor:pointer;display:flex;gap:8px}.sf-check--inline{display:inline-flex}.sf-stack{display:flex;flex-direction:column;gap:12px}.sf-stack p{margin:0}.sf-row--bottom{align-items:flex-end}.sf-field--narrow{flex:0 1 200px;min-width:140px}.sf-admin{border:1px solid var(--sf-border);border-radius:10px;padding:10px 14px}.sf-admin>summary{cursor:pointer;font-weight:600}.sf-admin[open]>summary{margin-bottom:12px}.sf-card{border:1px solid var(--sf-border);border-radius:8px;display:flex;flex-direction:column;gap:10px;padding:12px}.sf-card h4,.sf-card p{margin:0}.sf-code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;resize:vertical}.sf-roots{display:flex;flex-direction:column;gap:6px;list-style:none;margin:0;padding:0}.sf-roots li{align-items:center;display:flex;gap:12px;justify-content:space-between}.sf-root-select{max-width:420px}.sf-browser{border:1px solid var(--sf-border);border-radius:6px;display:flex;flex-direction:column;max-height:320px;overflow:auto}.sf-browser>*{border-bottom:1px solid var(--sf-border);padding:5px 10px}.sf-browser>:last-child{border-bottom:none}.sf-browser__dir{background:none;border:none;border-bottom:1px solid var(--sf-border);color:inherit;cursor:pointer;font:inherit;text-align:left}.sf-browser__all,.sf-browser__dir:hover{background:var(--sf-subtle)}.sf-browser__all{font-weight:600}.sf-browser__name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sf-tag{border:1px solid var(--sf-border);border-radius:999px;display:inline-block;font-size:11px;margin-left:8px;padding:0 7px;vertical-align:middle}.sf-tag--warn{border-color:var(--sf-danger);color:var(--sf-danger)}.sf-strike{opacity:.7;text-decoration:line-through}";
477
+ styleInject(css_248z);
478
+
726
479
  function buildTree(files) {
727
- const root = { name: '', path: '', children: new Map(), files: [] };
728
- files.forEach(file => {
729
- const parts = file.filepath.split('/');
480
+ const root = { name: "", path: "", folders: new Map(), files: [] };
481
+ for (const f of files) {
482
+ const parts = f.filepath.split("/");
730
483
  let node = root;
731
- parts.slice(0, -1).forEach((seg, idx) => {
732
- const subPath = parts.slice(0, idx + 1).join('/');
733
- if (!node.children.has(seg)) {
734
- node.children.set(seg, { name: seg, path: subPath, children: new Map(), files: [] });
484
+ parts.slice(0, -1).forEach((part, i) => {
485
+ if (!node.folders.has(part)) {
486
+ node.folders.set(part, { name: part, path: parts.slice(0, i + 1).join("/"), folders: new Map(), files: [] });
735
487
  }
736
- node = node.children.get(seg);
488
+ node = node.folders.get(part);
737
489
  });
738
- node.files.push(file);
739
- });
490
+ node.files.push(f);
491
+ }
740
492
  return root;
741
493
  }
742
- // Collect all file IDs under a node (recursive)
743
- function collectNodeIds(node) {
744
- let ids = [];
745
- node.files.forEach(f => ids.push(f.id));
746
- node.children.forEach(child => {
747
- ids = ids.concat(collectNodeIds(child));
748
- });
749
- return ids;
494
+ function allFiles(node) {
495
+ return [...node.files, ...[...node.folders.values()].flatMap(allFiles)];
750
496
  }
751
- function FileTable({ files, loading, error, onToggleShare, onPatchShare, onDelete }) {
752
- const { load } = useFiles();
753
- const [search, setSearch] = useState('');
754
- const [modalFile, setModalFile] = useState(null);
497
+ function SecureFiles({ apiBase }) {
498
+ const api = useMemo(() => createApi(apiBase), [apiBase]);
499
+ const [files, setFiles] = useState([]);
500
+ const [user, setUser] = useState(null);
501
+ const [isAdmin, setIsAdmin] = useState(false);
502
+ const [loading, setLoading] = useState(true);
503
+ const [error, setError] = useState(null);
504
+ const [notice, setNotice] = useState(null);
505
+ const [search, setSearch] = useState("");
755
506
  const [selected, setSelected] = useState(new Set());
756
- const [expanded, setExpanded] = useState(new Set());
757
- // Upload controls
758
- const [uploadDir, setUploadDir] = useState('');
759
- const [uploadFile, setUploadFile] = useState(null);
760
- // Filter files by search term
761
- const filtered = useMemo(() => files.filter(f => f.filename.toLowerCase().includes(search.trim().toLowerCase())), [files, search]);
762
- // Build tree and directory paths list
763
- const tree = useMemo(() => buildTree(filtered), [filtered]);
764
- const allDirPaths = useMemo(() => {
765
- const paths = [''];
766
- function collect(node) {
767
- node.children.forEach(child => {
768
- paths.push(child.path);
769
- collect(child);
770
- });
507
+ const [collapsed, setCollapsed] = useState(new Set());
508
+ const [editing, setEditing] = useState(null);
509
+ const [busyIds, setBusyIds] = useState(new Set());
510
+ const load = useCallback(async () => {
511
+ setError(null);
512
+ try {
513
+ const data = await api.list();
514
+ setUser(data.user_name);
515
+ setIsAdmin(data.is_admin);
516
+ setFiles(data.files);
517
+ setSelected((prev) => new Set([...prev].filter((id) => data.files.some((f) => f.id === id))));
771
518
  }
772
- collect(tree);
773
- return paths;
774
- }, [tree]);
775
- // Selection & expand/collapse logic
776
- const allIds = filtered.map(f => f.id);
777
- const toggleAllSelection = () => selected.size < allIds.length ? setSelected(new Set(allIds)) : setSelected(new Set());
778
- const toggleDirOpen = (path) => setExpanded(prev => {
779
- const next = new Set(prev);
780
- next.has(path) ? next.delete(path) : next.add(path);
781
- return next;
782
- });
783
- const expandAll = () => setExpanded(new Set(allDirPaths));
784
- const collapseAll = () => setExpanded(new Set());
785
- // Recursive renderer: directory row with select-all checkbox, then its files, then subdirectories
786
- const renderNode = (node, depth = 0) => {
787
- const rows = [];
788
- if (node.path) {
789
- const isOpen = expanded.has(node.path);
790
- const nodeIds = collectNodeIds(node);
791
- const allSelected = nodeIds.every(id => selected.has(id));
792
- const someSelected = nodeIds.some(id => selected.has(id));
793
- rows.push(jsxs("tr", { children: [jsx("td", { className: "px-4 py-2 bg-gray-100", children: jsx("input", { type: "checkbox", checked: allSelected, ref: el => { if (el)
794
- el.indeterminate = !allSelected && someSelected; }, onChange: () => {
795
- setSelected(prev => {
796
- const next = new Set(prev);
797
- if (allSelected) {
798
- nodeIds.forEach(id => next.delete(id));
799
- }
800
- else {
801
- nodeIds.forEach(id => next.add(id));
802
- }
803
- return next;
804
- });
805
- } }) }), jsx("td", { className: "px-4 py-2 bg-gray-100 font-bold", colSpan: 5, style: { textAlign: 'left' }, children: node.path }), jsx("td", { className: "px-4 py-2 bg-gray-100 text-right", children: jsx("button", { onClick: () => toggleDirOpen(node.path), children: isOpen ? '▾' : '▸' }) })] }, node.path));
806
- if (!isOpen)
807
- return rows;
519
+ catch (err) {
520
+ setError(err instanceof Error ? err.message : String(err));
808
521
  }
809
- // Render files in this directory
810
- node.files.sort((a, b) => a.filename.localeCompare(b.filename)).forEach(f => {
811
- const isOwner = f.uploader_id.toLowerCase() === (currentUsername() ?? '').toLowerCase();
812
- const canDownload = isOwner || f.shareable;
813
- rows.push(jsxs("tr", { children: [jsx("td", { className: "px-4 py-2", children: jsx("input", { type: "checkbox", checked: selected.has(f.id), onChange: () => setSelected(prev => {
814
- const next = new Set(prev);
815
- next.has(f.id) ? next.delete(f.id) : next.add(f.id);
816
- return next;
817
- }) }) }), jsx("td", { className: "px-4 py-2", style: { paddingLeft: (depth + 1) * 20 }, children: f.filename }), jsx("td", { className: "px-4 py-2", children: canDownload ? jsx(Button, { variant: "secondary", onClick: () => downloadFile(f), children: "Download" }) : jsx("span", { children: "\uD83D\uDD12" }) }), jsx("td", { className: "px-4 py-2", children: isOwner && jsx(Button, { variant: "icon", onClick: () => setModalFile(f), children: "\u2699\uFE0F" }) }), jsx("td", { className: "px-4 py-2", children: isOwner && jsx(Button, { variant: f.shareable ? 'primary' : 'secondary', onClick: () => onToggleShare(f), children: f.shareable ? 'Sharing' : 'Share' }) }), jsx("td", { className: "px-4 py-2", children: isOwner && jsx(Button, { variant: "icon", onClick: () => onDelete(f).then(load), children: "\uD83D\uDDD1" }) }), jsxs("td", { className: "px-4 py-2", children: [f.download_count, " / ", f.download_limit ?? '∞'] })] }, f.id));
818
- });
819
- // Render subdirectories
820
- Array.from(node.children.values())
821
- .sort((a, b) => a.name.localeCompare(b.name))
822
- .forEach(child => rows.push(...renderNode(child, depth + 1)));
823
- return rows;
824
- };
825
- // Batch actions
826
- const handleDownloadAll = async () => {
827
- const inputs = filtered.filter(f => selected.has(f.id)).map(f => document.createElement('input'));
828
- inputs.forEach((cb, idx) => cb.value = filtered.filter(f => selected.has(f.id))[idx].filepath);
829
- await downloadSelected(inputs);
830
- };
831
- const handleDeleteAll = async () => { await onDelete(filtered.filter(f => selected.has(f.id))); setSelected(new Set()); await load(); };
832
- const handleShareAll = async () => { for (const f of filtered.filter(f => selected.has(f.id)))
833
- await onToggleShare(f); };
834
- if (loading)
835
- return jsx(Spinner, {});
836
- if (error)
837
- return jsx("p", { className: "text-red-600", children: error.message });
838
- return (jsxs(Fragment, { children: [jsxs("div", { className: "mb-4 flex flex-col md:flex-row md:justify-between gap-4", children: [jsx(Input, { label: "Search files", type: "text", value: search, onChange: (e) => setSearch(e.target.value), placeholder: "Enter filename\u2026", className: "form-input flex-1" }), jsxs("div", { className: "flex gap-2", children: [jsx(Button, { onClick: expandAll, disabled: !allDirPaths.length, children: "Expand All" }), jsx(Button, { onClick: collapseAll, disabled: !allDirPaths.length, children: "Collapse All" }), jsx(Button, { onClick: handleDownloadAll, disabled: !selected.size, children: "Download Selected" }), jsx(Button, { color: "gray", onClick: handleDeleteAll, disabled: !selected.size, children: "Delete Selected" }), jsx(Button, { onClick: handleShareAll, disabled: !selected.size, children: "Share Selected" })] })] }), jsx("div", { className: "overflow-x-auto wm-container", children: jsxs("table", { className: "file-table w-full", children: [jsx("thead", { className: "wm-thead", children: jsxs("tr", { children: [jsx("th", { className: "px-4 py-2 w-12", children: jsx("input", { type: "checkbox", checked: selected.size === filtered.length && filtered.length > 0, onChange: toggleAllSelection }) }), jsx("th", { className: "px-4 py-2", children: "Filename" }), jsx("th", { className: "px-4 py-2", children: "Download" }), jsx("th", { className: "px-4 py-2", children: "Settings" }), jsx("th", { className: "px-4 py-2", children: "Share" }), jsx("th", { className: "px-4 py-2", children: "Delete" }), jsx("th", { className: "px-4 py-2", children: "Downloads" })] }) }), jsx("tbody", { children: renderNode(tree) })] }) }), jsx(ShareModal, { file: modalFile, onClose: () => setModalFile(null), onSave: async (patch) => {
839
- if (!modalFile)
840
- return;
841
- const updated = { ...modalFile, ...patch };
842
- await onPatchShare(updated);
843
- setModalFile(null);
844
- } })] }));
845
- }
846
-
847
- function Upload({ onUploaded }) {
848
- const [queue, setQueue] = useState([]);
849
- const [busy, setBusy] = useState(false);
850
- const [message, setMessage] = useState(null);
851
- const [drag, setDrag] = useState(false);
852
- const inputRef = useRef(null);
853
- const [dirs, setDirs] = useState([]);
854
- // — existing files → directory list —
855
- const { files, load } = useFiles();
522
+ finally {
523
+ setLoading(false);
524
+ }
525
+ }, [api]);
856
526
  useEffect(() => {
857
- const dirSet = new Set();
858
- files.forEach(f => {
859
- const parts = f.filepath.split('/');
860
- if (parts.length > 1) {
861
- parts.pop();
862
- dirSet.add(parts.join('/') + '/');
863
- }
864
- });
865
- setDirs(Array.from(dirSet).sort());
866
- }, [files]);
867
- // — directory selection state —
868
- const [uploadDir, setUploadDir] = useState('');
869
- const [creatingNew, setCreatingNew] = useState(false);
870
- const [newDirName, setNewDirName] = useState('');
871
- // — queue logic —
872
- const enqueue = useCallback((files) => {
873
- setQueue(prev => {
874
- const map = new Map(prev.map(q => [`${q.file.name}-${q.file.size}`, q]));
875
- files.forEach(q => map.set(`${q.file.name}-${q.file.size}`, q));
876
- return Array.from(map.values());
877
- });
878
- }, []);
879
- const extractFromDataTransfer = useCallback(async (dt) => {
880
- const out = [];
881
- const walk = async (entry, path = "") => {
882
- if (!entry)
883
- return;
884
- if (entry.isFile) {
885
- const file = await new Promise(res => entry.file(res));
886
- out.push({ file, relPath: path, progress: 0 });
887
- }
888
- else if (entry.isDirectory) {
889
- const reader = entry.createReader();
890
- const entries = await new Promise(r => reader.readEntries(r));
891
- await Promise.all(entries.map(e => walk(e, `${path}${entry.name}/`)));
892
- }
527
+ load();
528
+ const onVisible = () => document.visibilityState === "visible" && load();
529
+ document.addEventListener("visibilitychange", onVisible);
530
+ window.addEventListener("focus", onVisible);
531
+ return () => {
532
+ document.removeEventListener("visibilitychange", onVisible);
533
+ window.removeEventListener("focus", onVisible);
893
534
  };
894
- await Promise.all(Array.from(dt.items).map(i => walk(i.webkitGetAsEntry())));
895
- return out;
896
- }, []);
897
- const handleSelect = (e) => {
898
- const files = Array.from(e.target.files || []);
899
- const queued = files.map(f => ({
900
- file: f,
901
- relPath: f.webkitRelativePath.replace(/[^/]*$/, ""),
902
- progress: 0,
903
- }));
904
- enqueue(queued);
905
- e.target.value = "";
906
- };
907
- const handleDrop = async (e) => {
908
- e.preventDefault();
909
- const files = await extractFromDataTransfer(e.dataTransfer);
910
- enqueue(files.length ? files : []);
911
- setDrag(false);
912
- };
913
- const handleUploadAll = async () => {
914
- if (!queue.length) {
915
- setMessage("No files queued.");
916
- return;
917
- }
918
- setBusy(true);
919
- setMessage(null);
920
- const targetDir = creatingNew
921
- ? (newDirName.trim().replace(/^\/+|\/+$/g, "") + "/")
922
- : uploadDir;
535
+ }, [load]);
536
+ const run = async (ids, action) => {
537
+ setBusyIds((s) => new Set([...s, ...ids]));
538
+ setNotice(null);
923
539
  try {
924
- for (const { file, relPath } of queue) {
925
- await uploadFiles(file, targetDir + relPath);
926
- setQueue(cur => cur.map(item => item.file === file ? { ...item, progress: 100 } : item));
927
- }
928
- setQueue([]);
929
- await onUploaded();
930
- setMessage("Upload complete");
931
- load();
540
+ await action();
932
541
  }
933
- catch {
934
- setMessage("Upload failed");
542
+ catch (err) {
543
+ setNotice(err instanceof Error ? err.message : String(err));
935
544
  }
936
545
  finally {
937
- setBusy(false);
546
+ setBusyIds((s) => new Set([...s].filter((id) => !ids.includes(id))));
938
547
  }
939
548
  };
940
- // — directory selector handlers —
941
- const handleDirChange = (e) => {
942
- const v = e.target.value;
943
- if (v === "__new__") {
944
- setCreatingNew(true);
945
- setNewDirName("");
946
- }
947
- else {
948
- setCreatingNew(false);
949
- setUploadDir(v);
549
+ const replaceFile = (file) => setFiles((fs) => fs.map((f) => (f.id === file.id ? file : f)));
550
+ const saveShare = async (update) => {
551
+ const { file } = await api.updateShare(update);
552
+ replaceFile(file);
553
+ };
554
+ const download = (items) => {
555
+ const ready = items.filter((f) => f.available);
556
+ if (!ready.length)
557
+ return;
558
+ return run(ready.map((f) => f.id), () => api.download(ready.map((f) => f.id), ready.length === 1 ? ready[0].filename : "downloads.zip"));
559
+ };
560
+ const setShared = (items, shareable) => run(items.map((f) => f.id), async () => {
561
+ for (const f of items)
562
+ await saveShare({ id: f.id, shareable });
563
+ });
564
+ const remove = (items) => run(items.map((f) => f.id), async () => {
565
+ const res = await api.remove(items.map((f) => f.id));
566
+ if (res.errors.length)
567
+ setNotice(`${res.errors.length} file(s) could not be deleted`);
568
+ await load();
569
+ });
570
+ const filtered = useMemo(() => {
571
+ const q = search.trim().toLowerCase();
572
+ return q ? files.filter((f) => f.filepath.toLowerCase().includes(q)) : files;
573
+ }, [files, search]);
574
+ const tree = useMemo(() => buildTree(filtered), [filtered]);
575
+ const folders = useMemo(() => {
576
+ const set = new Set();
577
+ for (const f of files) {
578
+ const parts = f.filepath.split("/").slice(0, -1);
579
+ parts.forEach((_, i) => set.add(parts.slice(0, i + 1).join("/")));
950
580
  }
581
+ return [...set];
582
+ }, [files]);
583
+ const selectedFiles = files.filter((f) => selected.has(f.id));
584
+ const toggle = (ids, on) => setSelected((prev) => {
585
+ const next = new Set(prev);
586
+ ids.forEach((id) => (on ? next.add(id) : next.delete(id)));
587
+ return next;
588
+ });
589
+ const toggleFolder = (path) => setCollapsed((c) => {
590
+ const next = new Set(c);
591
+ next.has(path) ? next.delete(path) : next.add(path);
592
+ return next;
593
+ });
594
+ const allVisibleSelected = filtered.length > 0 && filtered.every((f) => selected.has(f.id));
595
+ const searching = search.trim().length > 0;
596
+ const renderFile = (f, depth) => {
597
+ const busy = busyIds.has(f.id);
598
+ return (jsxs("tr", { className: busy ? "sf-busy" : undefined, children: [jsx("td", { className: "sf-col-check", children: jsx("input", { type: "checkbox", "aria-label": `Select ${f.filename}`, checked: selected.has(f.id), onChange: (e) => toggle([f.id], e.target.checked) }) }), jsxs("td", { style: { paddingLeft: 10 + depth * 20 }, children: [jsx("span", { className: f.available ? undefined : "sf-strike", children: f.filename }), f.linked && (jsx("span", { className: "sf-tag", title: f.source_path ?? undefined, children: "linked" })), !f.available && (jsx("span", { className: "sf-tag sf-tag--warn", title: f.linked ? "Source file is gone or its directory is no longer allowed" : "File is missing on disk", children: "missing" }))] }), jsxs("td", { children: [jsx("button", { type: "button", className: `sf-pill${f.shareable ? " sf-pill--on" : ""}`, disabled: busy || !f.available, onClick: () => setShared([f], !f.shareable), title: f.shareable ? "Click to stop sharing" : "Click to share", children: f.shareable ? "Shared" : "Private" }), f.shareable && f.has_password && jsx("span", { title: "Password protected", children: " \uD83D\uDD12" })] }), jsxs("td", { children: [f.download_count, " / ", f.download_limit ?? "∞"] }), jsx("td", { className: "sf-col-actions", children: jsxs("div", { className: "sf-row sf-row--end", children: [jsx("button", { type: "button", className: "sf-btn", disabled: busy || !f.available, onClick: () => download([f]), children: "Download" }), f.shareable && f.available && jsx(CopyButton, { text: f.share_url }), jsx("button", { type: "button", className: "sf-icon-btn", "aria-label": `Share settings for ${f.filename}`, title: "Share settings", onClick: () => setEditing(f), children: "\u2699\uFE0F" }), jsx(ConfirmButton, { label: f.linked ? "Unlink" : "Delete", disabled: busy, onConfirm: () => remove([f]) })] }) })] }, f.id));
951
599
  };
952
- const acceptNewDir = () => {
953
- // normalize like before
954
- const cleanName = newDirName.trim().replace(/^\/+|\/+$/g, '');
955
- const normalized = `${uploadDir}${cleanName}/`;
956
- // ① add it to our dirs list if it isn't there already
957
- setDirs(prev => {
958
- if (prev.includes(normalized))
959
- return prev;
960
- return [...prev, normalized].sort();
961
- });
962
- // ② select it & flip back to the <select>
963
- setUploadDir(normalized);
964
- setCreatingNew(false);
965
- setNewDirName('');
600
+ const renderFolder = (node, depth) => {
601
+ const rows = [];
602
+ const subFolders = [...node.folders.values()].sort((a, b) => a.name.localeCompare(b.name));
603
+ const ownFiles = [...node.files].sort((a, b) => a.filename.localeCompare(b.filename));
604
+ for (const folder of subFolders) {
605
+ const contents = allFiles(folder);
606
+ const ids = contents.map((f) => f.id);
607
+ const open = searching || !collapsed.has(folder.path);
608
+ rows.push(jsxs("tr", { className: "sf-dir", children: [jsx("td", { className: "sf-col-check", children: jsx("input", { type: "checkbox", "aria-label": `Select folder ${folder.path}`, checked: ids.length > 0 && ids.every((id) => selected.has(id)), onChange: (e) => toggle(ids, e.target.checked) }) }), jsx("td", { colSpan: 4, style: { paddingLeft: 10 + depth * 20 }, children: jsxs("button", { type: "button", className: "sf-dir__toggle", onClick: () => toggleFolder(folder.path), children: [open ? "▾" : "▸", " \uD83D\uDCC1 ", folder.name, " ", jsxs("span", { className: "sf-muted", children: ["(", contents.length, ")"] })] }) })] }, `dir:${folder.path}`));
609
+ if (open)
610
+ rows.push(...renderFolder(folder, depth + 1));
611
+ }
612
+ rows.push(...ownFiles.map((f) => renderFile(f, depth)));
613
+ return rows;
966
614
  };
967
- return (jsxs("div", { className: "form-container max-w-2xl mx-auto", children: [jsxs("div", { className: `flex items-center border-2 border-dashed rounded-lg p-6 bg-white shadow-md space-x-4 transition-shadow duration-150
968
- ${drag ? 'border-indigo-500 bg-indigo-50 shadow-lg' : 'border-gray-300 hover:shadow-lg'}`, onClick: () => inputRef.current?.click(), onDragEnter: e => { e.preventDefault(); setDrag(true); }, onDragOver: e => e.preventDefault(), onDragLeave: () => setDrag(false), onDrop: handleDrop, role: "region", "aria-label": "File upload area", children: [jsx(ForwardRef, { style: { width: 300, height: 300 }, className: "text-gray-500 mb-3", "aria-hidden": "true" }), jsxs("div", { className: "flex-1", children: [jsx("p", { className: "text-base font-semibold text-gray-700", children: "Drag & drop files or folders here" }), queue.length > 0 && (jsxs("p", { className: "mt-1 text-sm text-gray-600", children: [queue.length, " item", queue.length > 1 && 's', " queued"] }))] })] }), jsx("input", { ref: inputRef, type: "file", multiple: true, className: "hidden", ...{ webkitdirectory: true, directory: '' }, onChange: handleSelect }), jsxs("div", { className: "flex items-center justify-between mt-4", children: [jsx("div", { className: "flex-1 mr-4", children: !creatingNew ? (jsxs("select", { value: uploadDir, onChange: handleDirChange, className: "form-select w-full", children: [dirs.map(d => (jsx("option", { value: d, children: d }, d))), jsx("option", { value: "__new__", children: "+ Create new directory\u2026" })] })) : (jsxs("div", { className: "flex", children: [jsx("input", { type: "text", value: newDirName, placeholder: "new-folder-name", onChange: e => setNewDirName(e.target.value), onBlur: acceptNewDir, onKeyDown: e => e.key === 'Enter' && acceptNewDir(), className: "form-input flex-1" }), jsx(Button, { onClick: acceptNewDir, className: "ml-2", children: "OK" })] })) }), jsx(Button, { color: "blue", variant: "primary", onClick: handleUploadAll, disabled: busy || !queue.length, children: busy ? 'Uploading…' : `Upload ${queue.length}` })] }), message && (jsx("p", { className: `text-center text-sm ${message.includes('failed') ? 'text-red-600' : 'text-gray-600'}`, role: "alert", children: message })), queue.length > 0 && (jsxs("div", { className: "wm-container mt-4", children: [jsx("h3", { className: "mb-2 text-sm font-semibold text-gray-700", children: "Queued Files" }), jsx("ul", { className: "max-h-64 space-y-4 overflow-y-auto", children: queue.map(({ file, relPath, progress }) => (jsxs("li", { className: "space-y-1", children: [jsxs("div", { className: "flex justify-between items-center", children: [jsxs("span", { className: "truncate text-sm text-gray-800", children: [relPath, file.name] }), jsxs("span", { className: "text-xs text-gray-500", children: [progress, "%"] })] }), jsx("div", { className: "w-full bg-gray-200 rounded-full h-2 overflow-hidden", children: jsx("div", { className: "bg-indigo-600 h-2", style: { width: `${progress}%` } }) })] }, `${file.name}-${file.size}`))) })] }))] }));
615
+ return (jsxs("div", { className: "sf-root", children: [jsxs("header", { className: "sf-head", children: [jsx("h2", { children: "Secure Files" }), user && jsxs("span", { className: "sf-muted", children: ["Signed in as ", user] })] }), jsx(UploadPanel, { api: api, folders: folders, onUploaded: load }), isAdmin && jsx(ServerFiles, { api: api, folders: folders, onLinked: load }), jsxs("section", { className: "sf-toolbar", children: [jsx("input", { className: "sf-input sf-search", type: "search", placeholder: "Search files\u2026", value: search, onChange: (e) => setSearch(e.target.value) }), jsxs("div", { className: "sf-row", children: [jsxs("span", { className: "sf-muted", children: [selected.size, " selected"] }), folders.length > 0 && (jsxs(Fragment, { children: [jsx("button", { type: "button", className: "sf-btn", onClick: () => setCollapsed(new Set()), children: "Expand all" }), jsx("button", { type: "button", className: "sf-btn", onClick: () => setCollapsed(new Set(folders)), children: "Collapse all" })] })), jsx("button", { type: "button", className: "sf-btn", disabled: !selected.size, onClick: () => download(selectedFiles), children: "Download" }), jsx("button", { type: "button", className: "sf-btn", disabled: !selected.size, onClick: () => setShared(selectedFiles, true), children: "Share" }), jsx("button", { type: "button", className: "sf-btn", disabled: !selected.size, onClick: () => setShared(selectedFiles, false), children: "Unshare" }), jsx(ConfirmButton, { label: "Delete", disabled: !selected.size, onConfirm: () => remove(selectedFiles) })] })] }), notice && (jsx("p", { className: "sf-error", role: "alert", children: notice })), loading ? (jsx("p", { className: "sf-muted", children: "Loading\u2026" })) : error ? (jsx("p", { className: "sf-error", role: "alert", children: error })) : files.length === 0 ? (jsx("p", { className: "sf-muted", children: "No files yet \u2014 upload something above." })) : (jsx("div", { className: "sf-table-wrap", children: jsxs("table", { className: "sf-table", children: [jsx("thead", { children: jsxs("tr", { children: [jsx("th", { className: "sf-col-check", children: jsx("input", { type: "checkbox", "aria-label": "Select all", checked: allVisibleSelected, onChange: (e) => toggle(filtered.map((f) => f.id), e.target.checked) }) }), jsx("th", { children: "Name" }), jsx("th", { children: "Sharing" }), jsx("th", { children: "Downloads" }), jsx("th", { className: "sf-col-actions", children: "Actions" })] }) }), jsx("tbody", { children: renderFolder(tree, 0) })] }) })), editing && (jsx(ShareDialog, { file: files.find((f) => f.id === editing.id) ?? editing, onClose: () => setEditing(null), onSave: saveShare }, editing.id))] }));
969
616
  }
970
617
 
971
- const SecureFiles = () => {
972
- const [authChecked, setAuthChecked] = useState(false);
973
- const [loggedIn, setLoggedIn] = useState(false);
974
- const filesHook = useFiles();
975
- useEffect(() => {
976
- checkAuth().then(ok => {
977
- setLoggedIn(ok);
978
- setAuthChecked(true);
979
- });
980
- }, []);
981
- if (!authChecked)
982
- return null;
983
- if (!loggedIn) {
984
- return (jsx("p", { style: { textAlign: 'center', marginTop: '2rem', color: '#6b7280' }, children: "Please log in to access your files." }));
985
- }
986
- return (jsxs(Fragment, { children: [jsx(Upload, { onUploaded: filesHook.load }), jsx(FileTable, { files: filesHook.files, loading: filesHook.loading, error: filesHook.error, onDownload: filesHook.toggleShare, onToggleShare: filesHook.toggleShare, onPatchShare: filesHook.patchShareSettings, onDelete: filesHook.deleteFile })] }));
987
- };
988
-
989
- export { Button, Checkbox, FileRow, FileTable, Input, SecureFiles, ShareModal, Spinner, Upload, directDownload, downloadFile, downloadRow, downloadSelect, downloadSelected, initSelectAll, listFiles, patchFileSetting, removeFile, removeRow, removeSelected, syncHeaderCheckbox, toggleCheckboxes, toggleShare, triggerDownload, uploadFile, uploadFiles, useDeleteFile, useFiles, useLoadFiles, usePatchShareSettings, useSaveShareSettings, useToggleShare };
618
+ export { ApiError, DEFAULT_API_BASE, SecureFiles, createApi };
990
619
  //# sourceMappingURL=index.js.map