@ternarytech-io/gears-ui 0.14.0 → 0.16.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.
package/README.md CHANGED
@@ -110,7 +110,7 @@ add a page, add an entry to `preview/registry.ts` and a folder of examples.
110
110
  | Navigation | `TTabs`, `TPagination`, `TSteps`, `TNav`, `TPanelList`, `TCommandPalette`, `TSearchButton` |
111
111
  | Data | `TTable` (sorting, `selectable` rows), `TAdvancedTable` (filters by column), `TEditableTable` (editing in place, bulk actions, search, pages, column kinds; client-side or `manual`), `TDataGrid` and `TDataGridItem` (Tabler's datagrid: labels and values for detail panels), `TStatCard` (with a trend and a sparkline; `loading`, `clickable`), `TSparkline` (Tabler's, no library), `TLogView`, `TCodeBlock` (JSON or YAML to read and copy: light highlighting by `codeTokens()`, wrapping, a header with actions; no editor, so no Monaco) |
112
112
  | Layout | `TAppLayout` (an application's frame, laid out by its theme, with its menu's colors, a footer slot, and a menu button on small screens), `TScaledFrame` (a whole screen scaled to fit), `TShell`, `TTopbar`, `TPage`, `TSectionLayout`, `TSplitter`, `TAuthLayout`, `TColorModeButton` |
113
- | Plugins | `TAdvancedSelect`, `TChart`, `TPdfViewer`, `TCopyButton`, `TColorPicker`, `TDatePicker`, `TDropzone`, `TInputMask`, `TRangeSlider`, `TSortable`, `TSortableTree`, `TTimeInput`, `TVectorMap`, `TRichEditor` |
113
+ | Plugins | `TAdvancedSelect`, `TChart`, `TPdfViewer`, `TFileViewer`, `TFileView`, `TCopyButton`, `TColorPicker`, `TDatePicker`, `TDropzone`, `TInputMask`, `TRangeSlider`, `TSortable`, `TSortableTree`, `TTimeInput`, `TVectorMap`, `TRichEditor` |
114
114
 
115
115
  ### Plugins
116
116
 
@@ -124,6 +124,7 @@ Tabler's restyling of them (`tabler-vendors.css`), which must come after.
124
124
  | `TAdvancedSelect` | Tom Select | One or several (`multiple`, as chips); `create` adds new values; icons and avatars beside labels. Overlaps `TSelectMenu`, which has no dependency. |
125
125
  | `TChart` | Apache ECharts (Apache-2.0) | `line`, `area`, `bar` (across), `column`, `pie`, `donut`; `series` along `categories`, `stacked`, `format`, `point-click`. Colors follow the theme (and a `TThemeScope`), light or dark; `options` (ECharts options) is merged over everything for anything else. SVG by default, `renderer="canvas"` for very many points; it follows its box's size. Only the charts it uses are bundled. Before 0.4.0 it was ApexCharts, whose license no longer suits apps others use. |
126
126
  | `TPdfViewer` | PDF.js (Mozilla, Apache-2.0) | A PDF's pages, drawn as they scroll into view; `zoom` (fit width, fit page, a percent), `v-model:page`, a toolbar with download and open in a new tab; `setPage`, `download`. Its worker is loaded with Vite's `?url`. |
127
+ | `TFileViewer`, `TFileView` | docx-preview (Apache-2.0), ExcelJS (MIT), markdown-it (MIT), and PDF.js through `TPdfViewer` | Files shown in the page rather than downloaded. `TFileViewer`: `files` (name, `src`, `type`, `size`, `download`, or `load` for a source the browser can't just fetch), v-model is the one shown (null when closed); over the window, or `inline` in its box; previous and next (and the arrow keys), Download, `share` (emits `share` for the host's dialog), an `actions` slot, close (and Escape). `TFileView` is one file filling its box. PDFs, Word (pages zoomed to fit), Excel (a sheet at a time, the common number formats), CSV, Markdown (no HTML from the file), text and code, images, audio and video; anything else, or larger than its kind reads into the page, offers its download. Each library loads the first time its kind is shown, but all of them (and `pdfjs-dist`) need installing, since the bundler resolves them. |
127
128
  | `TCopyButton` | Tabler's clipboard | Copies `text`, or the field `target` selects. Needs https or localhost. |
128
129
  | `TColorPicker` | Coloris | `format`, `alpha`, `swatches`, `swatchesOnly`. The field isn't wrapped by Coloris (Vue owns it); the swatch is ours. |
129
130
  | `TDatePicker` | Tabler's date picker, on Vanilla Calendar Pro | `single`, `multiple` or `range`; `inline`; the model is `YYYY-MM-DD`, `format` only changes the display. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ternarytech-io/gears-ui",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "description": "Gears UI: Vue 3 components on Tabler, used by the Gears Studio and the applications it builds.",
6
6
  "license": "MPL-2.0",
@@ -47,10 +47,13 @@
47
47
  },
48
48
  "peerDependencies": {
49
49
  "@melloware/coloris": "^0.25.0",
50
+ "docx-preview": "^0.4.1",
50
51
  "dropzone": "^6.3.0",
51
52
  "echarts": "^6.1.0",
53
+ "exceljs": "^4.4.0",
52
54
  "hugerte": "^1.0.0",
53
55
  "imask": "^7.6.0",
56
+ "markdown-it": "^15.0.0",
54
57
  "monaco-editor": "^0.57.0",
55
58
  "nouislider": "^15.8.0",
56
59
  "pdfjs-dist": "^6.4.0",
@@ -66,12 +69,16 @@
66
69
  },
67
70
  "devDependencies": {
68
71
  "@melloware/coloris": "0.25.0",
72
+ "@types/markdown-it": "14.1.2",
69
73
  "@types/sortablejs": "1.15.9",
70
74
  "@vitejs/plugin-vue": "6.0.10",
75
+ "docx-preview": "0.4.1",
71
76
  "dropzone": "6.3.5",
72
77
  "echarts": "6.1.0",
78
+ "exceljs": "4.4.0",
73
79
  "hugerte": "1.0.14",
74
80
  "imask": "7.6.1",
81
+ "markdown-it": "15.0.3",
75
82
  "monaco-editor": "0.57.0",
76
83
  "nouislider": "15.8.1",
77
84
  "pdfjs-dist": "6.4.299",
@@ -117,6 +124,15 @@
117
124
  },
118
125
  "hugerte": {
119
126
  "optional": true
127
+ },
128
+ "docx-preview": {
129
+ "optional": true
130
+ },
131
+ "exceljs": {
132
+ "optional": true
133
+ },
134
+ "markdown-it": {
135
+ "optional": true
120
136
  }
121
137
  }
122
138
  }
@@ -6,9 +6,10 @@
6
6
  // or the cards. Selection works with the mouse (Ctrl, Shift) and the keyboard (arrows, Shift,
7
7
  // Ctrl+A); Enter opens a folder (a file emits `open`), F2 renames in place, Delete deletes (after
8
8
  // asking), Ctrl+X and Ctrl+V move, Backspace goes up. Items drag onto folders (in the list or the
9
- // tree) to move; files dropped from the computer upload, a queue with progress. The context menu
10
- // has the standard actions and `menu`'s own. The `info` slot is a side pane for the selection.
11
- // What the provider can't do is left out.
9
+ // tree) to move; files dropped from the computer upload, a queue with progress. Copy to… and Move
10
+ // to… send files to a folder of any drive (chosen in a dialog of the drives' folders), through the
11
+ // same queue. The context menu has the standard actions and `menu`'s own. The `info` slot is a side
12
+ // pane for the selection. What the provider can't do is left out.
12
13
  import { computed, onMounted, reactive, ref, watch } from 'vue'
13
14
  import TBreadcrumbs from './TBreadcrumbs.vue'
14
15
  import TButton from './TButton.vue'
