vue-grid-layout-headless 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![NPM downloads][badge-npm-downloads]][url-npm]
6
6
  [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
7
 
8
- A headless grid: `useGridLayout` returns the placement of items on a grid of cells, their tiles and a `startGesture` handler that moves or resizes them, with no styling.
8
+ This package is a headless grid with no styling. `useGridLayout` returns the placement of items on a grid of cells, their tiles, and a `startGesture` handler that moves or resizes them.
9
9
 
10
10
  Design notes live in [the specs](https://github.com/Esposter/Esposter/tree/main/openspec/specs/vue-grid-layout-headless).
11
11
 
@@ -19,17 +19,21 @@ Design notes live in [the specs](https://github.com/Esposter/Esposter/tree/main/
19
19
 
20
20
  ## <a name="getting-started">🚀 Getting Started</a>
21
21
 
22
+ 1. Install the package.
23
+
22
24
  ```bash
23
25
  pnpm i vue-grid-layout-headless
24
26
  ```
25
27
 
28
+ 2. Create a component from this code. After a release, `items` holds the changed cells.
29
+
26
30
  ```vue
27
31
  <script setup lang="ts">
28
- import { CollisionMode, CompactType, useGridLayout } from "vue-grid-layout-headless";
32
+ import { CollisionMode, CompactType, ResizeEdge, useGridLayout } from "vue-grid-layout-headless";
29
33
  import { shallowRef, useTemplateRef } from "vue";
30
34
 
31
35
  const root = useTemplateRef<HTMLElement>("root");
32
- const items = shallowRef([{ h: 2, id: "a", w: 4, x: 0, y: 0 }]);
36
+ const items = shallowRef([{ h: 2, id: "a", isAutoHeight: false, w: 4, x: 0, y: 0 }]);
33
37
  const { gridHeight, startGesture, tiles } = useGridLayout(root, () => ({
34
38
  collision: CollisionMode.Push,
35
39
  columnNumber: 12,
@@ -39,10 +43,9 @@ const { gridHeight, startGesture, tiles } = useGridLayout(root, () => ({
39
43
  items: items.value,
40
44
  rowHeight: 40,
41
45
  spacing: { gap: 10, padding: 10 },
42
- // A release replaces the cells it changed and drops the ids it removed
43
- onCommit: ({ changes, removed }) => {
44
- const changedIds = new Set(changes.map(({ id }) => id));
45
- items.value = [...items.value.filter(({ id }) => !changedIds.has(id) && !removed.includes(id)), ...changes];
46
+ // A release replaces the cells it changed, and keeps each item's other fields
47
+ onCommit: ({ changes }) => {
48
+ items.value = items.value.map((item) => ({ ...item, ...changes.find(({ id }) => id === item.id) }));
46
49
  },
47
50
  }));
48
51
  </script>
@@ -61,27 +64,39 @@ const { gridHeight, startGesture, tiles } = useGridLayout(root, () => ({
61
64
  width: `${geometry.width}px`,
62
65
  }"
63
66
  @pointerdown="startGesture($event, item)"
64
- />
67
+ >
68
+ <span class="resize-handle" @pointerdown.stop="startGesture($event, item, ResizeEdge.SouthEast)" />
69
+ </div>
65
70
  </div>
66
71
  </template>
67
72
  ```
68
73
 
69
- Each tile's `geometry` is the box to draw it in, in pixels from the grid's top left corner, and its `offset` moves a dragged tile so it stays under the pointer.
74
+ Each tile supplies these values:
75
+
76
+ - `geometry` is the box that draws the tile, in pixels from the grid's top left corner.
77
+ - `offset` moves a dragged tile, so that it stays under the pointer.
70
78
 
71
79
  ## <a name="key-exports">🧩 Key Exports</a>
72
80
 
73
- | Export | Kind | Purpose |
74
- | ------------------- | ---------- | ---------------------------------------------------------------------------------------------------------- |
75
- | `CollisionMode` | enum | What a dropped item does to the items it lands on: push, swap, or prevent the drop |
76
- | `CompactType` | enum | The direction a layout compacts in: vertical, horizontal, or none |
77
- | `GridCommit` | interface | What a release writes back: the cells one gesture changed or added, and the ids it removed |
78
- | `GridItem` | interface | A cell the grid places, named by the entity it lays out |
79
- | `GridLayout` | interface | What a grid hands its consumer: the tiles to draw, the drag placeholder, the height and the press handler |
80
- | `GridLayoutOptions` | interface | What a grid lays out and how its gestures read the pointer, passed to the composable as a getter |
81
- | `GridTile` | interface | An item as the grid draws it: its box, and the offset a dragged item is drawn at |
82
- | `ResizeEdge` | enum | The edge or corner a resize pulls |
83
- | `startExternalDrag` | function | Drags an item from outside every grid, such as a palette entry, and lands it on the grid under the release |
84
- | `useGridLayout` | composable | Places items on a grid, and previews and commits the moves and resizes a pointer makes of them |
81
+ | Export | Kind | Purpose |
82
+ | -------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `checkChangesHeight` | function | Whether pulling an edge or corner changes an item's height, since a north, south or corner pull has a vertical part |
84
+ | `CollisionMode` | enum | What a dropped item does to the items it lands on: push, swap, or prevent the drop |
85
+ | `CompactType` | enum | The direction a layout compacts in: vertical, horizontal, or none |
86
+ | `getFirstFreeCell` | function | The first cell a new item of a given span fits in, scanning rows from the top and columns from the left |
87
+ | `GridBlock` | interface | A cell the grid places, named by its id: what a move, a commit or a placement carries |
88
+ | `GridCommit` | interface | What a release writes back: the cells that one gesture changed |
89
+ | `GridItem` | interface | A block the grid places, named by the entity it lays out, with `isAutoHeight` for whether that entity takes its height from its content |
90
+ | `GridLayout` | interface | What a grid hands its consumer: the tiles to draw, the placeholder, the height, the press and the step |
91
+ | `GridLayoutOptions` | interface | What a grid lays out, how its gestures read the pointer, which items it refuses and which are solid, and where a body drag released over another grid goes, passed to the composable as a getter |
92
+ | `GridPlaceholder` | interface | The box a drag draws where its item would land, marked when the grid would refuse the landing |
93
+ | `GridRefusal` | type | Whether a grid refuses an item dragged into it, asked before the grid previews or lands it |
94
+ | `GridStep` | interface | A keyboard step: the whole cells an item moves by and the whole cells its span grows by |
95
+ | `GridTile` | interface | An item as the grid draws it: its box, and the offset a dragged item is drawn at |
96
+ | `GridTransfer` | interface | The hand-over of a body drag released over another grid: the item, the cell it lands in there and that grid's root element |
97
+ | `ResizeEdge` | enum | The edge or corner that a resize pulls |
98
+ | `startExternalDrag` | function | Drags an item from outside every grid, such as a palette entry. Previews it on the grid under the pointer, passes over a grid a refusal names for it, and passes the cell it lands on, and that grid's root element, to a drop callback |
99
+ | `useGridLayout` | composable | Places items on a grid. Previews and commits the moves and resizes that a pointer makes, keeps a body drag's other items in place while another grid previews it, and steps an item from the keyboard |
85
100
 
86
101
  ## <a name="license">⚖️ License</a>
87
102
 
@@ -0,0 +1,119 @@
1
+ import { ComputedRef, MaybeRefOrGetter, ShallowRef } from "vue";
2
+ interface GridCell {
3
+ h: number;
4
+ w: number;
5
+ x: number;
6
+ y: number;
7
+ }
8
+ interface GridBlock extends GridCell {
9
+ id: string;
10
+ }
11
+ interface GridItem extends GridBlock {
12
+ isAutoHeight: boolean;
13
+ }
14
+ interface GridGeometry {
15
+ height: number;
16
+ left: number;
17
+ top: number;
18
+ width: number;
19
+ }
20
+ interface GridPlaceholder {
21
+ geometry: GridGeometry;
22
+ isRefused: boolean;
23
+ }
24
+ interface GridStep {
25
+ dh?: number;
26
+ dw?: number;
27
+ dx?: number;
28
+ dy?: number;
29
+ }
30
+ interface GridPoint {
31
+ x: number;
32
+ y: number;
33
+ }
34
+ interface GridTile<T extends GridItem = GridItem> {
35
+ geometry: GridGeometry;
36
+ isDragged: boolean;
37
+ item: T;
38
+ offset: GridPoint;
39
+ }
40
+ export declare enum ResizeEdge {
41
+ East = "East",
42
+ North = "North",
43
+ NorthEast = "NorthEast",
44
+ NorthWest = "NorthWest",
45
+ South = "South",
46
+ SouthEast = "SouthEast",
47
+ SouthWest = "SouthWest",
48
+ West = "West"
49
+ }
50
+ interface GridLayout<T extends GridItem = GridItem> {
51
+ gridHeight: ComputedRef<number>;
52
+ placeholder: ComputedRef<GridPlaceholder | undefined>;
53
+ reportContentHeight: (id: string, contentHeight: number) => void;
54
+ startGesture: (event: PointerEvent, item: T, edge?: ResizeEdge) => void;
55
+ stepItem: (id: string, step: GridStep) => boolean;
56
+ tiles: ComputedRef<GridTile<T>[]>;
57
+ }
58
+ export declare enum CollisionMode {
59
+ Prevent = "Prevent",
60
+ Push = "Push",
61
+ Swap = "Swap"
62
+ }
63
+ export declare enum CompactType {
64
+ Horizontal = "Horizontal",
65
+ None = "None",
66
+ Vertical = "Vertical"
67
+ }
68
+ interface GridCommit {
69
+ changes: GridBlock[];
70
+ }
71
+ type GridRefusal = (item: GridItem, target: HTMLElement) => boolean;
72
+ interface GridSpacing {
73
+ gap: number;
74
+ padding: number;
75
+ }
76
+ interface GridTransfer<T extends GridItem = GridItem> {
77
+ cell: GridCell;
78
+ item: T;
79
+ target: HTMLElement;
80
+ }
81
+ interface GridLayoutOptions<T extends GridItem = GridItem> {
82
+ checkIsRefused?: GridRefusal;
83
+ checkIsSolid?: (item: T) => boolean;
84
+ collision: CollisionMode;
85
+ columnNumber: number;
86
+ compactType: CompactType;
87
+ dragStartDistance: number;
88
+ isEditable: boolean;
89
+ items: T[];
90
+ onCommit: (commit: GridCommit) => void;
91
+ onTransfer?: (transfer: GridTransfer<T>) => void;
92
+ rowHeight: number;
93
+ spacing: GridSpacing;
94
+ }
95
+ export declare const useGridLayout: <T extends GridItem>(root: Readonly<ShallowRef<HTMLElement | null>>, options: MaybeRefOrGetter<GridLayoutOptions<T>>) => GridLayout<T>;
96
+ interface MountedGrid {
97
+ accept: (item: GridItem, point: GridPoint) => GridCell | undefined;
98
+ clearPreview: () => void;
99
+ element: HTMLElement;
100
+ preview: (item: GridItem, point: GridPoint) => boolean;
101
+ }
102
+ interface GridGesture<T extends GridBlock = GridBlock> {
103
+ cell?: GridBlock;
104
+ edge?: ResizeEdge;
105
+ element: Element;
106
+ isStarted: boolean;
107
+ offset: GridPoint;
108
+ origin: T;
109
+ pointerId: number;
110
+ start: GridPoint;
111
+ transfer?: MountedGrid;
112
+ }
113
+ export declare const checkChangesHeight: (edge: ResizeEdge) => boolean;
114
+ export declare const getFirstFreeCell: (layout: GridBlock[], columnNumber: number, span: {
115
+ h: number;
116
+ w: number;
117
+ }) => GridCell;
118
+ export declare const startExternalDrag: (event: PointerEvent, item: GridItem, onDrop: (cell: GridCell, target: HTMLElement) => void, checkIsRefused?: GridRefusal) => void;
119
+ export type { GridBlock, GridCell, GridCommit, GridGeometry, GridGesture, GridItem, GridLayout, GridLayoutOptions, GridPlaceholder, GridPoint, GridRefusal, GridSpacing, GridStep, GridTile, GridTransfer };
package/dist/index.js ADDED
@@ -0,0 +1,599 @@
1
+ import { checkIsNestedControl } from "@esposter/shared";
2
+ import { computed, onMounted, onUnmounted, ref, shallowRef, toValue, watch } from "vue";
3
+ // src/models/ResizeEdge.ts
4
+ let ResizeEdge = /* @__PURE__ */ function(ResizeEdge) {
5
+ ResizeEdge["East"] = "East";
6
+ ResizeEdge["North"] = "North";
7
+ ResizeEdge["NorthEast"] = "NorthEast";
8
+ ResizeEdge["NorthWest"] = "NorthWest";
9
+ ResizeEdge["South"] = "South";
10
+ ResizeEdge["SouthEast"] = "SouthEast";
11
+ ResizeEdge["SouthWest"] = "SouthWest";
12
+ ResizeEdge["West"] = "West";
13
+ return ResizeEdge;
14
+ }({});
15
+ // src/placement/checkChangesHeight.ts
16
+ const HEIGHT_EDGES = /* @__PURE__ */ new Set([
17
+ "North",
18
+ "NorthEast",
19
+ "NorthWest",
20
+ "South",
21
+ "SouthEast",
22
+ "SouthWest"
23
+ ]);
24
+ const checkChangesHeight = (edge) => HEIGHT_EDGES.has(edge);
25
+ // src/placement/checkIsSameCell.ts
26
+ const checkIsSameCell = (cell, other) => cell.h === other.h && cell.w === other.w && cell.x === other.x && cell.y === other.y;
27
+ // src/placement/clampCell.ts
28
+ const clampCell = (cell, columnNumber) => {
29
+ const h = Math.max(1, cell.h);
30
+ const w = Math.max(1, Math.min(cell.w, columnNumber));
31
+ const x = Math.min(Math.max(cell.x, 0), columnNumber - w);
32
+ return {
33
+ ...cell,
34
+ h,
35
+ w,
36
+ x,
37
+ y: Math.max(cell.y, 0)
38
+ };
39
+ };
40
+ // src/models/CompactType.ts
41
+ let CompactType = /* @__PURE__ */ function(CompactType) {
42
+ CompactType["Horizontal"] = "Horizontal";
43
+ CompactType["None"] = "None";
44
+ CompactType["Vertical"] = "Vertical";
45
+ return CompactType;
46
+ }({});
47
+ // src/placement/checkIsColliding.ts
48
+ const checkIsColliding = (item, other) => item.id !== other.id && item.x < other.x + other.w && item.x + item.w > other.x && item.y < other.y + other.h && item.y + item.h > other.y;
49
+ // src/placement/compactLayout.ts
50
+ const compactLayout = (layout, columnNumber, compactType, solidIds = /* @__PURE__ */ new Set()) => {
51
+ const copies = layout.map((item) => ({ ...item }));
52
+ const isHorizontal = compactType === "Horizontal";
53
+ const axis = isHorizontal ? "x" : "y";
54
+ const crossAxis = isHorizontal ? "y" : "x";
55
+ const placedItems = [];
56
+ const checkIsBlocked = (candidate) => placedItems.some((placedItem) => checkIsColliding(candidate, placedItem));
57
+ const riseAlongAxis = (item) => {
58
+ while (item[axis] > 0 && !checkIsBlocked({
59
+ ...item,
60
+ [axis]: item[axis] - 1
61
+ })) item[axis] -= 1;
62
+ };
63
+ const pushAlongAxis = (item) => {
64
+ if (isHorizontal && item.x + item.w + 1 > columnNumber) {
65
+ item.x = columnNumber - item.w;
66
+ item.y += 1;
67
+ riseAlongAxis(item);
68
+ } else item[axis] += 1;
69
+ };
70
+ const sortedItems = copies.toSorted((firstItem, secondItem) => firstItem[axis] - secondItem[axis] || firstItem[crossAxis] - secondItem[crossAxis]);
71
+ const placementOrder = [...sortedItems.filter((item) => solidIds.has(item.id)), ...sortedItems.filter((item) => !solidIds.has(item.id))];
72
+ for (const item of placementOrder) {
73
+ if (compactType !== "None" && !solidIds.has(item.id)) riseAlongAxis(item);
74
+ while (checkIsBlocked(item)) pushAlongAxis(item);
75
+ placedItems.push(item);
76
+ }
77
+ return sortedItems;
78
+ };
79
+ // src/placement/fitLayout.ts
80
+ const fitLayout = (layout, columnNumber, compactType, solidIds) => compactLayout(layout.map((item) => clampCell(item, columnNumber)), columnNumber, compactType, solidIds);
81
+ // src/placement/getCellPosition.ts
82
+ const getCellPosition = (index, pitch, padding) => Math.round(index * pitch + padding);
83
+ // src/placement/getCellSize.ts
84
+ const getCellSize = (span, pitch, gap) => span * pitch - gap;
85
+ // src/placement/getCellSpan.ts
86
+ const getCellSpan = (size, pitch, gap) => Math.max(1, Math.ceil((size + gap) / pitch));
87
+ // src/placement/getColumnPitch.ts
88
+ const getColumnPitch = (width, columnNumber, { gap, padding }) => (width - 2 * padding + gap) / columnNumber;
89
+ // src/placement/getGestureCell.ts
90
+ const ResizeEdgeSidesMap = {
91
+ ["East"]: {
92
+ isEast: true,
93
+ isNorth: false,
94
+ isSouth: false,
95
+ isWest: false
96
+ },
97
+ ["North"]: {
98
+ isEast: false,
99
+ isNorth: true,
100
+ isSouth: false,
101
+ isWest: false
102
+ },
103
+ ["NorthEast"]: {
104
+ isEast: true,
105
+ isNorth: true,
106
+ isSouth: false,
107
+ isWest: false
108
+ },
109
+ ["NorthWest"]: {
110
+ isEast: false,
111
+ isNorth: true,
112
+ isSouth: false,
113
+ isWest: true
114
+ },
115
+ ["South"]: {
116
+ isEast: false,
117
+ isNorth: false,
118
+ isSouth: true,
119
+ isWest: false
120
+ },
121
+ ["SouthEast"]: {
122
+ isEast: true,
123
+ isNorth: false,
124
+ isSouth: true,
125
+ isWest: false
126
+ },
127
+ ["SouthWest"]: {
128
+ isEast: false,
129
+ isNorth: false,
130
+ isSouth: true,
131
+ isWest: true
132
+ },
133
+ ["West"]: {
134
+ isEast: false,
135
+ isNorth: false,
136
+ isSouth: false,
137
+ isWest: true
138
+ }
139
+ };
140
+ const getGestureCell = ({ columnNumber, columnPitch, edge, offset, origin, rowPitch }) => {
141
+ const columnDelta = Math.round(offset.x / columnPitch);
142
+ const rowDelta = Math.round(offset.y / rowPitch);
143
+ if (!edge) {
144
+ const x = Math.min(Math.max(origin.x + columnDelta, 0), columnNumber - origin.w);
145
+ const y = Math.max(0, origin.y + rowDelta);
146
+ return {
147
+ h: origin.h,
148
+ id: origin.id,
149
+ w: origin.w,
150
+ x,
151
+ y
152
+ };
153
+ }
154
+ const { isEast, isNorth, isSouth, isWest } = ResizeEdgeSidesMap[edge];
155
+ const right = origin.x + origin.w;
156
+ const bottom = origin.y + origin.h;
157
+ const leftX = Math.min(Math.max(origin.x + columnDelta, 0), right - 1);
158
+ const eastWidth = Math.min(Math.max(1, origin.w + columnDelta), columnNumber - origin.x);
159
+ const topY = Math.min(Math.max(origin.y + rowDelta, 0), bottom - 1);
160
+ const southHeight = Math.max(1, origin.h + rowDelta);
161
+ const x = isWest ? leftX : origin.x;
162
+ const widthFromRight = isEast ? eastWidth : origin.w;
163
+ const w = isWest ? right - leftX : widthFromRight;
164
+ const y = isNorth ? topY : origin.y;
165
+ const heightFromBottom = isSouth ? southHeight : origin.h;
166
+ return {
167
+ h: isNorth ? bottom - topY : heightFromBottom,
168
+ id: origin.id,
169
+ w,
170
+ x,
171
+ y
172
+ };
173
+ };
174
+ // src/placement/getLayoutBottom.ts
175
+ const getLayoutBottom = (layout) => Math.max(0, ...layout.map((item) => item.y + item.h));
176
+ // src/models/CollisionMode.ts
177
+ let CollisionMode = /* @__PURE__ */ function(CollisionMode) {
178
+ CollisionMode["Prevent"] = "Prevent";
179
+ CollisionMode["Push"] = "Push";
180
+ CollisionMode["Swap"] = "Swap";
181
+ return CollisionMode;
182
+ }({});
183
+ // src/placement/moveItem.ts
184
+ const moveItem = (layout, target) => {
185
+ const movedLayout = layout.map((item) => item.id === target.id ? {
186
+ ...item,
187
+ ...target
188
+ } : { ...item });
189
+ const pushedIds = /* @__PURE__ */ new Set([target.id]);
190
+ const pushBelow = (pusher) => {
191
+ for (const item of movedLayout) {
192
+ if (pushedIds.has(item.id) || !checkIsColliding(pusher, item)) continue;
193
+ if (item.y < pusher.y && pusher.y - item.y > item.h * .25) continue;
194
+ pushedIds.add(item.id);
195
+ item.y = pusher.y + pusher.h;
196
+ pushBelow(item);
197
+ }
198
+ };
199
+ const movedItem = movedLayout.find((item) => item.id === target.id);
200
+ if (movedItem) pushBelow(movedItem);
201
+ return movedLayout;
202
+ };
203
+ // src/placement/resolveMove.ts
204
+ const resolveMove = (layout, target, collision, columnNumber, solidIds = /* @__PURE__ */ new Set()) => {
205
+ const landedItems = layout.filter((item) => item.id !== target.id && checkIsColliding(target, item));
206
+ const [landedItem] = landedItems;
207
+ const movedItem = layout.find((item) => item.id === target.id);
208
+ if (collision === "Prevent" && landedItems.length > 0) return void 0;
209
+ if (landedItems.some((item) => solidIds.has(item.id))) return void 0;
210
+ const isMove = movedItem !== void 0 && movedItem.w === target.w && movedItem.h === target.h;
211
+ const resolvedLayout = collision === "Swap" && isMove && landedItems.length === 1 && landedItem && movedItem && movedItem.x + landedItem.w <= columnNumber && landedItem.x + movedItem.w <= columnNumber ? moveItem(layout.map((item) => item.id === landedItem.id ? {
212
+ ...item,
213
+ x: movedItem.x,
214
+ y: movedItem.y
215
+ } : { ...item }), {
216
+ ...target,
217
+ x: landedItem.x,
218
+ y: landedItem.y
219
+ }) : moveItem(layout, target);
220
+ return layout.some((item) => {
221
+ const resolvedItem = resolvedLayout.find(({ id }) => id === item.id);
222
+ return solidIds.has(item.id) && item.id !== target.id && resolvedItem !== void 0 && !checkIsSameCell(resolvedItem, item);
223
+ }) ? void 0 : resolvedLayout;
224
+ };
225
+ // src/placement/placeMove.ts
226
+ const placeMove = (layout, target, { collision, columnNumber, compactType }, solidIds) => {
227
+ const resolvedLayout = resolveMove(layout, target, collision, columnNumber, solidIds);
228
+ return resolvedLayout && compactLayout(resolvedLayout, columnNumber, compactType, solidIds);
229
+ };
230
+ // src/services/mountedGrids.ts
231
+ const mountedGrids = /* @__PURE__ */ new Map();
232
+ // src/services/findGridRoot.ts
233
+ const findGridRoot = (element) => {
234
+ let current = element;
235
+ while (current && !mountedGrids.has(current)) current = current.parentElement;
236
+ return current ?? void 0;
237
+ };
238
+ // src/services/findGridAt.ts
239
+ const findGridAt = (point, element) => {
240
+ const hit = window.document.elementsFromPoint(point.x, point.y).find((candidate) => !element.contains(candidate));
241
+ const root = findGridRoot(hit ?? null);
242
+ return root ? mountedGrids.get(root) : void 0;
243
+ };
244
+ // src/composables/useGridLayout.ts
245
+ const useGridLayout = (root, options) => {
246
+ const getOptions = () => toValue(options);
247
+ const solidIds = computed(() => {
248
+ const { checkIsSolid, items } = getOptions();
249
+ return new Set(checkIsSolid ? items.filter((item) => checkIsSolid(item)).map(({ id }) => id) : []);
250
+ });
251
+ const width = ref(0);
252
+ const gesture = shallowRef();
253
+ const gesturePreview = shallowRef();
254
+ const externalPreview = shallowRef();
255
+ const activePreview = computed(() => gesturePreview.value ?? externalPreview.value);
256
+ const columnPitch = computed(() => getColumnPitch(width.value, getOptions().columnNumber, getOptions().spacing));
257
+ const rowPitch = computed(() => getOptions().rowHeight + getOptions().spacing.gap);
258
+ const layout = computed(() => fitLayout(getOptions().items, getOptions().columnNumber, getOptions().compactType, solidIds.value));
259
+ const savedItemMap = computed(() => new Map(getOptions().items.map((item) => [item.id, item])));
260
+ const previewItemMap = computed(() => new Map((activePreview.value?.layout ?? []).map((item) => [item.id, item])));
261
+ const draggedGesture = computed(() => gesture.value?.isStarted && !gesture.value.edge ? gesture.value : void 0);
262
+ const getGeometry = (cell) => {
263
+ const { gap, padding } = getOptions().spacing;
264
+ return {
265
+ height: getCellSize(cell.h, rowPitch.value, gap),
266
+ left: getCellPosition(cell.x, columnPitch.value, padding),
267
+ top: getCellPosition(cell.y, rowPitch.value, padding),
268
+ width: getCellSize(cell.w, columnPitch.value, gap)
269
+ };
270
+ };
271
+ const tiles = computed(() => {
272
+ if (width.value === 0) return [];
273
+ return layout.value.map((item) => {
274
+ const dragged = draggedGesture.value?.origin.id === item.id ? draggedGesture.value : void 0;
275
+ const cell = dragged ? item : previewItemMap.value.get(item.id) ?? item;
276
+ return {
277
+ geometry: getGeometry(cell),
278
+ isDragged: dragged !== void 0,
279
+ item,
280
+ offset: dragged?.offset ?? {
281
+ x: 0,
282
+ y: 0
283
+ }
284
+ };
285
+ });
286
+ });
287
+ const placeholder = computed(() => {
288
+ if (!activePreview.value) return void 0;
289
+ const { cell, isRefused } = activePreview.value;
290
+ return {
291
+ geometry: getGeometry(cell),
292
+ isRefused
293
+ };
294
+ });
295
+ const gridHeight = computed(() => {
296
+ const { gap, padding } = getOptions().spacing;
297
+ const layoutBottom = getLayoutBottom(activePreview.value?.layout ?? layout.value);
298
+ return Math.max(0, getCellSize(layoutBottom, rowPitch.value, gap)) + 2 * padding;
299
+ });
300
+ const clearPreview = () => {
301
+ externalPreview.value = void 0;
302
+ };
303
+ const resetGesture = () => {
304
+ gesture.value?.transfer?.clearPreview();
305
+ gesture.value = void 0;
306
+ gesturePreview.value = void 0;
307
+ clearPreview();
308
+ };
309
+ watch(layout, () => {
310
+ resetGesture();
311
+ });
312
+ const getPreview = (cell, landingLayout) => {
313
+ const landedLayout = placeMove(landingLayout, cell, getOptions(), solidIds.value);
314
+ if (!landedLayout) return {
315
+ cell,
316
+ isRefused: true,
317
+ layout: layout.value
318
+ };
319
+ return {
320
+ cell: landedLayout.find(({ id }) => id === cell.id) ?? cell,
321
+ isRefused: false,
322
+ layout: landedLayout
323
+ };
324
+ };
325
+ const getDropPreview = (item, point) => {
326
+ const element = root.value;
327
+ if (!element || !getOptions().isEditable || getOptions().checkIsRefused?.(item, element)) return void 0;
328
+ const { left, top } = element.getBoundingClientRect();
329
+ const { padding } = getOptions().spacing;
330
+ const offset = {
331
+ x: point.x - left - padding,
332
+ y: point.y - top - padding
333
+ };
334
+ const columnIndex = Math.floor(offset.x / columnPitch.value);
335
+ const rowIndex = Math.floor(offset.y / rowPitch.value);
336
+ const cell = clampCell({
337
+ ...item,
338
+ x: columnIndex,
339
+ y: rowIndex
340
+ }, getOptions().columnNumber);
341
+ return getPreview(cell, [...layout.value, cell]);
342
+ };
343
+ const checkIsTransferable = (activeGesture) => getOptions().onTransfer !== void 0 && !activeGesture.edge;
344
+ const findTransfer = (activeGesture, point) => {
345
+ if (!checkIsTransferable(activeGesture)) return void 0;
346
+ const grid = findGridAt(point, activeGesture.element);
347
+ return grid?.element === root.value ? void 0 : grid;
348
+ };
349
+ const startGesture = (event, item, pressedEdge) => {
350
+ if (event.button !== 0) return;
351
+ if (!getOptions().isEditable || checkIsNestedControl(event)) return;
352
+ const edge = event.pointerType === "touch" ? void 0 : pressedEdge;
353
+ if (item.isAutoHeight && edge && checkChangesHeight(edge)) return;
354
+ if (gesture.value && gesture.value.pointerId !== event.pointerId) return;
355
+ if (!(event.currentTarget instanceof Element) || !(event.target instanceof Element)) return;
356
+ if (findGridRoot(event.target) !== root.value) return;
357
+ gesture.value = {
358
+ edge,
359
+ element: event.currentTarget,
360
+ isStarted: false,
361
+ offset: {
362
+ x: 0,
363
+ y: 0
364
+ },
365
+ origin: item,
366
+ pointerId: event.pointerId,
367
+ start: {
368
+ x: event.clientX,
369
+ y: event.clientY
370
+ }
371
+ };
372
+ };
373
+ const handlePointerMove = (event) => {
374
+ const activeGesture = gesture.value;
375
+ if (!activeGesture || event.pointerId !== activeGesture.pointerId) return;
376
+ if (!activeGesture.isStarted && event.buttons === 0) {
377
+ resetGesture();
378
+ return;
379
+ }
380
+ const offset = {
381
+ x: event.clientX - activeGesture.start.x,
382
+ y: event.clientY - activeGesture.start.y
383
+ };
384
+ if (!activeGesture.isStarted && Math.hypot(offset.x, offset.y) < getOptions().dragStartDistance) return;
385
+ if (!activeGesture.isStarted) activeGesture.element.setPointerCapture(event.pointerId);
386
+ const cell = getGestureCell({
387
+ columnNumber: getOptions().columnNumber,
388
+ columnPitch: columnPitch.value,
389
+ edge: activeGesture.edge,
390
+ offset,
391
+ origin: activeGesture.origin,
392
+ rowPitch: rowPitch.value
393
+ });
394
+ const point = {
395
+ x: event.clientX,
396
+ y: event.clientY
397
+ };
398
+ const isCellChanged = !activeGesture.cell || !checkIsSameCell(cell, activeGesture.cell);
399
+ const transfer = findTransfer(activeGesture, point);
400
+ if (activeGesture.transfer !== transfer) activeGesture.transfer?.clearPreview();
401
+ gesture.value = {
402
+ ...activeGesture,
403
+ cell,
404
+ isStarted: true,
405
+ offset,
406
+ transfer
407
+ };
408
+ if (Boolean(transfer?.preview(activeGesture.origin, point))) gesturePreview.value = void 0;
409
+ else if (isCellChanged || !gesturePreview.value) gesturePreview.value = getPreview(cell, layout.value);
410
+ };
411
+ const getChangedCells = (changedLayout) => changedLayout.flatMap((item) => {
412
+ const savedItem = savedItemMap.value.get(item.id);
413
+ return !savedItem || !checkIsSameCell(item, savedItem) ? [{
414
+ h: item.h,
415
+ id: item.id,
416
+ w: item.w,
417
+ x: item.x,
418
+ y: item.y
419
+ }] : [];
420
+ });
421
+ const accept = (item, point) => {
422
+ const preview = getDropPreview(item, point);
423
+ if (!preview || preview.isRefused) return void 0;
424
+ const changes = getChangedCells(preview.layout).filter(({ id }) => id !== item.id);
425
+ if (changes.length > 0) getOptions().onCommit({ changes });
426
+ const { h, w, x, y } = preview.cell;
427
+ return {
428
+ h,
429
+ w,
430
+ x,
431
+ y
432
+ };
433
+ };
434
+ const stepItem = (id, step) => {
435
+ const item = layout.value.find((other) => other.id === id);
436
+ if (!getOptions().isEditable || !item) return false;
437
+ const { dh = 0, dw = 0, dx = 0, dy = 0 } = step;
438
+ if (item.isAutoHeight && dh !== 0) return false;
439
+ const target = {
440
+ ...item,
441
+ h: Math.max(1, item.h + dh),
442
+ w: Math.max(1, item.w + dw),
443
+ x: item.x + dx,
444
+ y: item.y + dy
445
+ };
446
+ if (target.x < 0 || target.y < 0 || target.x + target.w > getOptions().columnNumber || checkIsSameCell(target, item)) return false;
447
+ const preview = getPreview(target, layout.value);
448
+ const changes = preview.isRefused ? [] : getChangedCells(preview.layout);
449
+ if (changes.length === 0) return false;
450
+ getOptions().onCommit({ changes });
451
+ return true;
452
+ };
453
+ const handlePointerUp = (event) => {
454
+ const activeGesture = gesture.value;
455
+ if (!activeGesture || event.pointerId !== activeGesture.pointerId) return;
456
+ const point = {
457
+ x: event.clientX,
458
+ y: event.clientY
459
+ };
460
+ const preview = gesturePreview.value;
461
+ const changes = preview && !preview.isRefused ? getChangedCells(preview.layout) : [];
462
+ const transfer = findTransfer(activeGesture, point);
463
+ resetGesture();
464
+ if (!transfer) {
465
+ if (changes.length > 0) getOptions().onCommit({ changes });
466
+ return;
467
+ }
468
+ const cell = transfer.accept(activeGesture.origin, point);
469
+ if (cell) getOptions().onTransfer?.({
470
+ cell,
471
+ item: activeGesture.origin,
472
+ target: transfer.element
473
+ });
474
+ };
475
+ const reportContentHeight = (id, contentHeight) => {
476
+ const savedItem = savedItemMap.value.get(id);
477
+ if (!getOptions().isEditable || !savedItem?.isAutoHeight) return;
478
+ const h = getCellSpan(contentHeight, rowPitch.value, getOptions().spacing.gap);
479
+ if (h === savedItem.h) return;
480
+ const otherItems = getOptions().items.filter((item) => item.id !== id);
481
+ const changes = getChangedCells(fitLayout([...otherItems, {
482
+ ...savedItem,
483
+ h
484
+ }], getOptions().columnNumber, getOptions().compactType, solidIds.value));
485
+ if (changes.length > 0) getOptions().onCommit({ changes });
486
+ };
487
+ const handlePointerCancel = (event) => {
488
+ if (event.pointerId === gesture.value?.pointerId) resetGesture();
489
+ };
490
+ const attached = shallowRef();
491
+ const previewDrop = (item, point) => {
492
+ const preview = getDropPreview(item, point);
493
+ const current = externalPreview.value;
494
+ if (preview && current?.cell.id === preview.cell.id && checkIsSameCell(preview.cell, current.cell)) return true;
495
+ externalPreview.value = preview;
496
+ return preview !== void 0;
497
+ };
498
+ onMounted(() => {
499
+ const element = root.value;
500
+ if (!element) return;
501
+ const controller = new AbortController();
502
+ const { signal } = controller;
503
+ const observer = new ResizeObserver(([entry]) => {
504
+ width.value = entry?.contentRect.width ?? 0;
505
+ });
506
+ observer.observe(element);
507
+ element.addEventListener("pointermove", handlePointerMove, { signal });
508
+ element.addEventListener("pointerup", handlePointerUp, { signal });
509
+ element.addEventListener("pointercancel", handlePointerCancel, { signal });
510
+ mountedGrids.set(element, {
511
+ accept,
512
+ clearPreview,
513
+ element,
514
+ preview: previewDrop
515
+ });
516
+ attached.value = {
517
+ controller,
518
+ element,
519
+ observer
520
+ };
521
+ });
522
+ onUnmounted(() => {
523
+ resetGesture();
524
+ if (!attached.value) return;
525
+ const { controller, element, observer } = attached.value;
526
+ observer.disconnect();
527
+ mountedGrids.delete(element);
528
+ controller.abort();
529
+ });
530
+ return {
531
+ gridHeight,
532
+ placeholder,
533
+ reportContentHeight,
534
+ startGesture,
535
+ stepItem,
536
+ tiles
537
+ };
538
+ };
539
+ // src/placement/getFirstFreeCell.ts
540
+ const getFirstFreeCell = (layout, columnNumber, span) => {
541
+ const { h, w } = clampCell({
542
+ h: span.h,
543
+ w: span.w,
544
+ x: 0,
545
+ y: 0
546
+ }, columnNumber);
547
+ for (let y = 0;; y += 1) for (let x = 0; x <= columnNumber - w; x += 1) {
548
+ const cell = {
549
+ h,
550
+ w,
551
+ x,
552
+ y
553
+ };
554
+ if (!layout.some((item) => checkIsColliding(cell, item))) return cell;
555
+ }
556
+ };
557
+ // src/services/startExternalDrag.ts
558
+ const startExternalDrag = (event, item, onDrop, checkIsRefused) => {
559
+ if (event.button !== 0) return;
560
+ if (!(event.currentTarget instanceof HTMLElement)) return;
561
+ const element = event.currentTarget;
562
+ const { pointerId } = event;
563
+ const checkIsGridRefused = (grid) => Boolean(checkIsRefused?.(item, grid.element));
564
+ element.setPointerCapture(pointerId);
565
+ const controller = new AbortController();
566
+ const { signal } = controller;
567
+ let lastGrid;
568
+ element.addEventListener("pointermove", (moveEvent) => {
569
+ if (moveEvent.pointerId !== pointerId) return;
570
+ const point = {
571
+ x: moveEvent.clientX,
572
+ y: moveEvent.clientY
573
+ };
574
+ const grid = findGridAt(point, element);
575
+ if (grid !== lastGrid) {
576
+ lastGrid?.clearPreview();
577
+ lastGrid = grid;
578
+ }
579
+ if (grid && !checkIsGridRefused(grid)) grid.preview(item, point);
580
+ }, { signal });
581
+ element.addEventListener("pointerup", (releaseEvent) => {
582
+ if (releaseEvent.pointerId !== pointerId) return;
583
+ controller.abort();
584
+ lastGrid?.clearPreview();
585
+ const point = {
586
+ x: releaseEvent.clientX,
587
+ y: releaseEvent.clientY
588
+ };
589
+ const grid = findGridAt(point, element);
590
+ const cell = grid && !checkIsGridRefused(grid) ? grid.accept(item, point) : void 0;
591
+ if (grid && cell) onDrop(cell, grid.element);
592
+ }, { signal });
593
+ element.addEventListener("pointercancel", (cancelEvent) => {
594
+ if (cancelEvent.pointerId !== pointerId) return;
595
+ controller.abort();
596
+ lastGrid?.clearPreview();
597
+ }, { signal });
598
+ };
599
+ export { CollisionMode, CompactType, ResizeEdge, checkChangesHeight, getFirstFreeCell, startExternalDrag, useGridLayout };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-grid-layout-headless",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "description": "A headless grid: the placement of items on a grid of cells, and the pointer gestures that move and resize them, with no styling.",
5
5
  "keywords": [
6
6
  "dashboard",
@@ -44,16 +44,16 @@
44
44
  "typecheck": "tsrs --fast"
45
45
  },
46
46
  "dependencies": {
47
- "@esposter/shared": "4.4.0"
47
+ "@esposter/shared": "4.5.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@esposter/configuration": "4.4.0",
50
+ "@esposter/configuration": "4.5.0",
51
51
  "@vue/test-utils": "^2.5.1",
52
52
  "happy-dom": "^21.0.4",
53
- "tsdown": "0.23.2"
53
+ "tsdown": "^0.23.5"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "vue": "^3.5.44"
57
57
  },
58
- "gitHead": "e1a416c4b91da69cc2aa259b50a4d656f204d272"
58
+ "gitHead": "e30c001f3b4b15693e75fb53092d62a97ade4d2b"
59
59
  }