@antelopejs/dms-media 0.3.0 → 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 (57) hide show
  1. package/README.md +5 -1
  2. package/dist/index.d.ts +3 -0
  3. package/dist/index.js +8 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/pages/uploads.js +2 -1
  6. package/dist/pages/uploads.js.map +1 -1
  7. package/dist/test/antelope.test.js +3 -2
  8. package/dist/test/antelope.test.js.map +1 -1
  9. package/dist/test/helpers/pages.js +3 -2
  10. package/dist/test/helpers/pages.js.map +1 -1
  11. package/dist/test/integration/frontend-module.test.d.ts +1 -0
  12. package/dist/test/integration/frontend-module.test.js +13 -0
  13. package/dist/test/integration/frontend-module.test.js.map +1 -0
  14. package/dist/test/unit/config.test.js +0 -4
  15. package/dist/test/unit/config.test.js.map +1 -1
  16. package/frontend-vue/app/components/FileProperties.vue +9 -3
  17. package/frontend-vue/app/components/FirstRun.vue +1 -1
  18. package/frontend-vue/app/components/ImageEditor.vue +43 -26
  19. package/frontend-vue/app/components/PresetCards.vue +3 -11
  20. package/frontend-vue/app/components/RecentFiles.vue +6 -14
  21. package/frontend-vue/app/components/UploadQueue.vue +1 -1
  22. package/frontend-vue/app/components/UploadStrip.vue +1 -1
  23. package/frontend-vue/app/components/dialogs/DestinationDialog.vue +1 -2
  24. package/frontend-vue/app/components/explorer/ExplorerInspector.vue +17 -16
  25. package/frontend-vue/app/components/explorer/ExplorerShell.vue +11 -3
  26. package/frontend-vue/app/components/explorer/ExplorerToolbar.vue +2 -1
  27. package/frontend-vue/app/components/field/AssetValue.vue +12 -13
  28. package/frontend-vue/app/components/file/FileViewer.vue +1 -14
  29. package/frontend-vue/app/composables/library/useLibraryListing.ts +180 -79
  30. package/frontend-vue/app/composables/library/useLibraryTree.ts +31 -15
  31. package/frontend-vue/app/composables/library/useMediaLibrary.ts +17 -7
  32. package/frontend-vue/app/composables/uploadLimits.ts +25 -0
  33. package/frontend-vue/app/composables/useAssetContent.ts +20 -0
  34. package/frontend-vue/app/composables/useCurrentFile.ts +10 -8
  35. package/frontend-vue/app/composables/useFieldFolders.ts +19 -18
  36. package/frontend-vue/app/composables/useFileDetails.ts +117 -90
  37. package/frontend-vue/app/composables/useMediaApi.ts +18 -24
  38. package/frontend-vue/i18n/locales/media-en-GB.json +1 -0
  39. package/frontend-vue/i18n/locales/media-fr-FR.json +1 -0
  40. package/frontend-vue/package.json +2 -1
  41. package/frontend-vue/pnpm-lock.yaml +17 -2
  42. package/frontend-vue/tests/engines.test.ts +20 -0
  43. package/frontend-vue/tests/fixtures/inertia.ts +8 -0
  44. package/frontend-vue/tests/fixtures/serverRender.ts +200 -0
  45. package/frontend-vue/tests/fixtures/unhead.ts +3 -0
  46. package/frontend-vue/tests/fixtures/vueI18n.ts +4 -0
  47. package/frontend-vue/tests/libraryListing.test.ts +120 -0
  48. package/frontend-vue/tests/serverRender.test.ts +215 -0
  49. package/frontend-vue/vitest.config.ts +21 -0
  50. package/package.json +16 -10
  51. package/src/index.ts +19 -2
  52. package/src/pages/uploads.ts +2 -1
  53. package/src/test/antelope.test.ts +3 -2
  54. package/src/test/helpers/pages.ts +3 -2
  55. package/src/test/integration/frontend-module.test.ts +13 -0
  56. package/src/test/unit/config.test.ts +0 -5
  57. package/frontend-vue/app/composables/useSharedTree.ts +0 -73
@@ -4,8 +4,6 @@ import AssetThumb from '../shared/AssetThumb.vue'
4
4
 
5
5
  const props = defineProps<{ value: unknown }>()
6
6
  const { t } = useI18n()
7
- const api = useMediaApi()
8
- const assets = ref<(MediaAsset | null)[]>([])
9
7
 