@@ -305,8 +306,17 @@ async function createFolder() {
305
306
  })
306
307
  }
307
308
 
308
- // ---- Uploads: one at a time, each with its progress, cancelable ----
309
- interface Upload { id: number; name: string; size: number; sent: number; state: 'waiting' | 'sending' | 'done' | 'failed' | 'canceled'; error?: string; abort: AbortController; drive: string; folder: string | null; file: File }
309
+ // ---- The queue: uploads, copies and moves to other drives, one at a time, each cancelable ----
310
+ interface Upload {
311
+ id: number; kind: 'upload' | 'copy' | 'move'; name: string; size: number; sent: number; state: 'waiting' | 'sending' | 'done' | 'failed' | 'canceled'; error?: string
312
+ abort: AbortController
313
+ /** Where it goes. */
314
+ drive: string; folder: string | null
315
+ /** An upload's file. */
316
+ file?: File
317
+ /** A copy's or move's item, from where it is, and where it goes as people read it. */
318
+ item?: ExplorerItem; from?: { drive: string; folder: string | null }; to?: string
319
+ }
310
320
  const uploads = reactive<Upload[]>([])
311
321
  let uploadIds = 0
312
322
  let uploading = false
@@ -315,7 +325,7 @@ function queue(files: File[]) {
315
325
  const at = location.value
316
326
  if (!at || !props.provider.upload || !writable.value) return
317
327
  for (const file of files)
318
- uploads.push({ id: ++uploadIds, name: file.name, size: file.size, sent: 0, state: 'waiting', abort: new AbortController(), drive: at.drive, folder: at.folder, file })
328
+ uploads.push({ id: ++uploadIds, kind: 'upload', name: file.name, size: file.size, sent: 0, state: 'waiting', abort: new AbortController(), drive: at.drive, folder: at.folder, file })
319
329
  void run()
320
330
  }
321
331
  async function run() {
@@ -326,15 +336,20 @@ async function run() {
326
336
  const upload = next
327
337
  upload.state = 'sending'
328
338
  try {
329
- await props.provider.upload!(upload.drive, upload.folder, upload.file, sent => { upload.sent = sent }, upload.abort.signal)
339
+ if (upload.kind === 'upload')
340
+ await props.provider.upload!(upload.drive, upload.folder, upload.file!, sent => { upload.sent = sent }, upload.abort.signal)
341
+ else
342
+ await (upload.kind === 'copy' ? props.provider.copy! : props.provider.transfer!)(upload.from!.drive, upload.item!, upload.drive, upload.folder, upload.abort.signal)
330
343
  upload.state = 'done'
331
344
  upload.sent = upload.size
332
- if (location.value?.drive === upload.drive && location.value.folder === upload.folder) await load()
345
+ const here = location.value
346
+ const at = (place?: { drive: string; folder: string | null }) => !!place && here?.drive === place.drive && here.folder === place.folder
347
+ if (at(upload) || at(upload.from)) await load()
333
348
  } catch (e) {
334
349
  if (upload.abort.signal.aborted) upload.state = 'canceled'
335
350
  else {
336
351
  upload.state = 'failed'
337
- upload.error = e instanceof Error ? e.message : 'It couldn\'t be uploaded.'
352
+ upload.error = e instanceof Error ? e.message : upload.kind === 'upload' ? 'It couldn\'t be uploaded.' : `It couldn't be ${upload.kind === 'copy' ? 'copied' : 'moved'}.`
338
353
  }
339
354
  }
340
355
  }
@@ -356,6 +371,64 @@ const picked = (event: Event) => {
356
371
  input.value = ''
357
372
  }
358
373
 
374
+ // ---- Copy to… and Move to…: a folder of any drive, chosen in a dialog ----
375
+ const sending = ref<{ mode: 'copy' | 'move'; items: ExplorerItem[]; from: ExplorerLocation } | null>(null)
376
+ const sendOpen = computed({ get: () => !!sending.value, set: open => { if (!open) sending.value = null } })
377
+ const sendSelected = ref<string | null>(null)
378
+ const sendExpanded = ref<string[]>([])
379
+ // The drives a copy or move can go to: read-only and unavailable ones can't take files.
380
+ const sendNodes = computed<TreeNode[]>(() => drives.value.map(d => ({
381
+ id: nodeId(d.id, null), label: d.name, icon: d.icon ?? 'server-2', leaf: !!d.unavailable, disabled: d.readOnly || !!d.unavailable
382
+ })))
383
+ const canCopy = (list: ExplorerItem[]) => !!props.provider.copy && list.length > 0 && list.every(i => !i.folder)
384
+ const canSend = (list: ExplorerItem[]) => (!!props.provider.transfer || !!props.provider.move) && list.length > 0 && list.every(i => i.can?.move !== false)
385
+ function sendTo(mode: 'copy' | 'move', list: ExplorerItem[]) {
386
+ const at = location.value
387
+ if (!at) return
388
+ sendSelected.value = nodeId(at.drive, at.folder)
389
+ sendExpanded.value = [nodeId(at.drive, null), ...at.path.map(p => nodeId(at.drive, p.id))]
390
+ sending.value = { mode, items: [...list], from: at }
391
+ }
392
+ const sendTarget = computed(() => {
393
+ const id = sendSelected.value
394
+ if (!id) return null
395
+ const driveId = id.split('|')[0]!
396
+ const target = drives.value.find(d => d.id === driveId)
397
+ const place = places.get(id)
398
+ return target ? { drive: driveId, folder: place?.folder ?? null, label: [target.name, ...(place ? pathTo(id).map(p => p.name) : [])].join(' / '), writable: !target.readOnly && !target.unavailable } : null
399
+ })
400
+ // Why the chosen folder won't do; null when it will.
401
+ const sendProblem = computed(() => {
402
+ const job = sending.value
403
+ const target = sendTarget.value
404
+ if (!job || !target) return 'Choose a folder.'
405
+ if (!target.writable) return 'That drive is read-only here.'
406
+ if (job.mode === 'move' && target.drive === job.from.drive && target.folder === job.from.folder) return 'They\'re in this folder already.'
407
+ if (job.mode === 'move' && target.drive !== job.from.drive) {
408
+ if (!props.provider.transfer) return 'Items move within their drive here.'
409
+ if (job.items.some(i => i.folder)) return 'Folders move within their drive; their files can go to another one.'
410
+ }
411
+ if (job.mode === 'move' && target.drive === job.from.drive && job.items.some(i => i.id === target.folder)) return 'A folder can\'t go inside itself.'
412
+ return null
413
+ })
414
+ async function confirmSend() {
415
+ const job = sending.value
416
+ const target = sendTarget.value
417
+ if (!job || !target || sendProblem.value) return
418
+ sending.value = null
419
+ // Within a drive, a move is the drive's own (folders too); otherwise each file is queued.
420
+ if (job.mode === 'move' && target.drive === job.from.drive) {
421
+ await moveTo(job.items, target.folder)
422
+ return
423
+ }
424
+ for (const item of job.items)
425
+ uploads.push({
426
+ id: ++uploadIds, kind: job.mode, name: item.name, size: item.size ?? 0, sent: 0, state: 'waiting', abort: new AbortController(),
427
+ drive: target.drive, folder: target.folder, item, from: { drive: job.from.drive, folder: job.from.folder }, to: target.label
428
+ })
429
+ void run()
430
+ }
431
+
359
432
  // ---- Dragging: items onto folders (list or tree) to move; files from the computer to upload ----
360
433
  const dragType = 'application/x-t-explorer'
361
434
  const over = ref<string | null>(null)
@@ -423,6 +496,11 @@ function menuFor(event: MouseEvent | KeyboardEvent): ContextMenuItem[][] {
423
496
  ...(props.provider.rename && one ? [{ label: 'Rename', icon: 'pencil', kbd: 'F2', disabled: !canRename(one), reason: reasonFor(one, 'rename'), onSelect: () => startRename(one) }] : []),
424
497
  ...(props.provider.move ? [{ label: 'Cut', icon: 'scissors', kbd: 'Ctrl+X', disabled: !canMove(list), reason: list.length === 1 ? reasonFor(list[0]!, 'move') : undefined, onSelect: () => cut(list) }] : []),
425
498
  ...(clipboard.value && one?.folder ? [{ label: 'Paste into', icon: 'clipboard', onSelect: () => void paste(one.id) }] : [])
499
+ ], [
500
+ ...(props.provider.copy ? [{ label: 'Copy to…', icon: 'copy', disabled: !canCopy(list), reason: list.some(i => i.folder) ? 'Folders can\'t be copied yet' : undefined,
501
+ onSelect: () => sendTo('copy', list) }] : []),
502
+ ...(props.provider.transfer || props.provider.move ? [{ label: 'Move to…', icon: 'folder-share', disabled: !canSend(list),
503
+ reason: list.length === 1 ? reasonFor(list[0]!, 'move') : undefined, onSelect: () => sendTo('move', list) }] : [])
426
504
  ], ...(props.menu?.(list, at) ?? []), [
427
505
  ...(props.provider.remove ? [{ label: 'Delete', icon: 'trash', color: 'error' as const, kbd: 'Del', disabled: !canDelete(list), reason: list.length === 1 ? reasonFor(list[0]!, 'delete') : undefined, onSelect: () => askDelete(list) }] : [])
428
506
  ]]
