@xleddyl/443-components-vue 0.16.94 → 0.16.95

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
@@ -473,7 +473,7 @@ async function switchView() {
473
473
  | core | Root, Icon, Button, Spinner, Input, Textarea, FormField, FieldMessage, FieldBoundary, Form, FormAlerts, Kbd, VisuallyHidden |
474
474
  | forms | Calendar, Checkbox, CheckboxGroup, ColorInput, Combobox, DateInput, DatePicker, FileInput, FocalPointInput, InputAddon, InputGroup, NumberInput, PaletteSelect, PasswordInput, PinInput, Radio, RadioGroup, SegmentedControl, Select, Slider, Switch, TimeInput, TreeSelect |
475
475
  | overlays | CommandButton, CommandList, CommandPalette, ConfirmDialog, ConfirmHost, ContextMenu, Drawer, DropdownMenu, HoverCard, Modal, OverlayHost, Popover, Toaster, Tooltip |
476
- | data | Avatar, AvatarGroup, Badge, DescriptionList, FilterPill, FilterPills, Pagination, RecordList, SelectionBar, Stat, Table, Tag, TagList, Thumbnail, Timeline, Tree |
476
+ | data | Avatar, AvatarGroup, Badge, DescriptionList, FilterPill, FilterPills, Pagination, RecordList, SelectionBar, SortableList, Stat, Table, Tag, TagList, Thumbnail, TileGrid, Timeline, Tree |
477
477
  | layout | Accordion, AppShell, Breadcrumbs, Card, CopyButton, Grid, NavLink, PageHeader, Separator, Sidebar, SidebarNav, SidebarSection, Stack, Stepper, Tabs, ThemeSwitch, Toolbar |
478
478
  | templates | DashboardLayout, AuthLayout, AuthLogin, AuthLogout, DashboardPage, ListPage, DetailPage, FormPage, SettingsPage, SettingsSection, SettingsModal, SettingsGroup, AppearanceSettings, SaveBar, ErrorPage, NotFoundPage, EmptyPage, Brand, AccountMenu, FormDrawer |
479
479
  | feedback | Alert, EmptyState, LoadingOverlay, Meter, Progress, ProgressRing, Skeleton, SkeletonForm, SkeletonList |
@@ -570,7 +570,17 @@ On your own elements, `paletteClass(color)` gives the class of a palette name an
570
570
  />
571
571
  ```
572
572
 
573
- - `useSortable(container, options)` is the reorder logic of `TagList` for any list. Options: `items` (a ref or getter), `onMove(items, move)` (`SortableMove`: `{ item, from, to, items, source }`, write `items` back to your state), `orientation` (`'vertical'` by default, `'horizontal'` for wrapping rows), `disabled`, `handle` (a selector: only a pointer down on it starts a drag; without it any pointer down outside buttons, links and inputs does), `canMove(item, index)`, `label(item)` and `movedText(move)` for the announcement. Bind `itemProps(index)` on each item element (the attribute marks it, plus pointer and Alt with arrow key handlers) and render `announcement` in a polite live region. `move(from, to, { announce })` moves from your own buttons, `dragging` is the index being dragged (for a lifted style), `canMove(index)` reports locked items. Pointer drags reorder live and follow the pointer, Escape or a cancelled pointer puts the item back, and the click after a drag is swallowed.
573
+ - `SortableList` is a vertical list of rows to reorder: `v-model` (`SortableListItem[]`: `value`, `label`, `description`, `icon`, `disabled`) in a labelled list (`label`, default "Items"). Each row has a drag handle, the icon, the label with the description under it (both on one line with an ellipsis) and the `#trailing` slot (`{ item, index }`) for switches or actions. A drag starts from the handle or the label (not from the trailing controls), the row follows the pointer and its slot stays as a dashed placeholder, Escape cancels. The handle is a button ("Move Title", `handleLabel` is a `'Move {label}'` template): the up and down arrow keys, Home and End move the row, Alt with an arrow key works from anywhere in the row, and every move is announced. A disabled item cannot be picked up or moved by its handle (the handle is disabled), `disabled` locks the whole list (the trailing controls stay usable). `move({ item, from, to })` fires after each move. `size` is `'md'` (default) or `'sm'` (`SortableListSize`); `#item` replaces the icon, label and description; `emptyText` or `#empty` shows when the list is empty.
574
+
575
+ ```vue
576
+ <KSortableList v-model="columns" label="Visible columns">
577
+ <template #trailing="{ item }">
578
+ <KSwitch :model-value="true" :aria-label="`Hide ${item.label}`" @update:model-value="hide(item)" />
579
+ </template>
580
+ </KSortableList>
581
+ ```
582
+
583
+ - `useSortable(container, options)` is the reorder logic of `TagList` for any list. Options: `items` (a ref or getter), `onMove(items, move)` (`SortableMove`: `{ item, from, to, items, source }`, write `items` back to your state), `orientation` (`'vertical'` by default, `'horizontal'` for wrapping rows, `'grid'` for a CSS grid of cells: the item lands in the cell nearest to the pointer across wrapped rows, Alt with Left and Right moves it by one and Alt with Up and Down to the nearest cell of the row above or below), `disabled`, `handle` (a selector: only a pointer down on it starts a drag; without it any pointer down outside buttons, links and inputs does), `preview` (a selector inside the item: only that part follows the pointer and the item stays in its slot, so style the dragged item as the drop indicator, a dashed placeholder), `canMove(item, index)`, `label(item)` and `movedText(move)` for the announcement. Bind `itemProps(index)` on each item element (the attribute marks it, plus pointer and Alt with arrow key handlers) and render `announcement` in a polite live region. `move(from, to, { announce })` moves from your own buttons, `dragging` is the index being dragged (for a lifted style), `canMove(index)` reports locked items. Pointer drags reorder live and follow the pointer, Escape or a cancelled pointer puts the item back, and the click after a drag is swallowed.
574
584
 
575
585
  - `Thumbnail` previews an image, a video or a file: `kind` (`ThumbnailKind`, `'image' | 'video' | 'file' | 'icon'`, default `'image'`), `src`, `alt` and `icon` (the fallback icon, by default `photo`, `video-camera` or `document`). A video shows its first frame (`preload="metadata"`, muted, no controls) under a play glyph. Without `size` it is fluid (the width of its parent, the height from `aspect`, a ratio string like `'4/3'` or a number, default 1); `size` (`ThumbnailSize`, `'xs' | 'sm' | 'md' | 'lg'`) gives a fixed inline box for tables and lists. `fit` is `'cover'` (default) or `'contain'`, `rounded` (`ThumbnailRounded`, `'none' | 'sm' | 'md' | 'lg' | 'full'`) overrides the radius of the size, and `focal` (`FocalPoint`, `{ x, y }` from 0 to 1, what `FocalPointInput` edits) or `objectPosition` (any CSS value, it wins) choose the part of the image that stays in view. While the media loads the box pulses; `missing`, or an image or video that fails to load, shows a hatched box with the icon and a hidden "File not available" (`thumbnail.missing`, `missingText` overrides it). The `top-start` and `top-end` slots put badges and actions in the corners, `caption` (or the `#caption` slot) sits at the bottom on a readable scrim, and `reveal` (`ThumbnailOverlay[]`, default `['caption']`) lists the overlays that only show on hover and focus, also when a link or button around the thumbnail is hovered or focused (always on touch screens). The default slot replaces the media with your own content (a text preview). Text and icons over media use the `--k-media-scrim` and `--k-media-text` tokens, the same in both themes; use them for your own overlays too.
576
586
 
@@ -582,6 +592,40 @@ On your own elements, `paletteClass(color)` gives the class of a palette name an
582
592
  </KThumbnail>
583
593
  ```
584
594
 
595
+ - `TileGrid` lays out `items` as a responsive grid of tiles: `minItemWidth` (default `10rem`, the narrowest tile), `columns` (the most columns, unset fills the row) and `gap` (`LayoutGap`, default `md`). The `#tile` slot (`{ item, index, selected, dragging }`) renders each tile (a `Card`, a `Thumbnail`) and stretches it to the cell; `#add` is a last cell after the tiles (a `Card variant="dashed" as="button"`). `itemKey` (a field name, default `id`, or `(item, index) => key`) keys the tiles and the selection, `itemLabel(item)` names each tile and its announcements, `label` names the grid (default "Items"). The tiles are one tab stop: the arrow keys move between them across wrapped rows (Up and Down go to the nearest tile of the row above or below), Home and End go to the ends, and the controls inside a tile keep their own tab stops. `selectable` with `v-model:selected` (the keys) makes it a multi select `listbox` (otherwise a `list`): a round check shows on hover, focus and on every tile while something is selected (always on touch screens), a click on it toggles the tile, Shift adds the range from the last toggled tile, Space and Shift with Space do the same from the keyboard and Ctrl or Cmd with A selects all. A click on the tile itself toggles it while something is selected or with Shift, Ctrl or Cmd held, and calls `@activate(item, index, event)` otherwise (Enter too; without an `activate` listener it toggles). `sortable` reorders by pointer drag (the tile follows the pointer and its cell stays as a dashed placeholder, Escape cancels; `handle`, a selector, limits where a drag starts and keeps touch scrolling on the rest of the tile) and by Alt with an arrow key on a focused tile, with an announcement; bind `v-model:items` (or write `items` back from `move({ item, from, to, items })`). `dragData(item, items)` makes tiles native drag sources for drop targets outside the grid (folders): it returns `{ [mimeType]: string }` for the `DataTransfer` (or `null` to refuse the drag), `items` is the whole selection when the dragged tile is selected, `dragEffect` sets `effectAllowed` (default `move`), the dragged tiles fade and `itemDragStart` and `itemDragEnd` (`{ item, items, event }`) fire. `dragData` is ignored when `sortable` is set. `--k-tile-grid-radius` (default `--k-radius-lg`) is the radius of the tiles, the selected ring and the placeholder.
596
+
597
+ ```vue
598
+ <KTileGrid
599
+ v-model:selected="selected"
600
+ :items="files"
601
+ :item-label="(file) => file.name"
602
+ label="Files"
603
+ min-item-width="9rem"
604
+ selectable
605
+ :drag-data="(file, files) => ({ 'application/x-media': files.map((f) => f.id).join(',') })"
606
+ @activate="open"
607
+ >
608
+ <template #tile="{ item }">
609
+ <KThumbnail :src="item.url" aspect="1/1" :caption="item.name" />
610
+ </template>
611
+ </KTileGrid>
612
+ ```
613
+
614
+ - `Table` takes `rowAttrs(row, index)` (`TableRowAttrs`): attributes and listeners bound on each `<tr>` (`data-*`, `title`, `onDragover` to make rows drop targets); classes and listeners merge with the table's own. `rowDraggable` (`true` or `(row, index) => boolean`) with `dragData(row, rows)` makes rows native drag sources for drop targets outside the table (folders): `dragData` returns `{ [mimeType]: string }` for the `DataTransfer` (or `null` to refuse the drag), `rows` is the whole selection when the dragged row is selected, `dragEffect` sets `effectAllowed` (default `move`), the dragged rows fade and `rowDragStart` and `rowDragEnd` (`{ row, rows, event }`) fire. Selection, `rowClick`, row links and the keyboard keep working; links in draggable rows are not dragged on their own.
615
+
616
+ ```vue
617
+ <KTable
618
+ v-model:selected="selected"
619
+ :rows="files"
620
+ :columns="columns"
621
+ row-key="name"
622
+ selectable
623
+ row-draggable
624
+ :drag-data="(file, rows) => ({ 'application/x-media': rows.map((r) => r.name).join(',') })"
625
+ @row-click="open"
626
+ />
627
+ ```
628
+
585
629
  - `useFileDrop` returns `{ over, reset }` and takes `ignore(event)`. A drop handled by a nested drop zone is skipped by the outer ones, and the state resets after any drop, even when a child stops propagation. `readDroppedFiles(dataTransfer)` walks dropped folders (call it synchronously in the drop handler) and resolves to `[{ file, path }]`; `readDroppedFiles(dataTransfer, { directories: true })` resolves to `{ files, directories }` with every folder path, empty ones included, and `skipHidden: true` leaves out dot entries.
586
630
  - `Tabs` items take `badgeTone` and `badgeLabel` (the accessible name of the badge); the `#panel="{ item }"` slot renders a single panel for the active tab. `stretch` makes the tabs fill the remaining height of a flex column and the active panel grow with it (`flex: 1; min-height: 0`), and `inset` spaces the tab list from the container edges with the panel flush below it, for inspectors and side panes. `Breadcrumbs` items take `attrs` and `onClick` (an item without a link renders a button, handy for drop targets), `#item` customizes the content, and `ancestors` links every item and ends with a separator (`breadcrumbsAncestors` on `PageHeader`). `heading` (a heading level) renders the current item as that heading, for a trail that is the title of the page. `Accordion` takes `variant` `card` (default), `outline` (the same card without a shadow), `separated` or `plain`; items take `description`, and `contentVariant="neutral"` drops the content padding and text styling.
587
631
  - `RichTextEditor` labels heading buttons by their real level (`headingLabel="relative"` numbers them from 1) and `toolbar` picks and orders the buttons: `['headings', '|', 'bold', 'italic', 'link']`.
@@ -0,0 +1,120 @@
1
+ <template>
2
+ <div
3
+ class="k-sortable-list"
4
+ :class="[
5
+ `k-sortable-list-${size}`,
6
+ {
7
+ 'is-sortable': canSort,
8
+ 'is-dragging': sorter.dragging.value !== null,
9
+ 'is-disabled': disabled
10
+ }
11
+ ]"
12
+ >
13
+ <ul
14
+ v-if="items.length"
15
+ ref="list"
16
+ class="k-sortable-list-items"
17
+ :aria-label="labelText"
18
+ :aria-describedby="hintId"
19
+ >
20
+ <li
21
+ v-for="(item, index) in items"
22
+ :key="item.value"
23
+ class="k-sortable-list-item"
24
+ :class="{
25
+ 'is-moving': sorter.dragging.value === index,
26
+ 'is-locked': !sorter.canMove(index)
27
+ }"
28
+ v-bind="sorter.itemProps(index)"
29
+ >
30
+ <div class="k-sortable-list-row">
31
+ <button
32
+ type="button"
33
+ class="k-sortable-list-handle"
34
+ :aria-label="handleText(item)"
35
+ :aria-describedby="hintId"
36
+ :disabled="!sorter.canMove(index)"
37
+ @keydown="onHandleKeydown($event, index)"
38
+ >
39
+ <Icon name="bars-2" />
40
+ </button>
41
+ <span class="k-sortable-list-content">
42
+ <slot name="item" :item="item" :index="index">
43
+ <Icon v-if="item.icon" :name="item.icon" class="k-sortable-list-icon" />
44
+ <span class="k-sortable-list-text">
45
+ <span class="k-sortable-list-label">{{ item.label }}</span>
46
+ <span v-if="item.description" class="k-sortable-list-description">{{
47
+ item.description
48
+ }}</span>
49
+ </span>
50
+ </slot>
51
+ </span>
52
+ <span v-if="$slots.trailing" class="k-sortable-list-trailing">
53
+ <slot name="trailing" :item="item" :index="index" />
54
+ </span>
55
+ </div>
56
+ </li>
57
+ </ul>
58
+ <p v-else class="k-sortable-list-empty">
59
+ <slot name="empty">{{ emptyLabel }}</slot>
60
+ </p>
61
+ <span :id="hintId" class="k-visually-hidden">{{ t("sortableList.hint") }}</span>
62
+ <LiveRegion :message="sorter.announcement.value" />
63
+ </div>
64
+ </template>
65
+
66
+ <script setup>
67
+ import { computed, useId, useTemplateRef } from "vue";
68
+ import { useLocale } from "../../composables/useLocale";
69
+ import { useSortable } from "../../composables/useSortable";
70
+ import LiveRegion from "../../internal/core/LiveRegion.vue";
71
+ import { translateOr } from "../../locale";
72
+ import Icon from "../core/Icon.vue";
73
+ const props = defineProps({
74
+ label: { type: String, required: false },
75
+ size: { type: String, required: false, default: "md" },
76
+ disabled: { type: Boolean, required: false },
77
+ emptyText: { type: String, required: false },
78
+ handleLabel: { type: String, required: false }
79
+ });
80
+ const model = defineModel({ type: Array, ...{ default: () => [] } });
81
+ const emit = defineEmits(["move"]);
82
+ defineSlots();
83
+ const { t, locale } = useLocale();
84
+ const hintId = `${useId()}-hint`;
85
+ const list = useTemplateRef("list");
86
+ const items = computed(() => model.value);
87
+ const canSort = computed(() => !props.disabled && items.value.length > 1);
88
+ const labelText = computed(() => props.label ?? t("sortableList.label"));
89
+ const emptyLabel = computed(() => props.emptyText ?? t("sortableList.empty"));
90
+ function handleText(item) {
91
+ return translateOr(locale.value, props.handleLabel, "sortableList.handle", { label: item.label });
92
+ }
93
+ const sorter = useSortable(list, {
94
+ items,
95
+ orientation: "vertical",
96
+ handle: ".k-sortable-list-handle, .k-sortable-list-content",
97
+ preview: ".k-sortable-list-row",
98
+ disabled: () => props.disabled,
99
+ canMove: (item) => !item.disabled,
100
+ label: (item) => item.label,
101
+ onMove: (next, move) => {
102
+ model.value = next;
103
+ emit("move", { item: move.item, from: move.from, to: move.to });
104
+ }
105
+ });
106
+ const HANDLE_KEYS = {
107
+ ArrowUp: (index) => index - 1,
108
+ ArrowDown: (index) => index + 1,
109
+ Home: () => 0,
110
+ End: (_, count) => count - 1
111
+ };
112
+ function onHandleKeydown(event, index) {
113
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
114
+ const target = HANDLE_KEYS[event.key];
115
+ if (!target) return;
116
+ event.preventDefault();
117
+ event.stopPropagation();
118
+ sorter.move(index, target(index, items.value.length), { announce: true, source: "keyboard" });
119
+ }
120
+ </script>
@@ -0,0 +1,48 @@
1
+ import type { SortableListItem, SortableListSize } from './types';
2
+ declare const __VLS_export: <T extends SortableListItem>(__VLS_props: NonNullable<Awaited<typeof __VLS_setup>>["props"], __VLS_ctx?: __VLS_PrettifyLocal<Pick<NonNullable<Awaited<typeof __VLS_setup>>, "attrs" | "emit" | "slots">>, __VLS_exposed?: NonNullable<Awaited<typeof __VLS_setup>>["expose"], __VLS_setup?: Promise<{
3
+ props: import("vue").PublicProps & __VLS_PrettifyLocal<({
4
+ label?: string;
5
+ size?: SortableListSize;
6
+ disabled?: boolean;
7
+ emptyText?: string;
8
+ handleLabel?: string;
9
+ } & {
10
+ modelValue?: T[];
11
+ }) & {
12
+ onMove?: ((move: {
13
+ item: T;
14
+ from: number;
15
+ to: number;
16
+ }) => any) | undefined;
17
+ "onUpdate:modelValue"?: ((value: T[]) => any) | undefined;
18
+ } & Partial<import("vue").HTMLAttributes & import("vue").ReservedProps>> & (typeof globalThis extends {
19
+ __VLS_PROPS_FALLBACK: infer P;
20
+ } ? P : {});
21
+ expose: (exposed: {}) => void;
22
+ attrs: any;
23
+ slots: {
24
+ item?: (props: {
25
+ item: T;
26
+ index: number;
27
+ }) => unknown;
28
+ trailing?: (props: {
29
+ item: T;
30
+ index: number;
31
+ }) => unknown;
32
+ empty?: () => unknown;
33
+ };
34
+ emit: ((evt: "move", move: {
35
+ item: T;
36
+ from: number;
37
+ to: number;
38
+ }) => void) & ((event: "update:modelValue", value: T[]) => void);
39
+ }>) => import("vue").VNode & {
40
+ __ctx?: NonNullable<Awaited<typeof __VLS_setup>>;
41
+ };
42
+ declare const _default: typeof __VLS_export;
43
+ export default _default;
44
+ type __VLS_PrettifyLocal<T> = (T extends any ? {
45
+ [K in keyof T]: T[K];
46
+ } : {
47
+ [K in keyof T as K]: T[K];
48
+ }) & {};
@@ -111,10 +111,17 @@
111
111
  <tr
