@aphexcms/cms-core 9.9.0 → 10.0.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 (324) hide show
  1. package/dist/api/assets.d.ts +62 -7
  2. package/dist/api/assets.d.ts.map +1 -1
  3. package/dist/api/assets.js +116 -9
  4. package/dist/api/client.d.ts +1 -1
  5. package/dist/api/client.d.ts.map +1 -1
  6. package/dist/api/client.js +39 -9
  7. package/dist/api/limits.d.ts +55 -0
  8. package/dist/api/limits.d.ts.map +1 -0
  9. package/dist/api/limits.js +58 -0
  10. package/dist/api/schemas/assets.d.ts +94 -4
  11. package/dist/api/schemas/assets.d.ts.map +1 -1
  12. package/dist/api/schemas/assets.js +82 -5
  13. package/dist/api/schemas/documents.d.ts +1 -0
  14. package/dist/api/schemas/documents.d.ts.map +1 -1
  15. package/dist/api/schemas/documents.js +1 -0
  16. package/dist/api/types.d.ts +25 -0
  17. package/dist/api/types.d.ts.map +1 -1
  18. package/dist/api/upload-timeout.d.ts +17 -0
  19. package/dist/api/upload-timeout.d.ts.map +1 -0
  20. package/dist/api/upload-timeout.js +35 -0
  21. package/dist/api/upload.d.ts +42 -0
  22. package/dist/api/upload.d.ts.map +1 -0
  23. package/dist/api/upload.js +144 -0
  24. package/dist/components/AdminApp.svelte +213 -32
  25. package/dist/components/AdminApp.svelte.d.ts.map +1 -1
  26. package/dist/components/admin/AssetBrowserModal.svelte +4 -3
  27. package/dist/components/admin/AssetBrowserModal.svelte.d.ts +2 -1
  28. package/dist/components/admin/AssetBrowserModal.svelte.d.ts.map +1 -1
  29. package/dist/components/admin/MediaBrowser.svelte +1859 -281
  30. package/dist/components/admin/MediaBrowser.svelte.d.ts +21 -1
  31. package/dist/components/admin/MediaBrowser.svelte.d.ts.map +1 -1
  32. package/dist/components/admin/fields/ArrayField.svelte +21 -10
  33. package/dist/components/admin/fields/ArrayField.svelte.d.ts.map +1 -1
  34. package/dist/components/admin/fields/FileField.svelte +9 -2
  35. package/dist/components/admin/fields/FileField.svelte.d.ts.map +1 -1
  36. package/dist/components/admin/fields/ImageField.svelte +47 -12
  37. package/dist/components/admin/fields/ImageField.svelte.d.ts.map +1 -1
  38. package/dist/config.d.ts.map +1 -1
  39. package/dist/config.js +14 -0
  40. package/dist/db/interfaces/asset.d.ts +114 -5
  41. package/dist/db/interfaces/asset.d.ts.map +1 -1
  42. package/dist/db/interfaces/document.d.ts +107 -3
  43. package/dist/db/interfaces/document.d.ts.map +1 -1
  44. package/dist/hooks.d.ts.map +1 -1
  45. package/dist/hooks.js +2 -1
  46. package/dist/image/Image.svelte +72 -0
  47. package/dist/image/Image.svelte.d.ts +40 -0
  48. package/dist/image/Image.svelte.d.ts.map +1 -0
  49. package/dist/image/index.d.ts +3 -0
  50. package/dist/image/index.d.ts.map +1 -0
  51. package/dist/image/index.js +11 -0
  52. package/dist/image/types.d.ts +28 -0
  53. package/dist/image/types.d.ts.map +1 -0
  54. package/dist/image/types.js +1 -0
  55. package/dist/images/generate.d.ts +55 -0
  56. package/dist/images/generate.d.ts.map +1 -0
  57. package/dist/images/generate.js +243 -0
  58. package/dist/images/index.d.ts +2 -0
  59. package/dist/images/index.d.ts.map +1 -0
  60. package/dist/images/index.js +7 -0
  61. package/dist/images/variants.d.ts +82 -0
  62. package/dist/images/variants.d.ts.map +1 -0
  63. package/dist/images/variants.js +124 -0
  64. package/dist/jobs/asset-reference-jobs.d.ts +49 -0
  65. package/dist/jobs/asset-reference-jobs.d.ts.map +1 -0
  66. package/dist/jobs/asset-reference-jobs.js +74 -0
  67. package/dist/jobs/run-batch.d.ts.map +1 -1
  68. package/dist/jobs/run-batch.js +5 -0
  69. package/dist/lib/api/assets.d.ts +62 -7
  70. package/dist/lib/api/assets.d.ts.map +1 -1
  71. package/dist/lib/api/assets.js +116 -9
  72. package/dist/lib/api/assets.js.map +1 -1
  73. package/dist/lib/api/client.d.ts +1 -1
  74. package/dist/lib/api/client.d.ts.map +1 -1
  75. package/dist/lib/api/client.js +39 -9
  76. package/dist/lib/api/client.js.map +1 -1
  77. package/dist/lib/api/limits.d.ts +55 -0
  78. package/dist/lib/api/limits.d.ts.map +1 -0
  79. package/dist/lib/api/limits.js +59 -0
  80. package/dist/lib/api/limits.js.map +1 -0
  81. package/dist/lib/api/schemas/assets.d.ts +94 -4
  82. package/dist/lib/api/schemas/assets.d.ts.map +1 -1
  83. package/dist/lib/api/schemas/assets.js +82 -5
  84. package/dist/lib/api/schemas/assets.js.map +1 -1
  85. package/dist/lib/api/schemas/documents.d.ts +1 -0
  86. package/dist/lib/api/schemas/documents.d.ts.map +1 -1
  87. package/dist/lib/api/schemas/documents.js +1 -0
  88. package/dist/lib/api/schemas/documents.js.map +1 -1
  89. package/dist/lib/api/types.d.ts +25 -0
  90. package/dist/lib/api/types.d.ts.map +1 -1
  91. package/dist/lib/api/upload-timeout.d.ts +17 -0
  92. package/dist/lib/api/upload-timeout.d.ts.map +1 -0
  93. package/dist/lib/api/upload-timeout.js +36 -0
  94. package/dist/lib/api/upload-timeout.js.map +1 -0
  95. package/dist/lib/api/upload.d.ts +42 -0
  96. package/dist/lib/api/upload.d.ts.map +1 -0
  97. package/dist/lib/api/upload.js +145 -0
  98. package/dist/lib/api/upload.js.map +1 -0
  99. package/dist/lib/config.d.ts.map +1 -1
  100. package/dist/lib/config.js +14 -0
  101. package/dist/lib/config.js.map +1 -1
  102. package/dist/lib/db/interfaces/asset.d.ts +114 -5
  103. package/dist/lib/db/interfaces/asset.d.ts.map +1 -1
  104. package/dist/lib/db/interfaces/document.d.ts +107 -3
  105. package/dist/lib/db/interfaces/document.d.ts.map +1 -1
  106. package/dist/lib/hooks.d.ts.map +1 -1
  107. package/dist/lib/hooks.js +2 -1
  108. package/dist/lib/hooks.js.map +1 -1
  109. package/dist/lib/image/index.d.ts +3 -0
  110. package/dist/lib/image/index.d.ts.map +1 -0
  111. package/dist/lib/image/index.js +12 -0
  112. package/dist/lib/image/index.js.map +1 -0
  113. package/dist/lib/image/types.d.ts +28 -0
  114. package/dist/lib/image/types.d.ts.map +1 -0
  115. package/dist/lib/image/types.js +2 -0
  116. package/dist/lib/image/types.js.map +1 -0
  117. package/dist/lib/images/generate.d.ts +55 -0
  118. package/dist/lib/images/generate.d.ts.map +1 -0
  119. package/dist/lib/images/generate.js +244 -0
  120. package/dist/lib/images/generate.js.map +1 -0
  121. package/dist/lib/images/index.d.ts +2 -0
  122. package/dist/lib/images/index.d.ts.map +1 -0
  123. package/dist/lib/images/index.js +8 -0
  124. package/dist/lib/images/index.js.map +1 -0
  125. package/dist/lib/images/variants.d.ts +82 -0
  126. package/dist/lib/images/variants.d.ts.map +1 -0
  127. package/dist/lib/images/variants.js +125 -0
  128. package/dist/lib/images/variants.js.map +1 -0
  129. package/dist/lib/jobs/asset-reference-jobs.d.ts +49 -0
  130. package/dist/lib/jobs/asset-reference-jobs.d.ts.map +1 -0
  131. package/dist/lib/jobs/asset-reference-jobs.js +75 -0
  132. package/dist/lib/jobs/asset-reference-jobs.js.map +1 -0
  133. package/dist/lib/jobs/run-batch.d.ts.map +1 -1
  134. package/dist/lib/jobs/run-batch.js +5 -0
  135. package/dist/lib/jobs/run-batch.js.map +1 -1
  136. package/dist/lib/local-api/collection-api.d.ts +25 -2
  137. package/dist/lib/local-api/collection-api.d.ts.map +1 -1
  138. package/dist/lib/local-api/collection-api.js +107 -20
  139. package/dist/lib/local-api/collection-api.js.map +1 -1
  140. package/dist/lib/preview/assets.d.ts +19 -0
  141. package/dist/lib/preview/assets.d.ts.map +1 -1
  142. package/dist/lib/preview/assets.js +6 -0
  143. package/dist/lib/preview/assets.js.map +1 -1
  144. package/dist/lib/routes/assets-cdn.d.ts +19 -0
  145. package/dist/lib/routes/assets-cdn.d.ts.map +1 -1
  146. package/dist/lib/routes/assets-cdn.js +295 -17
  147. package/dist/lib/routes/assets-cdn.js.map +1 -1
  148. package/dist/lib/schema-utils/utils.d.ts +31 -1
  149. package/dist/lib/schema-utils/utils.d.ts.map +1 -1
  150. package/dist/lib/schema-utils/utils.js +68 -0
  151. package/dist/lib/schema-utils/utils.js.map +1 -1
  152. package/dist/lib/server/api/index.d.ts.map +1 -1
  153. package/dist/lib/server/api/index.js +87 -8
  154. package/dist/lib/server/api/index.js.map +1 -1
  155. package/dist/lib/server/api/routes/assets-bulk.d.ts.map +1 -1
  156. package/dist/lib/server/api/routes/assets-bulk.js +36 -7
  157. package/dist/lib/server/api/routes/assets-bulk.js.map +1 -1
  158. package/dist/lib/server/api/routes/assets-by-id.d.ts.map +1 -1
  159. package/dist/lib/server/api/routes/assets-by-id.js +32 -15
  160. package/dist/lib/server/api/routes/assets-by-id.js.map +1 -1
  161. package/dist/lib/server/api/routes/assets-direct-upload.d.ts +4 -0
  162. package/dist/lib/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  163. package/dist/lib/server/api/routes/assets-direct-upload.js +164 -0
  164. package/dist/lib/server/api/routes/assets-direct-upload.js.map +1 -0
  165. package/dist/lib/server/api/routes/assets-poster.d.ts +4 -0
  166. package/dist/lib/server/api/routes/assets-poster.d.ts.map +1 -0
  167. package/dist/lib/server/api/routes/assets-poster.js +120 -0
  168. package/dist/lib/server/api/routes/assets-poster.js.map +1 -0
  169. package/dist/lib/server/api/routes/assets-references.d.ts.map +1 -1
  170. package/dist/lib/server/api/routes/assets-references.js +64 -5
  171. package/dist/lib/server/api/routes/assets-references.js.map +1 -1
  172. package/dist/lib/server/api/routes/assets.d.ts.map +1 -1
  173. package/dist/lib/server/api/routes/assets.js +116 -12
  174. package/dist/lib/server/api/routes/assets.js.map +1 -1
  175. package/dist/lib/server/api/routes/clear-asset-references.d.ts +18 -0
  176. package/dist/lib/server/api/routes/clear-asset-references.d.ts.map +1 -0
  177. package/dist/lib/server/api/routes/clear-asset-references.js +32 -0
  178. package/dist/lib/server/api/routes/clear-asset-references.js.map +1 -0
  179. package/dist/lib/server/api/routes/documents.d.ts.map +1 -1
  180. package/dist/lib/server/api/routes/documents.js +28 -1
  181. package/dist/lib/server/api/routes/documents.js.map +1 -1
  182. package/dist/lib/server/index.d.ts +2 -0
  183. package/dist/lib/server/index.d.ts.map +1 -1
  184. package/dist/lib/server/index.js +4 -0
  185. package/dist/lib/server/index.js.map +1 -1
  186. package/dist/lib/services/asset-references-service.d.ts +93 -0
  187. package/dist/lib/services/asset-references-service.d.ts.map +1 -0
  188. package/dist/lib/services/asset-references-service.js +198 -0
  189. package/dist/lib/services/asset-references-service.js.map +1 -0
  190. package/dist/lib/services/asset-service.d.ts +115 -14
  191. package/dist/lib/services/asset-service.d.ts.map +1 -1
  192. package/dist/lib/services/asset-service.js +312 -31
  193. package/dist/lib/services/asset-service.js.map +1 -1
  194. package/dist/lib/services/references-service.d.ts +19 -15
  195. package/dist/lib/services/references-service.d.ts.map +1 -1
  196. package/dist/lib/services/references-service.js +59 -31
  197. package/dist/lib/services/references-service.js.map +1 -1
  198. package/dist/lib/services/version-service.d.ts +10 -1
  199. package/dist/lib/services/version-service.d.ts.map +1 -1
  200. package/dist/lib/services/version-service.js +26 -4
  201. package/dist/lib/services/version-service.js.map +1 -1
  202. package/dist/lib/storage/adapters/local-storage-adapter.d.ts +38 -0
  203. package/dist/lib/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  204. package/dist/lib/storage/adapters/local-storage-adapter.js +86 -19
  205. package/dist/lib/storage/adapters/local-storage-adapter.js.map +1 -1
  206. package/dist/lib/storage/index.d.ts +1 -0
  207. package/dist/lib/storage/index.d.ts.map +1 -1
  208. package/dist/lib/storage/index.js +2 -0
  209. package/dist/lib/storage/index.js.map +1 -1
  210. package/dist/lib/storage/interfaces/storage.d.ts +135 -5
  211. package/dist/lib/storage/interfaces/storage.d.ts.map +1 -1
  212. package/dist/lib/storage/keys.d.ts +96 -0
  213. package/dist/lib/storage/keys.d.ts.map +1 -0
  214. package/dist/lib/storage/keys.js +160 -0
  215. package/dist/lib/storage/keys.js.map +1 -0
  216. package/dist/lib/type-gen.d.ts.map +1 -1
  217. package/dist/lib/type-gen.js +11 -5
  218. package/dist/lib/type-gen.js.map +1 -1
  219. package/dist/lib/types/asset.d.ts +92 -12
  220. package/dist/lib/types/asset.d.ts.map +1 -1
  221. package/dist/lib/types/capabilities.d.ts +11 -0
  222. package/dist/lib/types/capabilities.d.ts.map +1 -1
  223. package/dist/lib/types/capabilities.js +20 -6
  224. package/dist/lib/types/capabilities.js.map +1 -1
  225. package/dist/lib/types/config.d.ts +127 -0
  226. package/dist/lib/types/config.d.ts.map +1 -1
  227. package/dist/lib/types/filters.d.ts +31 -0
  228. package/dist/lib/types/filters.d.ts.map +1 -1
  229. package/dist/lib/types/schemas.d.ts +14 -0
  230. package/dist/lib/types/schemas.d.ts.map +1 -1
  231. package/dist/lib/utils/asset-reference-walk.d.ts +44 -0
  232. package/dist/lib/utils/asset-reference-walk.d.ts.map +1 -0
  233. package/dist/lib/utils/asset-reference-walk.js +144 -0
  234. package/dist/lib/utils/asset-reference-walk.js.map +1 -0
  235. package/dist/lib/utils/image-url.d.ts +61 -26
  236. package/dist/lib/utils/image-url.d.ts.map +1 -1
  237. package/dist/lib/utils/image-url.js +143 -26
  238. package/dist/lib/utils/image-url.js.map +1 -1
  239. package/dist/lib/utils/video-metadata.d.ts +39 -0
  240. package/dist/lib/utils/video-metadata.d.ts.map +1 -0
  241. package/dist/lib/utils/video-metadata.js +161 -0
  242. package/dist/lib/utils/video-metadata.js.map +1 -0
  243. package/dist/local-api/collection-api.d.ts +25 -2
  244. package/dist/local-api/collection-api.d.ts.map +1 -1
  245. package/dist/local-api/collection-api.js +107 -20
  246. package/dist/preview/assets.d.ts +19 -0
  247. package/dist/preview/assets.d.ts.map +1 -1
  248. package/dist/preview/assets.js +6 -0
  249. package/dist/routes/assets-cdn.d.ts +19 -0
  250. package/dist/routes/assets-cdn.d.ts.map +1 -1
  251. package/dist/routes/assets-cdn.js +295 -17
  252. package/dist/schema-utils/utils.d.ts +31 -1
  253. package/dist/schema-utils/utils.d.ts.map +1 -1
  254. package/dist/schema-utils/utils.js +68 -0
  255. package/dist/server/api/index.d.ts.map +1 -1
  256. package/dist/server/api/index.js +87 -8
  257. package/dist/server/api/routes/assets-bulk.d.ts.map +1 -1
  258. package/dist/server/api/routes/assets-bulk.js +36 -7
  259. package/dist/server/api/routes/assets-by-id.d.ts.map +1 -1
  260. package/dist/server/api/routes/assets-by-id.js +32 -15
  261. package/dist/server/api/routes/assets-direct-upload.d.ts +4 -0
  262. package/dist/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  263. package/dist/server/api/routes/assets-direct-upload.js +163 -0
  264. package/dist/server/api/routes/assets-poster.d.ts +4 -0
  265. package/dist/server/api/routes/assets-poster.d.ts.map +1 -0
  266. package/dist/server/api/routes/assets-poster.js +119 -0
  267. package/dist/server/api/routes/assets-references.d.ts.map +1 -1
  268. package/dist/server/api/routes/assets-references.js +64 -5
  269. package/dist/server/api/routes/assets.d.ts.map +1 -1
  270. package/dist/server/api/routes/assets.js +116 -12
  271. package/dist/server/api/routes/clear-asset-references.d.ts +18 -0
  272. package/dist/server/api/routes/clear-asset-references.d.ts.map +1 -0
  273. package/dist/server/api/routes/clear-asset-references.js +31 -0
  274. package/dist/server/api/routes/documents.d.ts.map +1 -1
  275. package/dist/server/api/routes/documents.js +28 -1
  276. package/dist/server/index.d.ts +2 -0
  277. package/dist/server/index.d.ts.map +1 -1
  278. package/dist/server/index.js +4 -0
  279. package/dist/services/asset-references-service.d.ts +93 -0
  280. package/dist/services/asset-references-service.d.ts.map +1 -0
  281. package/dist/services/asset-references-service.js +197 -0
  282. package/dist/services/asset-service.d.ts +115 -14
  283. package/dist/services/asset-service.d.ts.map +1 -1
  284. package/dist/services/asset-service.js +312 -31
  285. package/dist/services/references-service.d.ts +19 -15
  286. package/dist/services/references-service.d.ts.map +1 -1
  287. package/dist/services/references-service.js +59 -31
  288. package/dist/services/version-service.d.ts +10 -1
  289. package/dist/services/version-service.d.ts.map +1 -1
  290. package/dist/services/version-service.js +26 -4
  291. package/dist/storage/adapters/local-storage-adapter.d.ts +38 -0
  292. package/dist/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  293. package/dist/storage/adapters/local-storage-adapter.js +86 -19
  294. package/dist/storage/index.d.ts +1 -0
  295. package/dist/storage/index.d.ts.map +1 -1
  296. package/dist/storage/index.js +2 -0
  297. package/dist/storage/interfaces/storage.d.ts +135 -5
  298. package/dist/storage/interfaces/storage.d.ts.map +1 -1
  299. package/dist/storage/keys.d.ts +96 -0
  300. package/dist/storage/keys.d.ts.map +1 -0
  301. package/dist/storage/keys.js +159 -0
  302. package/dist/type-gen.d.ts.map +1 -1
  303. package/dist/type-gen.js +11 -5
  304. package/dist/types/asset.d.ts +92 -12
  305. package/dist/types/asset.d.ts.map +1 -1
  306. package/dist/types/capabilities.d.ts +11 -0
  307. package/dist/types/capabilities.d.ts.map +1 -1
  308. package/dist/types/capabilities.js +20 -6
  309. package/dist/types/config.d.ts +127 -0
  310. package/dist/types/config.d.ts.map +1 -1
  311. package/dist/types/filters.d.ts +31 -0
  312. package/dist/types/filters.d.ts.map +1 -1
  313. package/dist/types/schemas.d.ts +14 -0
  314. package/dist/types/schemas.d.ts.map +1 -1
  315. package/dist/utils/asset-reference-walk.d.ts +44 -0
  316. package/dist/utils/asset-reference-walk.d.ts.map +1 -0
  317. package/dist/utils/asset-reference-walk.js +143 -0
  318. package/dist/utils/image-url.d.ts +61 -26
  319. package/dist/utils/image-url.d.ts.map +1 -1
  320. package/dist/utils/image-url.js +143 -26
  321. package/dist/utils/video-metadata.d.ts +39 -0
  322. package/dist/utils/video-metadata.d.ts.map +1 -0
  323. package/dist/utils/video-metadata.js +160 -0
  324. package/package.json +6 -1
