@ternarytech-io/gears-ui 0.2.0 → 0.3.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.
@@ -0,0 +1,203 @@
1
+ <script setup lang="ts" generic="Row extends Record<string, any>">
2
+ // An editable table: TTable with a toolbar (a title, search, and actions), pages, and per-column kinds
3
+ // (text, number, date, yes/no) that decide how cells are written and aligned. `selectable` rows
4
+ // show how many are chosen and the `bulk-actions` slot in the footer, so the table doesn't move.
5
+ // `truncate` cuts a column's long values to one line (the whole value on hover). When `editable`, a
6
+ // column marked `editable` is changed in place: click anywhere in the cell, then Enter (or leave
7
+ // it) to keep the change, Esc to drop it; each change emits `edit` for the caller to save. By
8
+ // default the table searches, sorts and pages
9
+ // the rows it has; `manual` leaves that to the caller (the rows are one page of `total`), who
10
+ // watches v-model:search, v-model:sort and v-model:page.
11
+ import { computed, nextTick, ref, watch } from 'vue'
12
+ import TButton from './TButton.vue'
13
+ import TCard from './TCard.vue'
14
+ import TCheckbox from './TCheckbox.vue'
15
+ import TInput from './TInput.vue'
16
+ import TPagination from './TPagination.vue'
17
+ import TTable from './TTable.vue'
18
+ import type { EditableTableColumn, TableEdit, TableColumn, TableSort } from '../types'
19
+
20
+ const props = withDefaults(defineProps<{
21
+ columns: EditableTableColumn<Row>[]
22
+ rows: Row[]
23
+ rowKey?: string | ((row: Row) => string | number)
24
+ title?: string
25
+ subtitle?: string
26
+ searchable?: boolean
27
+ // Rows per page; 0 shows them all.
28
+ pageSize?: number
29
+ selectable?: boolean
30
+ editable?: boolean
31
+ manual?: boolean
32
+ // The rows there are, for `manual` grids.
33
+ total?: number
34
+ loading?: boolean
35
+ empty?: string
36
+ striped?: boolean
37
+ // Rows can be clicked; each click emits `select`.
38
+ clickable?: boolean
39
+ }>(), { rowKey: 'id', searchable: true, pageSize: 25, empty: 'Nothing to show.' })
40
+
41
+ const emit = defineEmits<{ edit: [edit: TableEdit<Row>]; select: [row: Row] }>()
42
+ const search = defineModel<string>('search', { default: '' })
43
+ const sort = defineModel<TableSort | null>('sort', { default: null })
44
+ const page = defineModel<number>('page', { default: 1 })
45
+ const selected = defineModel<(string | number)[]>('selected', { default: () => [] })
46
+
47
+ const value = (row: Row, column: EditableTableColumn<Row>) => column.value ? column.value(row) : row[column.key]
48
+ const keyOf = (row: Row) => typeof props.rowKey === 'function' ? props.rowKey(row) : row[props.rowKey]
49
+
50
+ const numberFormat = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 })
51
+ const dateFormat = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' })
52
+ const dateTimeFormat = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' })
53
+ /** A cell as text: the column's format, else by its kind. */
54
+ function text(row: Row, column: EditableTableColumn<Row>): string {
55
+ const v = value(row, column)
56
+ if (column.format) return column.format(v, row)
57
+ if (v == null || v === '') return '—'
58
+ switch (column.type) {
59
+ case 'number': return typeof v === 'number' || (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) ? numberFormat.format(Number(v)) : String(v)
60
+ case 'boolean': return v ? 'Yes' : 'No'
61
+ case 'date': {
62
+ const d = v instanceof Date ? v : new Date(String(v))
63
+ if (Number.isNaN(d.getTime())) return String(v)
64
+ // A date alone (2026-11-01) has no time to show.
65
+ return typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) ? dateFormat.format(d) : dateTimeFormat.format(d)
66
+ }
67
+ default: return typeof v === 'boolean' ? (v ? 'Yes' : 'No') : String(v)
68
+ }
69
+ }
70
+
71
+ // TTable's columns: numbers to the right, sortable unless said otherwise.
72
+ const tableColumns = computed<TableColumn<Row>[]>(() => props.columns.map(c => ({
73
+ ...c, align: c.align ?? (c.type === 'number' ? 'end' : undefined), sortable: c.sortable ?? true
74
+ })))
75
+
76
+ // ---- Search, sort and pages (unless manual) ----
77
+ const matching = computed(() => {
78
+ const term = search.value.trim().toLowerCase()
79
+ if (props.manual || !term) return props.rows
80
+ return props.rows.filter(row => props.columns.some(c => text(row, c).toLowerCase().includes(term)))
81
+ })
82
+ const sorted = computed(() => {
83
+ const by = sort.value
84
+ const column = by && props.columns.find(c => c.key === by.key)
85
+ if (props.manual || !by || !column) return matching.value
86
+ const factor = by.direction === 'asc' ? 1 : -1
87
+ return [...matching.value].sort((a, b) => {
88
+ const x = value(a, column) as any
89
+ const y = value(b, column) as any
90
+ if (x == null) return y == null ? 0 : 1
91
+ if (y == null) return -1
92
+ const numeric = column.type === 'number' || (typeof x === 'number' && typeof y === 'number')
93
+ return (numeric ? Number(x) - Number(y) : String(x).localeCompare(String(y), undefined, { numeric: true })) * factor
94
+ })
95
+ })
96
+ const count = computed(() => props.manual ? props.total ?? props.rows.length : sorted.value.length)
97
+ const shown = computed(() => {
98
+ if (props.manual || !props.pageSize) return sorted.value
99
+ const start = (page.value - 1) * props.pageSize
100
+ return sorted.value.slice(start, start + props.pageSize)
101
+ })
102
+ // A new search starts at the first page; a page past the end moves back.
103
+ watch(search, () => { page.value = 1 })
104
+ watch(count, total => {
105
+ const last = Math.max(1, Math.ceil(total / (props.pageSize || total || 1)))
106
+ if (page.value > last) page.value = last
107
+ })
108
+ const range = computed(() => {
109
+ if (!count.value) return ''
110
+ if (!props.pageSize) return `${count.value} row${count.value === 1 ? '' : 's'}`
111
+ const from = (page.value - 1) * props.pageSize + 1
112
+ return `${from}–${Math.min(from + props.pageSize - 1, count.value)} of ${count.value}`
113
+ })
114
+
115
+ // ---- Editing in place ----
116
+ const editing = ref<{ key: string | number; column: string } | null>(null)
117
+ const draft = ref<string | boolean>('')
118
+ const editor = ref<{ $el?: HTMLElement } | null>(null)
119
+ const canEdit = (column: EditableTableColumn<Row>) => !!(props.editable && column.editable)
120
+
121
+ async function startEdit(row: Row, column: EditableTableColumn<Row>) {
122
+ if (!canEdit(column)) return
123
+ const v = value(row, column)
124
+ draft.value = column.type === 'boolean' ? !!v : v == null ? '' : column.type === 'date' ? String(v).slice(0, 10) : String(v)
125
+ editing.value = { key: keyOf(row), column: column.key }
126
+ await nextTick()
127
+ editor.value?.$el?.querySelector?.('input')?.focus()
128
+ }
129
+ const isEditing = (row: Row, column: EditableTableColumn<Row>) => editing.value?.key === keyOf(row) && editing.value?.column === column.key
130
+
131
+ function commit(row: Row, column: EditableTableColumn<Row>) {
132
+ if (!isEditing(row, column)) return
133
+ editing.value = null
134
+ const before = value(row, column)
135
+ const raw = draft.value
136
+ const next = column.type === 'number' ? (raw === '' ? null : Number(raw)) : column.type === 'boolean' ? raw === true : raw === '' ? null : raw
137
+ if (column.type === 'number' && next !== null && !Number.isFinite(next)) return
138
+ if (next === before || (next == null && (before == null || before === ''))) return
139
+ emit('edit', { row, key: column.key, value: next })
140
+ }
141
+ function cancel() { editing.value = null }
142
+
143
+ const inputType = (column: EditableTableColumn<Row>) => column.type === 'number' ? 'number' : column.type === 'date' ? 'date' : 'text'
144
+ </script>
145
+
146
+ <template>
147
+ <TCard flush class="t-editable-table mb-0">
148
+ <template v-if="title || searchable || $slots.actions" #header>
149
+ <div class="d-flex flex-wrap align-items-center gap-2 w-100">
150
+ <div v-if="title" class="me-auto min-w-0">
151
+ <h3 class="card-title text-truncate">{{ title }}</h3>
152
+ <div v-if="subtitle" class="card-subtitle small text-secondary mb-0">{{ subtitle }}</div>
153
+ </div>
154
+ <TInput v-if="searchable" v-model="search" icon="search" size="sm" placeholder="Search…" aria-label="Search the rows"
155
+ :class="['t-editable-table-search', { 'ms-auto': !title }]" />
156
+ <slot name="actions" />
157
+ </div>
158
+ </template>
159
+
160
+ <TTable v-model:sort="sort" v-model:selected="selected" :columns="tableColumns" :rows="shown" :row-key="rowKey" :loading="loading"
161
+ :empty="search && rows.length ? 'No rows match the search.' : empty" card :striped="striped" :selectable="selectable" :clickable="clickable"
162
+ manual-sort :cell-clickable="(row, column) => canEdit(column as EditableTableColumn<Row>) && !isEditing(row, column as EditableTableColumn<Row>)"
163
+ @select="row => emit('select', row)" @cell-click="(row, column) => startEdit(row, column as EditableTableColumn<Row>)">
164
+ <template #cell="{ row, column }">
165
+ <slot :name="`${column.key}-cell`" :row="row" :value="value(row, column as EditableTableColumn<Row>)">
166
+ <div v-if="isEditing(row, column as EditableTableColumn<Row>)" class="t-editable-table-editor" @click.stop>
167
+ <TCheckbox v-if="(column as EditableTableColumn<Row>).type === 'boolean'" ref="editor" v-model="draft as boolean" class="mb-0"
168
+ :label="column.label ?? column.key" @update:model-value="commit(row, column as EditableTableColumn<Row>)" />
169
+ <TInput v-else ref="editor" v-model="draft as string" size="sm" :type="inputType(column as EditableTableColumn<Row>)" :aria-label="column.label ?? column.key"
170
+ @keydown.enter.prevent="commit(row, column as EditableTableColumn<Row>)" @keydown.esc.prevent="cancel"
171
+ @blur="commit(row, column as EditableTableColumn<Row>)" />
172
+ </div>
173
+ <span v-else-if="canEdit(column as EditableTableColumn<Row>)" role="button" tabindex="0" class="t-editable-table-editable"
174
+ :class="{ 'text-truncate d-inline-block align-middle': (column as EditableTableColumn<Row>).truncate }"
175
+ :style="(column as EditableTableColumn<Row>).truncate ? { maxWidth: (column as EditableTableColumn<Row>).truncate } : undefined"
176
+ :title="`${text(row, column as EditableTableColumn<Row>)} (click to edit)`"
177
+ @keydown.enter.prevent="startEdit(row, column as EditableTableColumn<Row>)">
178
+ {{ text(row, column as EditableTableColumn<Row>) }}
179
+ </span>
180
+ <span v-else-if="(column as EditableTableColumn<Row>).truncate" class="text-truncate d-inline-block align-middle"
181
+ :style="{ maxWidth: (column as EditableTableColumn<Row>).truncate }" :title="text(row, column as EditableTableColumn<Row>)">
182
+ {{ text(row, column as EditableTableColumn<Row>) }}
183
+ </span>
184
+ <template v-else>{{ text(row, column as EditableTableColumn<Row>) }}</template>
185
+ </slot>
186
+ </template>
187
+ <template v-if="$slots.empty" #empty><slot name="empty" /></template>
188
+ </TTable>
189
+
190
+ <!-- The selection and pages; with selectable rows it's always there, so choosing rows moves nothing. -->
191
+ <template v-if="selectable || (pageSize && count > 0)" #footer>
192
+ <div class="d-flex flex-wrap align-items-center gap-2 t-editable-table-footer">
193
+ <template v-if="selectable && selected.length">
194
+ <span class="small fw-medium">{{ selected.length }} selected</span>
195
+ <TButton size="xs" color="neutral" variant="ghost" label="Clear" @click="selected = []" />
196
+ <slot name="bulk-actions" :selected="selected" />
197
+ </template>
198
+ <span v-else class="small text-secondary">{{ range || (selectable ? 'Select rows for more actions.' : '') }}</span>
199
+ <TPagination v-if="pageSize && count > pageSize" v-model:page="page" :total="count" :items-per-page="pageSize" size="sm" class="ms-auto" />
200
+ </div>
201
+ </template>
202
+ </TCard>
203
+ </template>
@@ -1,21 +1,21 @@
1
- <script setup lang="ts">
2
- // A theme's corner radius, Tabler's scale from 0 (square corners) to 2 (round), as tiles showing a
3
- // shape drawn with each.
4
- import TRadioGroup from './TRadioGroup.vue'
5
- import { themeRadii } from '../theme'
6
- import type { ThemeRadius } from '../types'
7
-
8
- defineProps<{ disabled?: boolean; legend?: string }>()
9
-
10
- const model = defineModel<ThemeRadius | null | undefined>()
11
- // At 2 the shape is a circle.
12
- const radius = (scale: ThemeRadius) => `calc(1.125rem * ${scale} / 2)`
13
- </script>
14
-
15
- <template>
16
- <TRadioGroup v-model="model" :items="themeRadii" variant="tiles" :disabled="disabled" :legend="legend">
17
- <template #preview="{ item }">
18
- <span class="t-theme-radius" :style="{ borderRadius: radius(item.value as ThemeRadius) }" />
19
- </template>
20
- </TRadioGroup>
21
- </template>
1
+ <script setup lang="ts">
2
+ // A theme's corner radius, from 0 (square corners) to 2.5 (Tabler's extra large), as tiles showing
3
+ // a button-sized shape with each one's base radius.
4
+ import TRadioGroup from './TRadioGroup.vue'
5
+ import { themeRadii, themeRadiusSizes } from '../theme'
6
+ import type { ThemeRadius } from '../types'
7
+
8
+ defineProps<{ disabled?: boolean; legend?: string }>()
9
+
10
+ const model = defineModel<ThemeRadius | null | undefined>()
11
+ // Drawn at its real size, so the tile shows the corner a button or a field gets.
12
+ const radius = (value: ThemeRadius) => themeRadiusSizes[value]
13
+ </script>
14
+
15
+ <template>
16
+ <TRadioGroup v-model="model" :items="themeRadii" variant="tiles" :disabled="disabled" :legend="legend">
17
+ <template #preview="{ item }">
18
+ <span class="t-theme-radius" :style="{ borderRadius: radius(item.value as ThemeRadius) }" />
19
+ </template>
20
+ </TRadioGroup>
21
+ </template>
@@ -0,0 +1,34 @@
1
+ <script setup lang="ts">
2
+ // A tiny chart in a line of text or a stat card: Tabler's sparkline (an inline SVG, no library), as
3
+ // a line, bars, or a circle for one percentage. It takes the text color, so a color names it.
4
+ import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
5
+ import { Sparkline } from '@tabler/core'
6
+ import { toTabler, type Color } from '../types'
7
+
8
+ const props = withDefaults(defineProps<{
9
+ values: number[]
10
+ type?: 'line' | 'bar' | 'circle'
11
+ color?: Color
12
+ width?: number
13
+ height?: number
14
+ // Mark the last, highest or lowest value with a dot.
15
+ spot?: 'none' | 'last' | 'max' | 'min'
16
+ label?: string
17
+ }>(), { type: 'line', color: 'primary', width: 64, height: 24, spot: 'none' })
18
+
19
+ const el = ref<HTMLElement>()
20
+ let sparkline: InstanceType<typeof Sparkline> | null = null
21
+
22
+ onMounted(() => {
23
+ sparkline = new Sparkline(el.value!, {
24
+ type: props.type, values: props.values, width: props.width, height: props.height,
25
+ spot: props.spot, fill: props.type === 'line' ? 'auto' : 'none', animation: 0, label: false
26
+ })
27
+ })
28
+ watch(() => props.values, values => sparkline?.update(values), { deep: true })
29
+ onBeforeUnmount(() => sparkline?.dispose())
30
+ </script>
31
+
32
+ <template>
33
+ <span ref="el" :class="['sparkline', `text-${toTabler(color)}`]" role="img" :aria-label="label ?? `Trend: ${values.join(', ')}`" />
34
+ </template>
@@ -1,9 +1,31 @@
1
1
  <script setup lang="ts">