112
112
  v-for="(row, index) in rows"
113
113
  :key="keyOf(row, index)"
114
+ :draggable="isDraggable(row, index) ? 'true' : void 0"
115
+ v-bind="rowAttrs?.(row, index)"
114
116
  class="k-table-row"
115
- :class="{ 'is-selected': isSelected(row, index) }"
117
+ :class="{
118
+ 'is-selected': isSelected(row, index),
119
+ 'is-dragging': draggedKeys.has(keyOf(row, index))
120
+ }"
116
121
  :style="{ '--k-row-delay': rowDelay(index, stagger ? void 0 : 0) }"
117
122
  @click="onRowClick(row, index, $event)"
123
+ @dragstart="onRowDragStart(row, index, $event)"
124
+ @dragend="onRowDragEnd(row, $event)"
118
125
  >
119
126
  <td v-if="selectable" class="k-table-check-cell" @click.stop>
120
127
  <label class="k-table-check-hit">
@@ -148,6 +155,7 @@
148
155
  v-else-if="column.key === linkColumnKey && rowLinks.has(row)"
149
156
  v-bind="rowLinks.get(row).attrs"
150
157
  class="k-table-link"
158
+ :draggable="isDraggable(row, index) ? 'false' : void 0"
151
159
  @click.stop
152
160
  >