@@ -16,22 +16,41 @@
16
16
  Image as ImageIcon,
17
17
  FileText,
18
18
  FileImage,
19
+ Film,
20
+ Music,
21
+ FileArchive,
22
+ Play,
19
23
  ChevronLeft,
20
24
  ChevronRight,
21
25
  Download,
22
26
  Link,
23
27
  CheckCircle2,
24
28
  AlertCircle,
25
- SquareCheckBig
29
+ SquareCheckBig,
30
+ Lock
26
31
  } from '@lucide/svelte';
27
32
  import { page } from '$app/state';
28
33
  import { goto } from '$app/navigation';
29
34
  import { assets } from '../../api/assets';
30
- import type { AssetReference } from '../../api/assets';
35
+ import { ApiError } from '../../api/client';
36
+ import { MAX_UPLOAD_BYTES, maxUploadFileBytes } from '../../api/limits';
37
+ import { buildVariantUrl } from '../../storage/keys';
38
+ import {
39
+ canGenerateVariants,
40
+ thumbnailWidth,
41
+ usableWidths,
42
+ type ImageConfig
43
+ } from '../../images';
44
+ import type {
45
+ AssetDeleteConflict,
46
+ BulkAssetDeleteConflict,
47
+ AssetReference
48
+ } from '../../api/assets';
31
49
  import type { Asset } from '../../types/asset';
32
50
  import { toast } from 'svelte-sonner';
33
51
  import { copyUrlToClipboard, downloadFile } from '../../utils/asset-actions';
34
52
  import { cmsLogger } from '../../utils/logger';
53
+ import { extractVideoInfo, extractVideoInfoFromUrl } from '../../utils/video-metadata';
35
54
  import { SvelteSet } from 'svelte/reactivity';
36
55
  import { confirmDialog } from './confirm-dialog/confirm-dialog.svelte';
37
56
  import { usePermissions } from '../../permissions-context.svelte';
@@ -44,7 +63,12 @@
44
63
  /** Callback when an asset is selected (single select mode) */
45
64
  onSelect?: (asset: Asset) => void;
46
65
  /** Callback when multiple assets are selected (multi select mode) */
47
- onSelectMultiple?: (assets: Asset[]) => void;
66
+ /**
67
+ * Confirmed multi-selection, as the complete set of selected asset IDs —
68
+ * across every page, not just the visible one. Treat it as the desired
69
+ * final state: anything absent was deselected.
70
+ */
71
+ onSelectMultiple?: (assetIds: string[]) => void;
48
72
  /** Filter to specific asset type */
49
73
  assetTypeFilter?: 'image' | 'file';
50
74
  /** Number of assets per page */
@@ -53,6 +77,21 @@
53
77
  active?: boolean;
54
78
  /** Asset IDs already in use (shown with a tick indicator) */
55
79
  existingAssetIds?: Set<string>;
80
+ /**
81
+ * Asset to open on mount, addressed by id.
82
+ *
83
+ * Looked up on its own rather than searched for in the current page: a
84
+ * deep-linked asset is usually *not* on page 1 — that's why someone
85
+ * linked to it — so filtering the loaded list would silently do nothing
86
+ * for exactly the assets this exists to reach.
87
+ */
88
+ assetId?: string | null;
89
+ /**
90
+ * Fires when the open asset changes (null when the panel closes), so the
91
+ * host can reflect it in the URL. The component holds no opinion about
92
+ * routing; it only reports.
93
+ */
94
+ onAssetOpen?: (assetId: string | null) => void;
56
95
  }
57
96
 
58
97
  let {
@@ -63,20 +102,113 @@
63
102
  assetTypeFilter,
64
103
  pageSize = 30,
65
104
  active = true,
66
- existingAssetIds
105
+ existingAssetIds,
106
+ assetId = null,
107
+ onAssetOpen
67
108
  }: Props = $props();
68
109
 
69
110
  // State
70
111
  let assetList = $state<Asset[]>([]);
71
112
  let loading = $state(false);
72
113
  let searchQuery = $state('');
73
- let viewMode = $state<'grid' | 'list'>('grid');
74
- let sortOrder = $state<'newest' | 'oldest' | 'name-asc' | 'name-desc'>('newest');
114
+ /**
115
+ * How the library is displayed. These are per-editor habits rather than app
116
+ * state, so they're remembered per browser — resetting someone's view on every
117
+ * visit is a small daily annoyance. Storage can be unavailable or throw (a
118
+ * private window, blocked site data), and the defaults are correct when it is.
119
+ */
120
+ type GridDensity = 'compact' | 'default' | 'large';
121
+ type ViewMode = 'grid' | 'list';
122
+ type SortOrder = 'newest' | 'oldest' | 'name-asc' | 'name-desc';
123
+
124
+ /**
125
+ * Tile track minimums. The grid was laid out on a fixed `xl:grid-cols-10`,
126
+ * which on a wide screen produced ~90px thumbnails — a contact sheet you can
127
+ * count but not read. Sizing tracks by a minimum width instead lets the column
128
+ * count follow the space actually available (opening the inspector reflows it).
129
+ */
130
+ const TILE_MIN_WIDTH: Record<GridDensity, number> = {
131
+ compact: 110,
132
+ default: 165,
133
+ large: 240
134
+ };
135
+
136
+ const STORAGE_KEYS = {
137
+ density: 'aphex:media:density',
138
+ view: 'aphex:media:view',
139
+ sort: 'aphex:media:sort'
140
+ } as const;
141
+
142
+ function readStored<T extends string>(key: string, allowed: readonly T[], fallback: T): T {
143
+ if (typeof localStorage === 'undefined') return fallback;
144
+ try {
145
+ const stored = localStorage.getItem(key) as T | null;
146
+ return stored !== null && allowed.includes(stored) ? stored : fallback;
147
+ } catch {
148
+ return fallback;
149
+ }
150
+ }
151
+
152
+ function writeStored(key: string, value: string) {
153
+ try {
154
+ localStorage.setItem(key, value);
155
+ } catch {
156
+ /* not persisted */
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Media-kind filter, applied in SQL. Not persisted: unlike a view preference,
162
+ * a filter changes *which* assets exist as far as the editor can tell, and
163
+ * silently restoring one from a previous session reads as missing data.
164
+ */
165
+ type CategoryFilter = 'all' | 'image' | 'svg' | 'video' | 'audio' | 'document';
166
+ let categoryFilter = $state<CategoryFilter>('all');
167
+
168
+ /**
169
+ * Used / unused, answered by the asset-reference index. Not persisted, for the
170
+ * same reason as the kind filter: a restored filter reads as missing data.
171
+ */
172
+ type UsageFilter = 'all' | 'in-use' | 'unused';
173
+ let usageFilter = $state<UsageFilter>('all');
174
+
175
+ /**
176
+ * The server is still building the reference index for this org, so usage
177
+ * answers aren't trustworthy yet. Worth saying out loud: an unbuilt index makes
178
+ * every asset look unused, and "unused" is the answer that invites deletion.
179
+ */
180
+ let usageIndexing = $state(false);
181
+
182
+ let viewMode = $state<ViewMode>(readStored(STORAGE_KEYS.view, ['grid', 'list'], 'grid'));
183
+ let sortOrder = $state<SortOrder>(
184
+ readStored(STORAGE_KEYS.sort, ['newest', 'oldest', 'name-asc', 'name-desc'], 'newest')
185
+ );
186
+ let gridDensity = $state<GridDensity>(
187
+ readStored(STORAGE_KEYS.density, ['compact', 'default', 'large'], 'default')
188
+ );
189
+
190
+ $effect(() => writeStored(STORAGE_KEYS.view, viewMode));
191
+ $effect(() => writeStored(STORAGE_KEYS.sort, sortOrder));
192
+ $effect(() => writeStored(STORAGE_KEYS.density, gridDensity));
75
193
 
76
194
  const perms = usePermissions();
195
+ const canRead = $derived(perms.can('asset.read'));
77
196
  const canUpload = $derived(perms.can('asset.upload'));
78
197
  const canDeleteAssets = $derived(perms.can('asset.delete'));
79
198
 
199
+ /**
200
+ * Set when the server answers a read with 403.
201
+ *
202
+ * Normally `canRead` already stops us before the request, and the sidebar
203
+ * hides the media area entirely — but the client's capability set is a copy
204
+ * resolved at load, so a role edited in another tab (or a stale session) can
205
+ * disagree with the server. Treat the server's answer as the truth and show
206
+ * the same empty state rather than a "Failed to fetch assets" error, which
207
+ * reads as a broken CMS instead of a permission boundary.
208
+ */
209
+ let accessDenied = $state(false);
210
+ const showAccessDenied = $derived(!canRead || accessDenied);
211
+
80
212
  let selectedAsset = $state<Asset | null>(null);
81
213
  let lightboxOpen = $state(false);
82
214
  let currentPage = $state(1);
@@ -85,24 +217,91 @@
85
217
 
86
218
  // Upload state
87
219
  let isUploading = $state(false);
88
- let isDragging = $state(false);
89
220
  let showUploadModal = $state(false);
90
221
  let modalFileInputRef: HTMLInputElement;
91
- let modalIsDragging = $state(false);
222
+ // Same enter/leave counter as the browser region — see the note by
223
+ // `handleDragEnter`. This zone has no children to cross, but a drag that ends
224
+ // outside the window still strands the highlight without it.
225
+ let modalDragDepth = $state(0);
226
+ const modalIsDragging = $derived(modalDragDepth > 0);
92
227
 
93
228
  interface UploadQueueItem {
94
229
  file: File;
95
230
  status: 'pending' | 'uploading' | 'done' | 'failed';
231
+ /** Why it failed, shown next to the file. Absent unless `status` is 'failed'. */
232
+ error?: string;
233
+ /** 0–100 while uploading. */
234
+ progress?: number;
235
+ /**
236
+ * Object URL for an image preview, so a failed row can be identified by
237
+ * sight rather than by filename. Revoked when the queue is cleared —
238
+ * object URLs live until the document unloads otherwise.
239
+ */
240
+ previewUrl?: string;
96
241
  }
242
+
243
+ /**
244
+ * How many files upload at once.
245
+ *
246
+ * Sequential uploads make a 20-image drop feel broken — each waits for the
247
+ * whole of the previous one. Unbounded parallelism is worse: browsers cap
248
+ * connections per host anyway, so the extra requests queue invisibly while
249
+ * every progress bar crawls at once and the server handles a burst it
250
+ * didn't ask for. A small fixed width keeps throughput up and progress
251
+ * legible.
252
+ */
253
+ const UPLOAD_CONCURRENCY = 3;
97
254
  let uploadQueue = $state<UploadQueueItem[]>([]);
255
+ /**
256
+ * The server's request body limit. Seeded with the built-in default and
257
+ * replaced by the value the assets endpoint reports, so a configured limit is
258
+ * respected without the number being duplicated here.
259
+ */
260
+ let maxUploadBytes = $state(MAX_UPLOAD_BYTES);
261
+ /**
262
+ * Whether the server offers direct-to-storage upload. Reported by the assets
263
+ * endpoint rather than inferred: it depends on the adapter, an encryption
264
+ * key, and an operator opt-in that implies bucket CORS nothing here can see.
265
+ */
266
+ let directUpload = $state(false);
267
+ /**
268
+ * The image pipeline the server is running, or null when it's off.
269
+ *
270
+ * Needed so a grid tile can request a derivative instead of the original.
271
+ * Reported by the server, never derived here: the config hash decides which
272
+ * files exist, and a client that computed a different one would request URLs
273
+ * that silently fall back to the full-size original.
274
+ */
275
+ let imageConfig = $state<(ImageConfig & { configHash: string }) | null>(null);
98
276
 
99
277
  // Detail editing state
278
+ let editFilename = $state('');
100
279
  let editTitle = $state('');
101
280
  let editDescription = $state('');
102
281
  let editAlt = $state('');
103
282
  let editCreditLine = $state('');
104
283
  let isSaving = $state(false);
105
284
 
285
+ /**
286
+ * Whether the metadata form differs from the asset it was loaded from.
287
+ *
288
+ * Drives both the Save button's enabled state and the guard when switching
289
+ * assets. Compared against `selectedAsset` rather than a snapshot taken at
290
+ * open, so a successful save — which replaces `selectedAsset` with the
291
+ * server's row — settles back to clean without any extra bookkeeping.
292
+ *
293
+ * `?? ''` on both sides: the columns are nullable, the inputs are not, so a
294
+ * null title and an untouched empty input are the same thing.
295
+ */
296
+ const metadataDirty = $derived(
297
+ !!selectedAsset &&
298
+ (editFilename.trim() !== (selectedAsset.originalFilename ?? '') ||
299
+ editTitle !== (selectedAsset.title ?? '') ||
300
+ editDescription !== (selectedAsset.description ?? '') ||
301
+ editAlt !== (selectedAsset.alt ?? '') ||
302
+ editCreditLine !== (selectedAsset.creditLine ?? ''))
303
+ );
304
+
106
305
  // Bulk selection state
107
306
  let selectMode = $state(false);
108
307
  let selectedIds = $state<Set<string>>(
@@ -111,13 +310,65 @@
111
310
  );
112
311
  let isBulkDeleting = $state(false);
113
312
 
313
+ /**
314
+ * The asset a shift-click extends *from* — the last one whose selection the
315
+ * user set directly.
316
+ *
317
+ * Held as an id rather than an index because the list underneath it moves:
318
+ * sorting, searching and paging all reorder `orderedAssets`, and an index
319
+ * would then point at a different asset than the one that was clicked.
320
+ */
321
+ let selectionAnchor = $state<string | null>(null);
322
+
323
+ /**
324
+ * Which way the anchor click went — `true` if it selected, `false` if it
325
+ * deselected. A shift-click repeats it across the range.
326
+ *
327
+ * Recorded rather than read back off the anchor at shift-click time: by then
328
+ * the anchor may have been re-toggled by a checkbox or swept by select-all,
329
+ * and the range would silently invert.
330
+ */
331
+ let anchorSelects = $state(true);
332
+
333
+ /**
334
+ * Whether select mode was asked for, as opposed to entered by ticking a
335
+ * checkbox.
336
+ *
337
+ * Only used to decide whether emptying the selection should also leave the
338
+ * mode: an implicit entry should undo itself, so unticking the last checkbox
339
+ * puts the grid back to "click opens the asset". A deliberate entry stays put
340
+ * — the user pressed a button, and having it silently pop back off the first
341
+ * time they cleared a selection would be its own bug.
342
+ */
343
+ let selectModeExplicit = $state(false);
344
+
114
345
  // In selectable+multiSelect mode, always be in select mode
115
346
  const isSelectMode = $derived(selectMode || (selectable && multiSelect));
116
347
 
117
348
  function toggleSelectMode() {
118
349
  selectMode = !selectMode;
350
+ selectModeExplicit = selectMode;
119
351
  if (!selectMode) {
120
352
  selectedIds = new Set();
353
+ selectionAnchor = null;
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Keep the mode in step with the selection.
359
+ *
360
+ * The list view's checkboxes are always rendered, so a user can start
361
+ * selecting without ever finding the toolbar's select-mode button — and until
362
+ * this existed, doing so ticked boxes that produced no action bar and no way
363
+ * to delete anything. Selecting something *is* the request to be in select
364
+ * mode.
365
+ */
366
+ function syncSelectMode() {
367
+ if (selectable) return; // picker mode is permanently in select mode
368
+ if (selectedIds.size > 0) {
369
+ selectMode = true;
370
+ } else if (!selectModeExplicit) {
371
+ selectMode = false;
121
372
  }
122
373
  }
123
374
 
@@ -140,18 +391,45 @@
140
391
  }, 300);
141
392
  }
142
393
 
394
+ /**
395
+ * Monotonic id for the most recently *issued* asset fetch.
396
+ *
397
+ * Responses are not guaranteed to arrive in the order they were requested: a
398
+ * search for "a" and the search for "ab" typed 200ms later are two in-flight
399
+ * requests, and if the first is slower its results land last and win. The same
400
+ * applies to paging quickly, and to a refetch racing the initial load. Every
401
+ * fetch stamps itself, and only the newest is allowed to write state — an
402
+ * older response is read and discarded.
403
+ *
404
+ * Not `$state`: it's request bookkeeping, and nothing renders from it.
405
+ */
406
+ let fetchGeneration = 0;
407
+
143
408
  // Fetch assets
144
409
  async function fetchAssets(page = currentPage) {
410
+ // Don't ask for what we know we can't have — the request would only come
411
+ // back 403 and surface as an error toast.
412
+ if (!canRead) {
413
+ assetList = [];
414
+ loading = false;
415
+ return;
416
+ }
417
+ const generation = ++fetchGeneration;
145
418
  loading = true;
146
419
  try {
147
420
  const offset = (page - 1) * pageSize;
148
421
  const result = await assets.list({
149
422
  assetType: assetTypeFilter,
423
+ category: categoryFilter === 'all' ? undefined : categoryFilter,
424
+ usage: usageFilter === 'all' ? undefined : usageFilter,
150
425
  search: searchQuery || undefined,
426
+ sort: sortOrder,
151
427
  limit: pageSize,
152
428
  offset
153
429
  });
154
430
 
431
+ if (generation !== fetchGeneration) return;
432
+
155
433
  if (result.success && result.data) {
156
434
  assetList = result.data;
157
435
  currentPage = page;
@@ -159,18 +437,49 @@
159
437
  totalPages = result.pagination.totalPages;
160
438
  totalAssets = result.pagination.total;
161
439
  }
440
+ // Adopt the server's actual limit rather than trusting the compiled-in
441
+ // default, which is only correct until someone configures a different
442
+ // one. Absent on an older server, in which case the default stands.
443
+ if (typeof result.limits?.maxUploadBytes === 'number') {
444
+ maxUploadBytes = result.limits.maxUploadBytes;
445
+ }
446
+ directUpload = result.limits?.directUpload === true;
447
+ usageIndexing = (result as { indexing?: boolean }).indexing === true;
448
+
449
+ // Deliberately not awaited: posters are a nicety, and the grid should be
450
+ // on screen while they fill in behind it.
451
+ void backfillPosters(
452
+ assetList.filter(
453
+ (asset) =>
454
+ (isVideo(asset) && !getPosterUrl(asset)) || (isAudio(asset) && !formatDuration(asset))
455
+ )
456
+ );
457
+ imageConfig = result.images ?? null;
162
458
  // Clear bulk selection on page change (but never in multi-select picker mode —
163
459
  // selection is initialised once at mount and only changed by user interaction)
164
460
  if (!(selectable && multiSelect)) {
165
461
  selectedIds = new Set();
462
+ syncSelectMode();
166
463
  }
464
+ // The anchor always dies with the page: it names an asset that may no
465
+ // longer be rendered, and extending a range from off-screen produces a
466
+ // selection the user cannot see the ends of.
467
+ selectionAnchor = null;
167
468
  // Fetch reference counts for this page
168
469
  fetchReferenceCounts(result.data.map((a) => a.id));
169
470
  }
170
- } catch {
171
- toast.error('Failed to fetch assets');
471
+ } catch (error) {
472
+ if (generation !== fetchGeneration) return;
473
+ if (error instanceof ApiError && error.status === 403) {
474
+ accessDenied = true;
475
+ assetList = [];
476
+ } else {
477
+ toast.error('Failed to fetch assets');
478
+ }
172
479
  } finally {
173
- loading = false;
480
+ // Only the newest request owns the spinner. A superseded one clearing it
481
+ // would show "no assets" while its replacement is still in flight.
482
+ if (generation === fetchGeneration) loading = false;
174
483
  }
175
484
  }