10
8
  const SHOWN_NAMES = 2
11
9
 
@@ -18,21 +16,22 @@ const ids = computed<string[]>(() => {
18
16
  const shownIds = computed(() => ids.value.slice(0, SHOWN_NAMES))
19
17
  const hidden = computed(() => Math.max(ids.value.length - SHOWN_NAMES, 0))
20
18
 
21
- /** Only the files the cell names are read: the others are counted. */
22
- watch(
23
- shownIds,
24
- async (list) => {
25
- assets.value = await Promise.all(
26
- list.map((id) =>
27
- api
28
- .asset(id)
19
+ /**
20
+ * Only the files the cell names are read, with the page: the others are
21
+ * counted. A file the server does not answer for shows as missing.
22
+ */
23
+ const read = useApiData<(MediaAsset | null)[]>(
24
+ () => `dms-media:asset-names:${shownIds.value.join(',')}`,
25
+ ({ $authFetch, signal }) =>
26
+ Promise.all(
27
+ shownIds.value.map((id) =>
28
+ $authFetch<{ asset: MediaAsset }>(MEDIA_READS.asset(id), { signal })
29
29
  .then((response) => response.asset)
30
30
  .catch(() => null),
31
31
  ),
32
- )
33
- },
34
- { immediate: true },
32
+ ),
35
33
  )
34
+ const assets = computed(() => (read.placeholder.value ? [] : (read.data.value ?? [])))
36
35
  </script>
37
36
 
38
37
  <template>
@@ -1,28 +1,15 @@
1
1
  <script setup lang="ts">
2
2
  import type { MediaAsset } from '../../types/media'
3
- import type { AssetContent } from '../../composables/useAssetContent'
4
3
  import AssetThumb from '../shared/AssetThumb.vue'
5
4
 
6
5
  const props = defineProps<{ asset: MediaAsset; siblings: MediaAsset[] }>()
7
6
  const emit = defineEmits<{ open: [string]; fullscreen: [] }>()
8
- const contents = useAssetContent()
9
7
  const assetLink = useAssetLink()
10
8
  const format = useMediaFormat()
11
9
  const { t } = useI18n()
12
- const content = ref<AssetContent>({ kind: 'none' })
10
+ const content = useShownContent(() => props.asset)
13
11
  const filmstrip = useTemplateRef<HTMLElement>('filmstrip')
14
12
 
15
- watch(
16
- () => [props.asset.id, props.asset.updatedAt],
17
- async () => {
18
- const shown = props.asset
19
- content.value = { kind: 'none' }
20
- const loaded = await contents.load(shown)
21
- if (shown.id === props.asset.id) content.value = loaded
22
- },
23
- { immediate: true },
24
- )
25
-
26
13
  watch(
27
14
  () => props.asset.id,
28
15
  async (id) => {
@@ -7,6 +7,7 @@ import type {
7
7
  MediaFolder,
8
8
  ModifiedWindow,
9
9
  OrientationFilter,
10
+ SearchParams,
10
11
  SmartView,
11
12
  SortDirection,
12
13
  TypeFacets,
@@ -15,6 +16,14 @@ import type {
15
16
  import type { ListingSort } from '../useMediaPrefs'
16
17
  import type { LibraryTree } from './useLibraryTree'
17
18
 
19
+ /** Where a page of the listing starts: the number of files loaded before it. */
20
+ type ListingCursor = number
21
+
22
+ interface ListingRequest {
23
+ url: string
24
+ query: ListingParams | SearchParams
25
+ }
26
+
18
27
  export type LibraryLocation =
19
28
  | { kind: 'root' }
20
29
  | { kind: 'folder'; folderId: string }
@@ -33,13 +42,23 @@ export interface LibraryListingOptions {
33
42
  scopeFolderId?: string
34
43
  /** The explorer's tree, to skip folders the caller may see but not open. */
35
44
  tree?: LibraryTree
45
+ /** Where the listing starts, such as a link's folder: a server render reads it with the page. */
46
+ initialLocation?: LibraryLocation
47
+ /** The filters a link gives the starting location. */
48
+ initialFilters?: Partial<ListingFilters>
36
49
  }
37
50
 
38
51
  type AssetComparator = (left: MediaAsset, right: MediaAsset) => number
39
52
 
53
+ /** A page of the listing, with the size it was asked for: a revalidation asks for the same. */
54
+ interface ListingPage extends AssetPage {
55
+ limit: number
56
+ }
57
+
40
58
  const PAGE_SIZE = 120
41
- /** Largest page the API serves, used to reload or complete a long listing. */
59
+ /** Largest page the API serves, used to complete a long listing. */
42
60
  const MAX_PAGE_SIZE = 500
61
+ const LISTING_KEY_PREFIX = 'dms-media:listing:'
43
62
  const NARROWING_FILTERS: Omit<ListingFilters, keyof ListingSort> = {
44
63
  type: undefined,
45
64
  visibility: 'any',
@@ -59,11 +78,16 @@ const COMPARATORS: Record<AssetSortKey, AssetComparator> = {
59
78
  }
60
79
  const DIRECTION_FACTORS: Record<SortDirection, number> = { asc: 1, desc: -1 }
61
80
  const EMPTY_PAGE: AssetPage = { assets: [], total: 0, facets: {} }
81
+ const NO_FACETS: TypeFacets = {}
62
82
 
63
83
  export function sameLocation(left: LibraryLocation, right: LibraryLocation): boolean {
64
84
  return JSON.stringify(left) === JSON.stringify(right)
65
85
  }
66
86
 
87
+ function definedFilters(filters: Partial<ListingFilters> = {}): Partial<ListingFilters> {
88
+ return Object.fromEntries(Object.entries(filters).filter(([, value]) => value !== undefined))
89
+ }
90
+
67
91
  /** Where `asset` belongs among `assets` already in the listing's order. */
68
92
  function sortedIndex(assets: MediaAsset[], asset: MediaAsset, sort: ListingSort): number {
69
93
  const compare = COMPARATORS[sort.sort]
@@ -72,21 +96,50 @@ function sortedIndex(assets: MediaAsset[], asset: MediaAsset, sort: ListingSort)
72
96
  return index < 0 ? assets.length : index
73
97
  }
74
98
 
75
- /** What the explorer shows: the location, its files page by page and their filters. */
99
+ function loadedCount(pages: ListingPage[]): number {
100
+ return pages.reduce((count, page) => count + page.assets.length, 0)
101
+ }
102
+
103
+ /** Where the page after `pages` starts, or `null` once every file is loaded. */
104
+ function nextOffset(pages: ListingPage[]): number | null {
105
+ const last = pages.at(-1)
106
+ const loaded = loadedCount(pages)
107
+ return last && loaded < last.total ? loaded : null
108
+ }
109
+
110
+ /** Spreads `assets` over pages of the sizes `pages` hold, the last one taking the rest. */
111
+ function spreadOver(pages: ListingPage[], assets: MediaAsset[]): ListingPage[] {
112
+ let start = 0
113
+ return pages.map((page, index) => {
114
+ const end = index === pages.length - 1 ? assets.length : start + page.assets.length
115
+ const slice = assets.slice(start, end)
116
+ start = end
117
+ return { ...page, assets: slice }
118
+ })
119
+ }
120
+
121
+ /**
122
+ * What the explorer shows: the location, its files page by page and their
123
+ * filters. The files are one paged read keyed by the location and the
124
+ * filters: a return to a listing shows the pages loaded before at once, and
125
+ * a library change reads every loaded page again.
126
+ */
76
127
  export function useLibraryListing(options: LibraryListingOptions = {}) {
77
- const api = useMediaApi()
78
128
  const previews = useMediaPreviews()
79
- const location = ref<LibraryLocation>({ kind: 'root' })
129
+ const location = ref<LibraryLocation>(options.initialLocation ?? { kind: 'root' })
80
130
  const { prefs, update: updatePrefs } = useMediaPrefs()
81
131
  const preferredSort = computed(() => prefs.value.sort)
82
- const filters = ref<ListingFilters>({ ...preferredSort.value, ...NARROWING_FILTERS })
83
- const assets = ref<MediaAsset[]>([])
84
- const extraFolders = ref<MediaFolder[]>([])
85
- const total = ref(0)
86
- const facets = ref<TypeFacets>({})
87
- const isLoading = ref(false)
88
- const error = ref<unknown>(null)
89
- let requestId = 0
132
+ const filters = ref<ListingFilters>({
133
+ ...sortOf(location.value),
134
+ ...NARROWING_FILTERS,
135
+ ...definedFilters(options.initialFilters),
136
+ })
137
+
138
+ /** The order a location opens in: a smart view's own, the caller's otherwise. */
139
+ function sortOf(current: LibraryLocation): ListingSort {
140
+ return current.kind === 'view' ? (VIEW_SORTS[current.view] ?? preferredSort.value) : preferredSort.value
141
+ }
142
+ let pageLimit = PAGE_SIZE
90
143
 
91
144
  /** The picker's bound folder, once the tree confirms the caller can see it. */
92
145
  const scopeFolderId = computed(() => {
@@ -100,89 +153,119 @@ export function useLibraryListing(options: LibraryListingOptions = {}) {
100
153
  return Boolean(folder && (folder.shell || !folder.rights.read))
101
154
  }
102
155
 
156
+ const listingKey = computed(() =>
157
+ location.value.kind === 'root'
158
+ ? null
159
+ : `${LISTING_KEY_PREFIX}${JSON.stringify([location.value, filters.value, scopeFolderId.value ?? null])}`,
160
+ )
161
+
103
162
  function queryFor(offset: number, limit: number): ListingParams {
104
163
  const { sort, direction, type, visibility, modified, orientation } = filters.value
105
164
  return { offset, limit, sort, direction, type, visibility, modified, orientation }
106
165
  }
107
166
 
108
- function fetchPage(offset: number, limit = PAGE_SIZE): Promise<AssetPage> | null {
109
- const current = location.value
110
- const query = queryFor(offset, limit)
167
+ function requestFor(current: LibraryLocation, query: ListingParams): ListingRequest | null {
111
168
  if (current.kind === 'folder')
112
- return isUnreadable(current.folderId) ? Promise.resolve(EMPTY_PAGE) : api.folderAssets(current.folderId, query)
113
- if (current.kind === 'view') return api.smartView(current.view, { ...query, folderId: scopeFolderId.value })
169
+ return isUnreadable(current.folderId) ? null : { url: MEDIA_READS.folderAssets(current.folderId), query }
170
+ if (current.kind === 'view') return { url: MEDIA_READS.smartView(current.view), query: { ...query, folderId: scopeFolderId.value } }
114
171
  if (current.kind === 'search')
115
- return api.search({ ...query, q: current.query, folderId: current.scopeId ?? scopeFolderId.value })
172
+ return { url: MEDIA_READS.search, query: { ...query, q: current.query, folderId: current.scopeId ?? scopeFolderId.value } }
116
173
  return null
117
174
  }
118
175
 
119
- /** Every file up to `count`, fetched in the largest pages the API serves. */
120
- async function fetchFirst(count: number): Promise<AssetPage | null> {
121
- const first = await fetchPage(0, Math.min(Math.max(count, PAGE_SIZE), MAX_PAGE_SIZE))
122
- if (!first) return null
123
- const received = [...first.assets]
124
- while (received.length < Math.min(count, first.total)) {
125
- const next = await fetchPage(received.length, MAX_PAGE_SIZE)
126
- if (!next || next.assets.length === 0) break
127
- received.push(...next.assets)
128
- }
129
- return { ...first, assets: received }
130
- }
176
+ let shownPages = (): ListingPage[] => []
131
177
 
132
- function applyPage(page: AssetPage | null, append: boolean): void {
133
- const received = page?.assets ?? []
134
- assets.value = append ? [...assets.value, ...received] : received
135
- total.value = page?.total ?? 0
136
- facets.value = page?.facets ?? {}
137
- extraFolders.value = page?.folders ?? []
138
- previews.request(received)
178
+ /** The size of the page at `index`: the one it had when shown, so that a revalidation reads as many files. */
179
+ function limitOf(index: number): number {
180
+ return shownPages()[index]?.limit ?? pageLimit
139
181
  }
140
182
 
141
- async function run(fetch: () => Promise<AssetPage | null> | null, append: boolean, quiet = false): Promise<void> {
142
- const id = ++requestId
143
- if (!quiet) isLoading.value = true
144
- try {
145
- const page = await fetch()
146
- if (id !== requestId) return
147
- applyPage(page, append)
148
- error.value = null
149
- } catch (cause) {
150
- if (id === requestId && !quiet) error.value = cause
151
- } finally {
152
- if (id === requestId) isLoading.value = false
153
- }
183
+ const read = useApiPagedData<ListingPage, ListingCursor>(
184
+ listingKey,
185
+ async ({ $authFetch, cursor, index, signal }) => {
186
+ const limit = limitOf(index)
187
+ const request = requestFor(location.value, queryFor(cursor ?? 0, limit))
188
+ const page = request ? await $authFetch<AssetPage>(request.url, { query: request.query, signal }) : EMPTY_PAGE
189
+ return { ...page, limit }
190
+ },
191
+ {
192
+ nextCursor: (page, pages) => (page.assets.length === 0 ? null : nextOffset(pages)),
193
+ // Read again on each library change, its own trigger: the page's refreshes leave it alone.
194
+ refreshOnPageRefresh: false,
195
+ },
196
+ )
197
+
198
+ shownPages = () => (read.placeholder.value ? [] : read.pages.value)
199
+ const pages = computed<ListingPage[]>(() => shownPages())
200
+ const lastPage = computed(() => pages.value.at(-1))
201
+ const assets = computed<MediaAsset[]>(() => pages.value.flatMap((page) => page.assets))
202
+ const total = computed(() => lastPage.value?.total ?? 0)
203
+ const facets = computed(() => lastPage.value?.facets ?? NO_FACETS)
204
+ const extraFolders = computed<MediaFolder[]>(() => lastPage.value?.folders ?? [])
205
+ const isLoading = computed(
206
+ () => read.loadingMore.value || (read.pending.value && (read.placeholder.value || pages.value.length === 0)),
207
+ )
208
+ const error = computed(() => (listingKey.value ? read.error.value : null))
209
+ const hasMore = computed(() => read.hasMore.value)
210
+
211
+ watch(assets, (shown) => previews.request(shown))
212
+
213
+ /** Resolves once the read the location or the filters started is done. */
214
+ async function settled(): Promise<void> {
215
+ await nextTick()
216
+ if (!read.pending.value) return
217
+ await new Promise<void>((resolve) => {
218
+ const stop = watch(read.pending, (pending) => {
219
+ if (pending) return
220
+ stop()
221
+ resolve()
222
+ })
223
+ })
154
224
  }
155
225
 
226
+ /** Loads the next page, or reads the loaded ones again. */
156
227
  function load(append = false): Promise<void> {
157
- return run(() => fetchPage(append ? assets.value.length : 0), append)
228
+ return append ? read.loadMore() : read.refresh()
158
229
  }
159
230
 
160
- /** Loads the files not fetched yet, so a selection or an action covers the whole listing. */
161
- function loadAll(): Promise<void> {
162
- if (assets.value.length >= total.value) return Promise.resolve()
163
- return run(() => fetchFirst(total.value), false)
231
+ /** Loads the files not fetched yet, in the largest pages the API serves, so a selection or an action covers the whole listing. */
232
+ async function loadAll(): Promise<void> {
233
+ pageLimit = MAX_PAGE_SIZE
234
+ try {
235
+ let loaded = -1
236
+ while (read.hasMore.value && assets.value.length !== loaded) {
237
+ loaded = assets.value.length
238
+ await read.loadMore()
239
+ }
240
+ } finally {
241
+ pageLimit = PAGE_SIZE
242
+ }
164
243
  }
165
244
 
166
245
  /** Re-reads what is on screen after a change elsewhere, keeping as many files as were loaded. */
167
- function refresh(): Promise<void> {
246
+ async function refresh(): Promise<void> {
168
247
  const before = new Map(assets.value.map((asset) => [asset.id, asset.updatedAt]))
169
- return run(() => fetchFirst(assets.value.length), false, true).then(() => {
170
- for (const asset of assets.value) {
171
- const previous = before.get(asset.id)
172
- if (previous && previous !== asset.updatedAt) previews.forget(asset.id)
173
- }
174
- previews.request(assets.value)
175
- })
248
+ await read.refresh({ dedupe: 'defer' })
249
+ for (const asset of assets.value) {
250
+ const previous = before.get(asset.id)
251
+ if (previous && previous !== asset.updatedAt) previews.forget(asset.id)
252
+ }
253
+ previews.request(assets.value)
254
+ }
255
+
256
+ /** Replaces the pages shown with what `update` makes of them, the next page following. */
257
+ function rewritePages(update: (shown: ListingPage[]) => ListingPage[]): void {
258
+ if (pages.value.length === 0) return
259
+ const next = update(pages.value)
260
+ read.data.value = { pages: next, next: nextOffset(next) }
176
261
  }
177
262
 
178
263
  function setLocation(next: LibraryLocation): Promise<void> {
179
264
  const keepsNarrowing = location.value.kind === 'search' && next.kind === 'search'
180
265
  location.value = next
181
- const sort = next.kind === 'view' ? (VIEW_SORTS[next.view] ?? preferredSort.value) : preferredSort.value
266
+ const sort = sortOf(next)
182
267
  filters.value = keepsNarrowing ? { ...filters.value, ...sort } : { ...sort, ...NARROWING_FILTERS }
183
- assets.value = []
184
- total.value = 0
185
- return load()
268
+ return settled()
186
269
  }
187
270
 
188
271
  function rememberSort(changes: Partial<ListingFilters>): void {
@@ -195,20 +278,39 @@ export function useLibraryListing(options: LibraryListingOptions = {}) {
195
278
  function setFilters(changes: Partial<ListingFilters>): Promise<void> {
196
279
  filters.value = { ...filters.value, ...changes }
197
280
  rememberSort(changes)
198
- return load()
281
+ return settled()
199
282
  }
200
283
 
201
284
  function patchAsset(assetId: string, changes: Partial<MediaAsset>): void {
202
- assets.value = assets.value.map((asset) =>
203
- asset.id === assetId ? { ...asset, ...changes } : asset,
285
+ rewritePages((shown) =>
286
+ shown.map((page) => ({
287
+ ...page,
288
+ assets: page.assets.map((asset) => (asset.id === assetId ? { ...asset, ...changes } : asset)),
289
+ })),
204
290
  )
205
291
  }
206
292
 
293
+ /** Puts the loaded files in `order`, which holds the same files. */
294
+ function reorderAssets(order: MediaAsset[]): void {
295
+ rewritePages((shown) => spreadOver(shown, order))
296
+ }
297
+
207
298
  function removeAssets(ids: string[]): void {
208
299
  const removed = new Set(ids)
209
- const before = assets.value.length
210
- assets.value = assets.value.filter((asset) => !removed.has(asset.id))
211
- total.value = Math.max(total.value - (before - assets.value.length), 0)
300
+ const count = assets.value.filter((asset) => removed.has(asset.id)).length
301
+ rewritePages((shown) =>
302
+ shown.map((page) => ({
303
+ ...page,
304
+ assets: page.assets.filter((asset) => !removed.has(asset.id)),
305
+ total: Math.max(page.total - count, 0),
306
+ })),
307
+ )
308
+ }
309
+
310
+ function removeExtraFolder(folderId: string): void {
311
+ rewritePages((shown) =>
312
+ shown.map((page) => ({ ...page, folders: page.folders?.filter((folder) => folder.id !== folderId) })),
313
+ )
212
314
  }
213
315
 
214
316
  /** Places a new file where the current sort puts it, or only counts it when it belongs to a page not loaded yet. */
@@ -216,14 +318,11 @@ export function useLibraryListing(options: LibraryListingOptions = {}) {
216
318
  if (assets.value.some((entry) => entry.id === asset.id)) return
217
319
  if (filters.value.type && asset.typeGroup !== filters.value.type) return
218
320
  const index = sortedIndex(assets.value, asset, filters.value)
219
- total.value += 1
220
- if (index === assets.value.length && assets.value.length < total.value - 1) return
221
- assets.value = [...assets.value.slice(0, index), asset, ...assets.value.slice(index)]
222
- previews.request([asset])
321
+ const isBeyondLoaded = index === assets.value.length && hasMore.value
322
+ const order = isBeyondLoaded ? assets.value : [...assets.value.slice(0, index), asset, ...assets.value.slice(index)]
323
+ rewritePages((shown) => spreadOver(shown.map((page) => ({ ...page, total: page.total + 1 })), order))
223
324
  }
224
325
 
225
- const hasMore = computed(() => assets.value.length < total.value)
226
-
227
326
  onLibraryChange(() => location.value.kind !== 'root' && refresh())
228
327
 
229
328
  return {
@@ -243,7 +342,9 @@ export function useLibraryListing(options: LibraryListingOptions = {}) {
243
342
  setLocation,
244
343
  setFilters,
245
344
  patchAsset,
345
+ reorderAssets,
246
346
  removeAssets,
347
+ removeExtraFolder,
247
348
  insertAsset,
248
349
  }
249
350
  }
@@ -25,12 +25,21 @@ function subtreeIds(folders: MediaFolder[], rootId: string): Set<string> {
25
25
  return ids
26
26
  }
27
27
 
28
- /** The folder tree the caller can see, with lookups by id and by parent. */
28
+ /**
29
+ * The folder tree the caller can see, with lookups by id and by parent. The
30
+ * tree is read with the page (counted over the scope folder when given),
31
+ * shared with the other blocks reading it, and read again on each library
32
+ * change.
33
+ */
29
34
  export function useLibraryTree(options: LibraryTreeOptions = {}) {
30
- const api = useMediaApi()
31
- const tree = ref<MediaTree | null>(null)
32
- const isLoading = ref(false)
33
- const error = ref<unknown>(null)
35
+ // Read again on each library change, its own trigger: the page's refreshes leave it alone.
36
+ const read = useApiData<MediaTree>(MEDIA_READS.tree, {
37
+ query: options.scopeFolderId ? { folderId: options.scopeFolderId } : undefined,
38
+ refreshOnPageRefresh: false,
39
+ })
40
+ const tree = read.data
41
+ const isLoading = read.pending
42
+ const error = read.error
34
43
 
35
44
  const allFolders = computed(() => tree.value?.folders ?? [])
36
45
  const scopeFolder = computed(() =>
@@ -71,18 +80,24 @@ export function useLibraryTree(options: LibraryTreeOptions = {}) {
71
80
  return result
72
81
  }
73
82
 
74
- async function refresh(): Promise<void> {
75
- isLoading.value = true
76
- try {
77
- tree.value = await fetchTree(api, options.scopeFolderId)
78
- error.value = null
79
- } catch (cause) {
80
- error.value = cause
81
- } finally {
82
- isLoading.value = false
83
- }
83
+ /** Resolves once the tree's first read is done. */
84
+ async function ready(): Promise<void> {
85
+ await read
86
+ }
87
+
88
+ /** Reads the tree again; the blocks asking at once share one request. */
89
+ function refresh(): Promise<void> {
90
+ return read.refresh({ dedupe: 'defer' })
84
91
  }
85
92
 
93
+ watch(
94
+ tree,
95
+ (current) => {
96
+ if (current) rememberUploadLimits(current)
97
+ },
98
+ { immediate: true },
99
+ )
100
+
86
101
  function patchFolder(folderId: string, changes: Partial<MediaFolder>): void {
87
102
  if (!tree.value) return
88
103
  tree.value = {
@@ -141,6 +156,7 @@ export function useLibraryTree(options: LibraryTreeOptions = {}) {
141
156
  foldersById,
142
157
  childrenOf,
143
158
  descendantsOf,
159
+ ready,
144
160
  refresh,
145
161
  patchFolder,
146
162
  adjustCounts,
@@ -7,7 +7,7 @@ import type {
7
7
  MediaAsset,
8
8
  MediaFolder,
9
9
  } from '../../types/media'
10
- import { type LibraryLocation, sameLocation } from './useLibraryListing'
10
+ import { type LibraryLocation, type ListingFilters, sameLocation } from './useLibraryListing'
11
11
 
12
12
  const LIBRARY_KEY: InjectionKey<MediaLibrary> = Symbol('dms-media-library')
13
13
 
@@ -22,6 +22,10 @@ export interface MediaLibraryOptions {
22
22
  scopeFolderId?: string
23
23
  /** Files the picker's field already holds: shown, but not picked twice. */
24
24
  alreadyPicked?: string[]
25
+ /** Where the explorer starts, read with the page by a server render. */
26
+ initialLocation?: LibraryLocation
27
+ /** The filters it starts with. */
28
+ initialFilters?: Partial<ListingFilters>
25
29
  }
26
30
 
27
31
  /** What a name dialog learns from a write: whether it is done, or the refusal to show under the field. */
@@ -39,13 +43,19 @@ function createMediaLibrary(options: MediaLibraryOptions) {
39
43
  const previews = useMediaPreviews()
40
44
  const uploads = useUploadQueue()
41
45
  const tree = useLibraryTree({ scopeFolderId: options.scopeFolderId })
42
- const listing = useLibraryListing({ scopeFolderId: options.scopeFolderId, tree })
46
+ const listing = useLibraryListing({
47
+ scopeFolderId: options.scopeFolderId,
48
+ tree,
49
+ initialLocation: options.initialLocation,
50
+ initialFilters: options.initialFilters,
51
+ })
43
52
  const isPick = options.mode === 'pick'
44
53
  const selection = useLibrarySelection(listing.assets, isPick)
45
54
  const backStack = ref<LibraryLocation[]>([])
46
55
  const forwardStack = ref<LibraryLocation[]>([])
47
- const lastFolderId = ref<string | null>(null)
48
- const beforeSearch = ref<LibraryLocation>({ kind: 'root' })
56
+ const start = listing.location.value
57
+ const lastFolderId = ref<string | null>(start.kind === 'folder' ? start.folderId : null)
58
+ const beforeSearch = ref<LibraryLocation>(start.kind === 'search' ? { kind: 'root' } : start)
49
59
  const accept = options.accept ?? []
50
60
  const alreadyPicked = new Set(options.alreadyPicked ?? [])
51
61
 
@@ -269,8 +279,8 @@ function createDetailActions(library: LibraryCore) {
269
279
  const { sort, direction } = listing.filters.value
270
280
  if (sort !== 'name') return
271
281
  const factor = direction === 'desc' ? -1 : 1
272
- listing.assets.value = [...listing.assets.value].sort(
273
- (left, right) => NAME_COLLATOR.compare(left.name, right.name) * factor,
282
+ listing.reorderAssets(
283
+ [...listing.assets.value].sort((left, right) => NAME_COLLATOR.compare(left.name, right.name) * factor),
274
284
  )
275
285
  }
276
286
 
@@ -385,7 +395,7 @@ function createStarActions(library: LibraryCore) {
385
395
 
386
396
  function leaveStarredView(target: MediaAsset | MediaFolder, kind: 'asset' | 'folder'): void {
387
397
  if (kind === 'asset') listing.removeAssets([target.id])
388
- else listing.extraFolders.value = listing.extraFolders.value.filter((folder) => folder.id !== target.id)
398
+ else listing.removeExtraFolder(target.id)
389
399
  library.toast.add({
390
400
  title: t('dms_media.toasts.unstarred', { name: target.name }),
391
401
  color: 'neutral',
@@ -0,0 +1,25 @@
1
+ const DEFAULT_MAX_UPLOAD_BYTES = 500 * 1024 * 1024
2
+
3
+ /** What the library takes at all, from the module config: every upload is checked against it before it is sent. */
4
+ export interface UploadLimits {
5
+ maxUploadBytes: number
6
+ /** Mimetype patterns the library accepts; any type until the server says otherwise. */
7
+ allowedMimetypes: readonly string[] | null
8
+ }
9
+
10
+ const limits = ref<UploadLimits>({
11
+ maxUploadBytes: DEFAULT_MAX_UPLOAD_BYTES,
12
+ allowedMimetypes: null,
13
+ })
14
+
15
+ /** The upload limits the server last sent, shared by every screen that uploads. */
16
+ export const uploadLimits = readonly(limits)
17
+
18
+ /** Keeps the upload limits a server answer carries: browser state, which a server render leaves alone. */
19
+ export function rememberUploadLimits(answer: UploadLimits): void {
20
+ if (import.meta.env.SSR) return
21
+ limits.value = {
22
+ maxUploadBytes: answer.maxUploadBytes,
23
+ allowedMimetypes: answer.allowedMimetypes,
24
+ }
25
+ }
@@ -59,3 +59,23 @@ export function useAssetContent() {
59
59
 
60
60
  return { load }
61
61
  }
62
+
63
+ const NO_CONTENT: AssetContent = { kind: 'none' }
64
+
65
+ /**
66
+ * What a viewer shows of the file `asset` returns, read with the page under a
67
+ * key per file version. A server render gives an image, a video or a frame its
68
+ * read URL, so the browser loads it before hydrating; the first lines of a text
69
+ * file are read from the storage by the browser alone (the viewer's first file
70
+ * decides, as only it can be rendered on the server). Nothing shows while the
71
+ * next file's content loads.
72
+ */
73
+ export function useShownContent(asset: () => ShownAsset & Pick<MediaAsset, 'updatedAt'>) {
74
+ const { load } = useAssetContent()
75
+ const read = useApiData<AssetContent>(
76
+ () => `dms-media:content:${asset().id}:${asset().updatedAt}`,
77
+ () => load(asset()),
78
+ { server: contentKindOf(asset()) !== 'text' },
79
+ )
80
+ return computed(() => (read.placeholder.value ? NO_CONTENT : (read.data.value ?? NO_CONTENT)))
81
+ }