2
- // A figure on an overview page: label, value, a line under it, and an icon in a tinted square.
2
+ // A figure on an overview page: label, value, a line under it, and an icon in a tinted square. A
3
+ // `trend` (the change, in percent) shows beside the value, green when it's good: up, unless
4
+ // `trendGood` is 'down' (costs, errors). `sparkline` draws the recent values under it.
5
+ import { computed } from 'vue'
3
6
  import TIcon from './TIcon.vue'
7
+ import TSparkline from './TSparkline.vue'
4
8
  import { toTabler, type Color } from '../types'
5
9
 
6
- withDefaults(defineProps<{ label: string; value: string | number; detail?: string; icon: string; color?: Color }>(), { color: 'primary' })
10
+ const props = withDefaults(defineProps<{
11
+ label: string
12
+ value: string | number
13
+ detail?: string
14
+ icon?: string
15
+ color?: Color
16
+ trend?: number | null
17
+ trendLabel?: string
18
+ trendGood?: 'up' | 'down'
19
+ sparkline?: number[]
20
+ sparklineType?: 'line' | 'bar'
21
+ }>(), { color: 'primary', trendGood: 'up', sparklineType: 'line' })
22
+
23
+ const trendText = computed(() => props.trend == null ? '' : `${Math.abs(Math.round(props.trend * 10) / 10)}%`)
24
+ const trendClass = computed(() => {
25
+ if (props.trend == null || props.trend === 0) return 'text-secondary'
26
+ return (props.trend > 0) === (props.trendGood === 'up') ? 'text-success' : 'text-danger'
27
+ })
28
+ const trendIcon = computed(() => !props.trend ? 'minus' : props.trend > 0 ? 'trending-up' : 'trending-down')
7
29
  </script>