153
161
  <slot
@@ -216,9 +224,13 @@ const props = defineProps({
216
224
  stickyHeader: { type: Boolean, required: false, default: true },
217
225
  maxHeight: { type: String, required: false },
218
226
  bordered: { type: Boolean, required: false, default: true },
219
- stagger: { type: Boolean, required: false, default: true }
227
+ stagger: { type: Boolean, required: false, default: true },
228
+ rowAttrs: { type: Function, required: false },
229
+ rowDraggable: { type: [Boolean, Function], required: false },
230
+ dragData: { type: Function, required: false },
231
+ dragEffect: { type: null, required: false, default: "move" }
220
232
  });
221
- const emit = defineEmits(["rowClick"]);
233
+ const emit = defineEmits(["rowClick", "rowDragStart", "rowDragEnd"]);
222
234
  defineSlots();
223
235
  const sort = defineModel("sort", { type: [Object, null], ...{ default: null } });
224
236
  const selected = defineModel("selected", { type: Array, ...{ default: () => [] } });
@@ -372,6 +384,34 @@ function onRowClick(row, index, event) {
372
384
  })
373
385
  );
374
386
  }
387
+ function isDraggable(row, index) {
388
+ const draggable = props.rowDraggable;
389
+ if (!draggable || !props.dragData) return false;
390
+ return draggable === true || draggable(row, index);
391
+ }
392
+ const draggedKeys = ref(/* @__PURE__ */ new Set());
393
+ let draggedRows = [];
394
+ function onRowDragStart(row, index, event) {
395
+ if (!isDraggable(row, index) || !event.dataTransfer || !props.dragData) return;
396
+ const rows = props.selectable && isSelected(row, index) ? props.rows.filter((entry, position) => isSelected(entry, position)) : [row];
397
+ const data = props.dragData(row, rows);
398
+ if (!data) {
399
+ event.preventDefault();
400
+ return;
401
+ }
402
+ for (const [type, value] of Object.entries(data)) event.dataTransfer.setData(type, value);
403
+ event.dataTransfer.effectAllowed = props.dragEffect;
404
+ draggedRows = rows;
405
+ draggedKeys.value = new Set(rows.map((entry) => keyOf(entry, props.rows.indexOf(entry))));
406
+ emit("rowDragStart", { row, rows, event });
407
+ }
408
+ function onRowDragEnd(row, event) {
409
+ if (!draggedKeys.value.size) return;
410
+ const rows = draggedRows;
411
+ draggedRows = [];
412
+ draggedKeys.value = /* @__PURE__ */ new Set();
413
+ emit("rowDragEnd", { row, rows, event });
414
+ }
375
415
  const skeletonWidths = [72, 48, 60, 36, 54, 66, 42];