176
485
 
@@ -181,14 +490,18 @@
181
490
 
182
491
  // Fetch reference counts for current page of assets
183
492
  async function fetchReferenceCounts(assetIds: string[]) {
184
- if (assetIds.length === 0) return;
493
+ if (assetIds.length === 0 || !canRead) return;
185
494
  try {
186
495
  const result = await assets.getReferenceCounts(assetIds);
187
496
  if (result.success && result.data) {
188
497
  referenceCounts = { ...referenceCounts, ...result.data };
189
498
  }
190
- } catch {
191
- toast.error('Failed to fetch reference counts');
499
+ } catch (error) {
500
+ // A 403 here is already reported by the asset fetch that triggered it;
501
+ // a second toast would just be noise.
502
+ if (!(error instanceof ApiError && error.status === 403)) {
503
+ toast.error('Failed to fetch reference counts');
504
+ }
192
505
  }
193
506
  }
194
507
 
@@ -210,7 +523,6 @@
210
523
  }
211
524
  }
212
525
 
213
- // Sort assets client-side
214
526
  function isSystemAsset(asset: Asset): boolean {
215
527
  const metadata = asset.metadata as Record<string, unknown> | null | undefined;
216
528
  return (
@@ -220,51 +532,64 @@
220
532
  );
221
533
  }
222
534
 
223
- function sortAssets(list: Asset[]): Asset[] {
224
- const sorted = [...list];
225
- switch (sortOrder) {
226
- case 'newest':
227
- return sorted.sort(
228
- (a, b) => new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime()
229
- );
230
- case 'oldest':
231
- return sorted.sort(
232
- (a, b) => new Date(a.createdAt || 0).getTime() - new Date(b.createdAt || 0).getTime()
233
- );
234
- case 'name-asc':
235
- return sorted.sort((a, b) => a.originalFilename.localeCompare(b.originalFilename));
236
- case 'name-desc':
237
- return sorted.sort((a, b) => b.originalFilename.localeCompare(a.originalFilename));
238
- default:
239
- return sorted;
240
- }
241
- }
242
-
243
535
  // Pinned assets (already in array) — separate from the main sorted list
244
536
  const pinnedAssets = $derived.by(() => {
245
537
  if (!(selectable && multiSelect && existingAssetIds && existingAssetIds.size > 0)) return [];
246
538
  return assetList.filter((a) => !isSystemAsset(a) && existingAssetIds!.has(a.id));
247
539
  });
248
540
 
541
+ /**
542
+ * The page as the server ordered it, minus the system assets and (in picker
543
+ * mode) the ones shown as pinned.
544
+ *
545
+ * Deliberately does not re-sort. It used to, and that sort only ever saw the
546
+ * loaded page: "Name: A–Z" across 300 assets alphabetised whichever 30 rows
547
+ * happened to be in `assetList`, so the first page showed the A's from the
548
+ * newest 30 uploads rather than the A's from the library. It looked sorted,
549
+ * which is why it survived this long. `sort` is a query parameter now.
550
+ */
249
551
  const sortedAssets = $derived.by(() => {
250
552
  const visibleAssets = assetList.filter((a) => !isSystemAsset(a));
251
553
  if (selectable && multiSelect && existingAssetIds && existingAssetIds.size > 0) {
252
- return sortAssets(visibleAssets.filter((a) => !existingAssetIds!.has(a.id)));
554
+ return visibleAssets.filter((a) => !existingAssetIds!.has(a.id));
253
555
  }
254
- return sortAssets(visibleAssets);
556
+ return visibleAssets;
255
557
  });
256
558
 
257
- // Bulk selection derived (must be after sortedAssets)
559
+ /**
560
+ * Every visible asset, in the order it renders: pinned first, then the sorted
561
+ * page.
562
+ *
563
+ * Range selection needs one flat order that both views agree on, because
564
+ * "everything between these two" is meaningless against a list the user isn't
565
+ * looking at. It's also the honest answer for select-all: `sortedAssets`
566
+ * excludes the pinned ones in picker mode, so a select-all built on it could
567
+ * add every visible asset but never clear the pinned ones back off.
568
+ */
569
+ const orderedAssets = $derived([...pinnedAssets, ...sortedAssets]);
570
+
571
+ // Bulk selection derived (must be after orderedAssets)
258
572
  const allSelected = $derived(
259
- sortedAssets.length > 0 && sortedAssets.every((a) => selectedIds.has(a.id))
573
+ orderedAssets.length > 0 && orderedAssets.every((a) => selectedIds.has(a.id))
260
574
  );
261
575
 
576
+ /**
577
+ * Add or remove the *visible* assets, as a delta.
578
+ *
579
+ * Never assign the page as the whole set: in picker mode `selectedIds` spans
580
+ * pages, so replacing it would discard every selection not on screen —
581
+ * deleting those images from the field on confirm.
582
+ */
262
583
  function toggleSelectAll() {
584
+ const next = new SvelteSet(selectedIds);
263
585
  if (allSelected) {
264
- selectedIds = new Set();
586
+ for (const asset of orderedAssets) next.delete(asset.id);
265
587
  } else {
266
- selectedIds = new Set(sortedAssets.map((a) => a.id));
588
+ for (const asset of orderedAssets) next.add(asset.id);
267
589
  }
590
+ selectedIds = next;
591
+ selectionAnchor = null;
592
+ syncSelectMode();
268
593
  }
269
594
 
270
595
  function toggleSelect(id: string) {
@@ -275,39 +600,116 @@
275
600
  next.add(id);
276
601
  }
277
602
  selectedIds = next;
603
+ syncSelectMode();
278
604
  }
279
605
 
