@ternarytech-io/gears-ui 0.2.1 → 0.3.1

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.
@@ -1,41 +1,41 @@
1
- <script setup lang="ts">
2
- // A theme's accent color: Tabler's named colors as swatches (its color input). With `custom`, a
3
- // last swatch picks any color (#rrggbb) with the browser's color picker; it shows the custom color
4
- // while one is chosen. The `custom` slot goes after the swatches, for another picker.
5
- import { computed, useId } from 'vue'
6
- import TIcon from './TIcon.vue'
7
- import { isCustomAccent, themeAccents } from '../theme'
8
- import type { ThemeAccent } from '../types'
9
-
10
- defineProps<{ custom?: boolean; disabled?: boolean; legend?: string }>()
11
-
12
- const model = defineModel<ThemeAccent | null | undefined>()
13
- const name = useId()
14
- const customColor = computed(() => isCustomAccent(model.value ?? undefined) ? model.value! : null)
15
- const label = (color: string) => color[0].toUpperCase() + color.slice(1)
16
- </script>
17
-
18
- <template>
19
- <div role="radiogroup" :aria-label="legend ?? 'Accent color'">
20
- <div v-if="legend" class="form-label">{{ legend }}</div>
21
- <div class="t-accent-swatches align-items-center">
22
- <label v-for="color in themeAccents" :key="color" class="form-colorinput" :title="label(color)">
23
- <input type="radio" :name="name" :value="color" class="form-colorinput-input" :checked="model === color" :disabled="disabled"
24
- :aria-label="label(color)" @change="model = color">
25
- <span :class="['form-colorinput-color', `bg-${color}`]" />
26
- </label>
27
- <label v-if="custom" :class="['form-colorinput t-accent-custom', { active: customColor }]" :title="customColor ? `Custom: ${customColor}` : 'Custom color'">
28
- <input type="color" class="t-accent-custom-input" :value="customColor ?? '#3673d1'" :disabled="disabled" aria-label="Custom color"
29
- @input="model = ($event.target as HTMLInputElement).value">
30
- <span class="form-colorinput-color d-flex align-items-center justify-content-center" :style="customColor ? { background: customColor } : undefined">
31
- <TIcon :name="customColor ? 'check' : 'color-picker'" :class="customColor ? 'text-white' : 'text-secondary'" />
32
- </span>
33
- </label>
34
- <label v-else-if="customColor" class="form-colorinput" :title="customColor">
35
- <input type="radio" :name="name" class="form-colorinput-input" checked :disabled="disabled" :aria-label="`Custom: ${customColor}`">
36
- <span class="form-colorinput-color" :style="{ background: customColor }" />
37
- </label>
38
- <slot name="custom" />
39
- </div>
40
- </div>
41
- </template>
1
+ <script setup lang="ts">
2
+ // A theme's accent color: Tabler's named colors as swatches (its color input). With `custom`, a
3
+ // last swatch picks any color (#rrggbb) with the browser's color picker; it shows the custom color
4
+ // while one is chosen. The `custom` slot goes after the swatches, for another picker.
5
+ import { computed, useId } from 'vue'
6
+ import TIcon from './TIcon.vue'
7
+ import { isCustomAccent, themeAccents } from '../theme'
8
+ import type { ThemeAccent } from '../types'
9
+
10
+ defineProps<{ custom?: boolean; disabled?: boolean; legend?: string }>()
11
+
12
+ const model = defineModel<ThemeAccent | null | undefined>()
13
+ const name = useId()
14
+ const customColor = computed(() => isCustomAccent(model.value ?? undefined) ? model.value! : null)
15
+ const label = (color: string) => color[0].toUpperCase() + color.slice(1)
16
+ </script>
17
+
18
+ <template>
19
+ <div role="radiogroup" :aria-label="legend ?? 'Accent color'">
20
+ <div v-if="legend" class="form-label">{{ legend }}</div>
21
+ <div class="t-accent-swatches align-items-center">
22
+ <label v-for="color in themeAccents" :key="color" class="form-colorinput" :title="label(color)">
23
+ <input type="radio" :name="name" :value="color" class="form-colorinput-input" :checked="model === color" :disabled="disabled"
24
+ :aria-label="label(color)" @change="model = color">
25
+ <span :class="['form-colorinput-color', `bg-${color}`]" />
26
+ </label>
27
+ <label v-if="custom" :class="['form-colorinput t-accent-custom', { active: customColor }]" :title="customColor ? `Custom: ${customColor}` : 'Custom color'">
28
+ <input type="color" class="t-accent-custom-input" :value="customColor ?? '#3673d1'" :disabled="disabled" aria-label="Custom color"
29
+ @input="model = ($event.target as HTMLInputElement).value">
30
+ <span class="form-colorinput-color d-flex align-items-center justify-content-center" :style="customColor ? { background: customColor } : undefined">
31
+ <TIcon :name="customColor ? 'check' : 'color-picker'" :class="customColor ? 'text-white' : 'text-secondary'" />
32
+ </span>
33
+ </label>
34
+ <label v-else-if="customColor" class="form-colorinput" :title="customColor">
35
+ <input type="radio" :name="name" class="form-colorinput-input" checked :disabled="disabled" :aria-label="`Custom: ${customColor}`">
36
+ <span class="form-colorinput-color" :style="{ background: customColor }" />
37
+ </label>
38
+ <slot name="custom" />
39
+ </div>
40
+ </div>
41
+ </template>
@@ -0,0 +1,188 @@
1
+ <script setup lang="ts">
2
+ // A chart, as Tabler draws them with ApexCharts: a line, area, bar (across), column (up), pie or
3
+ // donut. `series` are named lists of numbers along `categories` (a pie or donut uses the first
4
+ // series, one slice per category). Colors come from the theme (the accent first), or `colors`
5
+ // (named colors such as 'success', or any CSS color); they follow light and dark mode and a
6
+ // TThemeScope around the chart. `format` writes values in the axis and tooltips; `options` is
7
+ // merged over everything for whatever else ApexCharts does. ApexCharts loads on first use.
8
+ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
9
+ import type ApexCharts from 'apexcharts'
10
+ import type { ApexOptions } from 'apexcharts'
11
+ import { loadApexCharts } from '../plugins/charts'
12
+ import type { ChartSeries, ChartType, Color } from '../types'
13
+ import { toTabler } from '../types'
14
+
15
+ const props = withDefaults(defineProps<{
16
+ type?: ChartType
17
+ series: ChartSeries[]
18
+ categories?: (string | number)[]
19
+ height?: number | string
20
+ stacked?: boolean
21
+ // Shown by default with more than one series, and for pies and donuts.
22
+ legend?: boolean
23
+ colors?: (Color | string)[]
24
+ format?: (value: number) => string
25
+ // No axes, grid or legend: a small chart inside a card or a stat.
26
+ sparkline?: boolean
27
+ label?: string
28
+ options?: ApexOptions
29
+ // Vue makes a missing boolean false; undefined keeps the legend's default.
30
+ }>(), { type: 'line', categories: () => [], height: 240, label: 'Chart', legend: undefined })
31
+
32
+ const emit = defineEmits<{ 'point-click': [point: { series: number; index: number; category: string | number | undefined }] }>()
33
+
34
+ const el = ref<HTMLElement>()
35
+ let chart: ApexCharts | null = null
36
+
37
+ // Tabler's chart colors after the accent: its named colors, in an order that keeps neighbors apart.
38
+ const palette = ['primary', 'green', 'orange', 'purple', 'cyan', 'pink', 'yellow', 'red', 'teal', 'indigo']
39
+ const named = new Set(['primary', 'neutral', 'success', 'warning', 'error', 'info'])
40
+
41
+ const round = computed(() => props.type === 'pie' || props.type === 'donut')
42
+
43
+ /** A CSS color as the browser resolves it here, inside any theme scope: `var(--tblr-primary)` → rgb(…). */
44
+ function resolve(color: string): string {
45
+ if (!el.value) return color
46
+ const probe = document.createElement('span')
47
+ probe.style.display = 'none'
48
+ probe.style.color = color
49
+ el.value.appendChild(probe)
50
+ const value = getComputedStyle(probe).color
51
+ probe.remove()
52
+ return value ? rgb(value) : color
53
+ }
54
+
55
+ // ApexCharts makes fills see-through only for hex and rgb() colors, and Tabler's theme colors can
56
+ // come back as oklch(…); painting one pixel gives any color as rgb().
57
+ let pixel: CanvasRenderingContext2D | null = null
58
+ function rgb(color: string): string {
59
+ if (/^(rgb|#)/i.test(color)) return color
60
+ pixel ??= document.createElement('canvas').getContext('2d', { willReadFrequently: true })
61
+ if (!pixel) return color
62
+ pixel.clearRect(0, 0, 1, 1)
63
+ pixel.fillStyle = color
64
+ pixel.fillRect(0, 0, 1, 1)
65
+ const [r, g, b, a] = pixel.getImageData(0, 0, 1, 1).data
66
+ return a === 255 ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${Math.round(a / 255 * 100) / 100})`
67
+ }
68
+ const cssColor = (color: string) => named.has(color) ? `var(--tblr-${toTabler(color as Color)})`
69
+ : /^[a-z]+$/.test(color) && palette.includes(color) ? `var(--tblr-${color})` : color
70
+
71
+ function themed(): ApexOptions {
72
+ const count = round.value ? props.categories.length : props.series.length
73
+ const colors = Array.from({ length: Math.max(count, 1) }, (_, i) =>
74
+ resolve(cssColor(props.series[i]?.color ?? props.colors?.[i] ?? palette[i % palette.length])))
75
+ const text = resolve('var(--tblr-secondary)')
76
+ const border = resolve('var(--tblr-border-color)')
77
+ return {
78
+ colors,
79
+ chart: { foreColor: text, background: 'transparent' },
80
+ grid: { borderColor: border },
81
+ stroke: { colors: round.value ? [resolve('var(--tblr-bg-surface)')] : undefined },
82
+ theme: { mode: el.value?.closest('[data-bs-theme]')?.getAttribute('data-bs-theme') === 'dark' ? 'dark' : 'light' }
83
+ }
84
+ }
85
+
86
+ function options(): ApexOptions {
87
+ const apexType = props.type === 'column' ? 'bar' : props.type
88
+ const formatter = props.format ? (value: number) => (value == null ? '' : props.format!(value)) : undefined
89
+ const base: ApexOptions = {
90
+ chart: {
91
+ type: apexType,
92
+ height: props.height,
93
+ fontFamily: 'inherit',
94
+ parentHeightOffset: 0,
95
+ toolbar: { show: false },
96
+ zoom: { enabled: false },
97
+ animations: { enabled: false },
98
+ stacked: props.stacked,
99
+ sparkline: { enabled: props.sparkline ?? false },
100
+ events: {
101
+ dataPointSelection: (_event, _chart, config) => {
102
+ if (config) emit('point-click', { series: config.seriesIndex, index: config.dataPointIndex, category: props.categories[config.dataPointIndex] })
103
+ }
104
+ }
105
+ },
106
+ series: round.value
107
+ ? (props.series[0]?.data ?? []).map(v => v ?? 0)
108
+ : props.series.map(s => ({ name: s.name, data: s.data })),
109
+ labels: round.value ? props.categories.map(String) : undefined,
110
+ xaxis: round.value ? undefined : {
111
+ categories: props.categories,
112
+ tooltip: { enabled: false },
113
+ axisBorder: { show: false },
114
+ axisTicks: { show: false },
115
+ labels: { formatter: props.type === 'bar' ? formatter as never : undefined }
116
+ },
117
+ yaxis: round.value ? undefined : { labels: { formatter: props.type === 'bar' ? undefined : formatter, padding: 4 } },
118
+ plotOptions: {
119
+ bar: { horizontal: props.type === 'bar', columnWidth: '50%', barHeight: '60%', borderRadius: 2 },
120
+ pie: { donut: { size: '70%' } }
121
+ },
122
+ dataLabels: { enabled: false },
123
+ fill: { opacity: props.type === 'area' ? 0.16 : 1, type: 'solid' },
124
+ stroke: { width: props.type === 'line' || props.type === 'area' ? 2 : round.value ? 2 : 0, curve: 'smooth', lineCap: 'round' },
125
+ // Bars across need room for their labels on the left.
126
+ grid: { strokeDashArray: 4, padding: { top: -16, right: 0, left: props.type === 'bar' ? 8 : -4, bottom: -4 } },
127
+ legend: {
128
+ show: props.legend ?? (round.value || props.series.length > 1),
129
+ position: 'bottom',
130
+ offsetY: 8,
131
+ markers: { size: 6, shape: 'circle', strokeWidth: 0 },
132
+ itemMargin: { horizontal: 8, vertical: 4 }
133
+ },
134
+ tooltip: { theme: 'dark', y: { formatter } },
135
+ noData: { text: 'No data' }
136
+ }
137
+ return defined(merge(merge(base, themed()), props.options ?? {}))
138
+ }
139
+
140
+ /** Without keys set to undefined: ApexCharts takes them as values, over its defaults (labels: undefined breaks it). */
141
+ function defined<T>(value: T): T {
142
+ if (!isObject(value)) return value
143
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => [k, defined(v)])) as T
144
+ }
145
+
146
+ /** Objects merged deeply; arrays and values replaced. */
147
+ function merge<T>(target: T, source: unknown): T {
148
+ if (!isObject(target) || !isObject(source)) return (source === undefined ? target : source) as T
149
+ const result: Record<string, unknown> = { ...target }
150
+ for (const [key, value] of Object.entries(source)) {
151
+ if (value === undefined) continue
152
+ result[key] = isObject(value) && isObject(result[key]) ? merge(result[key], value) : value
153
+ }
154
+ return result as T
155
+ }
156
+ function isObject(value: unknown): value is Record<string, unknown> {
157
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && typeof value !== 'function'
158
+ }
159
+
160
+ // The theme can change around the chart: light and dark, or a theme scope's accent and grays.
161
+ let observer: MutationObserver | null = null
162
+ function watchTheme() {
163
+ observer = new MutationObserver(() => chart?.updateOptions(options(), true))
164
+ const themedAncestors = new Set<Element>([document.documentElement])
165
+ for (let node = el.value?.parentElement; node; node = node.parentElement)
166
+ if ([...node.attributes].some(a => a.name.startsWith('data-bs-theme') || a.name === 'data-t-density')) themedAncestors.add(node)
167
+ for (const node of themedAncestors) observer.observe(node, { attributes: true, attributeFilter: ['data-bs-theme', 'data-bs-theme-primary', 'data-bs-theme-base', 'style', 'class'] })
168
+ }
169
+
170
+ onMounted(async () => {
171
+ const ApexCharts = await loadApexCharts()
172
+ if (!el.value) return
173
+ chart = new ApexCharts(el.value, options())
174
+ await chart.render()
175
+ watchTheme()
176
+ })
177
+ watch(() => [props.type, props.series, props.categories, props.stacked, props.legend, props.colors, props.height, props.options, props.sparkline],
178
+ () => chart?.updateOptions(options(), true), { deep: true })
179
+ onBeforeUnmount(() => {
180
+ observer?.disconnect()
181
+ chart?.destroy()
182
+ chart = null
183
+ })
184
+ </script>
185
+
186
+ <template>
187
+ <div ref="el" class="t-chart" role="img" :aria-label="label" />
188
+ </template>
@@ -1,22 +1,22 @@
1
- <script setup lang="ts">
2
- // Whether an application's page sits in a box, centered on wide screens with the background
3
- // around it, or fills the width. Each tile is a sketch of the page.
4
- import TRadioGroup from './TRadioGroup.vue'
5
- import { themeContainers } from '../theme'
6
- import type { ThemeContainer } from '../types'
7
-
8
- defineProps<{ disabled?: boolean; legend?: string }>()
9
-
10
- const model = defineModel<ThemeContainer | null | undefined>()
11
- </script>
12
-
13
- <template>
14
- <TRadioGroup v-model="model" :items="themeContainers" variant="tiles" tile-width="8rem" :disabled="disabled" :legend="legend">
15
- <template #preview="{ item }">
16
- <span :class="['t-sketch t-sketch-left', { 't-sketch-boxed': item.value === 'boxed' }]">
17
- <span class="t-sketch-nav" />
18
- <span class="t-sketch-page"><span /><span /><span /></span>
19
- </span>
20
- </template>
21
- </TRadioGroup>
22
- </template>
1
+ <script setup lang="ts">
2
+ // Whether an application's page sits in a box, centered on wide screens with the background
3
+ // around it, or fills the width. Each tile is a sketch of the page.
4
+ import TRadioGroup from './TRadioGroup.vue'
5
+ import { themeContainers } from '../theme'
6
+ import type { ThemeContainer } from '../types'
7
+
8
+ defineProps<{ disabled?: boolean; legend?: string }>()
9
+
10
+ const model = defineModel<ThemeContainer | null | undefined>()
11
+ </script>
12
+
13
+ <template>
14
+ <TRadioGroup v-model="model" :items="themeContainers" variant="tiles" tile-width="8rem" :disabled="disabled" :legend="legend">
15
+ <template #preview="{ item }">
16
+ <span :class="['t-sketch t-sketch-left', { 't-sketch-boxed': item.value === 'boxed' }]">
17
+ <span class="t-sketch-nav" />
18
+ <span class="t-sketch-page"><span /><span /><span /></span>
19
+ </span>
20
+ </template>
21
+ </TRadioGroup>
22
+ </template>
@@ -0,0 +1,41 @@
1
+ <script setup lang="ts">
2
+ // Tabler's datagrid: labels and their values, for detail panels and summaries, in a grid that fits
3
+ // as many columns as there's room for. `horizontal` puts each label beside its value; `cols` fixes
4
+ // the columns (1 to 4); `itemWidth`, `titleWidth` and `gap` set Tabler's datagrid variables. The
5
+ // pairs come from `items` (a slot named by an item's `key` draws its value; `copy` adds a copy
6
+ // button; an empty value is a dash) or from TDataGridItem children. It's a description list, so
7
+ // screen readers keep each label with its value.
8
+ import { computed } from 'vue'
9
+ import TDataGridItem from './TDataGridItem.vue'
10
+ import type { DataGridItem } from '../types'
11
+
12
+ const props = defineProps<{
13
+ items?: DataGridItem[]
14
+ horizontal?: boolean
15
+ cols?: 1 | 2 | 3 | 4
16
+ // The narrowest a column gets (Tabler's default is 15rem); lower fits more short values in a row.
17
+ itemWidth?: string
18
+ // The label's width when `horizontal` (Tabler's default is 10rem).
19
+ titleWidth?: string
20
+ // Between items, across and down (Tabler's default is 1.5rem).
21
+ gap?: string
22
+ }>()
23
+
24
+ const style = computed(() => ({
25
+ '--tblr-datagrid-item-width': props.itemWidth,
26
+ '--tblr-datagrid-title-width': props.titleWidth,
27
+ '--tblr-datagrid-padding': props.gap
28
+ }))
29
+ </script>
30
+
31
+ <template>
32
+ <dl :class="['datagrid mb-0', { 'datagrid-horizontal': horizontal }, cols && `datagrid-cols-${cols}`]" :style="style">
33
+ <template v-for="(item, i) in items ?? []" :key="item.key ?? `${i}-${item.label}`">
34
+ <TDataGridItem v-if="item.key && $slots[item.key]" :label="item.label" :copy="item.copy">
35
+ <slot :name="item.key" :item="item" />
36
+ </TDataGridItem>
37
+ <TDataGridItem v-else :label="item.label" :value="item.value" :copy="item.copy" />
38
+ </template>
39
+ <slot />
40
+ </dl>
41
+ </template>
@@ -0,0 +1,23 @@
1
+ <script setup lang="ts">
2
+ // One label and its value in a TDataGrid. The value is `value`, or the slot for anything else (a
3
+ // status, a badge, avatars, a progress bar, a field); empty, it's written as a dash so it doesn't
4
+ // look missing. `copy` adds a button that copies the value.
5
+ import { computed } from 'vue'
6
+ import TCopyButton from './TCopyButton.vue'
7
+
8
+ const props = defineProps<{ label: string; value?: string | number | boolean | null; copy?: boolean }>()
9
+
10
+ const text = computed(() => props.value == null || props.value === '' ? '' : typeof props.value === 'boolean' ? (props.value ? 'Yes' : 'No') : String(props.value))
11
+ </script>
12
+
13
+ <template>
14
+ <div class="datagrid-item">
15
+ <dt class="datagrid-title">{{ label }}</dt>
16
+ <dd :class="['datagrid-content mb-0', { 'd-flex align-items-center gap-2': copy }]">
17
+ <slot v-if="$slots.default" />
18
+ <template v-else-if="copy && text"><code class="text-break">{{ text }}</code></template>
19
+ <template v-else>{{ text || '–' }}</template>
20
+ <TCopyButton v-if="copy && text" :text="text" icon-only size="sm" variant="ghost" :label="`Copy the ${label.toLowerCase()}`" />
21
+ </dd>
22
+ </div>
23
+ </template>
@@ -1,19 +1,19 @@
1
- <script setup lang="ts">
2
- // How much room an application's content gets: padding inside cards, tables, buttons and fields,
3
- // and the gaps between them. Each tile shows rows at that spacing.
4
- import TRadioGroup from './TRadioGroup.vue'
5
- import { themeDensities } from '../theme'
6
- import type { ThemeDensity } from '../types'
7
-
8
- defineProps<{ disabled?: boolean; legend?: string }>()
9
-
10
- const model = defineModel<ThemeDensity | null | undefined>()
11
- </script>
12
-
13
- <template>
14
- <TRadioGroup v-model="model" :items="themeDensities" variant="tiles" tile-width="8rem" :disabled="disabled" :legend="legend">
15
- <template #preview="{ item }">
16
- <span :class="['t-sketch-rows', `t-sketch-${item.value}`]"><span /><span /><span /><span /></span>
17
- </template>
18
- </TRadioGroup>
19
- </template>
1
+ <script setup lang="ts">
2
+ // How much room an application's content gets: padding inside cards, tables, buttons and fields,
3
+ // and the gaps between them. Each tile shows rows at that spacing.
4
+ import TRadioGroup from './TRadioGroup.vue'
5
+ import { themeDensities } from '../theme'
6
+ import type { ThemeDensity } from '../types'
7
+
8
+ defineProps<{ disabled?: boolean; legend?: string }>()
9
+
10
+ const model = defineModel<ThemeDensity | null | undefined>()
11
+ </script>
12
+
13
+ <template>
14
+ <TRadioGroup v-model="model" :items="themeDensities" variant="tiles" tile-width="8rem" :disabled="disabled" :legend="legend">
15
+ <template #preview="{ item }">
16
+ <span :class="['t-sketch-rows', `t-sketch-${item.value}`]"><span /><span /><span /><span /></span>
17
+ </template>
18
+ </TRadioGroup>
19
+ </template>
@@ -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>