@@ -565,21 +643,41 @@ const infoShown = ref(true)
565
643
  </div>
566
644
  <div v-if="uploads.length" class="t-explorer-uploads" aria-label="Uploads">
567
645
  <div class="d-flex align-items-center gap-2 mb-1">
568
- <span class="small fw-medium flex-fill">Uploads</span>
646
+ <span class="small fw-medium flex-fill">{{ uploads.every(u => u.kind === 'upload') ? 'Uploads' : 'Uploads, copies and moves' }}</span>
569
647
  <TButton size="sm" variant="ghost" color="neutral" label="Clear finished" @click="clearUploads" />
570
648
  </div>
571
649
  <div v-for="u in uploads" :key="u.id" class="t-explorer-upload">
572
- <TIcon :name="u.state === 'done' ? 'circle-check' : u.state === 'failed' ? 'alert-circle' : u.state === 'canceled' ? 'circle-x' : 'upload'"
650
+ <TIcon :name="u.state === 'done' ? 'circle-check' : u.state === 'failed' ? 'alert-circle' : u.state === 'canceled' ? 'circle-x' : u.kind === 'copy' ? 'copy' : u.kind === 'move' ? 'folder-share' : 'upload'"
573
651
  :class="u.state === 'done' ? 'text-success' : u.state === 'failed' ? 'text-danger' : 'text-secondary'" />
574
652
  <span class="text-truncate small" style="min-width: 6rem; max-width: 16rem">{{ u.name }}</span>
575
- <TProgress v-if="u.state === 'sending' || u.state === 'waiting'" :value="u.state === 'waiting' ? 0 : u.sent" :max="u.size || 1" size="sm" class="flex-fill" :label="`${u.name} sent`" />
576
- <span v-else class="small text-secondary flex-fill text-truncate">{{ u.state === 'failed' ? u.error : u.state === 'canceled' ? 'Canceled' : sizeOf(u.size) }}</span>
653
+ <template v-if="u.kind === 'upload'">
654
+ <TProgress v-if="u.state === 'sending' || u.state === 'waiting'" :value="u.state === 'waiting' ? 0 : u.sent" :max="u.size || 1" size="sm" class="flex-fill" :label="`${u.name} sent`" />
655
+ <span v-else class="small text-secondary flex-fill text-truncate">{{ u.state === 'failed' ? u.error : u.state === 'canceled' ? 'Canceled' : sizeOf(u.size) }}</span>
656
+ </template>
657
+ <span v-else class="small text-secondary flex-fill text-truncate">
658
+ <TSpinner v-if="u.state === 'sending'" size="sm" class="me-1" />{{ u.state === 'failed' ? u.error : u.state === 'canceled' ? 'Canceled'
659
+ : `${u.state === 'done' ? (u.kind === 'copy' ? 'Copied' : 'Moved') : u.state === 'waiting' ? 'Waiting' : (u.kind === 'copy' ? 'Copying' : 'Moving')} to ${u.to}` }}
660
+ </span>
577
661
  <TButton v-if="u.state === 'waiting' || u.state === 'sending'" size="sm" variant="ghost" color="neutral" icon="x" :aria-label="`Cancel ${u.name}`" @click="cancel(u)" />
578
662
  </div>
579
663
  </div>
580
664
  </div>
581
665
  </template>
582
666
  </TSplitter>
667
+ <TModal v-model:open="sendOpen" :title="sending?.mode === 'copy' ? 'Copy to…' : 'Move to…'" size="md">
668
+ <p class="small text-secondary">
669
+ {{ sending?.items.length === 1 ? sending.items[0]!.name : `${sending?.items.length} items` }}: choose the folder {{ sending?.mode === 'copy' ? 'for the copy' : 'to move to' }}.
670
+ </p>
671
+ <div class="t-explorer-send">
672
+ <TTree v-model:selected="sendSelected" v-model:expanded="sendExpanded" :nodes="sendNodes" :load="loadFolders" size="sm" :label="`${label}: where to`" />
673
+ </div>
674
+ <p v-if="sendTarget" class="small mt-2 mb-0"><TIcon name="folder" class="text-secondary" /> {{ sendTarget.label }}</p>
675
+ <p v-if="sendProblem && sendTarget" class="small text-danger mb-0">{{ sendProblem }}</p>
676
+ <template #footer>
677
+ <TButton color="neutral" variant="ghost" label="Cancel" @click="sending = null" />
678
+ <TButton :icon="sending?.mode === 'copy' ? 'copy' : 'folder-share'" :label="sending?.mode === 'copy' ? 'Copy here' : 'Move here'" :disabled="!!sendProblem" @click="confirmSend" />
679
+ </template>
680
+ </TModal>
583
681
  <TModal v-model:open="deleteOpen" title="Delete?" size="sm">
584
682
  <p class="mb-0">
585
683
  {{ deleting?.length === 1 ? `Delete ${deleting[0]!.name}?` : `Delete these ${deleting?.length} items?` }}
@@ -619,4 +717,5 @@ const infoShown = ref(true)
619
717
  .t-explorer-info { width: 18rem; flex: none; overflow: auto; border-inline-start: var(--tblr-border-width) solid var(--tblr-border-color); }
620
718
  .t-explorer-uploads { border-top: var(--tblr-border-width) solid var(--tblr-border-color); padding: .5rem .75rem; max-height: 11rem; overflow: auto; }
621
719
  .t-explorer-upload { display: flex; align-items: center; gap: .5rem; padding-block: .125rem; }
720
+ .t-explorer-send { height: 18rem; overflow: auto; border: var(--tblr-border-width) solid var(--tblr-border-color); border-radius: var(--tblr-border-radius); padding: .375rem; }
622
721
  </style>