8
30
 
9
31
  <template>
@@ -12,15 +34,23 @@ withDefaults(defineProps<{ label: string; value: string | number; detail?: strin
12
34
  <div class="d-flex align-items-start justify-content-between gap-3">
13
35
  <div class="min-w-0">
14
36
  <div class="subheader">{{ label }}</div>
15
- <div class="h1 mb-0 mt-2">{{ value }}</div>
16
- <div v-if="detail || $slots.detail" class="text-secondary small mt-1">
17
- <slot name="detail">{{ detail }}</slot>
37
+ <div class="d-flex align-items-baseline gap-2 mt-2">
38
+ <div class="h1 mb-0">{{ value }}</div>
39
+ <span v-if="trend != null" :class="['d-inline-flex align-items-center gap-1 lh-1 small fw-medium', trendClass]"
40
+ :title="trendLabel">
41
+ {{ trendText }}<TIcon :name="trendIcon" />
42
+ </span>
43
+ </div>
44
+ <div v-if="detail || trendLabel || $slots.detail" class="text-secondary small mt-1">
45
+ <slot name="detail">{{ detail ?? trendLabel }}</slot>
18
46
  </div>
19
47
  </div>
20
- <div :class="['t-stat-icon', `bg-${toTabler(color)}-lt`]">
48
+ <div v-if="icon" :class="['t-stat-icon', `bg-${toTabler(color)}-lt`]">
21
49
  <TIcon :name="icon" />
22
50
  </div>
23
51
  </div>
52
+ <TSparkline v-if="sparkline?.length" :values="sparkline" :type="sparklineType" :color="color" :width="240" :height="36"
53
+ class="t-stat-sparkline mt-3" :label="`${label}: recent values`" />
24
54
  </div>
25
55
  </div>
26
56
  </template>
@@ -1,134 +1,138 @@
1
- <script setup lang="ts" generic="Row extends Record<string, any>">
2
- // A table of rows. Columns name a key, a label and how to align; a `{key}-cell` slot draws a cell
3
- // (it gets the row and value), `{key}-header` a heading, and the `cell` slot any cell without its
4
- // own slot. Sortable columns sort the rows here, unless `manualSort` leaves it to the caller (who
5
- // watches v-model:sort); a `{key}-header` slot gets the column's sort and `toggleSort` to draw its
6
- // own sort button. `selectable` adds a checkbox to each row (Tabler's table-selectable) and one in
7
- // the header for every row; v-model:selected holds the chosen rows' keys. `card` fits it into a
8
- // flush TCard; `sticky` keeps the header in view while the table scrolls in its container.
9
- import { computed, ref, watchEffect } from 'vue'
10
- import TSpinner from './TSpinner.vue'
11
- import type { TableColumn, TableSort } from '../types'
12
-
13
- const props = withDefaults(defineProps<{
14
- columns: TableColumn<Row>[]
15
- rows: Row[]
16
- rowKey?: string | ((row: Row) => string | number)
17
- loading?: boolean
18
- empty?: string
19
- card?: boolean
20
- striped?: boolean
21
- hover?: boolean
22
- // Rows can be clicked; each click emits `select`.
23
- clickable?: boolean
24
- // A checkbox on each row; clicking a row (unless it's `clickable`) checks it too.
25
- selectable?: boolean
26
- manualSort?: boolean
27
- sticky?: boolean
28
- }>(), { rowKey: 'id', empty: 'Nothing to show.' })
29
-
30
- const emit = defineEmits<{ select: [row: Row] }>()
31
- const sort = defineModel<TableSort | null>('sort', { default: null })
32
- const selected = defineModel<(string | number)[]>('selected', { default: () => [] })
33
-
34
- const cell = (row: Row, column: TableColumn<Row>) => column.value ? column.value(row) : row[column.key]
35
- const key = (row: Row, index: number) => typeof props.rowKey === 'function' ? props.rowKey(row) : row[props.rowKey] ?? index
36
- const align = (column: TableColumn<Row>) => column.align === 'end' ? 'text-end' : column.align === 'center' ? 'text-center' : undefined
37
-
38
- const sorted = computed(() => {
39
- const by = sort.value
40
- const column = by && props.columns.find(c => c.key === by.key)
41
- if (!by || !column || props.manualSort) return props.rows
42
- const factor = by.direction === 'asc' ? 1 : -1
43
- return [...props.rows].sort((a, b) => {
44
- const x = cell(a, column) as any
45
- const y = cell(b, column) as any
46
- if (x == null) return y == null ? 0 : 1
47
- if (y == null) return -1
48
- return (typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true })) * factor
49
- })
50
- })
51
-
52
- function sortOf(column: TableColumn<Row>) {
53
- return sort.value?.key === column.key ? sort.value.direction : null
54
- }
55
-
56
- function toggleSort(column: TableColumn<Row>) {
57
- const current = sort.value?.key === column.key ? sort.value.direction : null
58
- sort.value = current === 'asc' ? { key: column.key, direction: 'desc' } : current === 'desc' ? null : { key: column.key, direction: 'asc' }
59
- }
60
-
61
- // ---- Selection ----
62
- const keys = computed(() => sorted.value.map((row, index) => key(row, index)))
63
- const isChecked = (row: Row, index: number) => selected.value.includes(key(row, index))
64
- const allChecked = computed(() => keys.value.length > 0 && keys.value.every(k => selected.value.includes(k)))
65
- const someChecked = computed(() => !allChecked.value && keys.value.some(k => selected.value.includes(k)))
66
- const allBox = ref<HTMLInputElement>()
67
- watchEffect(() => { if (allBox.value) allBox.value.indeterminate = someChecked.value })
68
-
69
- function check(row: Row, index: number) {
70
- const k = key(row, index)
71
- selected.value = selected.value.includes(k) ? selected.value.filter(x => x !== k) : [...selected.value, k]
72
- }
73
- // The header's box checks every row shown, or unchecks them (keeping rows not shown).
74
- function checkAll() {
75
- selected.value = allChecked.value
76
- ? selected.value.filter(k => !keys.value.includes(k))
77
- : [...new Set([...selected.value, ...keys.value])]
78
- }
79
- function clickRow(row: Row, index: number) {
80
- if (props.clickable) emit('select', row)
81
- else if (props.selectable) check(row, index)
82
- }
83
-
84
- const span = computed(() => props.columns.length + (props.selectable ? 1 : 0))
85
-
86
- function format(value: unknown) {
87
- if (value == null || value === '') return '—'
88
- if (typeof value === 'boolean') return value ? 'Yes' : 'No'
89
- return String(value)
90
- }
91
- </script>
92
-
93
- <template>
94
- <div :class="sticky ? 't-table-sticky' : 'table-responsive'">
95
- <table :class="['table table-vcenter mb-0', { 'card-table': card, 'table-striped': striped, 'table-hover': hover || clickable, 'table-selectable': selectable }]">
96
- <thead>
97
- <tr>
98
- <th v-if="selectable" class="w-1">
99
- <input ref="allBox" type="checkbox" class="form-check-input m-0 align-middle" :checked="allChecked" :disabled="!keys.length"
100
- aria-label="Select every row" @change="checkAll">
101
- </th>
102
- <th v-for="column in columns" :key="column.key" :class="align(column)" :style="column.width ? { width: column.width } : undefined"
103
- :aria-sort="sort?.key === column.key ? (sort.direction === 'asc' ? 'ascending' : 'descending') : undefined">
104
- <slot :name="`${column.key}-header`" :column="column" :sort="sortOf(column)" :toggle-sort="() => toggleSort(column)">
105
- <button v-if="column.sortable" type="button" :class="['table-sort', { asc: sort?.key === column.key && sort.direction === 'asc', desc: sort?.key === column.key && sort.direction === 'desc' }]"
106
- @click="toggleSort(column)">{{ column.label ?? column.key }}</button>
107
- <template v-else>{{ column.label ?? column.key }}</template>
108
- </slot>
109
- </th>
110
- </tr>
111
- </thead>
112
- <tbody>
113
- <tr v-if="loading && !rows.length">
114
- <td :colspan="span" class="text-center py-4"><TSpinner size="sm" show-label /></td>
115
- </tr>
116
- <tr v-else-if="!rows.length">
117
- <td :colspan="span" class="text-center text-secondary py-4"><slot name="empty">{{ empty }}</slot></td>
118
- </tr>
119
- <tr v-for="(row, index) in sorted" v-else :key="key(row, index)"
120
- :class="{ 'cursor-pointer': clickable || selectable, 'table-active': selectable && isChecked(row, index) }" @click="clickRow(row, index)">
121
- <td v-if="selectable" @click.stop>
122
- <input type="checkbox" class="form-check-input m-0 align-middle table-selectable-check" :checked="isChecked(row, index)"
123
- aria-label="Select the row" @change="check(row, index)">
124
- </td>
125
- <td v-for="column in columns" :key="column.key" :class="align(column)">
126
- <slot :name="`${column.key}-cell`" :row="row" :value="cell(row, column)">
127
- <slot name="cell" :row="row" :column="column" :value="cell(row, column)">{{ format(cell(row, column)) }}</slot>
128
- </slot>
129
- </td>
130
- </tr>
131
- </tbody>
132
- </table>
133
- </div>
134
- </template>
1
+ <script setup lang="ts" generic="Row extends Record<string, any>">
2
+ // A table of rows. Columns name a key, a label and how to align; a `{key}-cell` slot draws a cell
3
+ // (it gets the row and value), `{key}-header` a heading, and the `cell` slot any cell without its
4
+ // own slot. Sortable columns sort the rows here, unless `manualSort` leaves it to the caller (who
5
+ // watches v-model:sort); a `{key}-header` slot gets the column's sort and `toggleSort` to draw its
6
+ // own sort button. `selectable` adds a checkbox to each row (Tabler's table-selectable) and one in
7
+ // the header for every row; v-model:selected holds the chosen rows' keys. `card` fits it into a
8
+ // flush TCard; `sticky` keeps the header in view while the table scrolls in its container.
9
+ // `cellClickable` names cells that take a click of their own: the whole cell emits `cell-click`,
10
+ // instead of the row's click or check.
11
+ import { computed, ref, watchEffect } from 'vue'
12
+ import TSpinner from './TSpinner.vue'
13
+ import type { TableColumn, TableSort } from '../types'
14
+
15
+ const props = withDefaults(defineProps<{
16
+ columns: TableColumn<Row>[]
17
+ rows: Row[]
18
+ rowKey?: string | ((row: Row) => string | number)
19
+ loading?: boolean
20
+ empty?: string
21
+ card?: boolean
22
+ striped?: boolean
23
+ hover?: boolean
24
+ // Rows can be clicked; each click emits `select`.
25
+ clickable?: boolean
26
+ // A checkbox on each row; clicking a row (unless it's `clickable`) checks it too.
27
+ selectable?: boolean
28
+ manualSort?: boolean
29
+ sticky?: boolean
30
+ cellClickable?: (row: Row, column: TableColumn<Row>) => boolean
31
+ }>(), { rowKey: 'id', empty: 'Nothing to show.' })
32
+
33
+ const emit = defineEmits<{ select: [row: Row]; 'cell-click': [row: Row, column: TableColumn<Row>] }>()
34
+ const sort = defineModel<TableSort | null>('sort', { default: null })
35
+ const selected = defineModel<(string | number)[]>('selected', { default: () => [] })
36
+
37
+ const cell = (row: Row, column: TableColumn<Row>) => column.value ? column.value(row) : row[column.key]
38
+ const key = (row: Row, index: number) => typeof props.rowKey === 'function' ? props.rowKey(row) : row[props.rowKey] ?? index
39
+ const align = (column: TableColumn<Row>) => column.align === 'end' ? 'text-end' : column.align === 'center' ? 'text-center' : undefined
40
+
41
+ const sorted = computed(() => {
42
+ const by = sort.value
43
+ const column = by && props.columns.find(c => c.key === by.key)
44
+ if (!by || !column || props.manualSort) return props.rows
45
+ const factor = by.direction === 'asc' ? 1 : -1
46
+ return [...props.rows].sort((a, b) => {
47
+ const x = cell(a, column) as any
48
+ const y = cell(b, column) as any
49
+ if (x == null) return y == null ? 0 : 1
50
+ if (y == null) return -1
51
+ return (typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true })) * factor
52
+ })
53
+ })
54
+
55
+ function sortOf(column: TableColumn<Row>) {
56
+ return sort.value?.key === column.key ? sort.value.direction : null
57
+ }
58
+
59
+ function toggleSort(column: TableColumn<Row>) {
60
+ const current = sort.value?.key === column.key ? sort.value.direction : null
61
+ sort.value = current === 'asc' ? { key: column.key, direction: 'desc' } : current === 'desc' ? null : { key: column.key, direction: 'asc' }
62
+ }
63
+
64
+ // ---- Selection ----
65
+ const keys = computed(() => sorted.value.map((row, index) => key(row, index)))
66
+ const isChecked = (row: Row, index: number) => selected.value.includes(key(row, index))
67
+ const allChecked = computed(() => keys.value.length > 0 && keys.value.every(k => selected.value.includes(k)))
68
+ const someChecked = computed(() => !allChecked.value && keys.value.some(k => selected.value.includes(k)))
69
+ const allBox = ref<HTMLInputElement>()
70
+ watchEffect(() => { if (allBox.value) allBox.value.indeterminate = someChecked.value })
71
+
72
+ function check(row: Row, index: number) {
73
+ const k = key(row, index)
74
+ selected.value = selected.value.includes(k) ? selected.value.filter(x => x !== k) : [...selected.value, k]
75
+ }
76
+ // The header's box checks every row shown, or unchecks them (keeping rows not shown).
77
+ function checkAll() {
78
+ selected.value = allChecked.value
79
+ ? selected.value.filter(k => !keys.value.includes(k))
80
+ : [...new Set([...selected.value, ...keys.value])]
81
+ }
82
+ function clickRow(row: Row, index: number) {
83
+ if (props.clickable) emit('select', row)
84
+ else if (props.selectable) check(row, index)
85
+ }
86
+
87
+ const span = computed(() => props.columns.length + (props.selectable ? 1 : 0))
88
+
89
+ function format(value: unknown) {
90
+ if (value == null || value === '') return '—'
91
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No'
92
+ return String(value)
93
+ }
94
+ </script>
95
+
96
+ <template>
97
+ <div :class="sticky ? 't-table-sticky' : 'table-responsive'">
98
+ <table :class="['table table-vcenter mb-0', { 'card-table': card, 'table-striped': striped, 'table-hover': hover || clickable, 'table-selectable': selectable }]">
99
+ <thead>
100
+ <tr>
101
+ <th v-if="selectable" class="w-1">
102
+ <input ref="allBox" type="checkbox" class="form-check-input m-0 align-middle" :checked="allChecked" :disabled="!keys.length"
103
+ aria-label="Select every row" @change="checkAll">
104
+ </th>
105
+ <th v-for="column in columns" :key="column.key" :class="align(column)" :style="column.width ? { width: column.width } : undefined"
106
+ :aria-sort="sort?.key === column.key ? (sort.direction === 'asc' ? 'ascending' : 'descending') : undefined">
107
+ <slot :name="`${column.key}-header`" :column="column" :sort="sortOf(column)" :toggle-sort="() => toggleSort(column)">
108
+ <button v-if="column.sortable" type="button" :class="['table-sort', { asc: sort?.key === column.key && sort.direction === 'asc', desc: sort?.key === column.key && sort.direction === 'desc' }]"
109
+ @click="toggleSort(column)">{{ column.label ?? column.key }}</button>
110
+ <template v-else>{{ column.label ?? column.key }}</template>
111
+ </slot>
112
+ </th>
113
+ </tr>
114
+ </thead>
115
+ <tbody>
116
+ <tr v-if="loading && !rows.length">
117
+ <td :colspan="span" class="text-center py-4"><TSpinner size="sm" show-label /></td>
118
+ </tr>
119
+ <tr v-else-if="!rows.length">
120
+ <td :colspan="span" class="text-center text-secondary py-4"><slot name="empty">{{ empty }}</slot></td>
121
+ </tr>
122
+ <tr v-for="(row, index) in sorted" v-else :key="key(row, index)"
123
+ :class="{ 'cursor-pointer': clickable || selectable, 'table-active': selectable && isChecked(row, index) }" @click="clickRow(row, index)">
124
+ <td v-if="selectable" @click.stop>
125
+ <input type="checkbox" class="form-check-input m-0 align-middle table-selectable-check" :checked="isChecked(row, index)"
126
+ aria-label="Select the row" @change="check(row, index)">
127
+ </td>
128
+ <td v-for="column in columns" :key="column.key" :class="[align(column), { 't-cell-clickable': cellClickable?.(row, column) }]"
129
+ @click="event => { if (cellClickable?.(row, column)) { event.stopPropagation(); emit('cell-click', row, column) } }">
130
+ <slot :name="`${column.key}-cell`" :row="row" :value="cell(row, column)">
131
+ <slot name="cell" :row="row" :column="column" :value="cell(row, column)">{{ format(cell(row, column)) }}</slot>
132
+ </slot>
133
+ </td>
134
+ </tr>
135
+ </tbody>
136
+ </table>
137
+ </div>
138
+ </template>