@shellui/core 0.3.1 → 0.4.0

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 (56) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +11 -1
  3. package/src/components/ui/dialog.tsx +26 -6
  4. package/src/components/ui/sonner.tsx +9 -5
  5. package/src/features/admin/AdminView.tsx +1 -20
  6. package/src/features/auth/AuthProvider.tsx +68 -13
  7. package/src/features/auth/backends/shellui.ts +8 -1
  8. package/src/features/auth/components/AccessPendingView.tsx +112 -0
  9. package/src/features/auth/components/LoginView.tsx +17 -0
  10. package/src/features/auth/components/OAuthCallbackView.tsx +211 -48
  11. package/src/features/auth/hooks/useAuth.tsx +8 -1
  12. package/src/features/auth/utils/authRequestError.spec.ts +52 -0
  13. package/src/features/auth/utils/authRequestError.ts +45 -0
  14. package/src/features/auth/utils/index.ts +7 -0
  15. package/src/features/auth/utils/isTokenAutoRefreshDisabled.spec.ts +71 -0
  16. package/src/features/auth/utils/isTokenAutoRefreshDisabled.ts +18 -0
  17. package/src/features/config/types.ts +46 -0
  18. package/src/features/layouts/AppLayout.tsx +3 -3
  19. package/src/features/layouts/OverlayShell.tsx +10 -6
  20. package/src/features/settings/SettingsIcons.tsx +35 -0
  21. package/src/features/settings/SettingsProvider.tsx +69 -4
  22. package/src/features/settings/SettingsRoutes.tsx +14 -6
  23. package/src/features/settings/SettingsView.tsx +11 -5
  24. package/src/features/settings/components/Advanced.tsx +117 -44
  25. package/src/features/settings/components/Develop.tsx +38 -0
  26. package/src/features/settings/components/Storage.tsx +138 -0
  27. package/src/features/settings/components/develop/StoragePickerTestButtons.tsx +148 -0
  28. package/src/features/settings/components/develop/UploadToastTestButton.tsx +29 -0
  29. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -0
  30. package/src/features/settings/utils/buildSettingsForPropagation.ts +34 -0
  31. package/src/features/settings/utils/toSettingsUser.spec.ts +4 -0
  32. package/src/features/settings/utils/toSettingsUser.ts +2 -0
  33. package/src/features/storage/StorageBridge.tsx +50 -0
  34. package/src/features/storage/StoragePickerContext.tsx +214 -0
  35. package/src/features/storage/api.spec.ts +303 -0
  36. package/src/features/storage/api.ts +414 -0
  37. package/src/features/storage/handleRequest.spec.ts +88 -0
  38. package/src/features/storage/handleRequest.ts +53 -0
  39. package/src/features/storage/quota.spec.ts +151 -0
  40. package/src/features/storage/quota.ts +104 -0
  41. package/src/features/storage/uploads/UploadToastCard.tsx +442 -0
  42. package/src/features/storage/uploads/UploadToaster.tsx +41 -0
  43. package/src/features/storage/uploads/handleTrackedUpload.spec.ts +170 -0
  44. package/src/features/storage/uploads/handleTrackedUpload.ts +97 -0
  45. package/src/features/storage/uploads/types.ts +24 -0
  46. package/src/features/storage/uploads/uploadQueue.spec.ts +118 -0
  47. package/src/features/storage/uploads/uploadQueue.ts +349 -0
  48. package/src/features/storage/uploads/useUploadQueue.ts +30 -0
  49. package/src/i18n/translations/en/common.json +33 -0
  50. package/src/i18n/translations/en/settings.json +47 -4
  51. package/src/i18n/translations/fr/common.json +33 -0
  52. package/src/i18n/translations/fr/settings.json +47 -4
  53. package/src/index.css +2 -1
  54. package/src/index.ts +2 -0
  55. package/src/lib/z-index.ts +9 -3
  56. package/src/service-worker/register.ts +4 -12