280
- function confirmMultiSelect() {
281
- if (onSelectMultiple) {
282
- const selected = assetList.filter((a) => selectedIds.has(a.id));
283
- onSelectMultiple(selected);
284
- selectedIds = new Set();
606
+ /**
607
+ * Apply the anchor's own outcome to everything between it and `id`, inclusive.
608
+ *
609
+ * The range doesn't always *select*: it repeats whatever the anchor click did.
610
+ * Ticking one asset and shift-clicking ten below it selects eleven; unticking
611
+ * one and shift-clicking ten below it clears eleven. Deselecting a range is
612
+ * the only practical way to undo an overshoot on a hundred-item page, and
613
+ * making the gesture mean "select" in both directions would leave the
614
+ * correction to a hundred individual clicks.
615
+ *
616
+ * Only the assets between the two ends are touched, so a picker-mode
617
+ * selection that spans other pages survives either direction.
618
+ *
619
+ * The anchor deliberately stays put afterwards, so a second shift-click
620
+ * re-extends from the same origin instead of chaining off the previous target.
621
+ * That's what makes "oops, one too far" a correction rather than a restart.
622
+ */
623
+ function selectRange(id: string) {
624
+ const to = orderedAssets.findIndex((a) => a.id === id);
625
+ if (to === -1) return;
626
+
627
+ // No anchor yet — a shift-click is the first click. Nothing to extend
628
+ // from, so treat it as an ordinary one rather than doing nothing.
629
+ const from = selectionAnchor ? orderedAssets.findIndex((a) => a.id === selectionAnchor) : -1;
630
+ if (from === -1) {
631
+ setAnchor(id);
632
+ return;
633
+ }
634
+
635
+ const [start, end] = from < to ? [from, to] : [to, from];
636
+ const next = new SvelteSet(selectedIds);
637
+ for (let i = start; i <= end; i++) {
638
+ const rangeId = orderedAssets[i]!.id;
639
+ if (anchorSelects) next.add(rangeId);
640
+ else next.delete(rangeId);
285
641
  }
642
+ selectedIds = next;
643
+ syncSelectMode();
286
644
  }
287
645
 
288
- async function bulkDelete() {
289
- if (selectedIds.size === 0) return;
646
+ /**
647
+ * Toggle `id` and make it the anchor, recording which way it went so a
648
+ * following shift-click can repeat it.
649
+ */
650
+ function setAnchor(id: string) {
651
+ anchorSelects = !selectedIds.has(id);
652
+ toggleSelect(id);
653
+ selectionAnchor = id;
654
+ }
290
655
 
291
- // Fetch fresh reference counts before checking
292
- const idsToCheck = [...selectedIds];
293
- try {
294
- const result = await assets.getReferenceCounts(idsToCheck);
295
- if (result.success && result.data) {
296
- referenceCounts = { ...referenceCounts, ...result.data };
297
- }
298
- } catch {
299
- toast.error('Failed to check references');
656
+ /**
657
+ * The single entry point for "the user clicked this asset to select it".
658
+ *
659
+ * Every tile, row and checkbox routes through here so the anchor is
660
+ * maintained in one place — a path that toggles without moving the anchor
661
+ * leaves shift-click extending from an asset the user stopped thinking about
662
+ * several clicks ago.
663
+ */
664
+ function handleSelectClick(id: string, event: { shiftKey: boolean }) {
665
+ if (event.shiftKey) {
666
+ selectRange(id);
667
+ return;
300
668
  }
669
+ setAnchor(id);
670
+ }
301
671
 
302
- // Check for referenced assets
303
- const referencedAssets = idsToCheck.filter((id) => (referenceCounts[id] || 0) > 0);
304
- if (referencedAssets.length > 0) {
305
- toast.error(
306
- `Cannot delete ${referencedAssets.length} asset${referencedAssets.length > 1 ? 's' : ''} — still referenced by documents. Remove the references first.`
307
- );
308
- return;
672
+ function clearSelection() {
673
+ selectedIds = new Set();
674
+ selectionAnchor = null;
675
+ syncSelectMode();
676
+ }
677
+
678
+ /**
679
+ * Hand back the complete selected ID set — never a list of `Asset` objects.
680
+ *
681
+ * `selectedIds` is seeded from `existingAssetIds` and spans every page, but
682
+ * `assetList` only ever holds the current one. Resolving the selection through
683
+ * `assetList` therefore silently dropped every selected asset that wasn't on
684
+ * the visible page, and the consumer — which treats the result as the complete
685
+ * desired set — deleted them from the field.
686
+ *
687
+ * IDs are also all the consumer needs: it rebuilds items as `{ _ref: id }` and
688
+ * preserves per-item data (alt text, `_key`, order) from what it already holds.
689
+ */
690
+ function confirmMultiSelect() {
691
+ if (onSelectMultiple) {
692
+ onSelectMultiple([...selectedIds]);
693
+ clearSelection();
309
694
  }
695
+ }
696
+
697
+ async function bulkDelete() {
698
+ if (selectedIds.size === 0) return;
310
699
 
700
+ // No client-side reference pre-check.
701
+ //
702
+ // There used to be one, and it disagreed with the server in the one case
703
+ // that matters. It counted references via `getReferenceCounts`, which
704
+ // filters to *registered* schema types; the server's delete guard scans
705
+ // unfiltered, because a document whose type was removed from the codebase
706
+ // still holds its reference. So an asset blocked only by an orphaned type
707
+ // passed the client check, hit the server, and came back 409 — with the
708
+ // client insisting nothing referenced it. Asking two different questions
709
+ // and treating them as one answer is the bug.
710
+ //
711
+ // The server does a fresh authoritative scan on every attempt, so it is the
712
+ // only sensible authority. Attempt the delete and handle its refusal.
311
713
  const count = selectedIds.size;
312
714
  const confirmed = await confirmDialog({
313
715
  title: `Delete ${count} asset${count > 1 ? 's' : ''}?`,
@@ -317,91 +719,335 @@
317
719
  });
318
720
  if (!confirmed) return;
319
721
 
722
+ await performBulkDelete([...selectedIds], false);
723
+ }
724
+
725
+ async function performBulkDelete(ids: string[], force: boolean) {
320
726
  isBulkDeleting = true;
321
727
  try {
322
- const result = await assets.deleteBulk([...selectedIds]);
728
+ const result = await assets.deleteBulk(ids, force ? { force: true } : undefined);
323
729
  if (result.success) {
324
- if (selectedAsset && selectedIds.has(selectedAsset.id)) {
730
+ if (selectedAsset && ids.includes(selectedAsset.id)) {
325
731
  selectedAsset = null;
326
732
  }
327
- selectedIds = new Set();
733
+ clearSelection();
328
734
  await fetchAssets();
329
735
  }
330
- } catch {
736
+ } catch (err) {
737
+ if (err instanceof ApiError && err.status === 409) {
738
+ await handleBulkDeleteConflict(ids, err.response as BulkAssetDeleteConflict);
739
+ return;
740
+ }
331
741
  toast.error('Failed to delete assets');
332
742
  } finally {
333
743
  isBulkDeleting = false;
334
744
  }
335
745
  }
336
746
 
747
+ /**
748
+ * The batch was refused. Mirrors {@link handleDeleteConflict}: offer force only
749
+ * when an unregistered schema type is what's blocking, because that is the case
750
+ * where removing the reference by hand is impossible.
751
+ */
752
+ async function handleBulkDeleteConflict(ids: string[], conflict: BulkAssetDeleteConflict) {
753
+ const blocked = conflict.referencedIds ?? [];
754
+ const unregisteredTypes = conflict.unregisteredTypes ?? [];
755
+
756
+ // The server just told us these are referenced; correct the cached counts so
757
+ // the grid stops showing them as unused before the next fetch.
758
+ const corrected = { ...referenceCounts };
759
+ for (const id of blocked) corrected[id] = Math.max(corrected[id] ?? 0, 1);
760
+ referenceCounts = corrected;
761
+
762
+ if (unregisteredTypes.length === 0) {
763
+ toast.error(conflict.error);
764
+ return;
765
+ }
766
+
767
+ const forced = await confirmDialog({
768
+ title: 'Referenced by documents you cannot open',
769
+ // Two sentences: what's blocking, and what the button does. The rest —
770
+ // which plane gets cleaned, when a published page catches up — is true
771
+ // but belongs in the docs, not in front of someone mid-cleanup.
772
+ description:
773
+ `${blocked.length} asset${blocked.length > 1 ? 's are' : ' is'} used by documents of type ${unregisteredTypes.join(', ')}, which no longer ${unregisteredTypes.length > 1 ? 'exist' : 'exists'} in your schema. ` +
774
+ `Force delete removes the references for you.`,
775
+ confirmText: 'Force delete',
776
+ variant: 'destructive'
777
+ });
778
+ if (forced) {
779
+ await performBulkDelete(ids, true);
780
+ }
781
+ }
782
+
337
783
  // Upload files via modal queue
784
+ //
785
+ // Oversized files are failed here rather than sent, because `File.size` is
786
+ // known before a single byte goes over the wire. Uploading a 50MB file for
787
+ // the length of the transfer only to be told it was never going to be
788
+ // accepted is the worst version of this. Rejecting up front is purely a
789
+ // courtesy though — the server enforces the same limit, since nothing stops
790
+ // a caller posting straight to the API.
338
791
  function addFilesToQueue(files: FileList | null) {
339
792
  if (!files || files.length === 0) return;
340
- const newItems: UploadQueueItem[] = Array.from(files).map((file) => ({
341
- file,
342
- status: 'pending' as const
343
- }));
793
+ const fileLimit = maxUploadFileBytes(maxUploadBytes);
794
+ const newItems: UploadQueueItem[] = Array.from(files).map((file) => {
795
+ const previewUrl = file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined;
796
+ return file.size > fileLimit
797
+ ? {
798
+ file,
799
+ previewUrl,
800
+ status: 'failed' as const,
801
+ error: `Too large — ${formatSize(file.size)}, limit is ${formatSize(fileLimit)}`
802
+ }
803
+ : { file, previewUrl, status: 'pending' as const };
804
+ });
344
805
  uploadQueue = [...uploadQueue, ...newItems];
345
806
  processUploadQueue();
346
807
  }
347
808
 
809
+ /** Upload one queued item, reporting progress as it goes. */
810
+ async function uploadItem(index: number) {
811
+ const item = uploadQueue[index];
812
+ if (!item) return;
813
+
814
+ item.status = 'uploading';
815
+ item.progress = 0;
816
+ item.error = undefined;
817
+ uploadQueue = [...uploadQueue];
818
+
819
+ try {
820
+ // Read duration, real dimensions and a frame off the local file before it
821
+ // goes anywhere. Only possible here: once uploaded, the same work would
822
+ // mean fetching the video back, and the server has no decoder without
823
+ // taking on ffmpeg.
824
+ const videoInfo = await extractVideoInfo(item.file);
825
+
826
+ const result = await assets.uploadFile(item.file, {
827
+ direct: directUpload,
828
+ videoDuration: videoInfo.duration,
829
+ videoWidth: videoInfo.width,
830
+ videoHeight: videoInfo.height,
831
+ onProgress: (percent) => {
832
+ item.progress = percent;
833
+ uploadQueue = [...uploadQueue];
834
+ }
835
+ });
836
+
837
+ // The poster is a second request because its storage key derives from the
838
+ // asset id, which doesn't exist until the row does. Deliberately not
839
+ // awaited into the upload's own success: a video that uploaded fine has
840
+ // uploaded fine, and losing its thumbnail must not report as a failure.
841
+ const uploadedId = result?.data?.id;
842
+ if (uploadedId && videoInfo.poster) {
843
+ try {
844
+ await assets.uploadPoster(uploadedId, videoInfo.poster, {
845
+ duration: videoInfo.duration,
846
+ width: videoInfo.width,
847
+ height: videoInfo.height
848
+ });
849
+ } catch (err) {
850
+ cmsLogger.warn('[Media]', 'Poster upload failed; video is fine:', err);
851
+ }
852
+ }
853
+
854
+ item.status = 'done';
855
+ item.progress = 100;
856
+ } catch (err) {
857
+ item.status = 'failed';
858
+ item.error = uploadErrorMessage(err);
859
+ }
860
+ uploadQueue = [...uploadQueue];
861
+ }
862
+
348
863
  async function processUploadQueue() {
349
864
  if (isUploading) return;
350
865
  isUploading = true;
351
866
 
352
- for (let i = 0; i < uploadQueue.length; i++) {
353
- if (uploadQueue[i]!.status !== 'pending') continue;
354
- uploadQueue[i]!.status = 'uploading';
355
- uploadQueue = [...uploadQueue]; // trigger reactivity
356
-
357
- try {
358
- const formData = new FormData();
359
- formData.append('file', uploadQueue[i]!.file);
360
- const result = await assets.upload(formData);
361
- uploadQueue[i]!.status = result.success ? 'done' : 'failed';
362
- } catch {
363
- uploadQueue[i]!.status = 'failed';
867
+ // A pool of workers pulling from the queue, rather than a fixed split:
868
+ // files differ wildly in size, so slicing the queue into equal shares
869
+ // would leave one worker on a 9MB photo while the others idle.
870
+ const next = (): number => uploadQueue.findIndex((item) => item.status === 'pending');
871
+ const worker = async () => {
872
+ for (let i = next(); i !== -1; i = next()) {
873
+ await uploadItem(i);
364
874
  }
875
+ };
876
+ await Promise.all(
877
+ Array.from({ length: Math.min(UPLOAD_CONCURRENCY, uploadQueue.length) }, worker)
878
+ );
879
+
880
+ isUploading = false;
881
+
882
+ // The dialog stays open when the queue drains, and the editor dismisses it.
883
+ //
884
+ // It used to close itself 800ms after a fully successful run (and, before
885
+ // that, on `done || failed`, so a rejected upload dismissed the modal
886
+ // exactly like a successful one and the failure was never read). Even
887
+ // limited to the all-succeeded case, closing on a timer takes the result
888
+ // away just as it appears — and on a slow backend a large video upload is
889
+ // precisely when someone wants to see it land. Staying open also keeps the
890
+ // drop zone available for the next batch.
891
+ currentPage = 1;
892
+ await fetchAssets(1);
893
+ }
894
+
895
+ /**
896
+ * Re-queue a failed upload.
897
+ *
898
+ * The `File` is still held by the queue item, so this costs the editor
899
+ * nothing — the alternative was closing the dialog and picking the file
900
+ * again, which for a drag-and-drop of twenty images meant redoing the lot to
901
+ * retry one.
902
+ */
903
+ function retryUpload(index: number) {
904
+ const item = uploadQueue[index];
905
+ if (!item || item.status !== 'failed') return;
906
+ // Re-check the size: a failure caused by exceeding the limit is not worth
907
+ // a round trip, and the limit may have been learned since.
908
+ const fileLimit = maxUploadFileBytes(maxUploadBytes);
909
+ if (item.file.size > fileLimit) {
910
+ item.error = `Too large — ${formatSize(item.file.size)}, limit is ${formatSize(fileLimit)}`;
365
911
  uploadQueue = [...uploadQueue];
912
+ return;
913
+ }
914
+ item.status = 'pending';
915
+ item.error = undefined;
916
+ uploadQueue = [...uploadQueue];
917
+ processUploadQueue();
918
+ }
919
+
920
+ function retryAllFailed() {
921
+ for (let i = 0; i < uploadQueue.length; i++) {
922
+ const item = uploadQueue[i]!;
923
+ if (item.status === 'failed' && item.file.size <= maxUploadFileBytes(maxUploadBytes)) {
924
+ item.status = 'pending';
925
+ item.error = undefined;
926
+ }
366
927
  }
928
+ uploadQueue = [...uploadQueue];
929
+ processUploadQueue();
930
+ }
367
931
 
368
- isUploading = false;
932
+ const failedCount = $derived(uploadQueue.filter((i) => i.status === 'failed').length);
933
+ const queuedBytes = $derived(uploadQueue.reduce((total, item) => total + item.file.size, 0));
369
934
 
370
- // If all done, refetch and close after a brief pause
371
- if (uploadQueue.every((item) => item.status === 'done' || item.status === 'failed')) {
372
- currentPage = 1;
373
- await fetchAssets(1);
374
- setTimeout(() => {
375
- showUploadModal = false;
376
- uploadQueue = [];
377
- }, 800);
935
+ /** Empty the queue, releasing the preview object URLs it holds. */
936
+ function clearUploadQueue() {
937
+ for (const item of uploadQueue) {
938
+ if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
939
+ }
940
+ uploadQueue = [];
941
+ }
942
+
943
+ /**
944
+ * Turn a thrown upload error into something an editor can act on.
945
+ *
946
+ * The server's own message is preferred — it's the one that names the actual
947
+ * limit — with the status only used to fill in cases where the response
948
+ * carries no body, such as a proxy rejecting an oversized request before it
949
+ * ever reaches the app.
950
+ */
951
+ function uploadErrorMessage(err: unknown): string {
952
+ if (err instanceof ApiError) {
953
+ const serverMessage = err.response?.error;
954
+ if (typeof serverMessage === 'string' && serverMessage) return serverMessage;
955
+ if (err.status === 413) return 'File is too large for this server’s upload limit';
956
+ return `Upload failed (${err.status})`;
378
957
  }
958
+ if (err instanceof Error && err.message) return err.message;
959
+ return 'Upload failed';
379
960
  }
380
961
 
381
962
  // Drag and drop
963
+ //
964
+ // `dragleave` fires whenever the pointer crosses onto a *child* element, not
965
+ // only when it leaves the region — and the grid is nothing but children. So
966
+ // toggling a boolean on enter/leave switched the overlay off every time the
967
+ // cursor moved between tiles, and `dragover` immediately switched it back on:
968
+ // the flashing.
969
+ //
970
+ // The counter is the fix for that. Enter and leave arrive in pairs as the drag
971
+ // crosses each boundary, so the depth only reaches zero when the drag has
972
+ // genuinely left the region.
973
+ let dragDepth = $state(0);
974
+ const isDragging = $derived(dragDepth > 0);
975
+
976
+ /**
977
+ * Ignore drags that aren't files.
978
+ *
979
+ * Dragging a text selection, or one of the grid's own tiles, would otherwise
980
+ * put a "Drop files to upload" overlay over the page for a drop that can
981
+ * produce nothing.
982
+ */
983
+ function isFileDrag(e: DragEvent): boolean {
984
+ const types = e.dataTransfer?.types;
985
+ return types ? Array.from(types).includes('Files') : false;
986
+ }
987
+
988
+ function handleDragEnter(e: DragEvent) {
989
+ if (!isFileDrag(e)) return;
990
+ e.preventDefault();
991
+ dragDepth++;
992
+ }
993
+
382
994
  function handleDragOver(e: DragEvent) {
995
+ if (!isFileDrag(e)) return;
996
+ // Required on every dragover, or the browser treats the region as a
997
+ // non-target and shows the "no drop" cursor.
383
998
  e.preventDefault();
384
- isDragging = true;
385
999
  }
386
1000
 
387
1001
  function handleDragLeave(e: DragEvent) {
1002
+ if (dragDepth === 0) return;
388
1003
  e.preventDefault();
389
- isDragging = false;
1004
+ dragDepth--;
390
1005
  }
391
1006
 
392
1007
  function handleDrop(e: DragEvent) {
393
1008
  e.preventDefault();
394
- isDragging = false;
1009
+ dragDepth = 0;
1010
+ if (!e.dataTransfer?.files?.length) return;
395
1011
  showUploadModal = true;
396
- addFilesToQueue(e.dataTransfer?.files || null);
1012
+ addFilesToQueue(e.dataTransfer.files);
1013
+ }
1014
+
1015
+ /**
1016
+ * A drag that ends outside the window — dropped on the desktop, or cancelled
1017
+ * with Escape — delivers no `dragleave` to us, so the counter would stay above
1018
+ * zero and strand the overlay on screen until the next drag.
1019
+ */
1020
+ function handleDragEnd() {
1021
+ dragDepth = 0;
1022
+ }
1023
+
1024
+ /**
1025
+ * Ask before throwing away metadata edits.
1026
+ *
1027
+ * Everything that replaces or closes the detail panel goes through here.
1028
+ * Without it, typing alt text and then clicking the next thumbnail — the
1029
+ * natural rhythm of captioning a shoot — discarded the text silently, with
1030
+ * the panel that appeared next looking exactly like a successful save.
1031
+ */
1032
+ async function confirmDiscardEdits(): Promise<boolean> {
1033
+ if (!metadataDirty) return true;
1034
+ return confirmDialog({
1035
+ title: 'Discard unsaved changes?',
1036
+ description: 'The metadata you edited on this asset has not been saved.',
1037
+ confirmText: 'Discard',
1038
+ variant: 'destructive'
1039
+ });
397
1040
  }
398
1041
 
399
1042
  // Select an asset for detail view — re-fetch to get fresh data
400
1043
  // Select an asset for detail view
401
- function openAssetDetail(asset: Asset) {
1044
+ async function openAssetDetail(asset: Asset) {
402
1045
  const isSameAsset = selectedAsset?.id === asset.id;
1046
+ if (!isSameAsset && !(await confirmDiscardEdits())) return;
403
1047
 
404
1048
  selectedAsset = asset;
1049
+ if (!isSameAsset) onAssetOpen?.(asset.id);
1050
+ editFilename = asset.originalFilename || '';
405
1051
  editTitle = asset.title || '';
406
1052
  editDescription = asset.description || '';
407
1053
  editAlt = asset.alt || '';
@@ -415,20 +1061,65 @@
415
1061
  }
416
1062
  }
417
1063
 
418
- function closeAssetDetail() {
1064
+ async function closeAssetDetail() {
1065
+ if (!(await confirmDiscardEdits())) return;
419
1066
  selectedAsset = null;
1067
+ onAssetOpen?.(null);
420
1068
  }
421
1069
 
422
- // Save metadata
1070
+ /**
1071
+ * Open the asset named by `assetId`, fetching it if it isn't already loaded.
1072
+ *
1073
+ * Runs once per distinct incoming id. It deliberately does not react to
1074
+ * `selectedAsset` changing, or clicking a thumbnail would re-enter through
1075
+ * the host's URL update and fight the user's selection.
1076
+ */
1077
+ let resolvedDeepLink = $state<string | null>(null);
1078
+
1079
+ $effect(() => {
1080
+ const wanted = assetId;
1081
+ if (!wanted || wanted === resolvedDeepLink || !canRead) return;
1082
+ resolvedDeepLink = wanted;
1083
+ if (selectedAsset?.id === wanted) return;
1084
+
1085
+ const loaded = assetList.find((a) => a.id === wanted);
1086
+ if (loaded) {
1087
+ openAssetDetail(loaded);
1088
+ return;
1089
+ }
1090
+
1091
+ void (async () => {
1092
+ try {
1093
+ const result = await assets.getById(wanted);
1094
+ if (result.success && result.data) await openAssetDetail(result.data);
1095
+ else toast.error('That asset could not be found');
1096
+ } catch {
1097
+ // A bad id in a URL is a dead link, not a broken media browser —
1098
+ // the library behind it still loaded and is perfectly usable.
1099
+ toast.error('That asset could not be found');
1100
+ }
1101
+ })();
1102
+ });
1103
+
1104
+ // Save metadata.
1105
+ //
1106
+ // Emptied fields are sent as `null`, not `undefined`: `JSON.stringify` drops
1107
+ // undefined keys from the body, so an omitted field reads on the server as
1108
+ // "leave this alone" — metadata could be added but never cleared. `null` is
1109
+ // the explicit "clear it" signal the PATCH route and adapters honour.
423
1110
  async function saveMetadata() {
424
- if (!selectedAsset) return;
1111
+ if (!selectedAsset || !canUpload) return;
425
1112
  isSaving = true;
426
1113
  try {
427
1114
  const result = await assets.update(selectedAsset.id, {
428
- title: editTitle || undefined,
429
- description: editDescription || undefined,
430
- alt: editAlt || undefined,
431
- creditLine: editCreditLine || undefined
1115
+ // Renaming is metadata-only: the object is stored under the asset id,
1116
+ // so nothing moves and existing references keep resolving. Blank means
1117
+ // "unchanged" rather than "clear it" — an asset always has a name.
1118
+ originalFilename: editFilename.trim() || undefined,
1119
+ title: editTitle || null,
1120
+ description: editDescription || null,
1121
+ alt: editAlt || null,
1122
+ creditLine: editCreditLine || null
432
1123
  });
433
1124
  if (result.success && result.data) {
434
1125
  // Update in list
@@ -442,23 +1133,13 @@
442
1133
  }
443
1134
  }
444
1135
 
445
- // Delete asset
1136
+ // Delete asset.
1137
+ //
1138
+ // No client-side reference pre-check: the server scans unfiltered and is the
1139
+ // only authority. A local check would duplicate that scan, and it reads from
1140
+ // `referenceCounts`, which goes stale the moment a document changes (#233) —
1141
+ // blocking deletes that should succeed and permitting ones that shouldn't.
446
1142
  async function deleteAsset(asset: Asset) {
447
- try {
448
- const result = await assets.getReferenceCounts([asset.id]);
449
- if (result.success && result.data) {
450
- referenceCounts = { ...referenceCounts, ...result.data };
451
- }
452
- } catch {
453
- // Fall through to cached count
454
- }
455
- const refCount = referenceCounts[asset.id] || 0;
456
- if (refCount > 0) {
457
- toast.error(
458
- `Cannot delete "${asset.originalFilename}" — referenced by ${refCount} document${refCount > 1 ? 's' : ''}. Remove the references first.`
459
- );
460
- return;
461
- }
462
1143
  const confirmed = await confirmDialog({
463
1144
  title: 'Delete asset?',
464
1145
  description: `"${asset.originalFilename}" will be permanently deleted. This cannot be undone.`,
@@ -466,24 +1147,90 @@
466
1147
  variant: 'destructive'
467
1148
  });
468
1149
  if (!confirmed) return;
1150
+ await performDelete(asset, false);
1151
+ }
1152
+
1153
+ async function performDelete(asset: Asset, force: boolean) {
469
1154
  try {
470
- const result = await assets.delete(asset.id);
1155
+ const result = await assets.delete(asset.id, force ? { force: true } : undefined);
471
1156
  if (result.success) {
472
1157
  if (selectedAsset?.id === asset.id) {
473
1158
  selectedAsset = null;
474
1159
  }
1160
+ // Drop the cached count rather than leave it behind for an id that
1161
+ // no longer exists.
1162
+ const next = { ...referenceCounts };
1163
+ delete next[asset.id];
1164
+ referenceCounts = next;
475
1165
  await fetchAssets();
476
1166
  }
477
- } catch {
1167
+ } catch (error) {
1168
+ if (error instanceof ApiError && error.status === 409) {
1169
+ await handleDeleteConflict(asset, error.response as AssetDeleteConflict);
1170
+ return;
1171
+ }
478
1172
  toast.error('Failed to delete asset');
479
1173
  }
480
1174
  }
481
1175
 
1176
+ /**
1177
+ * The asset is still referenced. The server has just done a fresh unfiltered
1178
+ * scan, so treat its answer as the truth and correct the cached count with it.
1179
+ *
1180
+ * When any referencing document uses an unregistered schema type, force is the
1181
+ * user's only route — that document cannot be opened in the admin, so the
1182
+ * reference cannot be removed by hand and the asset would be undeletable.
1183
+ */
1184
+ async function handleDeleteConflict(asset: Asset, conflict: AssetDeleteConflict) {
1185
+ const references = conflict.references ?? [];
1186
+ const unregisteredTypes = conflict.unregisteredTypes ?? [];
1187
+ referenceCounts = { ...referenceCounts, [asset.id]: references.length };
1188
+
1189
+ if (unregisteredTypes.length === 0) {
1190
+ toast.error(conflict.error);
1191
+ return;
1192
+ }
1193
+
1194
+ const blocking = references.filter((ref) => unregisteredTypes.includes(ref.type));
1195
+ const forced = await confirmDialog({
1196
+ title: 'Referenced by a document you cannot open',
1197
+ // See the bulk dialog: what's blocking, then what the button does.
1198
+ description:
1199
+ `"${asset.originalFilename}" is used by ${blocking.length} document${blocking.length > 1 ? 's' : ''} of type ${unregisteredTypes.join(', ')}, which no longer ${unregisteredTypes.length > 1 ? 'exist' : 'exists'} in your schema. ` +
1200
+ `Force delete removes the reference${blocking.length > 1 ? 's' : ''} for you.`,
1201
+ confirmText: 'Force delete',
1202
+ variant: 'destructive'
1203
+ });
1204
+ if (forced) {
1205
+ await performDelete(asset, true);
1206
+ }
1207
+ }
1208
+
482
1209
  // Copy URL state
483
1210
  let copiedUrl = $state(false);
484
1211
 
1212
+ let copiedId = $state(false);
1213
+
1214
+ /**
1215
+ * Copy the raw asset id.
1216
+ *
1217
+ * Not `copyUrlToClipboard`, which prefixes `window.location.origin` for a
1218
+ * shareable link — correct for a URL and wrong for an id, which is pasted
1219
+ * into a query, a seed, or an `{ asset: { _ref } }`, never into a browser.
1220
+ */
1221
+ async function copyAssetId(asset: Asset) {
1222
+ try {
1223
+ await navigator.clipboard.writeText(asset.id);
1224
+ copiedId = true;
1225
+ toast.success('Asset ID copied');
1226
+ setTimeout(() => (copiedId = false), 2000);
1227
+ } catch {
1228
+ toast.error('Failed to copy asset ID');
1229
+ }
1230
+ }
1231
+
485
1232
  async function copyAssetUrl(asset: Asset) {
486
- const url = getThumbnailUrl(asset);
1233
+ const url = getOriginalUrl(asset);
487
1234
  const success = await copyUrlToClipboard(url);
488
1235
  if (success) {
489
1236
  copiedUrl = true;
@@ -492,7 +1239,18 @@
492
1239
  }
493
1240
 
494
1241
  function downloadAsset(asset: Asset) {
495
- downloadFile(getThumbnailUrl(asset), asset.originalFilename);
1242
+ downloadFile(getOriginalUrl(asset), asset.originalFilename);
1243
+ }
1244
+
1245
+ /**
1246
+ * Secondary line on a grid tile: `PNG · 2.4 MB`, with dimensions when known.
1247
+ * The filename alone rarely distinguishes two crops of the same photo, which
1248
+ * is the case where a contact-sheet grid is least useful.
1249
+ */
1250
+ function assetMetaLine(asset: Asset): string {
1251
+ const kind = (asset.mimeType?.split('/')[1] ?? '').toUpperCase();
1252
+ const dimensions = asset.width && asset.height ? `${asset.width}×${asset.height}` : null;
1253
+ return [kind || null, dimensions, formatSize(asset.size)].filter(Boolean).join(' · ');
496
1254
  }
497
1255
 
498
1256
  // Format file size
@@ -509,16 +1267,272 @@
509
1267
  return d.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
510
1268
  }
511
1269
 
512
- // Get thumbnail URL
1270
+ /**
1271
+ * URL to draw an asset at tile size.
1272
+ *
1273
+ * Prefers the smallest derivative on the ladder. This grid used to render
1274
+ * `asset.url` — the original — so a page of thirty photographs pulled thirty
1275
+ * full-resolution files to fill thirty ~200px tiles. Nothing looked wrong,
1276
+ * which is precisely why it went unnoticed.
1277
+ *
1278
+ * Falls back to the original when the pipeline is off or the asset can't be
1279
+ * resized (SVG, animated): the variant route would serve the original for
1280
+ * those anyway, and naming it directly saves a pointless redirect through a
1281
+ * generation attempt.
1282
+ */
1283
+ /**
1284
+ * A video's poster frame, when one was extracted at upload.
1285
+ *
1286
+ * Gated on the recorded flag rather than optimistically requesting the URL: a
1287
+ * video without a poster answers 404, and a grid of broken <img> is worse than
1288
+ * a grid of honest placeholder icons.
1289
+ */
1290
+ let generatingPoster = $state(false);
1291
+
1292
+ /**
1293
+ * Videos whose poster we have already tried to produce this session.
1294
+ *
1295
+ * Without it a video the browser cannot decode is retried on every render:
1296
+ * failure leaves no poster, an absent poster is the trigger, and the loop
1297
+ * costs a fetch and a decode attempt each time round.
1298
+ */
1299
+ const posterAttempts = new SvelteSet<string>();
1300
+
1301
+ /**
1302
+ * Fill in posters for videos that have none.
1303
+ *
1304
+ * Automatic rather than a button, because "this video has no thumbnail" is not
1305
+ * a decision an editor should have to make — it is just an asset uploaded
1306
+ * before posters existed, or through the API where no browser saw the file.
1307
+ *
1308
+ * Only a browser can do this (see `video-metadata.ts`), so it happens here
1309
+ * rather than in a job. Three deliberate limits: only assets on the page in
1310
+ * front of the user, one at a time, and never the same asset twice — each
1311
+ * fetches part of a video and runs a decode, and thirty of those at once would
1312
+ * make opening the media library expensive.
1313
+ */
1314
+ async function backfillPosters(candidates: Asset[]) {
1315
+ for (const asset of candidates) {
1316
+ if (posterAttempts.has(asset.id)) continue;
1317
+ posterAttempts.add(asset.id);
1318
+ try {
1319
+ const info = await extractVideoInfoFromUrl(getOriginalUrl(asset));
1320
+ // Audio yields a duration and no frame, which is still worth storing —
1321
+ // a WAV's length is exactly what the grid has no other way to show.
1322
+ if (!info.poster && info.duration == null) continue;
1323
+ await assets.uploadPoster(asset.id, info.poster, {
1324
+ duration: info.duration,
1325
+ width: info.width,
1326
+ height: info.height
1327
+ });
1328
+ // Patch in place rather than refetching the page: a background task
1329
+ // must not move the grid under someone mid-click.
1330
+ assetList = assetList.map((item) =>
1331
+ item.id === asset.id
1332
+ ? {
1333
+ ...item,
1334
+ width: info.width ?? item.width,
1335
+ height: info.height ?? item.height,
1336
+ metadata: {
1337
+ ...(item.metadata ?? {}),
1338
+ poster: true,
1339
+ duration: info.duration ?? item.metadata?.duration
1340
+ }
1341
+ }
1342
+ : item
1343
+ );
1344
+ } catch (err) {
1345
+ cmsLogger.debug('[Media]', 'Poster backfill skipped for', asset.id, err);
1346
+ }
1347
+ }
1348
+ }
1349
+
1350
+ /**
1351
+ * Produce a poster for a video that has none — one uploaded before posters
1352
+ * existed, or through the API where no browser saw the file.
1353
+ *
1354
+ * Cheap only because the media route serves byte ranges: the browser fetches
1355
+ * the container header and the frames around the seek point rather than the
1356
+ * whole video.
1357
+ */
1358
+ async function generatePoster(asset: Asset) {
1359
+ generatingPoster = true;
1360
+ try {
1361
+ const info = await extractVideoInfoFromUrl(getOriginalUrl(asset));
1362
+ if (!info.poster) {
1363
+ toast.error('Could not read a frame — this browser may not decode that codec');
1364
+ return;
1365
+ }
1366
+ await assets.uploadPoster(asset.id, info.poster, {
1367
+ duration: info.duration,
1368
+ width: info.width,
1369
+ height: info.height
1370
+ });
1371
+ toast.success('Poster generated');
1372
+ await fetchAssets(currentPage);
1373
+ // Re-read so the inspector's own copy carries metadata.poster.
1374
+ const refreshed = await assets.getById(asset.id);
1375
+ if (refreshed.success && refreshed.data) selectedAsset = refreshed.data;
1376
+ } catch (err) {
1377
+ cmsLogger.error('[Media]', 'Poster generation failed:', err);
1378
+ toast.error('Failed to save poster');
1379
+ } finally {
1380
+ generatingPoster = false;
1381
+ }
1382
+ }
1383
+
1384
+ function getPosterUrl(asset: Asset): string | null {
1385
+ const hasPoster = (asset.metadata as { poster?: unknown } | null)?.poster === true;
1386
+ return hasPoster ? `/media/${asset.id}/poster.webp` : null;
1387
+ }
1388
+
513
1389
  function getThumbnailUrl(asset: Asset): string {
1390
+ return variantUrlAt(asset, (config) => thumbnailWidth(config, asset.width ?? null));
1391
+ }
1392
+
1393
+ /**
1394
+ * The asset's own URL — the file that was uploaded, at full size.
1395
+ *
1396
+ * Distinct from {@link getThumbnailUrl} on purpose. Copying a URL and
1397
+ * downloading a file both mean the *original*: handing someone a 320px webp
1398
+ * when they asked for the asset is a data-loss-shaped bug, even though
1399
+ * nothing errors.
1400
+ */
1401
+ function getOriginalUrl(asset: Asset): string {
514
1402
  return asset.url || `/media/${asset.id}/${asset.filename}`;
515
1403
  }
516
1404
 
1405
+ /**
1406
+ * A derivative at the width `pick` chooses, or the original when the pipeline
1407
+ * is off or the asset can't be resized (SVG, animated). The variant route
1408
+ * serves the original for those anyway; naming it directly skips a pointless
1409
+ * generation attempt.
1410
+ */
1411
+ function variantUrlAt(asset: Asset, pick: (config: ImageConfig) => number): string {
1412
+ if (!imageConfig || !canGenerateVariants(asset)) return getOriginalUrl(asset);
1413
+ return buildVariantUrl(asset.id, pick(imageConfig), imageConfig.configHash);
1414
+ }
1415
+
1416
+ /** Detail-pane preview: a panel-width rung, not a tile and not the original. */
1417
+ function getPreviewUrl(asset: Asset): string {
1418
+ return variantUrlAt(asset, (config) => {
1419
+ const widths = usableWidths(config, asset.width ?? null);
1420
+ return widths.find((w) => w >= 640) ?? widths[widths.length - 1]!;
1421
+ });
1422
+ }
1423
+
1424
+ /**
1425
+ * Lightbox: the largest rung, not the original.
1426
+ *
1427
+ * "Enlarge" on a 14MB photograph should not mean downloading 14MB — the top
1428
+ * rung is already beyond any screen it will be shown on. `Download` is right
1429
+ * there for anyone who wants the actual file.
1430
+ */
1431
+ function getLightboxUrl(asset: Asset): string {
1432
+ return variantUrlAt(asset, (config) => {
1433
+ const widths = usableWidths(config, asset.width ?? null);
1434
+ return widths[widths.length - 1]!;
1435
+ });
1436
+ }
1437
+
517
1438
  // Is image type
518
1439
  function isImage(asset: Asset): boolean {
519
1440
  return asset.assetType === 'image' || asset.mimeType.startsWith('image/');
520
1441
  }
521
1442
 
1443
+ /**
1444
+ * Placeholder icon for an asset with no visual preview.
1445
+ *
1446
+ * Everything non-image used to fall through to one page icon, so an mp4, an
1447
+ * mp3 and a PDF were indistinguishable in the grid — most obvious once the
1448
+ * media-kind filter existed, where narrowing to "Video" produced a wall of
1449
+ * identical document icons.
1450
+ */
1451
+ /**
1452
+ * Whether a tile should show the whole asset rather than fill its frame.
1453
+ *
1454
+ * `object-contain` everywhere honoured "don't crop the assets", but in a square
1455
+ * tile it pillarboxes every portrait photo, so the grid became mostly empty
1456
+ * background. The reason not to crop was logos and transparent artwork — a
1457
+ * wordmark cropped to a square is unrecognisable — and that reason doesn't
1458
+ * extend to photographs, where the tile is a recognition aid and the inspector
1459
+ * still shows the full uncropped image.
1460
+ *
1461
+ * SVG is the case we can detect from the mime type. Transparency in a PNG
1462
+ * isn't knowable without decoding the file, so PNGs are treated as artwork
1463
+ * too: over-containing a photo costs some whitespace, while over-cropping a
1464
+ * logo destroys it.
1465
+ */
1466
+ /**
1467
+ * Turn a stored field path into something an editor recognises:
1468
+ * `coverImage` → "Cover image", `seo.ogImage` → "Seo › Og image",
1469
+ * `content[13].images[0]` → "Content 14 › Images 1".
1470
+ *
1471
+ * Indices are shown 1-based because they are being read by a person counting
1472
+ * items on a page, not by anything that will index back into the array.
1473
+ */
1474
+ function humanizeFieldPath(path: string): string {
1475
+ return path
1476
+ .split('.')
1477
+ .map((segment) => {
1478
+ const match = /^(.*?)((\[\d+\])*)$/.exec(segment);
1479
+ const name = match?.[1] ?? segment;
1480
+ const indices = (match?.[2] ?? '')
1481
+ .match(/\d+/g)
1482
+ ?.map((n) => ` ${Number(n) + 1}`)
1483
+ .join('');
1484
+ const label = name
1485
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
1486
+ .replace(/^./, (c) => c.toUpperCase())
1487
+ .toLowerCase()
1488
+ .replace(/^./, (c) => c.toUpperCase());
1489
+ return `${label}${indices ?? ''}`;
1490
+ })
1491
+ .join(' › ');
1492
+ }
1493
+
1494
+ function isVectorOrTransparent(asset: Asset): boolean {
1495
+ const mime = asset.mimeType ?? '';
1496
+ return mime === 'image/svg+xml' || mime === 'image/png';
1497
+ }
1498
+
1499
+ function isVideo(asset: Asset): boolean {
1500
+ return (asset.mimeType ?? '').startsWith('video/');
1501
+ }
1502
+
1503
+ function isAudio(asset: Asset): boolean {
1504
+ return (asset.mimeType ?? '').startsWith('audio/');
1505
+ }
1506
+
1507
+ /**
1508
+ * Playable length, when we know it. Read from `metadata.duration` (seconds) —
1509
+ * the column set doesn't have a duration field, but `AssetMetadata` carries an
1510
+ * open index signature, so this needs no migration. It is only populated for
1511
+ * assets uploaded through the browser, which is where the duration can be read
1512
+ * off a `<video>` element; anything uploaded via the API has none, hence the
1513
+ * null return rather than a "0:00" that would look like an empty file.
1514
+ */
1515
+ function formatDuration(asset: Asset): string | null {
1516
+ const seconds = Number((asset.metadata as { duration?: unknown } | null)?.duration);
1517
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
1518
+ const total = Math.round(seconds);
1519
+ const hours = Math.floor(total / 3600);
1520
+ const minutes = Math.floor((total % 3600) / 60);
1521
+ const secs = total % 60;
1522
+ return hours > 0
1523
+ ? `${hours}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
1524
+ : `${minutes}:${String(secs).padStart(2, '0')}`;
1525
+ }
1526
+
1527
+ function fileIconFor(mimeType: string | null | undefined) {
1528
+ const mime = mimeType ?? '';
1529
+ if (mime.startsWith('video/')) return Film;
1530
+ if (mime.startsWith('audio/')) return Music;
1531
+ if (mime.startsWith('image/')) return FileImage;
1532
+ if (/zip|tar|gzip|compressed|archive/.test(mime)) return FileArchive;
1533
+ return FileText;
1534
+ }
1535
+
522
1536
  // Compute visible page numbers (show up to 5 pages with ellipsis)
523
1537
  const visiblePages = $derived.by(() => {
524
1538
  const pages: (number | '...')[] = [];
@@ -547,33 +1561,84 @@
547
1561
  : 'Name: Z-A'
548
1562
  );
549
1563
 
550
- // Cycle sort
1564
+ /**
1565
+ * Cycle the sort and refetch.
1566
+ *
1567
+ * The refetch is the point: the order is the server's now, so changing it
1568
+ * without asking for a new page would leave the previous ordering on screen
1569
+ * under a label claiming otherwise. Back to page 1 too — "page 3 of newest"
1570
+ * and "page 3 of A–Z" hold unrelated rows, so keeping the number would land
1571
+ * the user somewhere arbitrary.
1572
+ */
551
1573
  function cycleSort() {
552
1574
  const orders: (typeof sortOrder)[] = ['newest', 'oldest', 'name-asc', 'name-desc'];
553
1575
  const idx = orders.indexOf(sortOrder);
554
1576
  sortOrder = orders[(idx + 1) % orders.length]!;
1577
+ currentPage = 1;
1578
+ fetchAssets(1);
555
1579
  }
556
1580
 
557
- // Track org changes to refetch assets
558
- let currentOrgId = $state<string | null>(null);
559
-
560
- // Track whether we've been active before to detect tab switches
561
- let wasActive = $state(false);
562
-
563
- // Load on mount and refetch when org changes
1581
+ /**
1582
+ * The org the current `assetList` was loaded for, and whether a load has been
1583
+ * issued at all.
1584
+ *
1585
+ * `hasLoaded` is what makes the initial load explicit. Keying purely off
1586
+ * "`orgId` changed" made the first load depend on the URL gaining an `orgId`
1587
+ * that isn't there at mount: on a bare `/admin` the effect compared
1588
+ * `null !== null`, was false, and never fetched. It happens to work today only
1589
+ * because `OrganizationSwitcher` appends `orgId` via `replaceState` shortly
1590
+ * after mount, which flips the comparison — an accident of another component's
1591
+ * behaviour, not something this one should rely on.
1592
+ *
1593
+ * Neither is `$state`: they're written by the effect that reads them, so
1594
+ * making them reactive would re-trigger it for no reason.
1595
+ */
1596
+ let hasLoaded = false;
1597
+ let currentOrgId: string | null = null;
1598
+
1599
+ // Previous value of `active`. `undefined` until the effect below has run once,
1600
+ // which lets that run seed rather than fire — the initial load belongs to the
1601
+ // org effect. Seeding it to `false` instead swallowed the *first* activation:
1602
+ // a browser mounted inactive never refetched when the user first switched to
1603
+ // it, so it showed whatever had been loaded at mount.
1604
+ let wasActive = $state<boolean | undefined>(undefined);
1605
+
1606
+ // Load once on mount, and again whenever the org actually changes.
564
1607
  $effect(() => {
565
1608
  const orgId = page.url.searchParams.get('orgId');
566
- if (orgId !== currentOrgId) {
1609
+
1610
+ if (!hasLoaded) {
1611
+ hasLoaded = true;
567
1612
  currentOrgId = orgId;
568
- selectedAsset = null;
569
- currentPage = 1;
570
1613
  fetchAssets(1);
1614
+ return;
571
1615
  }
1616
+
1617
+ // `null → id` is `OrganizationSwitcher` back-filling the URL just after
1618
+ // mount, not a switch. The list route scopes by the session's active
1619
+ // organization rather than this param, so the initial load already fetched
1620
+ // the right org — refetching here would be a duplicate round-trip on every
1621
+ // single mount. Adopt the id silently and wait for a real change.
1622
+ if (orgId === currentOrgId || currentOrgId === null) {
1623
+ currentOrgId = orgId;
1624
+ return;
1625
+ }
1626
+
1627
+ currentOrgId = orgId;
1628
+ selectedAsset = null;
1629
+ currentPage = 1;
1630
+ fetchAssets(1);
572
1631
  });
573
1632
 
574
- // Refetch when tab becomes active (switching from another tab)
1633
+ // Refetch every time the tab becomes active.
1634
+ //
1635
+ // This is the only invalidation reference counts get (#233): they are fetched
1636
+ // solely as a follow-up to fetching a page of assets, and nothing signals the
1637
+ // media browser when a document edit adds or removes a reference. Re-entering
1638
+ // the tab is the moment the user expects to see the truth, so it must refetch
1639
+ // on *every* activation — including the first.
575
1640
  $effect(() => {
576
- if (active && wasActive) {
1641
+ if (wasActive !== undefined && active && !wasActive) {
577
1642
  selectedAsset = null;
578
1643
  fetchAssets();
579
1644
  }
@@ -581,17 +1646,64 @@
581
1646
  });
582
1647
  </script>
583
1648
 
1649
+ <!--
1650
+ The selection checkbox, shared by every tile and row.
1651
+
1652
+ The capture-phase handler is what makes shift-click work on the checkbox
1653
+ itself and not just the tile around it: bits-ui's Checkbox fires
1654
+ `onCheckedChange` from its own click, so by the time the event bubbled out to
1655
+ us the single-item toggle had already happened and the range would have been
1656
+ computed against a selection that had moved underneath it. Intercepting in
1657
+ capture — only when Shift is held — stops the click before the checkbox ever
1658
+ sees it. Without Shift the event passes straight through, and the
1659
+ `stopPropagation` on the checkbox keeps it from also reaching the row.
1660
+ -->
1661
+ <!-- Stand-in for an asset with no visual preview. A snippet because `{@const}`
1662
+ has to be the immediate child of a block, and the icon component is chosen
1663
+ per mime type. -->
1664
+ {#snippet fileIcon(mimeType: string | null | undefined, sizeClass: string)}
1665
+ {@const Icon = fileIconFor(mimeType)}
1666
+ <Icon class="text-muted-foreground {sizeClass}" />
1667
+ {/snippet}
1668
+
1669
+ {#snippet selectCheckbox(asset: Asset)}
1670
+ <div
1671
+ onclickcapture={(e) => {
1672
+ if (!e.shiftKey) return;
1673
+ e.preventDefault();
1674
+ e.stopPropagation();
1675
+ selectRange(asset.id);
1676
+ }}
1677
+ >
1678
+ <Checkbox
1679
+ checked={selectedIds.has(asset.id)}
1680
+ onCheckedChange={() => handleSelectClick(asset.id, { shiftKey: false })}
1681
+ onclick={(e) => e.stopPropagation()}
1682
+ />
1683
+ </div>
1684
+ {/snippet}
1685
+
584
1686
  <div
585
1687
  class="flex h-full flex-col"
586
1688
  role="region"
1689
+ ondragenter={handleDragEnter}
587
1690
  ondragover={handleDragOver}
588
1691
  ondragleave={handleDragLeave}
1692
+ ondragend={handleDragEnd}
589
1693
  ondrop={handleDrop}
590
1694
  >
591
1695
  <!-- Drag overlay -->
592
1696
  {#if isDragging}
1697
+ <!--
1698
+ `pointer-events-none` is load-bearing, not cosmetic. The overlay appears
1699
+ directly under the cursor mid-drag, so without it the overlay becomes the
1700
+ drag target the moment it renders: that fires dragleave on the region,
1701
+ which hides the overlay, which puts the cursor back over the grid, which
1702
+ shows it again — a feedback loop running at pointer-move rate. The counter
1703
+ alone doesn't save you here, because these are real boundary crossings.
1704
+ -->
593
1705
  <div
594
- class="bg-primary/5 border-primary absolute inset-0 z-50 flex items-center justify-center border-2 border-dashed"
1706
+ class="bg-primary/5 border-primary pointer-events-none absolute inset-0 z-50 flex items-center justify-center border-2 border-dashed"
595
1707
  >
596
1708
  <div class="text-center">
597
1709
  <Upload class="text-primary mx-auto mb-2 h-12 w-12" />
@@ -607,8 +1719,12 @@
607
1719
  <Button
608
1720
  size="sm"
609
1721
  onclick={() => {
1722
+ // Deliberately does not clear the queue. Clicking outside the dialog
1723
+ // dismisses it, and wiping the list on reopen meant an accidental
1724
+ // click discarded a batch — including uploads still running, which
1725
+ // carry on regardless and were simply no longer visible. The queue is
1726
+ // cleared only on an explicit Clear list or Done.
610
1727
  showUploadModal = true;
611
- uploadQueue = [];
612
1728
  }}
613
1729
  >
614
1730
  <Upload size={16} class="sm:mr-2" />
@@ -638,25 +1754,75 @@
638
1754
  {/if}
639
1755
  <div class="hidden flex-1 sm:block"></div>
640
1756
 
641
- <!-- Page size -->
642
- <div class="hidden items-center gap-1.5 sm:flex">
643
- <span class="text-muted-foreground text-xs">Show</span>
644
- <select
645
- value={pageSize}
646
- onchange={(e) => {
647
- pageSize = parseInt((e.target as HTMLSelectElement).value);
648
- currentPage = 1;
649
- fetchAssets(1);
650
- }}
651
- class="border-input bg-background text-foreground h-7 rounded-md border px-1.5 text-xs"
1757
+ <!-- Media kind. Filtering happens in SQL, so it narrows the whole library
1758
+ rather than the loaded page. -->
1759
+ <select
1760
+ value={categoryFilter}
1761
+ onchange={(e) => {
1762
+ categoryFilter = (e.target as HTMLSelectElement).value as CategoryFilter;
1763
+ currentPage = 1;
1764
+ fetchAssets(1);
1765
+ }}
1766
+ aria-label="Filter by media type"
1767
+ class="border-input bg-background text-foreground hidden h-7 rounded-md border px-1.5 text-xs sm:block"
1768
+ >
1769
+ <option value="all">All types</option>
1770
+ <option value="image">Images</option>
1771
+ <option value="svg">SVG</option>
1772
+ <option value="video">Video</option>
1773
+ <option value="audio">Audio</option>
1774
+ <option value="document">Documents</option>
1775
+ </select>
1776
+
1777
+ {#if usageIndexing}
1778
+ <span
1779
+ class="text-muted-foreground hidden items-center gap-1.5 text-xs sm:inline-flex"
1780
+ title="Building the reference index. Usage results are incomplete until it finishes."
652
1781
  >
653
- <option value={10}>10</option>
654
- <option value={20}>20</option>
655
- <option value={30}>30</option>
656
- <option value={50}>50</option>
657
- <option value={100}>100</option>
658
- </select>
659
- </div>
1782
+ <span
1783
+ class="border-muted-foreground/40 h-3 w-3 animate-spin rounded-full border-2 border-t-transparent"
1784
+ ></span>
1785
+ Indexing usage…
1786
+ </span>
1787
+ {/if}
1788
+
1789
+ <!-- Used / unused. The actionable half is "Unused": it is how a library gets
1790
+ cleaned up, and it only became answerable once references were indexed. -->
1791
+ <select
1792
+ value={usageFilter}
1793
+ onchange={(e) => {
1794
+ usageFilter = (e.target as HTMLSelectElement).value as UsageFilter;
1795
+ currentPage = 1;
1796
+ fetchAssets(1);
1797
+ }}
1798
+ aria-label="Filter by usage"
1799
+ class="border-input bg-background text-foreground hidden h-7 rounded-md border px-1.5 text-xs sm:block"
1800
+ >
1801
+ <option value="all">All assets</option>
1802
+ <option value="in-use">In use</option>
1803
+ <option value="unused">Unused</option>
1804
+ </select>
1805
+
1806
+ <!-- Grid density. Replaces the page-size select, which cost permanent
1807
+ toolbar space to answer a question editors rarely have — how many
1808
+ assets fit on a page matters far less than whether they can tell one
1809
+ thumbnail from another. Grid only; the list view has a fixed row. -->
1810
+ {#if viewMode === 'grid'}
1811
+ <div class="bg-muted hidden items-center rounded-md p-0.5 sm:flex">
1812
+ {#each [{ id: 'compact' as const, label: 'Compact' }, { id: 'default' as const, label: 'Default' }, { id: 'large' as const, label: 'Large' }] as option (option.id)}
1813
+ <button
1814
+ onclick={() => (gridDensity = option.id)}
1815
+ title="{option.label} thumbnails"
1816
+ aria-pressed={gridDensity === option.id}
1817
+ class="rounded px-2 py-1 text-xs transition-colors {gridDensity === option.id
1818
+ ? 'bg-background text-foreground shadow-sm'
1819
+ : 'text-muted-foreground hover:text-foreground'}"
1820
+ >
1821
+ {option.label}
1822
+ </button>
1823
+ {/each}
1824
+ </div>
1825
+ {/if}
660
1826
 
661
1827
  <!-- View toggle -->
662
1828
  <div class="bg-muted flex items-center rounded-md p-0.5">
@@ -711,11 +1877,27 @@
711
1877
  <svelte:boundary
712
1878
  onerror={(error) => cmsLogger.error('[MediaBrowser]', 'Render error:', error)}
713
1879
  >
714
- {#if loading && assetList.length === 0}
1880
+ {#if showAccessDenied}
1881
+ <div class="flex h-full flex-col items-center justify-center gap-4">
1882
+ <div class="bg-muted/50 flex h-16 w-16 items-center justify-center rounded-full">
1883
+ <Lock class="text-muted-foreground h-8 w-8" />
1884
+ </div>
1885
+ <div class="text-center">
1886
+ <h3 class="mb-1 font-medium">No access to media</h3>
1887
+ <p class="text-muted-foreground text-sm">
1888
+ Your role doesn't include permission to view assets.
1889
+ </p>
1890
+ </div>
1891
+ </div>
1892
+ {:else if loading && assetList.length === 0}
715
1893
  <div class="flex h-full items-center justify-center">
716
1894
  <p class="text-muted-foreground">Loading assets...</p>
717
1895
  </div>
718
- {:else if sortedAssets.length === 0}
1896
+ <!-- `orderedAssets`, not `sortedAssets`: on a page where every asset is
1897
+ already selected, `sortedAssets` is empty and the pinned list holds
1898
+ all of them — this branch would have replaced those tiles with
1899
+ "No assets found". -->
1900
+ {:else if orderedAssets.length === 0}
719
1901
  <div class="flex h-full flex-col items-center justify-center gap-4">
720
1902
  <div class="bg-muted/50 flex h-16 w-16 items-center justify-center rounded-full">
721
1903
  <ImageIcon class="text-muted-foreground h-8 w-8" />
@@ -730,118 +1912,247 @@
730
1912
  </div>
731
1913
  </div>
732
1914
  {:else}
733
- <!-- Bulk action bar (shared for grid and list) -->
1915
+ <!-- Bulk action bar (shared for grid and list).
1916
+ Select-all lives here rather than only in the list header, which
1917
+ is where it used to be — the grid is the view people actually
1918
+ bulk-select in, and it had no way to do it at all.
1919
+
1920
+ `sticky top-0` against the scroll container: selecting is the one
1921
+ task here that involves scrolling far from the controls, so a bar
1922
+ that scrolls away strands the selection — you have to scroll back
1923
+ to act on it, and the running count is invisible while you build
1924
+ it. The opaque `bg-muted` is what keeps it legible over the tiles
1925
+ passing underneath. -->
734
1926
  {#if selectable && multiSelect}
735
- <div class="bg-muted border-border flex items-center gap-3 border-b px-4 py-2">
1927
+ <div
1928
+ class="bg-muted border-border sticky top-0 z-20 flex items-center gap-3 border-b px-4 py-2"
1929
+ >
736
1930
  <span class="text-sm font-medium">
737
1931
  {selectedIds.size} selected
738
1932
  </span>
1933
+ <button
1934
+ onclick={toggleSelectAll}
1935
+ class="text-muted-foreground hover:text-foreground text-sm transition-colors"
1936
+ >
1937
+ {allSelected ? 'Deselect page' : 'Select page'}
1938
+ </button>
1939
+ <span class="text-muted-foreground hidden text-xs lg:inline">
1940
+ Shift-click to extend a range
1941
+ </span>
1942
+ <div class="flex-1"></div>
739
1943
  <Button variant="default" size="sm" onclick={confirmMultiSelect}>Done</Button>
740
1944
  </div>
741
- {:else if selectedIds.size > 0}
742
- <div class="bg-muted border-border flex items-center gap-3 border-b px-4 py-2">
1945
+ {:else if isSelectMode}
1946
+ <div
1947
+ class="bg-muted border-border sticky top-0 z-20 flex items-center gap-3 border-b px-4 py-2"
1948
+ >
743
1949
  <span class="text-sm font-medium">
744
1950
  {selectedIds.size} selected
745
1951
  </span>
746
- {#if canDeleteAssets}
747
- <Button
748
- variant="destructive"
749
- size="sm"
750
- onclick={bulkDelete}
751
- disabled={isBulkDeleting}
752
- >
753
- <Trash2 size={14} class="mr-1.5" />
754
- {isBulkDeleting ? 'Deleting...' : 'Delete'}
755
- </Button>
756
- {/if}
757
1952
  <button
758
- onclick={() => (selectedIds = new Set())}
1953
+ onclick={toggleSelectAll}
759
1954
  class="text-muted-foreground hover:text-foreground text-sm transition-colors"
760
1955
  >
761
- Clear selection
1956
+ {allSelected ? 'Deselect page' : 'Select page'}
762
1957
  </button>
1958
+ {#if selectedIds.size > 0}
1959
+ {#if canDeleteAssets}
1960
+ <Button
1961
+ variant="destructive"
1962
+ size="sm"
1963
+ onclick={bulkDelete}
1964
+ disabled={isBulkDeleting}
1965
+ >
1966
+ <Trash2 size={14} class="mr-1.5" />
1967
+ {isBulkDeleting ? 'Deleting...' : 'Delete'}
1968
+ </Button>
1969
+ {/if}
1970
+ <button
1971
+ onclick={clearSelection}
1972
+ class="text-muted-foreground hover:text-foreground text-sm transition-colors"
1973
+ >
1974
+ Clear selection
1975
+ </button>
1976
+ {/if}
1977
+ <div class="flex-1"></div>
1978
+ <span class="text-muted-foreground hidden text-xs lg:inline">
1979
+ Shift-click to extend a range
1980
+ </span>
763
1981
  </div>
764
1982
  {/if}
765
1983
  {#if viewMode === 'grid'}
766
1984
  <!-- Grid View -->
767
- <div class="grid grid-cols-2 gap-0.5 p-1 sm:grid-cols-5 xl:grid-cols-10">
1985
+ <!-- `select-none`: shift-click is a selection gesture here, and
1986
+ without it the browser also drags a blue text highlight across
1987
+ every filename in the range. -->
1988
+ <div
1989
+ class="grid gap-3 p-3 select-none"
1990
+ style="grid-template-columns: repeat(auto-fill, minmax({TILE_MIN_WIDTH[
1991
+ gridDensity
1992
+ ]}px, 1fr));"
1993
+ >
768
1994
  {#each pinnedAssets as asset (asset.id)}
769
1995
  <button
770
- onclick={() => {
1996
+ onclick={(e) => {
771
1997
  if (selectable && multiSelect) {
772
- toggleSelect(asset.id);
1998
+ handleSelectClick(asset.id, e);
773
1999
  } else {
774
2000
  openAssetDetail(asset);
775
2001
  }
776
2002
  }}
777
- class="group relative flex flex-col overflow-hidden rounded-sm transition-colors {selectedIds.has(
2003
+ class="group border-border bg-card relative flex flex-col overflow-hidden rounded-md border text-left transition-all {selectedIds.has(
778
2004
  asset.id
779
2005
  )
780
- ? 'ring-primary ring-2'
2006
+ ? 'border-primary ring-primary/40 ring-2'
781
2007
  : selectedAsset?.id === asset.id
782
- ? 'ring-primary ring-2'
783
- : 'hover:bg-muted/50'}"
2008
+ ? 'border-primary ring-primary/40 ring-2'
2009
+ : 'hover:border-muted-foreground/40 hover:shadow-sm'}"
784
2010
  >
785
2011
  <div class="bg-muted/30 relative aspect-square overflow-hidden">
2012
+ <!-- Playable media reads as playable at a glance. Without this a
2013
+ video and a PDF differ only by a small glyph, which the
2014
+ media-kind filter made obvious: narrowing to Video produced a
2015
+ grid of near-identical cards. -->
2016
+ {#if isVideo(asset) || isAudio(asset)}
2017
+ {@const duration = formatDuration(asset)}
2018
+ <!-- The play glyph belongs over a picture, where it says "this
2019
+ still is a video". Over the placeholder icon used for audio, or
2020
+ for a video with no poster yet, it stacks a second symbol on a
2021
+ first — which is what made a WAV tile look cluttered. -->
2022
+ {#if getPosterUrl(asset)}
2023
+ <div
2024
+ class="pointer-events-none absolute inset-0 z-10 flex items-center justify-center"
2025
+ >
2026
+ <span
2027
+ class="flex h-9 w-9 items-center justify-center rounded-full bg-black/45 backdrop-blur-[1px]"
2028
+ >
2029
+ <Play class="h-4 w-4 translate-x-[1px] fill-white text-white" />
2030
+ </span>
2031
+ </div>
2032
+ {/if}
2033
+ {#if duration}
2034
+ <span
2035
+ class="pointer-events-none absolute right-1.5 bottom-1.5 z-10 rounded-sm bg-black/70 px-1 py-0.5 text-[10px] font-medium text-white tabular-nums"
2036
+ >
2037
+ {duration}
2038
+ </span>
2039
+ {/if}
2040
+ {/if}
786
2041
  {#if isImage(asset)}
787
2042
  <img
788
2043
  src={getThumbnailUrl(asset)}
789
2044
  alt={asset.alt || asset.originalFilename}
790
- class="h-full w-full object-contain"
2045
+ class="h-full w-full {isVectorOrTransparent(asset)
2046
+ ? 'object-contain p-3'
2047
+ : 'object-cover'}"
2048
+ loading="lazy"
2049
+ />
2050
+ {:else if getPosterUrl(asset)}
2051
+ <!-- A frame extracted at upload. Cropped like a photo: it is a
2052
+ still from a rectangular video, not artwork with edges to
2053
+ preserve. -->
2054
+ <img
2055
+ src={getPosterUrl(asset)}
2056
+ alt={asset.alt || asset.originalFilename}
2057
+ class="h-full w-full object-cover"
791
2058
  loading="lazy"
792
2059
  />
793
2060
  {:else}
794
2061
  <div class="flex h-full items-center justify-center">
795
- <FileText class="text-muted-foreground h-10 w-10" />
2062
+ {@render fileIcon(
2063
+ asset.mimeType,
2064
+ 'h-1/3 w-1/3 min-h-8 min-w-8 max-h-20 max-w-20'
2065
+ )}
796
2066
  </div>
797
2067
  {/if}
798
2068
  {#if isSelectMode && !selectable}
799
2069
  <div class="absolute top-1.5 left-1.5">
800
- <Checkbox
801
- checked={selectedIds.has(asset.id)}
802
- onCheckedChange={() => toggleSelect(asset.id)}
803
- onclick={(e) => e.stopPropagation()}
804
- />
2070
+ {@render selectCheckbox(asset)}
805
2071
  </div>
806
2072
  {/if}
807
2073
  </div>
808
- <div class="p-1.5">
809
- <p class="text-muted-foreground truncate text-xs">
2074
+ <div class="border-border min-w-0 border-t px-2 py-1.5">
2075
+ <p class="text-foreground truncate text-xs" title={asset.originalFilename}>
810
2076
  {asset.originalFilename}
811
2077
  </p>
2078
+ <p class="text-muted-foreground truncate text-[11px]">
2079
+ {assetMetaLine(asset)}
2080
+ </p>
812
2081
  </div>
813
2082
  </button>
814
2083
  {/each}
815
2084
  {#each sortedAssets as asset (asset.id)}
816
2085
  <button
817
- onclick={() => {
818
- if (selectable && multiSelect) {
819
- toggleSelect(asset.id);
820
- } else if (isSelectMode) {
821
- toggleSelect(asset.id);
2086
+ onclick={(e) => {
2087
+ if (isSelectMode) {
2088
+ handleSelectClick(asset.id, e);
822
2089
  } else {
823
2090
  openAssetDetail(asset);
824
2091
  }
825
2092
  }}
826
- class="group relative flex flex-col overflow-hidden rounded-sm transition-colors {selectedIds.has(
2093
+ class="group border-border bg-card relative flex flex-col overflow-hidden rounded-md border text-left transition-all {selectedIds.has(
827
2094
  asset.id
828
2095
  )
829
- ? 'ring-primary ring-2'
2096
+ ? 'border-primary ring-primary/40 ring-2'
830
2097
  : selectedAsset?.id === asset.id
831
- ? 'ring-primary ring-2'
832
- : 'hover:bg-muted/50'}"
2098
+ ? 'border-primary ring-primary/40 ring-2'
2099
+ : 'hover:border-muted-foreground/40 hover:shadow-sm'}"
833
2100
  >
834
2101
  <div class="bg-muted/30 relative aspect-square overflow-hidden">
2102
+ <!-- Playable media reads as playable at a glance. Without this a
2103
+ video and a PDF differ only by a small glyph, which the
2104
+ media-kind filter made obvious: narrowing to Video produced a
2105
+ grid of near-identical cards. -->
2106
+ {#if isVideo(asset) || isAudio(asset)}
2107
+ {@const duration = formatDuration(asset)}
2108
+ <!-- The play glyph belongs over a picture, where it says "this
2109
+ still is a video". Over the placeholder icon used for audio, or
2110
+ for a video with no poster yet, it stacks a second symbol on a
2111
+ first — which is what made a WAV tile look cluttered. -->
2112
+ {#if getPosterUrl(asset)}
2113
+ <div
2114
+ class="pointer-events-none absolute inset-0 z-10 flex items-center justify-center"
2115
+ >
2116
+ <span
2117
+ class="flex h-9 w-9 items-center justify-center rounded-full bg-black/45 backdrop-blur-[1px]"
2118
+ >
2119
+ <Play class="h-4 w-4 translate-x-[1px] fill-white text-white" />
2120
+ </span>
2121
+ </div>
2122
+ {/if}
2123
+ {#if duration}
2124
+ <span
2125
+ class="pointer-events-none absolute right-1.5 bottom-1.5 z-10 rounded-sm bg-black/70 px-1 py-0.5 text-[10px] font-medium text-white tabular-nums"
2126
+ >
2127
+ {duration}
2128
+ </span>
2129
+ {/if}
2130
+ {/if}
835
2131
  {#if isImage(asset)}
836
2132
  <img
837
2133
  src={getThumbnailUrl(asset)}
838
2134
  alt={asset.alt || asset.originalFilename}
839
- class="h-full w-full object-contain"
2135
+ class="h-full w-full {isVectorOrTransparent(asset)
2136
+ ? 'object-contain p-3'
2137
+ : 'object-cover'}"
2138
+ loading="lazy"
2139
+ />
2140
+ {:else if getPosterUrl(asset)}
2141
+ <!-- A frame extracted at upload. Cropped like a photo: it is a
2142
+ still from a rectangular video, not artwork with edges to
2143
+ preserve. -->
2144
+ <img
2145
+ src={getPosterUrl(asset)}
2146
+ alt={asset.alt || asset.originalFilename}
2147
+ class="h-full w-full object-cover"
840
2148
  loading="lazy"
841
2149
  />
842
2150
  {:else}
843
2151
  <div class="flex h-full items-center justify-center">
844
- <FileText class="text-muted-foreground h-10 w-10" />
2152
+ {@render fileIcon(
2153
+ asset.mimeType,
2154
+ 'h-1/3 w-1/3 min-h-8 min-w-8 max-h-20 max-w-20'
2155
+ )}
845
2156
  </div>
846
2157
  {/if}
847
2158
  {#if selectable}
@@ -876,21 +2187,36 @@
876
2187
  />
877
2188
  </svg>
878
2189
  </div>
879
- {:else if isSelectMode}
880
- <!-- Checkbox overlay for bulk mode -->
881
- <div class="absolute top-1.5 left-1.5">
882
- <Checkbox
883
- checked={selectedIds.has(asset.id)}
884
- onCheckedChange={() => toggleSelect(asset.id)}
885
- onclick={(e) => e.stopPropagation()}
886
- />
2190
+ {:else if isSelectMode || canDeleteAssets}
2191
+ <!--
2192
+ Checkbox overlay. Revealed on hover when not yet in select
2193
+ mode, which gives the grid the same way in as the list —
2194
+ whose checkboxes are always visible. Before this, starting a
2195
+ selection from the grid meant knowing that the toolbar's
2196
+ icon button existed, and the grid is where a page of
2197
+ thumbnails is actually triaged.
2198
+
2199
+ Gated on `canDeleteAssets` for the same reason that button
2200
+ is: with no bulk action available, a selection has nowhere
2201
+ to go.
2202
+ -->
2203
+ <div
2204
+ class="absolute top-1.5 left-1.5 transition-opacity {isSelectMode ||
2205
+ selectedIds.has(asset.id)
2206
+ ? 'opacity-100'
2207
+ : 'opacity-0 group-hover:opacity-100 focus-within:opacity-100'}"
2208
+ >
2209
+ {@render selectCheckbox(asset)}
887
2210
  </div>
888
2211
  {/if}
889
2212
  </div>
890
- <div class="p-1.5">
891
- <p class="text-muted-foreground truncate text-xs">
2213
+ <div class="border-border min-w-0 border-t px-2 py-1.5">
2214
+ <p class="text-foreground truncate text-xs" title={asset.originalFilename}>
892
2215
  {asset.originalFilename}
893
2216
  </p>
2217
+ <p class="text-muted-foreground truncate text-[11px]">
2218
+ {assetMetaLine(asset)}
2219
+ </p>
894
2220
  </div>
895
2221
  </button>
896
2222
  {/each}
@@ -933,7 +2259,7 @@
933
2259
  {/if}
934
2260
  {:else}
935
2261
  <!-- List View -->
936
- <div class="w-full">
2262
+ <div class="w-full select-none">
937
2263
  <!-- Table header -->
938
2264
  <div
939
2265
  class="bg-muted/30 border-border text-muted-foreground hidden items-center gap-4 border-b px-4 py-2 text-xs font-medium tracking-wider uppercase md:grid md:grid-cols-[auto_40px_1fr_100px_100px_80px_50px_100px]"
@@ -958,14 +2284,20 @@
958
2284
  </div>
959
2285
  <div>Assets</div>
960
2286
  </div>
961
- {#each sortedAssets as asset (asset.id)}
2287
+ <!-- `orderedAssets`, not `sortedAssets`: in multi-select picker mode
2288
+ the already-selected assets are filtered out of `sortedAssets`
2289
+ and rendered separately as pinned tiles — which the list view
2290
+ never rendered. The images already in the field were therefore
2291
+ invisible here, and so impossible to deselect without switching
2292
+ to grid. -->
2293
+ {#each orderedAssets as asset (asset.id)}
962
2294
  <!-- Desktop row -->
963
2295
  <button
964
- onclick={() => {
2296
+ onclick={(e) => {
965
2297
  if (selectable && multiSelect) {
966
2298
  openAssetDetail(asset);
967
2299
  } else if (isSelectMode) {
968
- toggleSelect(asset.id);
2300
+ handleSelectClick(asset.id, e);
969
2301
  } else if (selectable && onSelect) {
970
2302
  onSelect(asset);
971
2303
  } else {
@@ -980,11 +2312,7 @@
980
2312
  : 'hover:bg-muted/50'}"
981
2313
  >
982
2314
  <div class="w-4">
983
- <Checkbox
984
- checked={selectedIds.has(asset.id)}
985
- onCheckedChange={() => toggleSelect(asset.id)}
986
- onclick={(e) => e.stopPropagation()}
987
- />
2315
+ {@render selectCheckbox(asset)}
988
2316
  </div>
989
2317
  <div class="bg-muted/30 h-10 w-10 overflow-hidden rounded">
990
2318
  {#if isImage(asset)}
@@ -994,9 +2322,19 @@
994
2322
  class="h-full w-full object-cover"
995
2323
  loading="lazy"
996
2324
  />
2325
+ {:else if getPosterUrl(asset)}
2326
+ <!-- Same poster the grid uses. The list had only the placeholder
2327
+ icon branch, so a video with a perfectly good frame still
2328
+ rendered as a generic film glyph here. -->
2329
+ <img
2330
+ src={getPosterUrl(asset)}
2331
+ alt={asset.alt || asset.originalFilename}
2332
+ class="h-full w-full object-cover"
2333
+ loading="lazy"
2334
+ />
997
2335
  {:else}
998
2336
  <div class="flex h-full items-center justify-center">
999
- <FileText class="text-muted-foreground h-4 w-4" />
2337
+ {@render fileIcon(asset.mimeType, 'h-4 w-4')}
1000
2338
  </div>
1001
2339
  {/if}
1002
2340
  </div>
@@ -1015,11 +2353,11 @@
1015
2353
  </button>
1016
2354
  <!-- Mobile row -->
1017
2355
  <button
1018
- onclick={() => {
2356
+ onclick={(e) => {
1019
2357
  if (selectable && multiSelect) {
1020
2358
  openAssetDetail(asset);
1021
2359
  } else if (isSelectMode) {
1022
- toggleSelect(asset.id);
2360
+ handleSelectClick(asset.id, e);
1023
2361
  } else if (selectable && onSelect) {
1024
2362
  onSelect(asset);
1025
2363
  } else {
@@ -1034,11 +2372,7 @@
1034
2372
  : 'hover:bg-muted/50'}"
1035
2373
  >
1036
2374
  <div class="w-4">
1037
- <Checkbox
1038
- checked={selectedIds.has(asset.id)}
1039
- onCheckedChange={() => toggleSelect(asset.id)}
1040
- onclick={(e) => e.stopPropagation()}
1041
- />
2375
+ {@render selectCheckbox(asset)}
1042
2376
  </div>
1043
2377
  <div class="bg-muted/30 h-10 w-10 shrink-0 overflow-hidden rounded">
1044
2378
  {#if isImage(asset)}
@@ -1048,9 +2382,19 @@
1048
2382
  class="h-full w-full object-cover"
1049
2383
  loading="lazy"
1050
2384
  />
2385
+ {:else if getPosterUrl(asset)}
2386
+ <!-- Same poster the grid uses. The list had only the placeholder
2387
+ icon branch, so a video with a perfectly good frame still
2388
+ rendered as a generic film glyph here. -->
2389
+ <img
2390
+ src={getPosterUrl(asset)}
2391
+ alt={asset.alt || asset.originalFilename}
2392
+ class="h-full w-full object-cover"
2393
+ loading="lazy"
2394
+ />
1051
2395
  {:else}
1052
2396
  <div class="flex h-full items-center justify-center">
1053
- <FileText class="text-muted-foreground h-4 w-4" />
2397
+ {@render fileIcon(asset.mimeType, 'h-4 w-4')}
1054
2398
  </div>
1055
2399
  {/if}
1056
2400
  </div>
@@ -1121,8 +2465,19 @@
1121
2465
 
1122
2466
  <!-- Asset Detail Sidebar (extends page on mobile, side panel on desktop) -->
1123
2467
  {#if selectedAsset}
2468
+ <!--
2469
+ The panel is a fixed-height flex column with exactly one scrolling
2470
+ child (the tab content), rather than one big scroll container.
2471
+
2472
+ It used to be the latter: `md:overflow-y-auto` on the panel meant the
2473
+ preview, the tabs and the Save button all scrolled together, so saving
2474
+ alt text on any asset required scrolling past a 200px preview and five
2475
+ fields to reach the button — every time, for every asset. Constraining
2476
+ the scroll to the fields keeps the header, the preview, the tabs and
2477
+ the action footer on screen permanently.
2478
+ -->
1124
2479
  <div
1125
- class="bg-background border-border flex flex-col border-t md:w-[350px] md:shrink-0 md:overflow-y-auto md:border-t-0 md:border-l"
2480
+ class="bg-background border-border flex min-h-0 flex-col border-t md:w-[350px] md:shrink-0 md:border-t-0 md:border-l"
1126
2481
  >
1127
2482
  <!-- Header -->
1128
2483
  <div class="border-border flex items-center justify-between border-b px-4 py-3">
@@ -1188,17 +2543,56 @@
1188
2543
  title="Click to enlarge"
1189
2544
  >
1190
2545
  <img
1191
- src={getThumbnailUrl(selectedAsset)}
2546
+ src={getPreviewUrl(selectedAsset)}
1192
2547
  alt={selectedAsset.alt || selectedAsset.originalFilename}
1193
2548
  class="w-full object-contain"
1194
2549
  style="max-height: 200px;"
1195
2550
  />
1196
2551
  </button>
2552
+ {:else if isVideo(selectedAsset)}
2553
+ <!-- A real <video>, not an iframe: an iframe hands off to the browser's
2554
+ standalone media viewer, which can't be styled or controlled.
2555
+
2556
+ `preload="metadata"` is affordable because /media/:id/:filename now
2557
+ answers Range with 206, so the browser fetches the moov atom rather
2558
+ than the file — which is also where the duration in the controls
2559
+ comes from. Without ranges this had to be "none", since a partial
2560
+ fetch was impossible and metadata preload degraded into downloading
2561
+ the whole video just to draw the player. -->
2562
+ <video
2563
+ src={getOriginalUrl(selectedAsset)}
2564
+ controls
2565
+ preload="metadata"
2566
+ class="bg-muted/30 mb-3 max-h-52 w-full rounded-lg object-contain"
2567
+ >
2568
+ <track kind="captions" />
2569
+ </video>
2570
+ <!-- Only reachable when the automatic pass on load already failed —
2571
+ usually a codec this browser can't decode. Kept as an explicit
2572
+ retry rather than leaving the asset with no way forward. -->
2573
+ {#if !getPosterUrl(selectedAsset) && canUpload && posterAttempts.has(selectedAsset.id)}
2574
+ <Button
2575
+ variant="outline"
2576
+ size="sm"
2577
+ class="mb-3 w-full"
2578
+ disabled={generatingPoster}
2579
+ onclick={() => generatePoster(selectedAsset!)}
2580
+ >
2581
+ {generatingPoster ? 'Reading a frame…' : 'Generate poster'}
2582
+ </Button>
2583
+ {/if}
2584
+ {:else if isAudio(selectedAsset)}
2585
+ <audio
2586
+ src={getOriginalUrl(selectedAsset)}
2587
+ controls
2588
+ preload="metadata"
2589
+ class="mb-3 w-full"
2590
+ ></audio>
1197
2591
  {:else}
1198
2592
  <div
1199
2593
  class="bg-muted/30 mb-3 flex h-28 items-center justify-center overflow-hidden rounded-lg"
1200
2594
  >
1201
- <FileText class="text-muted-foreground h-12 w-12" />
2595
+ {@render fileIcon(selectedAsset.mimeType, 'h-12 w-12')}
1202
2596
  </div>
1203
2597
  {/if}
1204
2598
  </div>
@@ -1230,37 +2624,24 @@
1230
2624
  </div>
1231
2625
 
1232
2626
  <!-- Tab content -->
1233
- <div class="flex-1 overflow-y-auto p-4">
2627
+ <div class="min-h-0 flex-1 overflow-y-auto p-4">
1234
2628
  {#if detailTab === 'details'}
1235
- <!-- Info -->
1236
- <div class="mb-4 space-y-2 text-sm">
1237
- <div class="flex justify-between">
1238
- <span class="text-muted-foreground">Filename</span>
1239
- <span
1240
- class="max-w-[180px] truncate font-medium"
1241
- title={selectedAsset.originalFilename}
1242
- >
1243
- {selectedAsset.originalFilename}
1244
- </span>
1245
- </div>
1246
- <div class="flex justify-between">
1247
- <span class="text-muted-foreground">Type</span>
1248
- <span>{selectedAsset.mimeType}</span>
1249
- </div>
1250
- <div class="flex justify-between">
1251
- <span class="text-muted-foreground">Size</span>
1252
- <span>{formatSize(selectedAsset.size)}</span>
1253
- </div>
1254
- {#if selectedAsset.width && selectedAsset.height}
1255
- <div class="flex justify-between">
1256
- <span class="text-muted-foreground">Dimensions</span>
1257
- <span>{selectedAsset.width} x {selectedAsset.height}</span>
1258
- </div>
1259
- {/if}
1260
- <div class="flex justify-between">
1261
- <span class="text-muted-foreground">Uploaded</span>
1262
- <span>{formatDate(selectedAsset.createdAt)}</span>
1263
- </div>
2629
+ <!-- Summary, then the technical detail folded away.
2630
+ Filename, MIME type, size, dimensions, upload date and asset id
2631
+ all had equal billing above the fields an editor actually edits,
2632
+ so the panel led with facts nobody came for and pushed alt text
2633
+ below the fold. The one-line summary carries what identifies an
2634
+ asset at a glance; everything addressed to a developer moves into
2635
+ a disclosure that stays shut. -->
2636
+ <div class="mb-3">
2637
+ <p class="truncate text-sm font-medium" title={selectedAsset.originalFilename}>
2638
+ {selectedAsset.originalFilename}
2639
+ </p>
2640
+ <p class="text-muted-foreground mt-0.5 text-xs">
2641
+ {assetMetaLine(selectedAsset)}{formatDuration(selectedAsset)
2642
+ ? ` · ${formatDuration(selectedAsset)}`
2643
+ : ''}
2644
+ </p>
1264
2645
  </div>
1265
2646
 
1266
2647
  <!-- Actions -->
@@ -1287,13 +2668,30 @@
1287
2668
 
1288
2669
  <Separator class="my-4" />
1289
2670
 
1290
- <!-- Metadata editing -->
2671
+ <!-- Metadata editing.
2672
+ Gated on `asset.upload`, the capability the PATCH route
2673
+ enforces. Presenting an editable form to a user who can't
2674
+ save turned every keystroke into work discarded by a
2675
+ generic 403 at the end. -->
1291
2676
  <div class="space-y-3">
2677
+ <div>
2678
+ <Label for="asset-filename" class="text-xs">Filename</Label>
2679
+ <Input
2680
+ id="asset-filename"
2681
+ bind:value={editFilename}
2682
+ readonly={!canUpload}
2683
+ disabled={!canUpload}
2684
+ class="mt-1 h-8 text-sm"
2685
+ placeholder="filename.jpg"
2686
+ />
2687
+ </div>
1292
2688
  <div>
1293
2689
  <Label for="asset-title" class="text-xs">Title</Label>
1294
2690
  <Input
1295
2691
  id="asset-title"
1296
2692
  bind:value={editTitle}
2693
+ readonly={!canUpload}
2694
+ disabled={!canUpload}
1297
2695
  class="mt-1 h-8 text-sm"
1298
2696
  placeholder="Asset title"
1299
2697
  />
@@ -1303,7 +2701,9 @@
1303
2701
  <textarea
1304
2702
  id="asset-description"
1305
2703
  bind:value={editDescription}
1306
- class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring mt-1 flex w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"
2704
+ readonly={!canUpload}
2705
+ disabled={!canUpload}
2706
+ class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring mt-1 flex w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
1307
2707
  rows="2"
1308
2708
  placeholder="Description"
1309
2709
  ></textarea>
@@ -1313,6 +2713,8 @@
1313
2713
  <Input
1314
2714
  id="asset-alt"
1315
2715
  bind:value={editAlt}
2716
+ readonly={!canUpload}
2717
+ disabled={!canUpload}
1316
2718
  class="mt-1 h-8 text-sm"
1317
2719
  placeholder="Alternative text"
1318
2720
  />
@@ -1322,14 +2724,76 @@
1322
2724
  <Input
1323
2725
  id="asset-credit"
1324
2726
  bind:value={editCreditLine}
2727
+ readonly={!canUpload}
2728
+ disabled={!canUpload}
1325
2729
  class="mt-1 h-8 text-sm"
1326
2730
  placeholder="Credit / attribution"
1327
2731
  />
1328
2732
  </div>
1329
2733
 
1330
- <Button onclick={saveMetadata} disabled={isSaving} size="sm" class="w-full">
1331
- {isSaving ? 'Saving...' : 'Save changes'}
1332
- </Button>
2734
+ {#if !canUpload}
2735
+ <p class="text-muted-foreground text-xs">
2736
+ You don't have permission to edit asset metadata.
2737
+ </p>
2738
+ {/if}
2739
+
2740
+ <!-- Everything addressed to a developer rather than an editor.
2741
+ A native <details> rather than a toggle in component state:
2742
+ it needs no state to get wrong, it is keyboard accessible and
2743
+ findable by in-page search for free, and it reopens closed on
2744
+ the next asset, which is the right default for a panel whose
2745
+ job is the fields above. -->
2746
+ <details class="group border-border mt-2 border-t pt-3">
2747
+ <summary
2748
+ class="text-muted-foreground hover:text-foreground flex cursor-pointer list-none items-center gap-1 text-xs select-none [&::-webkit-details-marker]:hidden"
2749
+ >
2750
+ <!-- `list-none` alone leaves Safari's marker in place, and the
2751
+ webkit rule alone leaves nothing to indicate the row opens.
2752
+ Both, plus a chevron that turns with the group's open state. -->
2753
+ <ChevronRight size={12} class="transition-transform group-open:rotate-90" />
2754
+ File information
2755
+ </summary>
2756
+ <div class="mt-2 space-y-2 text-xs">
2757
+ <div class="flex justify-between gap-2">
2758
+ <span class="text-muted-foreground">Type</span>
2759
+ <span class="font-mono">{selectedAsset.mimeType}</span>
2760
+ </div>
2761
+ <div class="flex justify-between gap-2">
2762
+ <span class="text-muted-foreground">Size</span>
2763
+ <span>{formatSize(selectedAsset.size)}</span>
2764
+ </div>
2765
+ {#if selectedAsset.width && selectedAsset.height}
2766
+ <div class="flex justify-between gap-2">
2767
+ <span class="text-muted-foreground">Dimensions</span>
2768
+ <span>{selectedAsset.width} × {selectedAsset.height}</span>
2769
+ </div>
2770
+ {/if}
2771
+ {#if formatDuration(selectedAsset)}
2772
+ <div class="flex justify-between gap-2">
2773
+ <span class="text-muted-foreground">Duration</span>
2774
+ <span class="tabular-nums">{formatDuration(selectedAsset)}</span>
2775
+ </div>
2776
+ {/if}
2777
+ <div class="flex justify-between gap-2">
2778
+ <span class="text-muted-foreground">Uploaded</span>
2779
+ <span>{formatDate(selectedAsset.createdAt)}</span>
2780
+ </div>
2781
+ <!-- The id is the asset's real identity: what a document stores
2782
+ in `{ asset: { _ref } }`, what every storage key derives
2783
+ from, and the only stable handle once the filename is
2784
+ editable. Demoted, not dropped. -->
2785
+ <div class="flex items-center justify-between gap-2">
2786
+ <span class="text-muted-foreground">Asset ID</span>
2787
+ <button
2788
+ onclick={() => copyAssetId(selectedAsset!)}
2789
+ title="{selectedAsset.id} — click to copy"
2790
+ class="hover:text-foreground max-w-[180px] cursor-pointer truncate font-mono"
2791
+ >
2792
+ {copiedId ? 'Copied!' : selectedAsset.id}
2793
+ </button>
2794
+ </div>
2795
+ </div>
2796
+ </details>
1333
2797
  </div>
1334
2798
  {:else}
1335
2799
  <!-- References tab -->
@@ -1357,7 +2821,9 @@
1357
2821
  <div class="min-w-0">
1358
2822
  <p class="truncate text-sm font-medium">{ref.title}</p>
1359
2823
  <p class="text-muted-foreground truncate text-xs">
1360
- {ref.type}{ref.status ? ` · ${ref.status}` : ''}
2824
+ {ref.type}{ref.status ? ` · ${ref.status}` : ''}{ref.fieldPaths?.length
2825
+ ? ` · ${ref.fieldPaths.map(humanizeFieldPath).join(', ')}`
2826
+ : ''}
1361
2827
  </p>
1362
2828
  </div>
1363
2829
  </button>
@@ -1366,6 +2832,31 @@
1366
2832
  {/if}
1367
2833
  {/if}
1368
2834
  </div>
2835
+
2836
+ <!--
2837
+ Action footer — outside the scroll container, so Save is on screen
2838
+ whichever field is being edited.
2839
+
2840
+ `sticky bottom-0` is for the mobile layout, where the panel is
2841
+ stacked below the grid and the *page* is what scrolls; on desktop
2842
+ the flex column already puts it at the bottom and sticky is inert.
2843
+
2844
+ Disabled until something actually changed: the button used to be
2845
+ live at all times, so the only way to know whether an edit had been
2846
+ saved was to press it again.
2847
+ -->
2848
+ {#if detailTab === 'details' && canUpload}
2849
+ <div class="border-border bg-background sticky bottom-0 border-t p-3">
2850
+ <Button
2851
+ onclick={saveMetadata}
2852
+ disabled={isSaving || !metadataDirty}
2853
+ size="sm"
2854
+ class="w-full"
2855
+ >
2856
+ {isSaving ? 'Saving...' : metadataDirty ? 'Save changes' : 'Saved'}
2857
+ </Button>
2858
+ </div>
2859
+ {/if}
1369
2860
  </div>
1370
2861
  {/if}
1371
2862
  </div>
@@ -1386,7 +2877,7 @@
1386
2877
  </Dialog.Header>
1387
2878
  <div class="flex flex-1 items-center justify-center overflow-hidden p-4">
1388
2879
  <img
1389
- src={getThumbnailUrl(selectedAsset)}
2880
+ src={getLightboxUrl(selectedAsset)}
1390
2881
  alt={selectedAsset.alt || selectedAsset.originalFilename}
1391
2882
  class="max-h-[70vh] max-w-full object-contain"
1392
2883
  />
@@ -1427,17 +2918,26 @@
1427
2918
  class="border-border mt-2 flex flex-col items-center justify-center rounded-lg border-2 border-dashed px-6 py-10 transition-colors {modalIsDragging
1428
2919
  ? 'border-primary bg-primary/5'
1429
2920
  : 'hover:bg-muted/50'}"
2921
+ ondragenter={(e) => {
2922
+ if (!isFileDrag(e)) return;
2923
+ e.preventDefault();
2924
+ modalDragDepth++;
2925
+ }}
1430
2926
  ondragover={(e) => {
2927
+ if (!isFileDrag(e)) return;
1431
2928
  e.preventDefault();
1432
- modalIsDragging = true;
1433
2929
  }}
1434
2930
  ondragleave={(e) => {
2931
+ if (modalDragDepth === 0) return;
1435
2932
  e.preventDefault();
1436
- modalIsDragging = false;
2933
+ modalDragDepth--;
2934
+ }}
2935
+ ondragend={() => {
2936
+ modalDragDepth = 0;
1437
2937
  }}
1438
2938
  ondrop={(e) => {
1439
2939
  e.preventDefault();
1440
- modalIsDragging = false;
2940
+ modalDragDepth = 0;
1441
2941
  addFilesToQueue(e.dataTransfer?.files || null);
1442
2942
  }}
1443
2943
  role="button"
@@ -1468,13 +2968,62 @@
1468
2968
  />
1469
2969
 
1470
2970
  <!-- Upload queue -->
2971
+ {#if failedCount > 0 && !isUploading}
2972
+ <div class="mt-4 flex items-center justify-between gap-3">
2973
+ <p class="text-muted-foreground text-xs">
2974
+ {failedCount}
2975
+ {failedCount === 1 ? 'upload' : 'uploads'} failed
2976
+ </p>
2977
+ <Button variant="outline" size="sm" onclick={retryAllFailed}>Retry all</Button>
2978
+ </div>
2979
+ {/if}
2980
+
1471
2981
  {#if uploadQueue.length > 0}
1472
- <div class="mt-4 max-h-48 space-y-2 overflow-y-auto">
1473
- {#each uploadQueue as item}
1474
- <div class="border-border flex items-center gap-3 rounded-md border px-3 py-2">
2982
+ <div class="text-muted-foreground mt-4 flex items-baseline justify-between text-xs">
2983
+ <span>
2984
+ {uploadQueue.length}
2985
+ {uploadQueue.length === 1 ? 'file' : 'files'} selected
2986
+ </span>
2987
+ <span class="tabular-nums">{formatSize(queuedBytes)}</span>
2988
+ </div>
2989
+ <div class="mt-2 max-h-64 space-y-2 overflow-y-auto">
2990
+ {#each uploadQueue as item, index}
2991
+ <div
2992
+ class="border-border flex items-center gap-3 rounded-md border px-3 py-2 {item.status ===
2993
+ 'failed'
2994
+ ? 'border-destructive/50'
2995
+ : ''}"
2996
+ >
2997
+ <div class="bg-muted/40 border-border h-9 w-9 shrink-0 overflow-hidden rounded border">
2998
+ {#if item.previewUrl}
2999
+ <img src={item.previewUrl} alt="" class="h-full w-full object-cover" />
3000
+ {:else}
3001
+ <div class="flex h-full items-center justify-center">
3002
+ {@render fileIcon(item.file.type, 'h-4 w-4')}
3003
+ </div>
3004
+ {/if}
3005
+ </div>
1475
3006
  <div class="min-w-0 flex-1">
1476
3007
  <p class="truncate text-sm">{item.file.name}</p>
1477
- <p class="text-muted-foreground text-xs">{formatSize(item.file.size)}</p>
3008
+ {#if item.status === 'failed' && item.error}
3009
+ <p class="text-destructive text-xs">{item.error}</p>
3010
+ {:else if item.status === 'pending' && isUploading}
3011
+ <p class="text-muted-foreground text-xs">Waiting…</p>
3012
+ {:else if item.status === 'uploading'}
3013
+ <div class="mt-1 flex items-center gap-2">
3014
+ <div class="bg-muted h-1 flex-1 overflow-hidden rounded-full">
3015
+ <div
3016
+ class="bg-primary h-full transition-[width] duration-150"
3017
+ style="width: {item.progress ?? 0}%"
3018
+ ></div>
3019
+ </div>
3020
+ <span class="text-muted-foreground w-9 text-right text-xs tabular-nums">
3021
+ {item.progress ?? 0}%
3022
+ </span>
3023
+ </div>
3024
+ {:else}
3025
+ <p class="text-muted-foreground text-xs">{formatSize(item.file.size)}</p>
3026
+ {/if}
1478
3027
  </div>
1479
3028
  {#if item.status === 'uploading'}
1480
3029
  <div
@@ -1483,13 +3032,42 @@
1483
3032
  {:else if item.status === 'done'}
1484
3033
  <CheckCircle2 size={16} class="shrink-0 text-green-500" />
1485
3034
  {:else if item.status === 'failed'}
1486
- <AlertCircle size={16} class="text-destructive shrink-0" />
3035
+ <div class="flex shrink-0 items-center gap-1">
3036
+ <AlertCircle size={16} class="text-destructive" />
3037
+ <Button
3038
+ variant="ghost"
3039
+ size="sm"
3040
+ class="h-6 px-2 text-xs"
3041
+ onclick={() => retryUpload(index)}
3042
+ >
3043
+ Retry
3044
+ </Button>
3045
+ </div>
1487
3046
  {:else}
1488
3047
  <div class="bg-muted h-4 w-4 shrink-0 rounded-full"></div>
1489
3048
  {/if}
1490
3049
  </div>
1491
3050
  {/each}
1492
3051
  </div>
3052
+
3053
+ <!-- The dialog no longer closes itself, so it needs an explicit way out.
3054
+ Disabled mid-flight: dismissing it would hide in-progress uploads
3055
+ that are still running. -->
3056
+ <div class="mt-4 flex items-center justify-between gap-3">
3057
+ <Button variant="ghost" size="sm" disabled={isUploading} onclick={clearUploadQueue}>
3058
+ Clear list
3059
+ </Button>
3060
+ <Button
3061
+ size="sm"
3062
+ disabled={isUploading}
3063
+ onclick={() => {
3064
+ showUploadModal = false;
3065
+ clearUploadQueue();
3066
+ }}
3067
+ >
3068
+ Done
3069
+ </Button>
3070
+ </div>
1493
3071
  {/if}
1494
3072
  </Dialog.Content>
1495
3073
  </Dialog.Root>