@@ -0,0 +1,229 @@
1
+ <script setup lang="ts">
2
+ // One file, shown in its box: images, audio and video by the browser; PDFs by TPdfViewer; Word by
3
+ // docx-preview; Excel by ExcelJS, a sheet at a time; Markdown by markdown-it (no HTML from the
4
+ // file); CSV as a table; text and code as text. Each library loads the first time it's needed. A
5
+ // file with no way to show it, or larger than its kind reads into the page, offers its download.
6
+ // TFileViewer puts it in a frame with a toolbar; use this alone to show a file inside a page.
7
+ import { computed, nextTick, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
8
+ import TCodeBlock from './TCodeBlock.vue'
9
+ import TIcon from './TIcon.vue'
10
+ import TPdfViewer from './TPdfViewer.vue'
11
+ import TSpinner from './TSpinner.vue'
12
+ import {
13
+ codeLanguageOf, loadDocxPreview, loadExcelJs, loadMarkdown, parseCsv, readFile, sizeText, viewerColumns, viewerIcon, viewerKind,
14
+ sheetCellText, viewerLimits, viewerRows, type ViewerCell, type ViewerFile, type ViewerSheet
15
+ } from '../plugins/viewers'
16
+
17
+ const props = withDefaults(defineProps<{ file: ViewerFile; height?: number | string }>(), { height: '100%' })
18
+ const emit = defineEmits<{ load: []; error: [message: string] }>()
19
+
20
+ const kind = computed(() => viewerKind(props.file))
21
+ const limit = computed(() => viewerLimits[kind.value])
22
+ const tooLarge = computed(() => limit.value != null && props.file.size != null && props.file.size > limit.value)
23
+ const cssHeight = computed(() => (typeof props.height === 'number' ? `${props.height}px` : props.height))
24
+ const downloadHref = computed(() => (props.file.download === false ? null : props.file.download ?? props.file.src))
25
+
26
+ const loading = ref(false)
27
+ const problem = ref('')
28
+ const text = ref('')
29
+ const html = ref('')
30
+ const table = shallowRef<{ rows: string[][]; more: boolean } | null>(null)
31
+ const sheets = shallowRef<ViewerSheet[]>([])
32
+ const sheet = ref(0)
33
+ const docx = ref<HTMLElement>()
34
+ const docxStyles = ref<HTMLElement>()
35
+ const docxBox = ref<HTMLElement>()
36
+ // A Word page is drawn at its own width; in a narrower box it's zoomed to fit.
37
+ const docxZoom = ref(1)
38
+ function fitDocx() {
39
+ const page = docx.value?.querySelector<HTMLElement>('section.t-docx')
40
+ const box = docxBox.value
41
+ if (!page || !box || !box.clientWidth) return
42
+ docxZoom.value = Math.min(1, (box.clientWidth - 24) / page.offsetWidth)
43
+ }
44
+ const resized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fitDocx)
45
+ watch(docxBox, (box, old) => { if (old) resized?.unobserve(old); if (box) resized?.observe(box) })
46
+ onBeforeUnmount(() => resized?.disconnect())
47
+ const tooLargeRead = ref(false)
48
+
49
+ // Each file is read once; a newer file (or a close) drops an older read's result.
50
+ let reading = 0
51
+ async function show() {
52
+ const at = ++reading
53
+ problem.value = ''
54
+ text.value = ''
55
+ html.value = ''
56
+ table.value = null
57
+ sheets.value = []
58
+ sheet.value = 0
59
+ tooLargeRead.value = false
60
+ if (docx.value) docx.value.innerHTML = ''
61
+ if (docxStyles.value) docxStyles.value.innerHTML = ''
62
+ if (['image', 'video', 'audio', 'pdf', 'none'].includes(kind.value) || tooLarge.value) return
63
+ loading.value = true
64
+ try {
65
+ const blob = await readFile(props.file)
66
+ if (at !== reading) return
67
+ if (limit.value != null && blob.size > limit.value) { tooLargeRead.value = true; return }
68
+ switch (kind.value) {
69
+ case 'text': text.value = await blob.text(); break
70
+ case 'markdown': html.value = (await loadMarkdown()).render(await blob.text()); break
71
+ case 'csv': table.value = parseCsv(await blob.text(), props.file.name); break
72
+ case 'xlsx': sheets.value = await readSheets(await blob.arrayBuffer()); break
73
+ case 'docx': {
74
+ const { renderAsync } = await loadDocxPreview()
75
+ if (at !== reading) return
76
+ loading.value = false
77
+ await nextTick()
78
+ await renderAsync(blob, docx.value!, docxStyles.value!, { className: 't-docx', inWrapper: true, ignoreLastRenderedPageBreak: true, useBase64URL: true })
79
+ fitDocx()
80
+ break
81
+ }
82
+ }
83
+ if (at === reading) emit('load')
84
+ } catch (e) {
85
+ if (at !== reading) return
86
+ problem.value = e instanceof Error && /access|found/.test(e.message) ? e.message : `${props.file.name} couldn't be shown.`
87
+ emit('error', e instanceof Error ? e.message : problem.value)
88
+ } finally {
89
+ if (at === reading) loading.value = false
90
+ }
91
+ }
92
+ watch(() => props.file, show, { immediate: true })
93
+
94
+ async function readSheets(buffer: ArrayBuffer): Promise<ViewerSheet[]> {
95
+ const ExcelJS = await loadExcelJs()
96
+ const book = new ExcelJS.Workbook()
97
+ await book.xlsx.load(buffer)
98
+ return book.worksheets.filter(s => s.state !== 'hidden' && s.state !== 'veryHidden').map(s => {
99
+ const columns = Math.min(s.columnCount, viewerColumns)
100
+ const rows: ViewerCell[][] = []
101
+ const last = Math.min(s.rowCount, viewerRows)
102
+ for (let r = 1; r <= last; r++) {
103
+ const row = s.getRow(r)
104
+ rows.push(Array.from({ length: columns }, (_, c) => {
105
+ const cell = row.getCell(c + 1)
106
+ return sheetCellText(cell.value, cell.numFmt)
107
+ }))
108
+ }
109
+ return { name: s.name, rows, more: s.rowCount > viewerRows || s.columnCount > viewerColumns }
110
+ })
111
+ }
112
+ /** A sheet's column letters: A … Z, AA …. */
113
+ function columnName(index: number) {
114
+ let name = ''
115
+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) name = String.fromCharCode(65 + ((n - 1) % 26)) + name
116
+ return name
117
+ }
118
+
119
+ const shownSheet = computed(() => sheets.value[sheet.value])
120
+ const mediaFailed = () => { problem.value = `${props.file.name} couldn't be played here.`; emit('error', problem.value) }
121
+ const imageFailed = () => { problem.value = `${props.file.name} couldn't be shown.`; emit('error', problem.value) }
122
+ </script>
123
+
124
+ <template>
125
+ <div class="t-file-view" :data-kind="kind" :style="{ height: cssHeight }">
126
+ <!-- Nothing to show it with, too large, or failed: the download. -->
127
+ <div v-if="kind === 'none' || tooLarge || tooLargeRead || problem" class="t-file-view-card">
128
+ <div class="t-file-view-card-body">
129
+ <TIcon :name="problem ? 'alert-triangle' : viewerIcon(kind)" class="t-file-view-card-icon" />
130
+ <div class="fw-medium text-break">{{ file.name }}</div>
131
+ <div class="text-secondary small">
132
+ <template v-if="problem">{{ problem }}</template>
133
+ <template v-else-if="tooLarge || tooLargeRead">It's too large to show here{{ file.size != null ? ` (${sizeText(file.size)})` : '' }}.</template>
134
+ <template v-else>There's no preview for this kind of file{{ file.size != null ? ` (${sizeText(file.size)})` : '' }}.</template>
135
+ </div>
136
+ <a v-if="downloadHref" :href="downloadHref" :download="file.name" class="btn btn-primary mt-2"><TIcon name="download" class="me-2" />Download</a>
137
+ </div>
138
+ </div>
139
+
140
+ <div v-else-if="loading" class="t-file-view-loading"><TSpinner label="Loading the file" /></div>
141
+
142
+ <div v-else-if="kind === 'image'" class="t-file-view-image">
143
+ <img :src="file.src" :alt="file.name" @load="emit('load')" @error="imageFailed">
144
+ </div>
145
+
146
+ <div v-else-if="kind === 'video'" class="t-file-view-media">
147
+ <video :src="file.src" controls preload="metadata" :aria-label="file.name" @loadedmetadata="emit('load')" @error="mediaFailed" />
148
+ </div>
149
+
150
+ <div v-else-if="kind === 'audio'" class="t-file-view-media">
151
+ <div class="t-file-view-audio">
152
+ <TIcon name="music" class="t-file-view-card-icon" />
153
+ <div class="fw-medium text-break mb-2">{{ file.name }}</div>
154
+ <audio :src="file.src" controls preload="metadata" :aria-label="file.name" @loadedmetadata="emit('load')" @error="mediaFailed" />
155
+ </div>
156
+ </div>
157
+
158
+ <TPdfViewer v-else-if="kind === 'pdf'" :src="file.src" :file-name="file.name" :download="false" height="100%" :label="file.name"
159
+ class="t-file-view-pdf" @load="emit('load')" @error="m => emit('error', m)" />
160
+
161
+ <div v-else-if="kind === 'text'" class="t-file-view-scroll">
162
+ <TCodeBlock :code="text" :language="codeLanguageOf(file.name)" :label="file.name" :wrap="false" class="t-file-view-code" />
163
+ </div>
164
+
165
+ <div v-else-if="kind === 'markdown'" class="t-file-view-scroll">
166
+ <!-- markdown-it, with the file's own HTML turned off. -->
167
+ <!-- eslint-disable-next-line vue/no-v-html -->
168
+ <article class="markdown t-file-view-markdown" v-html="html" />
169
+ </div>
170
+
171
+ <div v-else-if="kind === 'csv' && table" class="t-file-view-scroll">
172
+ <table class="table table-sm table-bordered table-striped t-file-view-table mb-0">
173
+ <thead v-if="table.rows.length"><tr><th v-for="(cell, c) in table.rows[0]" :key="c">{{ cell }}</th></tr></thead>
174
+ <tbody><tr v-for="(row, r) in table.rows.slice(1)" :key="r"><td v-for="(cell, c) in row" :key="c">{{ cell }}</td></tr></tbody>
175
+ </table>
176
+ <div v-if="table.more" class="t-file-view-more">The first {{ table.rows.length.toLocaleString() }} rows are shown. Download it for the rest.</div>
177
+ </div>
178
+
179
+ <div v-else-if="kind === 'xlsx'" class="t-file-view-sheets">
180
+ <div class="t-file-view-scroll">
181
+ <table v-if="shownSheet" class="table table-sm table-bordered t-file-view-table t-file-view-grid mb-0">
182
+ <thead><tr><th class="t-file-view-corner" /><th v-for="(_, c) in shownSheet.rows[0] ?? []" :key="c">{{ columnName(c) }}</th></tr></thead>
183
+ <tbody><tr v-for="(row, r) in shownSheet.rows" :key="r"><th scope="row">{{ r + 1 }}</th><td v-for="(cell, c) in row" :key="c" :class="{ 'text-end': cell.number }">{{ cell.text }}</td></tr></tbody>
184
+ </table>
185
+ <div v-if="shownSheet?.more" class="t-file-view-more">Only the first {{ viewerRows.toLocaleString() }} rows and {{ viewerColumns }} columns are shown. Download it for the rest.</div>
186
+ <div v-if="!sheets.length" class="t-file-view-more">This workbook has no sheets to show.</div>
187
+ </div>
188
+ <div v-if="sheets.length > 1" class="t-file-view-tabs" role="tablist" aria-label="Sheets">
189
+ <button v-for="(s, i) in sheets" :key="s.name" type="button" role="tab" :aria-selected="i === sheet" :class="['t-file-view-tab', { active: i === sheet }]"
190
+ @click="sheet = i">{{ s.name }}</button>
191
+ </div>
192
+ </div>
193
+
194
+ <div v-show="kind === 'docx' && !loading && !problem" ref="docxBox" class="t-file-view-scroll t-file-view-docx">
195
+ <div ref="docxStyles" />
196
+ <div ref="docx" :style="docxZoom < 1 ? { zoom: docxZoom } : undefined" />
197
+ </div>
198
+ </div>
199
+ </template>
200
+
201
+ <style scoped>
202
+ .t-file-view { position: relative; display: flex; flex-direction: column; min-height: 12rem; overflow: hidden; background: var(--tblr-bg-surface-secondary); }
203
+ .t-file-view > * { flex: 1 1 auto; min-height: 0; }
204
+ .t-file-view-card, .t-file-view-loading, .t-file-view-media { display: flex; align-items: center; justify-content: center; padding: 1.5rem; }
205
+ .t-file-view-card-body, .t-file-view-audio { display: flex; flex-direction: column; align-items: center; gap: 0.25rem; max-width: 28rem; text-align: center; }
206
+ .t-file-view-card-icon { font-size: 3rem; color: var(--tblr-secondary); margin-bottom: 0.5rem; }
207
+ .t-file-view-image { display: flex; align-items: center; justify-content: center; padding: 1rem; overflow: auto; }
208
+ .t-file-view-image img { max-width: 100%; max-height: 100%; object-fit: contain; background: repeating-conic-gradient(rgba(127, 127, 127, 0.12) 0 25%, transparent 0 50%) 0 0 / 16px 16px; }
209
+ .t-file-view-media video { max-width: 100%; max-height: 100%; background: #000; }
210
+ .t-file-view-audio audio { width: min(28rem, 80vw); }
211
+ .t-file-view-scroll { overflow: auto; overscroll-behavior: contain; }
212
+ .t-file-view-code { min-height: 100%; border-radius: 0; }
213
+ .t-file-view-markdown { max-width: 52rem; margin: 0 auto; padding: 2rem 1.5rem; background: var(--tblr-bg-surface); min-height: 100%; }
214
+ .t-file-view-table { background: var(--tblr-bg-surface); width: max-content; min-width: 100%; font-size: 0.8125rem; }
215
+ .t-file-view-table th, .t-file-view-table td { white-space: pre; max-width: 32rem; overflow: hidden; text-overflow: ellipsis; }
216
+ .t-file-view-table thead th { position: sticky; top: 0; z-index: 1; background: var(--tblr-bg-surface-tertiary); }
217
+ .t-file-view-grid tbody th { position: sticky; left: 0; background: var(--tblr-bg-surface-tertiary); color: var(--tblr-secondary); font-weight: 400; text-align: right; }
218
+ .t-file-view-grid thead th { color: var(--tblr-secondary); font-weight: 400; text-align: center; text-transform: none; }
219
+ .t-file-view-corner { left: 0; z-index: 2 !important; }
220
+ .t-file-view-more { padding: 0.75rem 1rem; color: var(--tblr-secondary); font-size: 0.875rem; }
221
+ .t-file-view-sheets { display: flex; flex-direction: column; }
222
+ .t-file-view-sheets > .t-file-view-scroll { flex: 1 1 auto; min-height: 0; }
223
+ .t-file-view-tabs { display: flex; gap: 0.125rem; overflow-x: auto; padding: 0 0.5rem; border-top: 1px solid var(--tblr-border-color); background: var(--tblr-bg-surface); flex: none; }
224
+ .t-file-view-tab { border: 0; background: none; padding: 0.375rem 0.75rem; font-size: 0.8125rem; color: var(--tblr-secondary); border-top: 2px solid transparent; white-space: nowrap; }
225
+ .t-file-view-tab.active { color: var(--tblr-body-color); border-top-color: var(--tblr-primary); }
226
+ .t-file-view-pdf { flex: 1 1 auto; border: 0; border-radius: 0; box-shadow: none; }
227
+ .t-file-view-docx :deep(.t-docx-wrapper) { background: transparent; padding: 1.5rem 0.75rem; align-items: safe center; }
228
+ .t-file-view-docx :deep(.t-docx-wrapper > section.t-docx) { box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15); margin-bottom: 1.5rem; }
229
+ </style>
@@ -0,0 +1,140 @@
1
+ <script setup lang="ts">
2
+ // Files shown one at a time (TFileView) under a toolbar: the file's name and size, previous and
3
+ // next with a counter (and the arrow keys), Download, Share when `share` is on (it emits `share`;
4
+ // the host shows its own dialog), any `actions`, and close (the button or Escape). v-model is the
5
+ // one shown: its index in `files`, null when closed. Over the whole window by default, with focus
6
+ // moved into it and back after; `inline` shows it in its box instead, always open, without close.
7
+ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
8
+ import TFileView from './TFileView.vue'
9
+ import TIcon from './TIcon.vue'
10
+ import { sizeText, viewerIcon, viewerKind, type ViewerFile } from '../plugins/viewers'
11
+
12
+ const props = withDefaults(defineProps<{
13
+ files: ViewerFile[]
14
+ inline?: boolean
15
+ share?: boolean
16
+ loop?: boolean
17
+ // The inline viewer's height.
18
+ height?: number | string
19
+ }>(), { loop: false, height: 640 })
20
+ const index = defineModel<number | null>({ default: null })
21
+ const emit = defineEmits<{ share: [file: ViewerFile]; close: []; error: [file: ViewerFile, message: string] }>()
22
+
23
+ const at = computed(() => (props.inline ? Math.min(Math.max(index.value ?? 0, 0), props.files.length - 1) : index.value))
24
+ const open = computed(() => at.value != null && at.value >= 0 && at.value < props.files.length)
25
+ const file = computed(() => (open.value ? props.files[at.value!]! : null))
26
+ const many = computed(() => props.files.length > 1)
27
+ const canBack = computed(() => many.value && (props.loop || (at.value ?? 0) > 0))
28
+ const canOn = computed(() => many.value && (props.loop || (at.value ?? 0) < props.files.length - 1))
29
+ const downloadHref = computed(() => (!file.value || file.value.download === false ? null : file.value.download ?? file.value.src))
30
+ const cssHeight = computed(() => (typeof props.height === 'number' ? `${props.height}px` : props.height))
31
+
32
+ function step(by: 1 | -1) {
33
+ if (at.value == null || !many.value) return
34
+ const next = at.value + by
35
+ index.value = props.loop ? (next + props.files.length) % props.files.length : Math.min(Math.max(next, 0), props.files.length - 1)
36
+ }
37
+ function close() {
38
+ if (props.inline) return
39
+ index.value = null
40
+ emit('close')
41
+ }
42
+
43
+ /** Keys that belong to what's in the file (a page number, a player) are left to it. */
44
+ function typing(target: EventTarget | null) {
45
+ return target instanceof HTMLElement && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'VIDEO', 'AUDIO'].includes(target.tagName))
46
+ }
47
+ function key(event: KeyboardEvent) {
48
+ if (!open.value || event.altKey || event.ctrlKey || event.metaKey) return
49
+ if (event.key === 'Escape' && !props.inline) close()
50
+ else if (event.key === 'ArrowRight' && !typing(event.target) && canOn.value) step(1)
51
+ else if (event.key === 'ArrowLeft' && !typing(event.target) && canBack.value) step(-1)
52
+ else return
53
+ event.preventDefault()
54
+ }
55
+
56
+ const dialog = ref<HTMLElement>()
57
+ let before: Element | null = null
58
+ let overflow = ''
59
+ watch(() => open.value && !props.inline, async now => {
60
+ if (now) {
61
+ before = document.activeElement
62
+ overflow = document.body.style.overflow
63
+ document.body.style.overflow = 'hidden'
64
+ document.addEventListener('keydown', key)
65
+ await nextTick()
66
+ dialog.value?.focus()
67
+ } else {
68
+ document.removeEventListener('keydown', key)
69
+ document.body.style.overflow = overflow
70
+ if (before instanceof HTMLElement) before.focus()
71
+ before = null
72
+ }
73
+ }, { immediate: true })
74
+ onBeforeUnmount(() => {
75
+ document.removeEventListener('keydown', key)
76
+ if (before) document.body.style.overflow = overflow
77
+ })
78
+ </script>
79
+
80
+ <template>
81
+ <Teleport to="body" :disabled="inline">
82
+ <div v-if="open && file" ref="dialog" :class="['t-file-viewer', { 't-file-viewer-inline card': inline }]" :role="inline ? 'region' : 'dialog'"
83
+ :aria-modal="inline ? undefined : 'true'" :aria-label="file.name" tabindex="-1" :style="inline ? { height: cssHeight } : undefined"
84
+ @keydown="inline ? key($event) : undefined">
85
+ <div class="t-file-viewer-bar">
86
+ <TIcon :name="viewerIcon(viewerKind(file))" class="t-file-viewer-icon" />
87
+ <div class="t-file-viewer-title">
88
+ <div class="t-file-viewer-name" :title="file.name">{{ file.name }}</div>
89
+ <div v-if="file.size != null || many" class="t-file-viewer-meta">
90
+ <span v-if="file.size != null">{{ sizeText(file.size) }}</span>
91
+ <span v-if="many" class="t-file-viewer-count">{{ at! + 1 }} of {{ files.length }}</span>
92
+ </div>
93
+ </div>
94
+ <div class="t-file-viewer-actions">
95
+ <template v-if="many">
96
+ <button type="button" class="btn btn-icon btn-ghost-secondary" :disabled="!canBack" aria-label="Previous file" title="Previous (←)" @click="step(-1)">
97
+ <TIcon name="chevron-left" />
98
+ </button>
99
+ <button type="button" class="btn btn-icon btn-ghost-secondary" :disabled="!canOn" aria-label="Next file" title="Next (→)" @click="step(1)">
100
+ <TIcon name="chevron-right" />
101
+ </button>
102
+ <span class="t-file-viewer-divider" />
103
+ </template>
104
+ <slot name="actions" :file="file" />
105
+ <button v-if="share" type="button" class="btn btn-ghost-secondary" @click="emit('share', file)"><TIcon name="share" class="me-1" />Share</button>
106
+ <a v-if="downloadHref" :href="downloadHref" :download="file.name" class="btn btn-ghost-secondary"><TIcon name="download" class="me-1" />Download</a>
107
+ <button v-if="!inline" type="button" class="btn btn-icon btn-ghost-secondary" aria-label="Close" title="Close (Esc)" @click="close">
108
+ <TIcon name="x" />
109
+ </button>
110
+ </div>
111
+ </div>
112
+ <TFileView :key="file.id ?? `${at}:${file.src}`" :file="file" class="t-file-viewer-body" @error="m => emit('error', file!, m)" />
113
+ </div>
114
+ </Teleport>
115
+ </template>
116
+
117
+ <style scoped>
118
+ .t-file-viewer {
119
+ position: fixed; inset: 0; z-index: 2000; display: flex; flex-direction: column; background: var(--tblr-bg-surface-secondary);
120
+ outline: none; animation: t-file-viewer-in 0.12s ease-out;
121
+ }
122
+ .t-file-viewer-inline { position: relative; inset: auto; z-index: auto; overflow: hidden; animation: none; }
123
+ @keyframes t-file-viewer-in { from { opacity: 0; } }
124
+ .t-file-viewer-bar {
125
+ display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0.75rem 0.5rem 1rem; flex: none;
126
+ background: var(--tblr-bg-surface); border-bottom: 1px solid var(--tblr-border-color);
127
+ }
128
+ .t-file-viewer-icon { font-size: 1.25rem; color: var(--tblr-secondary); flex: none; }
129
+ .t-file-viewer-title { min-width: 0; flex: 1 1 auto; }
130
+ .t-file-viewer-name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
131
+ .t-file-viewer-meta { display: flex; gap: 0.75rem; color: var(--tblr-secondary); font-size: 0.8125rem; }
132
+ .t-file-viewer-count { font-variant-numeric: tabular-nums; }
133
+ .t-file-viewer-actions { display: flex; align-items: center; gap: 0.25rem; flex: none; }
134
+ .t-file-viewer-divider { width: 1px; align-self: stretch; margin: 0.25rem 0.25rem; background: var(--tblr-border-color); }
135
+ .t-file-viewer-body { flex: 1 1 auto; height: auto !important; }
136
+ @media (max-width: 576px) {
137
+ .t-file-viewer-actions .btn:not(.btn-icon) { font-size: 0; padding-inline: 0.5rem; }
138
+ .t-file-viewer-actions .btn:not(.btn-icon) :deep(.ti) { font-size: 1.25rem; margin: 0 !important; }
139
+ }
140
+ </style>
@@ -7,6 +7,8 @@ import TChart from '../components/TChart.vue'
7
7
  import TColorPicker from '../components/TColorPicker.vue'