@@ -0,0 +1,214 @@
1
+ import {
2
+ createContext,
3
+ useCallback,
4
+ useContext,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ type ReactNode,
9
+ } from 'react';
10
+ import { useTranslation } from 'react-i18next';
11
+ import {
12
+ shellui,
13
+ type ShellUIMessage,
14
+ type StorageSelectMode,
15
+ type StorageSelectRequestPayload,
16
+ type StorageSelectResponsePayload,
17
+ } from '@shellui/sdk';
18
+ import { ContentView } from '../../components/ContentView';
19
+ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../components/ui/dialog';
20
+ import { Z_INDEX } from '../../lib/z-index';
21
+ import type { NavigationItem } from '../config/types';
22
+ import { useConfig } from '../config/useConfig';
23
+ import { validateAndNormalizeUrl } from '../modal/ModalContext';
24
+
25
+ type PendingSelect = {
26
+ id: string;
27
+ from?: string[];
28
+ url: string;
29
+ };
30
+
31
+ interface StoragePickerContextValue {
32
+ isOpen: boolean;
33
+ closePicker: (cancelled?: boolean) => void;
34
+ }
35
+
36
+ const StoragePickerContext = createContext<StoragePickerContextValue | undefined>(undefined);
37
+
38
+ export function useStoragePicker(): StoragePickerContextValue {
39
+ const context = useContext(StoragePickerContext);
40
+ if (!context) {
41
+ throw new Error('useStoragePicker must be used within a StoragePickerProvider');
42
+ }
43
+ return context;
44
+ }
45
+
46
+ function buildPickerUrl(filesUrl: string, payload: StorageSelectRequestPayload): string {
47
+ const base = filesUrl.replace(/\/+$/, '');
48
+ const params = new URLSearchParams({
49
+ requestId: payload.id,
50
+ mode: payload.mode,
51
+ multiple: payload.multiple ? '1' : '0',
52
+ });
53
+ return `${base}/#/select?${params.toString()}`;
54
+ }
55
+
56
+ function replyToRequester(pending: PendingSelect, payload: StorageSelectResponsePayload): void {
57
+ const message = {
58
+ type: 'SHELLUI_SELECT_STORAGE_RESULT' as const,
59
+ payload,
60
+ };
61
+ const to = pending.from?.filter(Boolean);
62
+ if (to?.length) {
63
+ shellui.sendMessage({ ...message, to });
64
+ return;
65
+ }
66
+ if (typeof window !== 'undefined') {
67
+ window.postMessage(message, '*');
68
+ }
69
+ }
70
+
71
+ interface StoragePickerProviderProps {
72
+ children: ReactNode;
73
+ }
74
+
75
+ export const StoragePickerProvider = ({ children }: StoragePickerProviderProps) => {
76
+ const { config } = useConfig();
77
+ const { t } = useTranslation('common');
78
+ const [pending, setPending] = useState<PendingSelect | null>(null);
79
+ const pendingRef = useRef<PendingSelect | null>(null);
80
+ pendingRef.current = pending;
81
+
82
+ const closePicker = useCallback((cancelled = true) => {
83
+ const current = pendingRef.current;
84
+ if (!current) return;
85
+ if (cancelled) {
86
+ replyToRequester(current, { id: current.id, cancelled: true });
87
+ }
88
+ pendingRef.current = null;
89
+ setPending(null);
90
+ }, []);
91
+
92
+ const failRequest = useCallback((message: ShellUIMessage, errorMessage: string, status = 503) => {
93
+ const payload = message.payload as StorageSelectRequestPayload | undefined;
94
+ const id = payload?.id ?? '';
95
+ const reply = {
96
+ type: 'SHELLUI_SELECT_STORAGE_RESULT' as const,
97
+ payload: {
98
+ id,
99
+ error: { message: errorMessage, status },
100
+ },
101
+ };
102
+ const to = message.from?.filter(Boolean);
103
+ if (to?.length) {
104
+ shellui.sendMessage({ ...reply, to });
105
+ return;
106
+ }
107
+ window.postMessage(reply, '*');
108
+ }, []);
109
+
110
+ useEffect(() => {
111
+ if (typeof window === 'undefined' || window.parent !== window) {
112
+ return;
113
+ }
114
+
115
+ const stopOpen = shellui.addMessageListener('SHELLUI_SELECT_STORAGE', (message) => {
116
+ const payload = message.payload as StorageSelectRequestPayload | undefined;
117
+ if (!payload?.id) return;
118
+
119
+ const filesUrl = config?.storage?.filesUrl?.trim();
120
+ if (!filesUrl) {
121
+ failRequest(
122
+ message,
123
+ 'Storage picker is not configured. Set storage.filesUrl in shellui.config.ts.',
124
+ 503,
125
+ );
126
+ return;
127
+ }
128
+
129
+ const mode: StorageSelectMode =
130
+ payload.mode === 'files' || payload.mode === 'any' ? payload.mode : 'folders';
131
+ const rawUrl = buildPickerUrl(filesUrl, {
132
+ id: payload.id,
133
+ multiple: Boolean(payload.multiple),
134
+ mode,
135
+ });
136
+ const url = validateAndNormalizeUrl(rawUrl);
137
+ if (!url) {
138
+ failRequest(message, 'Storage picker URL is not allowed.', 400);
139
+ return;
140
+ }
141
+
142
+ const previous = pendingRef.current;
143
+ if (previous) {
144
+ replyToRequester(previous, { id: previous.id, cancelled: true });
145
+ }
146
+
147
+ const next: PendingSelect = {
148
+ id: payload.id,
149
+ from: message.from,
150
+ url,
151
+ };
152
+ pendingRef.current = next;
153
+ setPending(next);
154
+ });
155
+
156
+ const stopResult = shellui.addMessageListener('SHELLUI_SELECT_STORAGE_RESULT', (message) => {
157
+ const payload = message.payload as StorageSelectResponsePayload | undefined;
158
+ const current = pendingRef.current;
159
+ if (!payload?.id || !current || payload.id !== current.id) return;
160
+ // The files iframe posted the result. Forward to the original requester, then close.
161
+ replyToRequester(current, payload);
162
+ pendingRef.current = null;
163
+ setPending(null);
164
+ });
165
+
166
+ return () => {
167
+ stopOpen();
168
+ stopResult();
169
+ };
170
+ }, [config?.storage?.filesUrl, failRequest]);
171
+
172
+ const pickerNavItem = {
173
+ path: '__storage-picker',
174
+ url: pending?.url ?? '',
175
+ label: 'Select',
176
+ useHashRouter: true,
177
+ } as NavigationItem;
178
+
179
+ return (
180
+ <StoragePickerContext.Provider value={{ isOpen: Boolean(pending), closePicker }}>
181
+ {children}
182
+ <Dialog
183
+ open={Boolean(pending)}
184
+ onOpenChange={(open) => {
185
+ if (!open) closePicker(true);
186
+ }}
187
+ >
188
+ <DialogContent
189
+ className="flex h-[min(90vh,720px)] w-full max-w-5xl flex-col overflow-hidden p-0"
190
+ overlayZIndex={Z_INDEX.STORAGE_PICKER_OVERLAY}
191
+ contentZIndex={Z_INDEX.STORAGE_PICKER_CONTENT}
192
+ >
193
+ <DialogTitle className="sr-only">
194
+ {t('storagePicker.title') ?? 'Select files or folders'}
195
+ </DialogTitle>
196
+ <DialogDescription className="sr-only">
197
+ {t('storagePicker.description') ?? 'Choose items, then confirm.'}
198
+ </DialogDescription>
199
+ {pending ? (
200
+ <div className="min-h-0 flex-1">
201
+ <ContentView
202
+ key={pending.id}
203
+ url={pending.url}
204
+ pathPrefix="storage-picker"
205
+ ignoreMessages={true}
206
+ navItem={pickerNavItem}
207
+ />
208
+ </div>
209
+ ) : null}
210
+ </DialogContent>
211
+ </Dialog>
212
+ </StoragePickerContext.Provider>
213
+ );
214
+ };
@@ -0,0 +1,303 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ encodeObjectPath,
4
+ executeStorageOp,
5
+ FOLDER_PLACEHOLDER,
6
+ isFolderPlaceholderPath,
7
+ normalizeStoragePath,
8
+ } from './api';
9
+
10
+ const baseUrl = 'http://localhost:8001';
11
+ const token = 'token-1';
12
+
13
+ function jsonResponse(body: unknown, status = 200): Response {
14
+ return {
15
+ ok: status >= 200 && status < 300,
16
+ status,
17
+ statusText: 'OK',
18
+ headers: new Headers({ 'Content-Type': 'application/json' }),
19
+ json: async () => body,
20
+ blob: async () => new Blob(),
21
+ } as Response;
22
+ }
23
+
24
+ describe('encodeObjectPath', () => {
25
+ it('encodes nested folder segments', () => {
26
+ expect(encodeObjectPath('company', 'docs/reports/2024/q1.pdf')).toBe(
27
+ 'company/docs/reports/2024/q1.pdf',
28
+ );
29
+ expect(encodeObjectPath('company', '/docs/reports/q1.pdf/')).toBe(
30
+ 'company/docs/reports/q1.pdf',
31
+ );
32
+ expect(encodeObjectPath('my bucket', 'a b/c.pdf')).toBe('my%20bucket/a%20b/c.pdf');
33
+ });
34
+ });
35
+
36
+ describe('normalizeStoragePath', () => {
37
+ it('strips slashes', () => {
38
+ expect(normalizeStoragePath('/docs/reports/')).toBe('docs/reports');
39
+ });
40
+ });
41
+
42
+ describe('isFolderPlaceholderPath', () => {
43
+ it('detects the folder marker at any depth', () => {
44
+ expect(isFolderPlaceholderPath(FOLDER_PLACEHOLDER)).toBe(true);
45
+ expect(isFolderPlaceholderPath(`docs/${FOLDER_PLACEHOLDER}`)).toBe(true);
46
+ expect(isFolderPlaceholderPath('docs/q1.pdf')).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe('executeStorageOp', () => {
51
+ afterEach(() => {
52
+ vi.unstubAllGlobals();
53
+ });
54
+
55
+ it('lists buckets', async () => {
56
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{ name: 'company' }]));
57
+ vi.stubGlobal('fetch', fetchMock);
58
+ await expect(executeStorageOp(baseUrl, token, { op: 'listBuckets' })).resolves.toEqual([
59
+ { name: 'company' },
60
+ ]);
61
+ expect(fetchMock).toHaveBeenCalledWith('http://localhost:8001/storage/v1/bucket', {
62
+ headers: expect.any(Headers),
63
+ });
64
+ });
65
+
66
+ it('lists a nested prefix and hides folder placeholders', async () => {
67
+ const fetchMock = vi.fn().mockResolvedValue(
68
+ jsonResponse([
69
+ { name: 'q1.pdf', id: '1' },
70
+ { name: FOLDER_PLACEHOLDER, id: '2' },
71
+ { name: '2024', id: null },
72
+ ]),
73
+ );
74
+ vi.stubGlobal('fetch', fetchMock);
75
+
76
+ await expect(
77
+ executeStorageOp(baseUrl, token, {
78
+ op: 'list',
79
+ bucket: 'company',
80
+ prefix: 'docs/reports',
81
+ options: { limit: 200 },
82
+ }),
83
+ ).resolves.toEqual([
84
+ { name: 'q1.pdf', id: '1' },
85
+ { name: '2024', id: null },
86
+ ]);
87
+
88
+ expect(fetchMock).toHaveBeenCalledWith(
89
+ 'http://localhost:8001/storage/v1/object/list/company',
90
+ expect.objectContaining({
91
+ method: 'POST',
92
+ body: JSON.stringify({
93
+ prefix: 'docs/reports',
94
+ limit: 200,
95
+ offset: 0,
96
+ sortBy: { column: 'name', order: 'asc' },
97
+ }),
98
+ }),
99
+ );
100
+ });
101
+
102
+ it('uploads a file into a nested path with upsert', async () => {
103
+ const fetchMock = vi.fn().mockResolvedValue({
104
+ ok: true,
105
+ status: 200,
106
+ headers: new Headers(),
107
+ });
108
+ vi.stubGlobal('fetch', fetchMock);
109
+ const file = new Blob(['pdf'], { type: 'application/pdf' });
110
+
111
+ await expect(
112
+ executeStorageOp(baseUrl, token, {
113
+ op: 'upload',
114
+ bucket: 'company',
115
+ path: 'docs/reports/2024/q1.pdf',
116
+ file,
117
+ upsert: true,
118
+ contentType: 'application/pdf',
119
+ }),
120
+ ).resolves.toEqual({ path: 'docs/reports/2024/q1.pdf' });
121
+
122
+ expect(fetchMock).toHaveBeenCalledWith(
123
+ 'http://localhost:8001/storage/v1/object/company/docs/reports/2024/q1.pdf',
124
+ expect.objectContaining({
125
+ method: 'POST',
126
+ body: file,
127
+ }),
128
+ );
129
+ const headers = fetchMock.mock.calls[0][1].headers as Headers;
130
+ expect(headers.get('Authorization')).toBe('Bearer token-1');
131
+ expect(headers.get('Content-Type')).toBe('application/pdf');
132
+ expect(headers.get('x-upsert')).toBe('true');
133
+ });
134
+
135
+ it('downloads nested objects as blobs', async () => {
136
+ const blob = new Blob(['bytes']);
137
+ const fetchMock = vi.fn().mockResolvedValue({
138
+ ok: true,
139
+ status: 200,
140
+ headers: new Headers(),
141
+ blob: async () => blob,
142
+ });
143
+ vi.stubGlobal('fetch', fetchMock);
144
+ await expect(
145
+ executeStorageOp(baseUrl, token, {
146
+ op: 'download',
147
+ bucket: 'company',
148
+ path: 'docs/reports/q1.pdf',
149
+ }),
150
+ ).resolves.toBe(blob);
151
+ expect(fetchMock).toHaveBeenCalledWith(
152
+ 'http://localhost:8001/storage/v1/object/company/docs/reports/q1.pdf',
153
+ expect.objectContaining({
154
+ headers: { Authorization: 'Bearer token-1' },
155
+ }),
156
+ );
157
+ });
158
+
159
+ it('moves a file with bucket-qualified nested paths', async () => {
160
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({}));
161
+ vi.stubGlobal('fetch', fetchMock);
162
+ await executeStorageOp(baseUrl, token, {
163
+ op: 'move',
164
+ bucket: 'company',
165
+ fromPath: 'docs/reports/q1.pdf',
166
+ toPath: 'archive/2024/q1.pdf',
167
+ });
168
+ expect(fetchMock).toHaveBeenCalledWith(
169
+ 'http://localhost:8001/storage/v1/object/move',
170
+ expect.objectContaining({
171
+ method: 'POST',
172
+ body: JSON.stringify({
173
+ from: 'company/docs/reports/q1.pdf',
174
+ to: 'company/archive/2024/q1.pdf',
175
+ }),
176
+ }),
177
+ );
178
+ });
179
+
180
+ it('moves a folder prefix', async () => {
181
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ moved: 3 }));
182
+ vi.stubGlobal('fetch', fetchMock);
183
+ await executeStorageOp(baseUrl, token, {
184
+ op: 'move',
185
+ bucket: 'company',
186
+ fromPath: 'docs/reports',
187
+ toPath: 'archive/reports',
188
+ folder: true,
189
+ });
190
+ expect(fetchMock).toHaveBeenCalledWith(
191
+ 'http://localhost:8001/storage/v1/object/prefix/company',
192
+ expect.objectContaining({
193
+ method: 'POST',
194
+ body: JSON.stringify({ from: 'docs/reports', to: 'archive/reports' }),
195
+ }),
196
+ );
197
+ });
198
+
199
+ it('creates a nested folder via placeholder upload', async () => {
200
+ const fetchMock = vi.fn().mockResolvedValue(
201
+ jsonResponse({
202
+ Id: 'folder-uuid-1',
203
+ Key: 'company/docs/reports/2024/.emptyFolderPlaceholder',
204
+ }),
205
+ );
206
+ vi.stubGlobal('fetch', fetchMock);
207
+ await expect(
208
+ executeStorageOp(baseUrl, token, {
209
+ op: 'createFolder',
210
+ bucket: 'company',
211
+ path: 'docs/reports/2024',
212
+ }),
213
+ ).resolves.toEqual({ path: 'docs/reports/2024', id: 'folder-uuid-1' });
214
+ expect(fetchMock.mock.calls[0][0]).toBe(
215
+ `http://localhost:8001/storage/v1/object/company/docs/reports/2024/${FOLDER_PLACEHOLDER}`,
216
+ );
217
+ });
218
+
219
+ it('resolves a storage item by id', async () => {
220
+ const fetchMock = vi.fn().mockResolvedValue(
221
+ jsonResponse({
222
+ id: 'folder-uuid-1',
223
+ bucket: 'company',
224
+ path: 'docs/reports',
225
+ name: 'reports',
226
+ type: 'folder',
227
+ }),
228
+ );
229
+ vi.stubGlobal('fetch', fetchMock);
230
+ await expect(
231
+ executeStorageOp(baseUrl, token, { op: 'get', objectId: 'folder-uuid-1' }),
232
+ ).resolves.toEqual({
233
+ id: 'folder-uuid-1',
234
+ bucket: 'company',
235
+ path: 'docs/reports',
236
+ name: 'reports',
237
+ type: 'folder',
238
+ });
239
+ expect(fetchMock).toHaveBeenCalledWith(
240
+ 'http://localhost:8001/storage/v1/object/id/folder-uuid-1',
241
+ expect.objectContaining({ headers: expect.any(Headers) }),
242
+ );
243
+ });
244
+
245
+ it('removes files and folder prefixes', async () => {
246
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ count: 2 }, 200));
247
+ vi.stubGlobal('fetch', fetchMock);
248
+ await executeStorageOp(baseUrl, token, {
249
+ op: 'remove',
250
+ bucket: 'company',
251
+ paths: ['docs/a.pdf'],
252
+ });
253
+ expect(fetchMock.mock.calls[0][0]).toBe(
254
+ 'http://localhost:8001/storage/v1/object/company/docs/a.pdf',
255
+ );
256
+ expect(fetchMock.mock.calls[0][1]).toEqual(expect.objectContaining({ method: 'DELETE' }));
257
+
258
+ await executeStorageOp(baseUrl, token, {
259
+ op: 'removeFolder',
260
+ bucket: 'company',
261
+ path: 'docs/reports',
262
+ });
263
+ expect(fetchMock.mock.calls[1][0]).toBe(
264
+ 'http://localhost:8001/storage/v1/object/prefix/company',
265
+ );
266
+ expect(fetchMock.mock.calls[1][1]).toEqual(
267
+ expect.objectContaining({
268
+ method: 'DELETE',
269
+ body: JSON.stringify({ prefix: 'docs/reports' }),
270
+ }),
271
+ );
272
+ });
273
+
274
+ it('requests folder stats for a nested prefix', async () => {
275
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ file_count: 4 }));
276
+ vi.stubGlobal('fetch', fetchMock);
277
+ await executeStorageOp(baseUrl, token, {
278
+ op: 'folderStats',
279
+ bucket: 'company',
280
+ path: 'docs/reports/2024',
281
+ });
282
+ expect(fetchMock.mock.calls[0][0]).toBe(
283
+ 'http://localhost:8001/storage/v1/object/prefix/company?prefix=docs%2Freports%2F2024',
284
+ );
285
+ });
286
+
287
+ it('throws mapped http errors', async () => {
288
+ vi.stubGlobal(
289
+ 'fetch',
290
+ vi.fn().mockResolvedValue({
291
+ ok: false,
292
+ status: 403,
293
+ statusText: 'Forbidden',
294
+ json: async () => ({ message: 'Denied', error: 'access_denied' }),
295
+ }),
296
+ );
297
+ await expect(executeStorageOp(baseUrl, token, { op: 'listBuckets' })).rejects.toMatchObject({
298
+ status: 403,
299
+ code: 'access_denied',
300
+ message: 'Denied',
301
+ });
302
+ });
303
+ });