376
416
  function skeletonWidth(rowIndex, columnIndex) {
377
417
  return `${skeletonWidths[(rowIndex + columnIndex * 3) % skeletonWidths.length]}%`;
@@ -1,5 +1,5 @@
1
1
  import type { LinkTarget } from '../core/types';
2
- import type { RowKey, TableColumn, TableDensity, TableSort } from './types';
2
+ import type { RowKey, TableColumn, TableDensity, TableDragData, TableRowAttrs, TableRowDrag, TableSort } from './types';
3
3
  declare const __VLS_export: <T extends object>(__VLS_props: NonNullable<Awaited<typeof __VLS_setup>>["props"], __VLS_ctx?: __VLS_PrettifyLocal<Pick<NonNullable<Awaited<typeof __VLS_setup>>, "attrs" | "emit" | "slots">>, __VLS_exposed?: NonNullable<Awaited<typeof __VLS_setup>>["expose"], __VLS_setup?: Promise<{
4
4
  props: import("vue").PublicProps & __VLS_PrettifyLocal<({
5
5
  rows: T[];
@@ -22,11 +22,17 @@ declare const __VLS_export: <T extends object>(__VLS_props: NonNullable<Awaited<
22
22
  maxHeight?: string;
23
23
  bordered?: boolean;
24
24
  stagger?: boolean;
25
+ rowAttrs?: (row: T, index: number) => TableRowAttrs;
26
+ rowDraggable?: boolean | ((row: T, index: number) => boolean);
27
+ dragData?: (row: T, rows: T[]) => TableDragData | null | undefined;
28
+ dragEffect?: DataTransfer["effectAllowed"];
25
29
  } & {
26
30
  sort?: TableSort | null;
27
31
  selected?: RowKey[];
28
32
  }) & {
29
33
  onRowClick?: ((row: T, index: number, event: MouseEvent) => any) | undefined;
34
+ onRowDragStart?: ((drag: TableRowDrag<T>) => any) | undefined;
35
+ onRowDragEnd?: ((drag: TableRowDrag<T>) => any) | undefined;
30
36
  "onUpdate:sort"?: ((value: TableSort | null) => any) | undefined;
31
37
  "onUpdate:selected"?: ((value: RowKey[]) => any) | undefined;
32
38
  } & Partial<import("vue").HTMLAttributes & import("vue").ReservedProps>> & (typeof globalThis extends {
@@ -48,7 +54,7 @@ declare const __VLS_export: <T extends object>(__VLS_props: NonNullable<Awaited<
48
54
  } & {
49
55
  empty?: () => unknown;
50
56
  };
51
- emit: ((evt: "rowClick", row: T, index: number, event: MouseEvent) => void) & (((event: "update:sort", value: TableSort | null) => void) & ((event: "update:selected", value: RowKey[]) => void));
57
+ emit: (((evt: "rowClick", row: T, index: number, event: MouseEvent) => void) & ((evt: "rowDragStart", drag: TableRowDrag<T>) => void) & ((evt: "rowDragEnd", drag: TableRowDrag<T>) => void)) & (((event: "update:sort", value: TableSort | null) => void) & ((event: "update:selected", value: RowKey[]) => void));
52
58
  }>) => import("vue").VNode & {
53
59
  __ctx?: NonNullable<Awaited<typeof __VLS_setup>>;
54
60
  };
@@ -0,0 +1,274 @@
1
+ <template>
2
+ <div
3
+ class="k-tile-grid"
4
+ :class="{
5
+ 'is-selectable': selectable,
6
+ 'is-sortable': canSort,
7
+ 'has-handle': Boolean(handle),
8
+ 'has-selection': selectable && selected.length > 0,
9
+ 'is-dragging': sorter.dragging.value !== null || dragKeys.length > 0,
10
+ 'is-disabled': disabled
11
+ }"
12
+ >
13
+ <Grid :min-item-width="minItemWidth" :columns="columns ?? MAX_COLUMNS" :gap="gap">
14
+ <div
15
+ v-if="items.length"
16
+ ref="list"
17
+ class="k-tile-grid-list"
18
+ :role="selectable ? 'listbox' : 'list'"
19
+ :aria-label="labelText"
20
+ :aria-multiselectable="selectable ? 'true' : void 0"
21
+ :aria-disabled="selectable && disabled ? 'true' : void 0"
22
+ :aria-describedby="hintText ? hintId : void 0"
23
+ >
24
+ <div
25
+ v-for="(item, index) in items"
26
+ :key="keyOf(item, index)"
27
+ class="k-tile-grid-item"
28
+ :class="{
29
+ 'is-moving': sorter.dragging.value === index,
30
+ 'is-dragging': isDragged(item, index)
31
+ }"
32
+ :role="selectable ? 'option' : 'listitem'"
33
+ :aria-selected="selectable ? isSelected(item, index) : void 0"
34
+ :aria-label="itemLabel ? itemLabel(item) : void 0"
35
+ :tabindex="index === focusIndex ? 0 : -1"
36
+ :draggable="canDragOut ? 'true' : void 0"
37
+ v-bind="canSort ? sorter.itemProps(index) : void 0"
38
+ @focus="focusIndex = index"
39
+ @click="onTileClick($event, item, index)"
40
+ @keydown="onTileKeydown($event, item, index)"
41
+ @dragstart="onDragStart($event, item, index)"
42
+ @dragend="onDragEnd($event, item)"
43
+ >
44
+ <div class="k-tile-grid-tile">
45
+ <slot
46
+ name="tile"
47
+ :item="item"
48
+ :index="index"
49
+ :selected="isSelected(item, index)"
50
+ :dragging="sorter.dragging.value === index || isDragged(item, index)"
51
+ />
52
+ <span
53
+ v-if="selectable"
54
+ class="k-tile-grid-check"
55
+ aria-hidden="true"
56
+ @click.stop="onCheckClick($event, item, index)"
57
+ >
58
+ <Icon name="check" />
59
+ </span>
60
+ </div>
61
+ </div>
62
+ </div>
63
+ <div v-if="$slots.add" class="k-tile-grid-add">
64
+ <slot name="add" />
65
+ </div>
66
+ </Grid>
67
+ <span v-if="hintText" :id="hintId" class="k-visually-hidden">{{ hintText }}</span>
68
+ <LiveRegion :message="sorter.announcement.value" />
69
+ </div>
70
+ </template>
71
+
72
+ <script setup>
73
+ import { computed, ref, useId, useTemplateRef, watch } from "vue";
74
+ import { useLocale } from "../../composables/useLocale";
75
+ import { useSortable } from "../../composables/useSortable";
76
+ import LiveRegion from "../../internal/core/LiveRegion.vue";
77
+ import { gridNeighbor, isRtl, layoutRect } from "../../internal/data/sortable";
78
+ import Icon from "../core/Icon.vue";
79
+ import Grid from "../layout/Grid.vue";
80
+ const props = defineProps({
81
+ itemKey: { type: [String, Function], required: false, default: "id" },
82
+ itemLabel: { type: Function, required: false },
83
+ label: { type: String, required: false },
84
+ minItemWidth: { type: String, required: false, default: "10rem" },
85
+ columns: { type: Number, required: false },
86
+ gap: { type: String, required: false, default: "md" },
87
+ selectable: { type: Boolean, required: false },
88
+ sortable: { type: Boolean, required: false },
89
+ handle: { type: String, required: false },
90
+ dragData: { type: Function, required: false },
91
+ dragEffect: { type: null, required: false, default: "move" },
92
+ disabled: { type: Boolean, required: false },
93
+ onActivate: { type: Function, required: false }
94
+ });
95
+ const items = defineModel("items", { type: Array, ...{ required: true } });
96
+ const selected = defineModel("selected", { type: Array, ...{ default: () => [] } });
97
+ const emit = defineEmits(["move", "itemDragStart", "itemDragEnd"]);
98
+ defineSlots();
99
+ const MAX_COLUMNS = 64;
100
+ const INTERACTIVE = 'a, button, input, select, textarea, label, summary, [role="button"]';
101
+ const { t } = useLocale();
102
+ const hintId = `${useId()}-hint`;
103
+ const list = useTemplateRef("list");
104
+ const focusIndex = ref(0);
105
+ const anchor = ref(null);
106
+ const dragKeys = ref([]);
107
+ const canSort = computed(() => props.sortable && !props.disabled);
108
+ const canDragOut = computed(() => Boolean(props.dragData) && !canSort.value && !props.disabled);
109
+ const canSelect = computed(() => props.selectable && !props.disabled);
110
+ const labelText = computed(() => props.label ?? t("tileGrid.label"));
111
+ const hintText = computed(() => {
112
+ const parts = [t("tileGrid.navigateHint")];
113
+ if (canSelect.value) parts.push(t("tileGrid.selectHint"));
114
+ if (canSort.value) parts.push(t("tileGrid.sortHint"));
115
+ return parts.join(". ");
116
+ });
117
+ function keyOf(item, index) {
118
+ if (typeof props.itemKey === "function") return props.itemKey(item, index);
119
+ const value = item?.[props.itemKey];
120
+ return typeof value === "string" || typeof value === "number" ? value : index;
121
+ }
122
+ function labelOf(item) {
123
+ return props.itemLabel ? props.itemLabel(item) : String(keyOf(item, items.value.indexOf(item)));
124
+ }
125
+ const selectedSet = computed(() => new Set(selected.value));
126
+ function isSelected(item, index) {
127
+ return Boolean(props.selectable) && selectedSet.value.has(keyOf(item, index));
128
+ }
129
+ function isDragged(item, index) {
130
+ return dragKeys.value.includes(keyOf(item, index));
131
+ }
132
+ watch(
133
+ () => items.value.length,
134
+ (length) => {
135
+ if (focusIndex.value >= length) focusIndex.value = Math.max(0, length - 1);
136
+ }
137
+ );
138
+ const sorter = useSortable(list, {
139
+ items: () => items.value,
140
+ orientation: "grid",
141
+ handle: props.handle ?? ".k-tile-grid-tile",
142
+ preview: ".k-tile-grid-tile",
143
+ disabled: () => !canSort.value,
144
+ label: labelOf,
145
+ onMove: (next, move) => {
146
+ items.value = next;
147
+ focusIndex.value = move.to;
148
+ emit("move", { item: move.item, from: move.from, to: move.to, items: next });
149
+ }
150
+ });
151
+ function toggle(item, index, event) {
152
+ if (!canSelect.value) return;
153
+ const key = keyOf(item, index);
154
+ if (event?.shiftKey && anchor.value !== null) {
155
+ const keys = items.value.map((entry, position) => keyOf(entry, position));
156
+ const from = keys.indexOf(anchor.value);
157
+ if (from !== -1) {
158
+ const range = keys.slice(Math.min(from, index), Math.max(from, index) + 1);
159
+ selected.value = [.../* @__PURE__ */ new Set([...selected.value, ...range])];
160
+ anchor.value = key;
161
+ return;
162
+ }
163
+ }
164
+ selected.value = selectedSet.value.has(key) ? selected.value.filter((entry) => entry !== key) : [...selected.value, key];
165
+ anchor.value = key;
166
+ }
167
+ function selectAll() {
168
+ if (!canSelect.value) return;
169
+ const keys = items.value.map((item, index) => keyOf(item, index));
170
+ selected.value = [.../* @__PURE__ */ new Set([...selected.value, ...keys])];
171
+ }
172
+ function activate(item, index, event) {
173
+ if (props.onActivate) props.onActivate(item, index, event);
174
+ else toggle(item, index, event);
175
+ }
176
+ function onCheckClick(event, item, index) {
177
+ focusIndex.value = index;
178
+ toggle(item, index, event);
179
+ }
180
+ function onTileClick(event, item, index) {
181
+ const tile = event.currentTarget;
182
+ const origin = event.target?.closest(INTERACTIVE);
183
+ if (origin && origin !== tile && tile.contains(origin)) return;
184
+ const selecting = selected.value.length > 0 || event.shiftKey || event.metaKey || event.ctrlKey;
185
+ if (canSelect.value && selecting) toggle(item, index, event);
186
+ else activate(item, index, event);
187
+ }
188
+ function tileElements() {
189
+ return Array.from(list.value?.children ?? []);
190
+ }
191
+ function focusTile(index) {
192
+ focusIndex.value = index;
193
+ tileElements()[index]?.focus();
194
+ }
195
+ function navigationTarget(event, index) {
196
+ const count = items.value.length;
197
+ const rtl = isRtl(list.value);
198
+ switch (event.key) {
199
+ case "ArrowLeft":
200
+ return rtl ? index + 1 : index - 1;
201
+ case "ArrowRight":
202
+ return rtl ? index - 1 : index + 1;
203
+ case "ArrowUp":
204
+ case "ArrowDown":
205
+ return gridNeighbor(
206
+ tileElements().map(layoutRect),
207
+ index,
208
+ event.key === "ArrowUp" ? -1 : 1
209
+ );
210
+ case "Home":
211
+ return 0;
212
+ case "End":
213
+ return count - 1;
214
+ default:
215
+ return null;
216
+ }
217
+ }
218
+ function onTileKeydown(event, item, index) {
219
+ if (event.target !== event.currentTarget || event.altKey) return;
220
+ const modifier = event.ctrlKey || event.metaKey;
221
+ if (event.key === " " && !modifier) {
222
+ if (!canSelect.value) return;
223
+ event.preventDefault();
224
+ toggle(item, index, event);
225
+ return;
226
+ }
227
+ if (event.key === "Enter" && !modifier) {
228
+ if (!props.onActivate && !canSelect.value) return;
229
+ event.preventDefault();
230
+ activate(item, index, event);
231
+ return;
232
+ }
233
+ if (modifier && event.key.toLowerCase() === "a") {
234
+ if (!canSelect.value) return;
235
+ event.preventDefault();
236
+ selectAll();
237
+ return;
238
+ }
239
+ if (modifier) return;
240
+ const target = navigationTarget(event, index);
241
+ if (target === null) return;
242
+ event.preventDefault();
243
+ if (target >= 0 && target < items.value.length) focusTile(target);
244
+ }
245
+ function draggedGroup(item) {
246
+ if (!props.selectable || !selectedSet.value.has(keyOf(item, items.value.indexOf(item))))
247
+ return [item];
248
+ return items.value.filter((entry, index) => isSelected(entry, index));
249
+ }
250
+ let dragged = [];
251
+ function onDragStart(event, item, index) {
252
+ if (canSort.value) event.preventDefault();
253
+ if (!canDragOut.value || !event.dataTransfer || !props.dragData) return;
254
+ const group = draggedGroup(item);
255
+ const data = props.dragData(item, group);
256
+ if (!data) {
257
+ event.preventDefault();
258
+ return;
259
+ }
260
+ for (const [type, value] of Object.entries(data)) event.dataTransfer.setData(type, value);
261
+ event.dataTransfer.effectAllowed = props.dragEffect;
262
+ focusIndex.value = index;
263
+ dragged = group;
264
+ dragKeys.value = group.map((entry) => keyOf(entry, items.value.indexOf(entry)));
265
+ emit("itemDragStart", { item, items: group, event });
266
+ }
267
+ function onDragEnd(event, item) {
268
+ if (!dragKeys.value.length) return;
269
+ const group = dragged;
270
+ dragged = [];
271
+ dragKeys.value = [];
272
+ emit("itemDragEnd", { item, items: group, event });
273
+ }
274
+ </script>