8
8
  import TDatePicker from '../components/TDatePicker.vue'
9
9
  import TDropzone from '../components/TDropzone.vue'
10
+ import TFileView from '../components/TFileView.vue'
11
+ import TFileViewer from '../components/TFileViewer.vue'
10
12
  import TInputMask from '../components/TInputMask.vue'
11
13
  import TPdfViewer from '../components/TPdfViewer.vue'
12
14
  import TRangeSlider from '../components/TRangeSlider.vue'
@@ -21,6 +23,8 @@ export {
21
23
  TColorPicker,
22
24
  TDatePicker,
23
25
  TDropzone,
26
+ TFileView,
27
+ TFileViewer,
24
28
  TInputMask,
25
29
  TPdfViewer,
26
30
  TRangeSlider,
@@ -32,9 +36,10 @@ export {
32
36
 
33
37
  export type { RichEditorPlugin } from './richEditor'
34
38
  export type { PdfZoom } from '../components/TPdfViewer.vue'
39
+ export { viewerKind, type ViewerFile, type ViewerKind } from './viewers'
35
40
 
36
41
  const components = {
37
- TAdvancedSelect, TChart, TColorPicker, TDatePicker, TDropzone, TInputMask, TPdfViewer, TRangeSlider, TRichEditor,
42
+ TAdvancedSelect, TChart, TColorPicker, TDatePicker, TDropzone, TFileView, TFileViewer, TInputMask, TPdfViewer, TRangeSlider, TRichEditor,
38
43
  TSortable, TSortableTree, TTimeInput
39
44
  }
40
45
 
@@ -51,6 +56,8 @@ declare module 'vue' {
51
56
  TColorPicker: typeof TColorPicker
52
57
  TDatePicker: typeof TDatePicker
53
58
  TDropzone: typeof TDropzone
59
+ TFileView: typeof TFileView
60
+ TFileViewer: typeof TFileViewer
54
61
  TInputMask: typeof TInputMask
55
62
  TPdfViewer: typeof TPdfViewer
56
63
  TRangeSlider: typeof TRangeSlider
@@ -0,0 +1,199 @@
1
+ // What TFileViewer shows a file with, and the libraries it loads the first time a kind is shown:
2
+ // docx-preview (Apache-2.0) for Word, ExcelJS (MIT) for Excel, markdown-it (MIT) for Markdown; PDFs
3
+ // through TPdfViewer (PDF.js); images, audio and video by the browser; text, code and CSV by Gears UI.
4
+ import type { CodeLanguage } from '../codeTokens'
5
+ import { once } from './once'
6
+
7
+ /** A file to view: its name, where its content is, and what's known of it. */
8
+ export interface ViewerFile {
9
+ /** Its own key, when names repeat; the name otherwise. */
10
+ id?: string
11
+ name: string
12
+ /** The content's address: shown by the browser (images, media, PDFs) or read (everything else). */
13
+ src: string
14
+ /** Its media type, when known; the name's extension decides otherwise. */
15
+ type?: string | null
16
+ size?: number | null
17
+ /** Where Download gets it (the content's address by default); false for no Download. */
18
+ download?: string | false
19
+ /** Reads the content, for a source the browser can't just fetch (a header to send, another origin). */
20
+ load?: () => Promise<Blob>
21
+ }
22
+
23
+ export type ViewerKind = 'image' | 'video' | 'audio' | 'pdf' | 'markdown' | 'csv' | 'docx' | 'xlsx' | 'text' | 'none'
24
+
25
+ const extensions: Record<string, ViewerKind> = {
26
+ png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image', svg: 'image', bmp: 'image', avif: 'image', ico: 'image',
27
+ mp4: 'video', webm: 'video', ogv: 'video', m4v: 'video', mov: 'video',
28
+ mp3: 'audio', wav: 'audio', ogg: 'audio', oga: 'audio', m4a: 'audio', aac: 'audio', flac: 'audio', opus: 'audio',
29
+ pdf: 'pdf',
30
+ md: 'markdown', markdown: 'markdown',
31
+ csv: 'csv', tsv: 'csv',
32
+ docx: 'docx',
33
+ xlsx: 'xlsx', xlsm: 'xlsx',
34
+ txt: 'text', log: 'text', json: 'text', jsonl: 'text', ndjson: 'text', yaml: 'text', yml: 'text', xml: 'text', html: 'text', htm: 'text',
35
+ css: 'text', scss: 'text', js: 'text', mjs: 'text', ts: 'text', vue: 'text', cs: 'text', csproj: 'text', sql: 'text', ini: 'text',
36
+ conf: 'text', config: 'text', env: 'text', properties: 'text', toml: 'text', sh: 'text', ps1: 'text', py: 'text', java: 'text',
37
+ go: 'text', rs: 'text', rb: 'text', php: 'text', c: 'text', h: 'text', cpp: 'text', gears: 'text'
38
+ }
39
+
40
+ export function extensionOf(name: string) {
41
+ const dot = name.lastIndexOf('.')
42
+ return dot < 0 ? '' : name.slice(dot + 1).toLowerCase()
43
+ }
44
+
45
+ /** How a file is shown: by its extension, then by its media type. */
46
+ export function viewerKind(file: Pick<ViewerFile, 'name' | 'type'>): ViewerKind {
47
+ const byName = extensions[extensionOf(file.name)]
48
+ if (byName) return byName
49
+ const type = (file.type ?? '').toLowerCase()
50
+ if (type.startsWith('image/')) return 'image'
51
+ if (type.startsWith('video/')) return 'video'
52
+ if (type.startsWith('audio/')) return 'audio'
53
+ if (type === 'application/pdf') return 'pdf'
54
+ if (type === 'text/markdown') return 'markdown'
55
+ if (type === 'text/csv' || type === 'text/tab-separated-values') return 'csv'
56
+ if (type.includes('wordprocessingml')) return 'docx'
57
+ if (type.includes('spreadsheetml')) return 'xlsx'
58
+ if (type.startsWith('text/') || type === 'application/json' || type === 'application/xml' || type.endsWith('+json') || type.endsWith('+xml')) return 'text'
59
+ return 'none'
60
+ }
61
+
62
+ /** The largest file each kind reads into the page; a larger one offers its download instead. */
63
+ export const viewerLimits: Partial<Record<ViewerKind, number>> = {
64
+ text: 2 * 1024 * 1024,
65
+ markdown: 2 * 1024 * 1024,
66
+ csv: 5 * 1024 * 1024,
67
+ docx: 25 * 1024 * 1024,
68
+ xlsx: 15 * 1024 * 1024
69
+ }
70
+
71
+ /** The most rows (and columns) a CSV or a sheet shows. */
72
+ export const viewerRows = 1000
73
+ export const viewerColumns = 100
74
+
75
+ export function codeLanguageOf(name: string): CodeLanguage {
76
+ const ext = extensionOf(name)
77
+ if (ext === 'json' || ext === 'gears') return 'json'
78
+ if (ext === 'yaml' || ext === 'yml') return 'yaml'
79
+ return 'text'
80
+ }
81
+
82
+ export function viewerIcon(kind: ViewerKind) {
83
+ return {
84
+ image: 'photo', video: 'movie', audio: 'music', pdf: 'file-type-pdf', markdown: 'markdown', csv: 'file-spreadsheet',
85
+ docx: 'file-type-docx', xlsx: 'file-spreadsheet', text: 'file-text', none: 'file'
86
+ }[kind]
87
+ }
88
+
89
+ export function sizeText(bytes?: number | null) {
90
+ if (bytes == null) return ''
91
+ const units = ['B', 'KB', 'MB', 'GB', 'TB']
92
+ let value = bytes
93
+ let unit = 0
94
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++ }
95
+ return `${value.toFixed(value < 10 && unit > 0 ? 1 : 0)} ${units[unit]}`
96
+ }
97
+
98
+ /** Reads a file's content: its own `load`, or a fetch of `src` (with the page's cookies). */
99
+ export async function readFile(file: ViewerFile): Promise<Blob> {
100
+ if (file.load) return file.load()
101
+ const response = await fetch(file.src, { credentials: 'include' })
102
+ if (!response.ok) throw new Error(response.status === 404 ? 'The file wasn\'t found.' : response.status === 401 || response.status === 403 ? 'You don\'t have access to this file.' : `The file couldn't be read (${response.status}).`)
103
+ return response.blob()
104
+ }
105
+
106
+ /**
107
+ * CSV (or tab-separated) text as rows of cells: quoted cells may hold the separator, quotes ("")
108
+ * and line breaks. The separator is a tab for .tsv, otherwise whichever of `,` and `;` the first
109
+ * line has more of. Stops after `max` rows; `more` says whether there were more.
110
+ */
111
+ export function parseCsv(text: string, name = '', max = viewerRows): { rows: string[][]; more: boolean } {
112
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)
113
+ const firstLine = text.slice(0, text.indexOf('\n') < 0 ? text.length : text.indexOf('\n'))
114
+ const separator = extensionOf(name) === 'tsv' ? '\t' : (firstLine.split(';').length > firstLine.split(',').length ? ';' : ',')
115
+ const rows: string[][] = []
116
+ let row: string[] = []
117
+ let cell = ''
118
+ let quoted = false
119
+ for (let i = 0; i < text.length; i++) {
120
+ const c = text[i]!
121
+ if (quoted) {
122
+ if (c === '"' && text[i + 1] === '"') { cell += '"'; i++ }
123
+ else if (c === '"') quoted = false
124
+ else cell += c
125
+ } else if (c === '"' && cell === '') quoted = true
126
+ else if (c === separator) { row.push(cell); cell = '' }
127
+ else if (c === '\n' || c === '\r') {
128
+ if (c === '\r' && text[i + 1] === '\n') i++
129
+ row.push(cell); cell = ''
130
+ rows.push(row); row = []
131
+ if (rows.length > max) return { rows: rows.slice(0, max), more: true }
132
+ } else cell += c
133
+ }
134
+ if (cell !== '' || row.length > 0) { row.push(cell); rows.push(row) }
135
+ return { rows: rows.slice(0, max), more: rows.length > max }
136
+ }
137
+
138
+ // ---- The libraries ----
139
+
140
+ export const loadDocxPreview = once(() => import('docx-preview'))
141
+
142
+ export const loadExcelJs = once(async () => {
143
+ const mod = await import('exceljs')
144
+ return ((mod as unknown as { default?: typeof mod }).default ?? mod)
145
+ })
146
+
147
+ export const loadMarkdown = once(async () => {
148
+ const { default: MarkdownIt } = await import('markdown-it')
149
+ // No HTML from the file: it's text to read, not a page to run. Links open in a new tab.
150
+ const md = new MarkdownIt({ html: false, linkify: true, typographer: true })
151
+ const render = md.renderer.rules.link_open ?? ((tokens, i, options, _env, self) => self.renderToken(tokens, i, options))
152
+ md.renderer.rules.link_open = (tokens, i, options, env, self) => {
153
+ tokens[i]!.attrSet('target', '_blank')
154
+ tokens[i]!.attrSet('rel', 'noopener noreferrer')
155
+ return render(tokens, i, options, env, self)
156
+ }
157
+ return md
158
+ })
159
+
160
+ /** A sheet's cells as text (numbers to the right), up to the row and column limits. */
161
+ export interface ViewerCell { text: string; number?: boolean }
162
+ export interface ViewerSheet { name: string; rows: ViewerCell[][]; more: boolean }
163
+
164
+ /**
165
+ * A cell's value as a spreadsheet shows it, for the common number formats: decimals ("0.00"),
166
+ * thousands ("#,##0"), percents, dates and times (kept in UTC, as the file stores them),
167
+ * TRUE/FALSE, a formula's last result, rich text, links and errors. Other formats show the value.
168
+ */
169
+ export function sheetCellText(value: unknown, format?: string): ViewerCell {
170
+ if (value == null) return { text: '' }
171
+ if (value instanceof Date) {
172
+ const f = (format ?? '').toLowerCase()
173
+ const time = /h|:s|am\/pm/.test(f)
174
+ const day = /d|y/.test(f) || !time
175
+ const iso = value.toISOString()
176
+ return { text: [day ? iso.slice(0, 10) : '', time ? iso.slice(11, /:s/.test(f) ? 19 : 16) : ''].filter(Boolean).join(' '), number: true }
177
+ }
178
+ if (typeof value === 'number') return { text: formatNumber(value, format), number: true }
179
+ if (typeof value === 'boolean') return { text: value ? 'TRUE' : 'FALSE' }
180
+ if (typeof value === 'string') return { text: value }
181
+ if (typeof value === 'object') {
182
+ const v = value as { result?: unknown; formula?: string; sharedFormula?: string; richText?: { text: string }[]; text?: unknown; error?: string }
183
+ if ('result' in v || v.formula || v.sharedFormula) return sheetCellText(v.result ?? '', format)
184
+ if (v.richText) return { text: v.richText.map(r => r.text).join('') }
185
+ if (v.error) return { text: v.error }
186
+ if (v.text != null) return sheetCellText(v.text, format)
187
+ }
188
+ return { text: String(value) }
189
+ }
190
+
191
+ function formatNumber(value: number, format?: string) {
192
+ const f = (format ?? '').split(';')[0]!.replace(/"[^"]*"|\[[^\]]*\]|\\./g, '')
193
+ if (!f || f.toLowerCase() === 'general') return String(Math.round(value * 1e10) / 1e10)
194
+ const percent = f.includes('%')
195
+ const decimals = (/\.(0+)/.exec(f)?.[1] ?? '').length
196
+ const grouped = /#,#|0,0/.test(f)
197
+ const text = (percent ? value * 100 : value).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals, useGrouping: grouped })
198
+ return percent ? `${text}%` : text
199
+ }
package/src/types.ts CHANGED
@@ -127,6 +127,10 @@ export interface ExplorerProvider {
127
127
  move?(drive: string, items: ExplorerItem[], folder: string | null): Promise<void>
128
128
  remove?(drive: string, items: ExplorerItem[]): Promise<void>
129
129
  upload?(drive: string, folder: string | null, file: File, progress: (sent: number) => void, signal: AbortSignal): Promise<ExplorerItem>
130
+ /** Copies a file into a folder of any drive (its own too; null for the top): Copy to…. One file a call, queued like uploads. */
131
+ copy?(drive: string, item: ExplorerItem, toDrive: string, toFolder: string | null, signal: AbortSignal): Promise<ExplorerItem>
132
+ /** Moves a file into a folder of another drive (null for its top): Move to…. Within a drive, Move to… uses `move`. */
133
+ transfer?(drive: string, item: ExplorerItem, toDrive: string, toFolder: string | null, signal: AbortSignal): Promise<ExplorerItem>
130
134
  /** Where a file downloads from. */
131
135
  href?(drive: string, item: ExplorerItem): string
132
136
  }