@wordpress/grid 0.10.0 → 0.11.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.
Files changed (114) hide show
  1. package/README.md +35 -14
  2. package/build/dashboard-grid/grid-item.cjs +232 -295
  3. package/build/dashboard-grid/grid-item.cjs.map +1 -7
  4. package/build/dashboard-grid/index.cjs +525 -632
  5. package/build/dashboard-grid/index.cjs.map +1 -7
  6. package/build/dashboard-grid/resolve-fill-widths.cjs +159 -203
  7. package/build/dashboard-grid/resolve-fill-widths.cjs.map +1 -7
  8. package/build/dashboard-grid/types.cjs +4 -18
  9. package/build/dashboard-lanes/index.cjs +494 -576
  10. package/build/dashboard-lanes/index.cjs.map +1 -7
  11. package/build/dashboard-lanes/lane-placement.cjs +77 -100
  12. package/build/dashboard-lanes/lane-placement.cjs.map +1 -7
  13. package/build/dashboard-lanes/lanes-item.cjs +222 -278
  14. package/build/dashboard-lanes/lanes-item.cjs.map +1 -7
  15. package/build/dashboard-lanes/types.cjs +4 -18
  16. package/build/dashboard-lanes/use-lane-placement.cjs +172 -198
  17. package/build/dashboard-lanes/use-lane-placement.cjs.map +1 -7
  18. package/build/index.cjs +16 -31
  19. package/build/shared/array-move-with-pinned.cjs +29 -45
  20. package/build/shared/array-move-with-pinned.cjs.map +1 -7
  21. package/build/shared/column-policy.cjs +58 -0
  22. package/build/shared/column-policy.cjs.map +1 -0
  23. package/build/shared/drag-overlay-drop-animation.cjs +40 -66
  24. package/build/shared/drag-overlay-drop-animation.cjs.map +1 -7
  25. package/build/shared/grid-item-key.cjs +12 -29
  26. package/build/shared/grid-item-key.cjs.map +1 -7
  27. package/build/shared/grid-overlay.cjs +163 -164
  28. package/build/shared/grid-overlay.cjs.map +1 -7
  29. package/build/shared/item-exit-overlay.cjs +132 -134
  30. package/build/shared/item-exit-overlay.cjs.map +1 -7
  31. package/build/shared/resize-handle.cjs +213 -197
  32. package/build/shared/resize-handle.cjs.map +1 -7
  33. package/build/shared/resize-snap.cjs +116 -121
  34. package/build/shared/resize-snap.cjs.map +1 -7
  35. package/build/shared/types.cjs +4 -18
  36. package/build/shared/use-item-exit-animation.cjs +96 -143
  37. package/build/shared/use-item-exit-animation.cjs.map +1 -7
  38. package/build/shared/use-layout-shift-animation.cjs +121 -150
  39. package/build/shared/use-layout-shift-animation.cjs.map +1 -7
  40. package/build/shared/use-span-bounds.cjs +65 -79
  41. package/build/shared/use-span-bounds.cjs.map +1 -7
  42. package/build-module/dashboard-grid/grid-item.mjs +209 -265
  43. package/build-module/dashboard-grid/grid-item.mjs.map +1 -7
  44. package/build-module/dashboard-grid/index.mjs +502 -623
  45. package/build-module/dashboard-grid/index.mjs.map +1 -7
  46. package/build-module/dashboard-grid/resolve-fill-widths.mjs +155 -179
  47. package/build-module/dashboard-grid/resolve-fill-widths.mjs.map +1 -7
  48. package/build-module/dashboard-grid/types.mjs +0 -1
  49. package/build-module/dashboard-lanes/index.mjs +470 -567
  50. package/build-module/dashboard-lanes/index.mjs.map +1 -7
  51. package/build-module/dashboard-lanes/lane-placement.mjs +73 -76
  52. package/build-module/dashboard-lanes/lane-placement.mjs.map +1 -7
  53. package/build-module/dashboard-lanes/lanes-item.mjs +199 -248
  54. package/build-module/dashboard-lanes/lanes-item.mjs.map +1 -7
  55. package/build-module/dashboard-lanes/types.mjs +0 -1
  56. package/build-module/dashboard-lanes/use-lane-placement.mjs +167 -173
  57. package/build-module/dashboard-lanes/use-lane-placement.mjs.map +1 -7
  58. package/build-module/index.mjs +1 -6
  59. package/build-module/shared/array-move-with-pinned.mjs +25 -21
  60. package/build-module/shared/array-move-with-pinned.mjs.map +1 -7
  61. package/build-module/shared/column-policy.mjs +52 -0
  62. package/build-module/shared/column-policy.mjs.map +1 -0
  63. package/build-module/shared/drag-overlay-drop-animation.mjs +35 -44
  64. package/build-module/shared/drag-overlay-drop-animation.mjs.map +1 -7
  65. package/build-module/shared/grid-item-key.mjs +8 -5
  66. package/build-module/shared/grid-item-key.mjs.map +1 -7
  67. package/build-module/shared/grid-overlay.mjs +143 -136
  68. package/build-module/shared/grid-overlay.mjs.map +1 -7
  69. package/build-module/shared/item-exit-overlay.mjs +128 -110
  70. package/build-module/shared/item-exit-overlay.mjs.map +1 -7
  71. package/build-module/shared/resize-handle.mjs +191 -171
  72. package/build-module/shared/resize-handle.mjs.map +1 -7
  73. package/build-module/shared/resize-snap.mjs +108 -93
  74. package/build-module/shared/resize-snap.mjs.map +1 -7
  75. package/build-module/shared/types.mjs +0 -1
  76. package/build-module/shared/use-item-exit-animation.mjs +92 -124
  77. package/build-module/shared/use-item-exit-animation.mjs.map +1 -7
  78. package/build-module/shared/use-layout-shift-animation.mjs +114 -123
  79. package/build-module/shared/use-layout-shift-animation.mjs.map +1 -7
  80. package/build-module/shared/use-span-bounds.mjs +60 -57
  81. package/build-module/shared/use-span-bounds.mjs.map +1 -7
  82. package/build-types/dashboard-grid/index.d.ts.map +1 -1
  83. package/build-types/dashboard-grid/types.d.ts +9 -5
  84. package/build-types/dashboard-grid/types.d.ts.map +1 -1
  85. package/build-types/dashboard-lanes/index.d.ts.map +1 -1
  86. package/build-types/dashboard-lanes/types.d.ts +9 -5
  87. package/build-types/dashboard-lanes/types.d.ts.map +1 -1
  88. package/build-types/index.d.ts +1 -0
  89. package/build-types/index.d.ts.map +1 -1
  90. package/build-types/shared/column-policy.d.ts +43 -0
  91. package/build-types/shared/column-policy.d.ts.map +1 -0
  92. package/package.json +11 -11
  93. package/src/dashboard-grid/grid-item.tsx +1 -1
  94. package/src/dashboard-grid/index.tsx +11 -12
  95. package/src/dashboard-grid/stories/index.story.tsx +129 -50
  96. package/src/dashboard-grid/test/item-interactions.browser.test.tsx +1 -1
  97. package/src/dashboard-grid/types.ts +9 -5
  98. package/src/dashboard-lanes/index.tsx +11 -11
  99. package/src/dashboard-lanes/lanes-item.tsx +1 -1
  100. package/src/dashboard-lanes/stories/index.story.tsx +124 -28
  101. package/src/dashboard-lanes/test/item-interactions.browser.test.tsx +1 -1
  102. package/src/dashboard-lanes/types.ts +9 -5
  103. package/src/index.ts +1 -0
  104. package/src/shared/column-policy.ts +100 -0
  105. package/src/shared/test/column-policy.test.ts +215 -0
  106. package/src/shared/test/sortable-semantics.browser.test.tsx +122 -0
  107. package/build/dashboard-grid/types.cjs.map +0 -7
  108. package/build/dashboard-lanes/types.cjs.map +0 -7
  109. package/build/index.cjs.map +0 -7
  110. package/build/shared/types.cjs.map +0 -7
  111. package/build-module/dashboard-grid/types.mjs.map +0 -7
  112. package/build-module/dashboard-lanes/types.mjs.map +0 -7
  113. package/build-module/index.mjs.map +0 -7
  114. package/build-module/shared/types.mjs.map +0 -7
@@ -1,643 +1,522 @@
1
- // packages/grid/src/dashboard-grid/index.tsx
2
- import {
3
- DndContext,
4
- DragOverlay,
5
- KeyboardSensor,
6
- PointerSensor,
7
- useSensor,
8
- useSensors
9
- } from "@dnd-kit/core";
10
- import {
11
- SortableContext,
12
- sortableKeyboardCoordinates
13
- } from "@dnd-kit/sortable";
1
+ import { DndContext, DragOverlay, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
2
+ import { SortableContext, sortableKeyboardCoordinates } from "@dnd-kit/sortable";
14
3
  import clsx from "clsx";
15
- import { useResizeObserver, useEvent, useMergeRefs } from "@wordpress/compose";
16
- import {
17
- forwardRef,
18
- useMemo,
19
- Children,
20
- cloneElement,
21
- isValidElement,
22
- useLayoutEffect,
23
- useRef,
24
- useState
25
- } from "@wordpress/element";
4
+ import { useEvent, useMergeRefs, useResizeObserver } from "@wordpress/compose";
5
+ import { Children, cloneElement, forwardRef, isValidElement, useLayoutEffect, useMemo, useRef, useState } from "@wordpress/element";
26
6
  import { GridItem } from "./grid-item.mjs";
27
7
  import { arrayMoveWithPinned } from "../shared/array-move-with-pinned.mjs";
8
+ import { resolveColumnCount } from "../shared/column-policy.mjs";
28
9
  import { GridOverlay } from "../shared/grid-overlay.mjs";
29
10
  import { clampSpan, gridSpanToPixelSize } from "../shared/resize-snap.mjs";
30
11
  import { useResizePixelLimits, useSpanBounds } from "../shared/use-span-bounds.mjs";
31
-
12
+ import { ItemExitOverlay } from "../shared/item-exit-overlay.mjs";
13
+ import { getLayoutFingerprint, useLayoutShiftAnimation } from "../shared/use-layout-shift-animation.mjs";
14
+ import { useItemExitAnimation } from "../shared/use-item-exit-animation.mjs";
15
+ import { resolveFillWidths } from "./resolve-fill-widths.mjs";
16
+ import { createDashboardDragDropAnimation } from "../shared/drag-overlay-drop-animation.mjs";
17
+ import { jsx, jsxs } from "react/jsx-runtime";
32
18
  // packages/style-runtime/src/index.ts
33
- var STYLE_HASH_ATTRIBUTE = "data-wp-hash";
19
+ const STYLE_HASH_ATTRIBUTE = "data-wp-hash";
20
+ /**
21
+ * Returns the shared style runtime registry.
22
+ *
23
+ * The registry is stored on `globalThis` so separately bundled copies of this
24
+ * package can coordinate through the same document and style maps.
25
+ *
26
+ * @return The shared runtime registry.
27
+ */
34
28
  function getRuntime() {
35
- const globalScope = globalThis;
36
- if (globalScope.__wpStyleRuntime) {
37
- return globalScope.__wpStyleRuntime;
38
- }
39
- globalScope.__wpStyleRuntime = {
40
- documents: /* @__PURE__ */ new Map(),
41
- styles: /* @__PURE__ */ new Map(),
42
- injectedStyles: /* @__PURE__ */ new WeakMap()
43
- };
44
- if (typeof document !== "undefined") {
45
- registerDocument(document);
46
- }
47
- return globalScope.__wpStyleRuntime;
29
+ const globalScope = globalThis;
30
+ if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime;
31
+ globalScope.__wpStyleRuntime = {
32
+ documents: /* @__PURE__ */ new Map(),
33
+ styles: /* @__PURE__ */ new Map(),
34
+ injectedStyles: /* @__PURE__ */ new WeakMap()
35
+ };
36
+ if (typeof document !== "undefined") registerDocument(document);
37
+ return globalScope.__wpStyleRuntime;
48
38
  }
39
+ /**
40
+ * Checks whether a document already contains a style tag for a hash.
41
+ *
42
+ * @param targetDocument Document to inspect.
43
+ * @param hash Stable hash for the transformed CSS.
44
+ *
45
+ * @return Whether the style hash already exists in the document.
46
+ */
49
47
  function documentContainsStyleHash(targetDocument, hash) {
50
- if (!targetDocument.head) {
51
- return false;
52
- }
53
- for (const style of targetDocument.head.querySelectorAll(
54
- `style[${STYLE_HASH_ATTRIBUTE}]`
55
- )) {
56
- if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) {
57
- return true;
58
- }
59
- }
60
- return false;
48
+ if (!targetDocument.head) return false;
49
+ for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true;
50
+ return false;
61
51
  }
52
+ /**
53
+ * Injects a registered style into a document, unless that document already
54
+ * contains a style tag for the same hash.
55
+ *
56
+ * @param targetDocument Document to inject the style into.
57
+ * @param hash Stable hash for the transformed CSS.
58
+ * @param css CSS text to inject.
59
+ */
62
60
  function injectStyle(targetDocument, hash, css) {
63
- if (!targetDocument.head) {
64
- return;
65
- }
66
- const runtime = getRuntime();
67
- let injectedStyles = runtime.injectedStyles.get(targetDocument);
68
- if (!injectedStyles) {
69
- injectedStyles = /* @__PURE__ */ new Set();
70
- runtime.injectedStyles.set(targetDocument, injectedStyles);
71
- }
72
- if (injectedStyles.has(hash)) {
73
- return;
74
- }
75
- if (documentContainsStyleHash(targetDocument, hash)) {
76
- injectedStyles.add(hash);
77
- return;
78
- }
79
- const style = targetDocument.createElement("style");
80
- style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
81
- style.appendChild(targetDocument.createTextNode(css));
82
- targetDocument.head.appendChild(style);
83
- injectedStyles.add(hash);
61
+ if (!targetDocument.head) return;
62
+ const runtime = getRuntime();
63
+ let injectedStyles = runtime.injectedStyles.get(targetDocument);
64
+ if (!injectedStyles) {
65
+ injectedStyles = /* @__PURE__ */ new Set();
66
+ runtime.injectedStyles.set(targetDocument, injectedStyles);
67
+ }
68
+ if (injectedStyles.has(hash)) return;
69
+ if (documentContainsStyleHash(targetDocument, hash)) {
70
+ injectedStyles.add(hash);
71
+ return;
72
+ }
73
+ const style = targetDocument.createElement("style");
74
+ style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
75
+ style.appendChild(targetDocument.createTextNode(css));
76
+ targetDocument.head.appendChild(style);
77
+ injectedStyles.add(hash);
84
78
  }
79
+ /**
80
+ * Registers a document as a style injection target.
81
+ *
82
+ * Existing registered styles are replayed into the document immediately.
83
+ * Documents are reference-counted so multiple providers can safely register the
84
+ * same document without one cleanup removing it while another registration is
85
+ * still active.
86
+ *
87
+ * @param targetDocument Document to receive registered styles.
88
+ * @return Cleanup function that unregisters this document registration.
89
+ */
85
90
  function registerDocument(targetDocument) {
86
- const runtime = getRuntime();
87
- runtime.documents.set(
88
- targetDocument,
89
- (runtime.documents.get(targetDocument) ?? 0) + 1
90
- );
91
- for (const [hash, css] of runtime.styles) {
92
- injectStyle(targetDocument, hash, css);
93
- }
94
- return () => {
95
- const count = runtime.documents.get(targetDocument);
96
- if (count === void 0) {
97
- return;
98
- }
99
- if (count <= 1) {
100
- runtime.documents.delete(targetDocument);
101
- return;
102
- }
103
- runtime.documents.set(targetDocument, count - 1);
104
- };
91
+ const runtime = getRuntime();
92
+ runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1);
93
+ for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css);
94
+ return () => {
95
+ const count = runtime.documents.get(targetDocument);
96
+ if (count === void 0) return;
97
+ if (count <= 1) {
98
+ runtime.documents.delete(targetDocument);
99
+ return;
100
+ }
101
+ runtime.documents.set(targetDocument, count - 1);
102
+ };
105
103
  }
104
+ /**
105
+ * Registers a style and injects it into all registered documents.
106
+ *
107
+ * The hash is used as the deduplication key, so calling this repeatedly with
108
+ * the same hash will not add duplicate style tags to a document.
109
+ * Registered styles are retained for the lifetime of the page so they can be
110
+ * replayed into documents that are registered later.
111
+ *
112
+ * @param hash Stable hash for the transformed CSS.
113
+ * @param css CSS text to inject.
114
+ */
106
115
  function registerStyle(hash, css) {
107
- const runtime = getRuntime();
108
- runtime.styles.set(hash, css);
109
- for (const targetDocument of runtime.documents.keys()) {
110
- injectStyle(targetDocument, hash, css);
111
- }
116
+ const runtime = getRuntime();
117
+ runtime.styles.set(hash, css);
118
+ for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css);
112
119
  }
113
-
114
120
  // packages/grid/src/shared/layout-shift-animation.module.css
115
- if (typeof process === "undefined" || process.env.NODE_ENV !== "test") {
116
- registerStyle("9e5573e51f", "._2db63116caa90ae9__layout-animating [data-wp-grid-item-key]{transition:transform var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1))}@media (prefers-reduced-motion:reduce){._2db63116caa90ae9__layout-animating [data-wp-grid-item-key]{transition:none}}");
117
- }
118
- var layout_shift_animation_default = { "layout-animating": "_2db63116caa90ae9__layout-animating" };
119
-
120
- // packages/grid/src/dashboard-grid/index.tsx
121
- import { ItemExitOverlay } from "../shared/item-exit-overlay.mjs";
122
- import {
123
- getLayoutFingerprint,
124
- useLayoutShiftAnimation
125
- } from "../shared/use-layout-shift-animation.mjs";
126
- import { useItemExitAnimation } from "../shared/use-item-exit-animation.mjs";
127
- import { resolveFillWidths } from "./resolve-fill-widths.mjs";
128
- import { createDashboardDragDropAnimation } from "../shared/drag-overlay-drop-animation.mjs";
129
-
121
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("5d10111ab0", ".c68bb75eb6bf717a__layout-animating [data-wp-grid-item-key]{transition:transform var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1))}@media (prefers-reduced-motion:reduce){.c68bb75eb6bf717a__layout-animating [data-wp-grid-item-key]{transition:none}}");
122
+ var layout_shift_animation_module_default = { "layout-animating": "c68bb75eb6bf717a__layout-animating" };
130
123
  // packages/grid/src/dashboard-grid/grid.module.css
131
- if (typeof process === "undefined" || process.env.NODE_ENV !== "test") {
132
- registerStyle("9b45a626c9", "._960c435c33759f46__grid{display:grid;gap:var(--wp-grid-gap,var(--wpds-dimension-gap-xl,24px));position:relative}._48e8cd4225dcb813__drag-preview-frame{--_wp-grid-elevation-xs:0 1px 1px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.02),0 3px 3px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.01);--_wp-grid-elevation-md:0 2px 3px rgba(0,0,0,.05),0 4px 5px rgba(0,0,0,.04),0 12px 12px rgba(0,0,0,.03),0 16px 16px rgba(0,0,0,.02);border-radius:var(--wp-grid-drag-preview-radius,0);box-shadow:var(--_wp-grid-elevation-md);cursor:grabbing;height:100%;pointer-events:none}._4b471bf24f891d2d__drag-preview-frame__lift{height:100%;transform:scale(var(--wp-grid-drag-preview-scale,1.05));transform-origin:center}@media not (prefers-reduced-motion:reduce){._48e8cd4225dcb813__drag-preview-frame{animation:_08fdf90ef86c4706__wp-grid-drag-preview-shadow-enter var(--wpds-motion-duration-sm,.1s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) both}._4b471bf24f891d2d__drag-preview-frame__lift{animation:_8aaeb335436989f9__wp-grid-drag-preview-scale-enter var(--wpds-motion-duration-sm,.1s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) both}}@media not (prefers-reduced-motion:reduce){@keyframes _08fdf90ef86c4706__wp-grid-drag-preview-shadow-enter{0%{box-shadow:var(--_wp-grid-elevation-xs)}to{box-shadow:var(--_wp-grid-elevation-md)}}@keyframes _8aaeb335436989f9__wp-grid-drag-preview-scale-enter{0%{transform:scale(1)}to{transform:scale(var(--wp-grid-drag-preview-scale,1.05))}}}@media not (prefers-reduced-motion:reduce){._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting{animation:a7ead84bfd25ff8a__wp-grid-drag-preview-shadow-exit var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) forwards}._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting ._4b471bf24f891d2d__drag-preview-frame__lift{animation:_234ccad5c20d49f8__wp-grid-drag-preview-scale-exit var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) forwards}@keyframes a7ead84bfd25ff8a__wp-grid-drag-preview-shadow-exit{0%{box-shadow:var(--_wp-grid-elevation-md)}to{box-shadow:var(--_wp-grid-elevation-xs)}}@keyframes _234ccad5c20d49f8__wp-grid-drag-preview-scale-exit{0%{transform:scale(var(--wp-grid-drag-preview-scale,1.05))}to{transform:scale(1)}}}._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting{box-shadow:var(--_wp-grid-elevation-xs)}._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting ._4b471bf24f891d2d__drag-preview-frame__lift{transform:scale(1)}@media (prefers-reduced-motion:reduce){._48e8cd4225dcb813__drag-preview-frame{box-shadow:var(--_wp-grid-elevation-md)}._4b471bf24f891d2d__drag-preview-frame__lift{transform:none}._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting{box-shadow:var(--_wp-grid-elevation-xs);transition:none}._48e8cd4225dcb813__drag-preview-frame.cf64ad2b878ad478__is-exiting ._4b471bf24f891d2d__drag-preview-frame__lift{transition:none}}");
133
- }
134
- var grid_default = { "grid": "_960c435c33759f46__grid", "drag-preview-frame": "_48e8cd4225dcb813__drag-preview-frame", "drag-preview-frame__lift": "_4b471bf24f891d2d__drag-preview-frame__lift", "wp-grid-drag-preview-shadow-enter": "_08fdf90ef86c4706__wp-grid-drag-preview-shadow-enter", "wp-grid-drag-preview-scale-enter": "_8aaeb335436989f9__wp-grid-drag-preview-scale-enter", "is-exiting": "cf64ad2b878ad478__is-exiting", "wp-grid-drag-preview-shadow-exit": "a7ead84bfd25ff8a__wp-grid-drag-preview-shadow-exit", "wp-grid-drag-preview-scale-exit": "_234ccad5c20d49f8__wp-grid-drag-preview-scale-exit" };
135
-
136
- // packages/grid/src/dashboard-grid/index.tsx
137
- import { jsx, jsxs } from "react/jsx-runtime";
138
- var dashboardDragDropAnimation = createDashboardDragDropAnimation(
139
- grid_default["drag-preview-frame"],
140
- grid_default["is-exiting"]
141
- );
142
- var FALLBACK_GAP_PX = 24;
143
- var DEFAULT_COLUMNS = 6;
144
- var NO_SORT_STRATEGY = () => null;
145
- var DashboardGrid = forwardRef(
146
- function UnforwardedDashboardGrid(props, ref) {
147
- const {
148
- layout,
149
- columns,
150
- children,
151
- className,
152
- style,
153
- rowHeight = "auto",
154
- minColumnWidth,
155
- itemLimits,
156
- editMode = false,
157
- onChangeLayout,
158
- onPreviewLayout,
159
- renderResizeHandle,
160
- renderDragPreview,
161
- renderGridOverlay,
162
- ...divProps
163
- } = props;
164
- const [temporaryLayout, setTemporaryLayout] = useState();
165
- const [activeId, setActiveId] = useState(null);
166
- const [isResizing, setIsResizing] = useState(false);
167
- const [resizeSnapPreview, setResizeSnapPreview] = useState(null);
168
- const latestLayoutRef = useRef(
169
- void 0
170
- );
171
- const lastReorderCursorRef = useRef(null);
172
- const resizeBaselineRef = useRef(null);
173
- const captureLayoutSnapshotRef = useRef(() => {
174
- });
175
- const childrenCacheRef = useRef(
176
- /* @__PURE__ */ new Map()
177
- );
178
- const [gridRoot, setGridRoot] = useState(
179
- null
180
- );
181
- const [containerWidth, setContainerWidth] = useState(0);
182
- const [containerHeight, setContainerHeight] = useState(0);
183
- const [gapPx, setGapPx] = useState(FALLBACK_GAP_PX);
184
- const resizeObserverRef = useResizeObserver(
185
- ([{ contentRect }]) => {
186
- setContainerWidth(contentRect.width);
187
- setContainerHeight(contentRect.height);
188
- }
189
- );
190
- const mergedGridRef = useMergeRefs([
191
- setGridRoot,
192
- resizeObserverRef,
193
- ref
194
- ]);
195
- useLayoutEffect(() => {
196
- if (!gridRoot) {
197
- return;
198
- }
199
- const { width, height } = gridRoot.getBoundingClientRect();
200
- if (width > 0) {
201
- setContainerWidth(width);
202
- }
203
- if (height > 0) {
204
- setContainerHeight(height);
205
- }
206
- const parsed = Number.parseFloat(
207
- window.getComputedStyle(gridRoot).columnGap
208
- );
209
- if (Number.isFinite(parsed) && parsed > 0) {
210
- setGapPx(parsed);
211
- }
212
- }, [gridRoot]);
213
- const effectiveColumns = useMemo(() => {
214
- if (!minColumnWidth) {
215
- return columns ?? DEFAULT_COLUMNS;
216
- }
217
- const totalWidthPerColumn = minColumnWidth + gapPx;
218
- const maxFit = Math.max(
219
- 1,
220
- Math.floor((containerWidth + gapPx) / totalWidthPerColumn)
221
- );
222
- return columns !== void 0 ? Math.min(columns, maxFit) : maxFit;
223
- }, [minColumnWidth, gapPx, containerWidth, columns]);
224
- const columnWidth = (containerWidth - (effectiveColumns - 1) * gapPx) / effectiveColumns;
225
- const minResizeWidthPx = gridSpanToPixelSize(
226
- 1,
227
- 1,
228
- columnWidth,
229
- gapPx,
230
- null
231
- ).widthPx;
232
- const rowHeightPx = typeof rowHeight === "number" ? rowHeight : null;
233
- const minResizeHeightPx = rowHeightPx === null ? void 0 : gridSpanToPixelSize(1, 1, columnWidth, gapPx, rowHeightPx).heightPx ?? void 0;
234
- const spanBoundsByKey = useSpanBounds(
235
- itemLimits,
236
- columnWidth,
237
- gapPx,
238
- rowHeightPx,
239
- effectiveColumns
240
- );
241
- const resizeLimitsByKey = useResizePixelLimits(
242
- spanBoundsByKey,
243
- columnWidth,
244
- gapPx,
245
- rowHeightPx
246
- );
247
- const sourceLayout = temporaryLayout ?? layout;
248
- const activeLayout = useMemo(() => {
249
- if (spanBoundsByKey.size === 0) {
250
- return sourceLayout;
251
- }
252
- let changed = false;
253
- const bounded = sourceLayout.map((item) => {
254
- const bounds = spanBoundsByKey.get(item.key);
255
- if (!bounds) {
256
- return item;
257
- }
258
- const width = typeof item.width === "number" ? clampSpan(
259
- item.width,
260
- bounds.minWidth,
261
- bounds.maxWidth
262
- ) : item.width;
263
- const height = clampSpan(
264
- item.height ?? 1,
265
- bounds.minHeight,
266
- bounds.maxHeight
267
- );
268
- if (width === item.width && height === (item.height ?? 1)) {
269
- return item;
270
- }
271
- changed = true;
272
- return { ...item, width, height };
273
- });
274
- return changed ? bounded : sourceLayout;
275
- }, [sourceLayout, spanBoundsByKey]);
276
- const layoutMap = useMemo(() => {
277
- const map = /* @__PURE__ */ new Map();
278
- activeLayout.forEach((item) => map.set(item.key, item));
279
- return map;
280
- }, [activeLayout]);
281
- const layoutKeys = useMemo(
282
- () => new Set(layout.map((item) => item.key)),
283
- [layout]
284
- );
285
- const sortedItems = useMemo(
286
- () => activeLayout.map((item, index) => ({ item, index })).sort(
287
- (a, b) => (a.item.order ?? a.index) - (b.item.order ?? b.index)
288
- ).map(({ item }) => item.key),
289
- [activeLayout]
290
- );
291
- const items = sortedItems;
292
- const resolvedItemMap = useMemo(() => {
293
- const fillWidths = resolveFillWidths(
294
- items,
295
- layoutMap,
296
- effectiveColumns,
297
- spanBoundsByKey
298
- );
299
- if (fillWidths.size === 0) {
300
- return layoutMap;
301
- }
302
- const map = /* @__PURE__ */ new Map();
303
- for (const [key, item] of layoutMap) {
304
- const fillW = fillWidths.get(key);
305
- map.set(
306
- key,
307
- fillW !== void 0 ? { ...item, width: fillW } : item
308
- );
309
- }
310
- return map;
311
- }, [items, layoutMap, effectiveColumns, spanBoundsByKey]);
312
- const [childrenMap, actionableAreaMap, remaining, renderedByKey] = useMemo(() => {
313
- const childMap = /* @__PURE__ */ new Map();
314
- const actionableMap = /* @__PURE__ */ new Map();
315
- const rest = [];
316
- const byKey = /* @__PURE__ */ new Map();
317
- Children.forEach(children, (child) => {
318
- if (!isValidElement(child)) {
319
- rest.push(child);
320
- return;
321
- }
322
- const key = child.key?.toString();
323
- if (!key) {
324
- rest.push(child);
325
- return;
326
- }
327
- const typedChild = child;
328
- const { actionableArea } = typedChild.props;
329
- const stripped = actionableArea !== void 0 ? cloneElement(typedChild, {
330
- actionableArea: void 0
331
- }) : child;
332
- byKey.set(key, stripped);
333
- if (layoutKeys.has(key)) {
334
- if (actionableArea !== void 0) {
335
- actionableMap.set(key, actionableArea);
336
- }
337
- childMap.set(key, stripped);
338
- } else {
339
- rest.push(child);
340
- }
341
- });
342
- return [childMap, actionableMap, rest, byKey];
343
- }, [children, layoutKeys]);
344
- useLayoutEffect(() => {
345
- for (const [key, child] of renderedByKey) {
346
- childrenCacheRef.current.set(key, child);
347
- }
348
- }, [renderedByKey]);
349
- const sensors = useSensors(
350
- useSensor(PointerSensor),
351
- useSensor(KeyboardSensor, {
352
- coordinateGetter: sortableKeyboardCoordinates
353
- })
354
- );
355
- const handleDragStart = useEvent((event) => {
356
- setActiveId(String(event.active.id));
357
- lastReorderCursorRef.current = null;
358
- });
359
- const handleDragCancel = useEvent(() => {
360
- setActiveId(null);
361
- latestLayoutRef.current = void 0;
362
- lastReorderCursorRef.current = null;
363
- resizeBaselineRef.current = null;
364
- setIsResizing(false);
365
- setResizeSnapPreview(null);
366
- setTemporaryLayout(void 0);
367
- });
368
- const handleDragMove = useEvent((event) => {
369
- const { active, over } = event;
370
- if (!over || active.id === over.id) {
371
- return;
372
- }
373
- const activeRect = active.rect.current.translated;
374
- if (!activeRect) {
375
- return;
376
- }
377
- const activeCenterX = activeRect.left + activeRect.width / 2;
378
- const activeCenterY = activeRect.top + activeRect.height / 2;
379
- const lastCursor = lastReorderCursorRef.current;
380
- if (lastCursor) {
381
- const dx = activeCenterX - lastCursor.x;
382
- const dy = activeCenterY - lastCursor.y;
383
- if (dx * dx + dy * dy < 100) {
384
- return;
385
- }
386
- }
387
- const overCenterX = over.rect.left + over.rect.width / 2;
388
- const insertAfter = activeCenterX > overCenterX;
389
- const currentIndex = items.indexOf(String(active.id));
390
- const overIndex = items.indexOf(String(over.id));
391
- let newIndex;
392
- if (insertAfter) {
393
- newIndex = currentIndex > overIndex ? overIndex + 1 : overIndex;
394
- } else {
395
- newIndex = currentIndex > overIndex ? overIndex : overIndex - 1;
396
- }
397
- newIndex = Math.max(0, Math.min(newIndex, items.length - 1));
398
- if (newIndex === currentIndex) {
399
- return;
400
- }
401
- const updatedItems = arrayMoveWithPinned(
402
- items,
403
- currentIndex,
404
- newIndex,
405
- (key) => layoutMap.get(key)?.draggable === false
406
- );
407
- if (updatedItems.every((key, index) => key === items[index])) {
408
- return;
409
- }
410
- const updatedLayout = (latestLayoutRef.current ?? layout).map(
411
- (item) => ({
412
- ...item,
413
- order: updatedItems.indexOf(item.key)
414
- })
415
- );
416
- lastReorderCursorRef.current = {
417
- x: activeCenterX,
418
- y: activeCenterY
419
- };
420
- latestLayoutRef.current = updatedLayout;
421
- captureLayoutSnapshotRef.current();
422
- setTemporaryLayout(updatedLayout);
423
- onPreviewLayout?.(updatedLayout);
424
- });
425
- const persistTemporaryLayout = useEvent(() => {
426
- const latest = latestLayoutRef.current;
427
- latestLayoutRef.current = void 0;
428
- resizeBaselineRef.current = null;
429
- setIsResizing(false);
430
- setResizeSnapPreview(null);
431
- if (!onChangeLayout || !latest) {
432
- setTemporaryLayout(void 0);
433
- return;
434
- }
435
- onChangeLayout(latest);
436
- setTemporaryLayout(void 0);
437
- });
438
- const handleResize = useEvent((id, delta) => {
439
- if (!editMode) {
440
- return;
441
- }
442
- if (!isResizing) {
443
- setIsResizing(true);
444
- }
445
- const relativeDelta = {
446
- width: Math.round(delta.width / (columnWidth + gapPx)),
447
- height: rowHeight === "auto" ? 0 : Math.round(delta.height / (rowHeight + gapPx))
448
- };
449
- const bounds = spanBoundsByKey.get(id);
450
- if (!resizeBaselineRef.current) {
451
- const baseItem = layoutMap.get(id);
452
- const resolvedItem = resolvedItemMap.get(id);
453
- let baseWidth;
454
- if (baseItem?.width === "full") {
455
- baseWidth = bounds?.maxWidth ?? effectiveColumns;
456
- } else if (baseItem?.width === "fill") {
457
- baseWidth = typeof resolvedItem?.width === "number" ? resolvedItem.width : 1;
458
- } else {
459
- baseWidth = baseItem?.width ?? 1;
460
- }
461
- resizeBaselineRef.current = {
462
- width: baseWidth,
463
- height: baseItem?.height ?? 1
464
- };
465
- }
466
- const baseline = resizeBaselineRef.current;
467
- const newWidth = clampSpan(
468
- baseline.width + relativeDelta.width,
469
- bounds?.minWidth ?? 1,
470
- bounds?.maxWidth ?? effectiveColumns
471
- );
472
- const newHeight = clampSpan(
473
- baseline.height + relativeDelta.height,
474
- bounds?.minHeight ?? 1,
475
- bounds?.maxHeight ?? Infinity
476
- );
477
- setResizeSnapPreview({
478
- id,
479
- snap: gridSpanToPixelSize(
480
- newWidth,
481
- newHeight,
482
- columnWidth,
483
- gapPx,
484
- rowHeightPx
485
- )
486
- });
487
- const pendingItem = latestLayoutRef.current?.find(
488
- (item) => item.key === id
489
- );
490
- const currentItem = pendingItem ?? layoutMap.get(id);
491
- if (currentItem && currentItem.width === newWidth && (currentItem.height ?? 1) === newHeight) {
492
- return;
493
- }
494
- const updatedLayout = (latestLayoutRef.current ?? layout).map(
495
- (item) => item.key === id ? { ...item, width: newWidth, height: newHeight } : item
496
- );
497
- latestLayoutRef.current = updatedLayout;
498
- captureLayoutSnapshotRef.current();
499
- setTemporaryLayout(updatedLayout);
500
- onPreviewLayout?.(updatedLayout);
501
- });
502
- const activeClone = activeId ? childrenMap.get(activeId) : null;
503
- const DragPreview = renderDragPreview;
504
- const dragOverlayContent = activeId && activeClone ? /* @__PURE__ */ jsx("div", { className: grid_default["drag-preview-frame"], children: /* @__PURE__ */ jsx("div", { className: grid_default["drag-preview-frame__lift"], children: DragPreview ? /* @__PURE__ */ jsx(DragPreview, { itemId: activeId, children: activeClone }) : activeClone }) }) : null;
505
- const Overlay = renderGridOverlay ?? GridOverlay;
506
- const overlayRowHeight = typeof rowHeight === "number" ? rowHeight : void 0;
507
- const overlayRows = useMemo(() => {
508
- if (overlayRowHeight === void 0 || containerHeight <= 0) {
509
- return void 0;
510
- }
511
- const rowTile = overlayRowHeight + gapPx;
512
- return Math.max(
513
- 1,
514
- Math.floor((containerHeight + gapPx) / rowTile)
515
- );
516
- }, [overlayRowHeight, containerHeight, gapPx]);
517
- const gridOverlay = useMemo(
518
- () => /* @__PURE__ */ jsx(
519
- Overlay,
520
- {
521
- columns: effectiveColumns,
522
- rowHeight: overlayRowHeight,
523
- rows: overlayRows,
524
- isActive: editMode
525
- }
526
- ),
527
- [
528
- Overlay,
529
- editMode,
530
- effectiveColumns,
531
- overlayRowHeight,
532
- overlayRows
533
- ]
534
- );
535
- const layoutFingerprint = useMemo(
536
- () => getLayoutFingerprint([...resolvedItemMap.values()]),
537
- [resolvedItemMap]
538
- );
539
- const excludeLayoutAnimationKey = activeId ?? (isResizing ? resizeSnapPreview?.id : null);
540
- const { captureLayoutSnapshot, getPositionsBeforeLastChange } = useLayoutShiftAnimation({
541
- container: gridRoot,
542
- enabled: editMode,
543
- layoutFingerprint,
544
- excludeItemKey: excludeLayoutAnimationKey
545
- });
546
- const { exitingItems, clearExitingItem } = useItemExitAnimation({
547
- container: gridRoot,
548
- enabled: editMode,
549
- layoutKeys,
550
- getPositionsBeforeLastChange,
551
- childrenCacheRef
552
- });
553
- const layoutAnimating = editMode;
554
- useLayoutEffect(() => {
555
- captureLayoutSnapshotRef.current = captureLayoutSnapshot;
556
- }, [captureLayoutSnapshot]);
557
- return /* @__PURE__ */ jsxs(
558
- DndContext,
559
- {
560
- sensors,
561
- onDragStart: handleDragStart,
562
- onDragCancel: handleDragCancel,
563
- onDragMove: handleDragMove,
564
- onDragEnd: () => {
565
- persistTemporaryLayout();
566
- lastReorderCursorRef.current = null;
567
- setActiveId(null);
568
- },
569
- children: [
570
- /* @__PURE__ */ jsx(SortableContext, { items, strategy: NO_SORT_STRATEGY, children: /* @__PURE__ */ jsxs(
571
- "div",
572
- {
573
- ...divProps,
574
- ref: mergedGridRef,
575
- className: clsx(
576
- grid_default.grid,
577
- layoutAnimating && layout_shift_animation_default["layout-animating"],
578
- className
579
- ),
580
- "data-wp-grid-dragging": activeId || void 0,
581
- "data-wp-grid-resizing": isResizing || void 0,
582
- style: {
583
- ...style,
584
- gridTemplateColumns: `repeat(${effectiveColumns}, minmax(0, 1fr))`,
585
- gridAutoRows: rowHeight
586
- },
587
- children: [
588
- gridOverlay,
589
- items.map((id) => {
590
- const limitsPx = resizeLimitsByKey.get(id);
591
- return /* @__PURE__ */ jsx(
592
- GridItem,
593
- {
594
- item: resolvedItemMap.get(
595
- id
596
- ),
597
- maxColumns: spanBoundsByKey.get(id)?.maxWidth ?? effectiveColumns,
598
- disabled: !editMode,
599
- draggable: layoutMap.get(id)?.draggable !== false,
600
- resizable: layoutMap.get(id)?.resizable !== false,
601
- verticalResizable: rowHeight !== "auto",
602
- interacting: activeId !== null || isResizing,
603
- dragging: activeId !== null,
604
- onResize: handleResize,
605
- onResizeEnd: persistTemporaryLayout,
606
- resizeSnapPreview: resizeSnapPreview?.id === id ? resizeSnapPreview.snap : null,
607
- minResizeWidthPx: limitsPx?.minWidthPx ?? minResizeWidthPx,
608
- minResizeHeightPx: limitsPx?.minHeightPx ?? minResizeHeightPx,
609
- maxResizeWidthPx: limitsPx?.maxWidthPx,
610
- maxResizeHeightPx: limitsPx?.maxHeightPx ?? void 0,
611
- actionableArea: actionableAreaMap.get(
612
- id
613
- ),
614
- renderResizeHandle,
615
- children: childrenMap.get(id)
616
- },
617
- id
618
- );
619
- }),
620
- remaining,
621
- exitingItems.map(({ key, rect, child }) => /* @__PURE__ */ jsx(
622
- ItemExitOverlay,
623
- {
624
- itemKey: key,
625
- rect,
626
- onAnimationEnd: () => clearExitingItem(key),
627
- children: child
628
- },
629
- `exiting-${key}`
630
- ))
631
- ]
632
- }
633
- ) }),
634
- /* @__PURE__ */ jsx(DragOverlay, { dropAnimation: dashboardDragDropAnimation, children: dragOverlayContent })
635
- ]
636
- }
637
- );
638
- }
639
- );
640
- export {
641
- DashboardGrid
124
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("38b90762ee", "._21f1954f75f72766__grid{display:grid;gap:var(--wp-grid-gap,var(--wpds-dimension-gap-xl,24px));position:relative}.e464fb19a38466c5__drag-preview-frame{--_wp-grid-elevation-xs:0 1px 1px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.02),0 3px 3px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.01);--_wp-grid-elevation-md:0 2px 3px rgba(0,0,0,.05),0 4px 5px rgba(0,0,0,.04),0 12px 12px rgba(0,0,0,.03),0 16px 16px rgba(0,0,0,.02);border-radius:var(--wp-grid-drag-preview-radius,0);box-shadow:var(--_wp-grid-elevation-md);cursor:grabbing;height:100%;pointer-events:none}.da244be067f8f335__drag-preview-frame__lift{height:100%;transform:scale(var(--wp-grid-drag-preview-scale,1.05));transform-origin:center}@media not (prefers-reduced-motion:reduce){.e464fb19a38466c5__drag-preview-frame{animation:_1c00dcb154fe518d__wp-grid-drag-preview-shadow-enter var(--wpds-motion-duration-sm,.1s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) both}.da244be067f8f335__drag-preview-frame__lift{animation:ef2aa0b981f2c744__wp-grid-drag-preview-scale-enter var(--wpds-motion-duration-sm,.1s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) both}}@media not (prefers-reduced-motion:reduce){@keyframes _1c00dcb154fe518d__wp-grid-drag-preview-shadow-enter{0%{box-shadow:var(--_wp-grid-elevation-xs)}to{box-shadow:var(--_wp-grid-elevation-md)}}@keyframes ef2aa0b981f2c744__wp-grid-drag-preview-scale-enter{0%{transform:scale(1)}to{transform:scale(var(--wp-grid-drag-preview-scale,1.05))}}}@media not (prefers-reduced-motion:reduce){.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting{animation:f1ccc9200b4579c4__wp-grid-drag-preview-shadow-exit var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) forwards}.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting .da244be067f8f335__drag-preview-frame__lift{animation:c84abadc2143eb8a__wp-grid-drag-preview-scale-exit var(--wpds-motion-duration-md,.2s) var(--wpds-motion-easing-balanced,cubic-bezier(.4,0,.2,1)) forwards}@keyframes f1ccc9200b4579c4__wp-grid-drag-preview-shadow-exit{0%{box-shadow:var(--_wp-grid-elevation-md)}to{box-shadow:var(--_wp-grid-elevation-xs)}}@keyframes c84abadc2143eb8a__wp-grid-drag-preview-scale-exit{0%{transform:scale(var(--wp-grid-drag-preview-scale,1.05))}to{transform:scale(1)}}}.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting{box-shadow:var(--_wp-grid-elevation-xs)}.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting .da244be067f8f335__drag-preview-frame__lift{transform:scale(1)}@media (prefers-reduced-motion:reduce){.e464fb19a38466c5__drag-preview-frame{box-shadow:var(--_wp-grid-elevation-md)}.da244be067f8f335__drag-preview-frame__lift{transform:none}.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting{box-shadow:var(--_wp-grid-elevation-xs);transition:none}.e464fb19a38466c5__drag-preview-frame._4a025da98b54c1dc__is-exiting .da244be067f8f335__drag-preview-frame__lift{transition:none}}");
125
+ var grid_module_default = {
126
+ "grid": "_21f1954f75f72766__grid",
127
+ "drag-preview-frame": "e464fb19a38466c5__drag-preview-frame",
128
+ "drag-preview-frame__lift": "da244be067f8f335__drag-preview-frame__lift",
129
+ "wp-grid-drag-preview-shadow-enter": "_1c00dcb154fe518d__wp-grid-drag-preview-shadow-enter",
130
+ "wp-grid-drag-preview-scale-enter": "ef2aa0b981f2c744__wp-grid-drag-preview-scale-enter",
131
+ "is-exiting": "_4a025da98b54c1dc__is-exiting",
132
+ "wp-grid-drag-preview-shadow-exit": "f1ccc9200b4579c4__wp-grid-drag-preview-shadow-exit",
133
+ "wp-grid-drag-preview-scale-exit": "c84abadc2143eb8a__wp-grid-drag-preview-scale-exit"
642
134
  };
643
- //# sourceMappingURL=index.mjs.map
135
+ // packages/grid/src/dashboard-grid/index.tsx
136
+ const dashboardDragDropAnimation = createDashboardDragDropAnimation(grid_module_default["drag-preview-frame"], grid_module_default["is-exiting"]);
137
+ const FALLBACK_GAP_PX = 24;
138
+ const DEFAULT_COLUMNS = 6;
139
+ const NO_SORT_STRATEGY = () => null;
140
+ /**
141
+ * 2D packed dashboard grid with drag-to-reorder and resize handles.
142
+ * Supports fixed-column and responsive modes, `number | 'fill' | 'full'`
143
+ * widths, and multi-row tiles.
144
+ *
145
+ * Each child's `key` must match an entry in the `layout` array;
146
+ * children without a match render at the end of the grid without
147
+ * explicit placement and fall through CSS Grid's auto-flow.
148
+ *
149
+ * @example
150
+ * ```jsx
151
+ * const layout = [
152
+ * { key: 'a', width: 2 },
153
+ * { key: 'b', width: 'fill' },
154
+ * { key: 'c', width: 'full' },
155
+ * ];
156
+ *
157
+ * <DashboardGrid
158
+ * layout={ layout }
159
+ * columns={ 6 }
160
+ * editMode
161
+ * onChangeLayout={ setLayout }
162
+ * >
163
+ * <div key="a">A</div>
164
+ * <div key="b">B</div>
165
+ * <div key="c">C</div>
166
+ * </DashboardGrid>
167
+ * ```
168
+ *
169
+ * @param props Component props.
170
+ * @param ref Forwarded to the grid's root `<div>`.
171
+ */
172
+ const DashboardGrid = forwardRef(function UnforwardedDashboardGrid(props, ref) {
173
+ const { layout, columns, children, className, style, rowHeight = "auto", minColumnWidth, itemLimits, editMode = false, onChangeLayout, onPreviewLayout, renderResizeHandle, renderDragPreview, renderGridOverlay, ...divProps } = props;
174
+ const [temporaryLayout, setTemporaryLayout] = useState();
175
+ const [activeId, setActiveId] = useState(null);
176
+ const [isResizing, setIsResizing] = useState(false);
177
+ const [resizeSnapPreview, setResizeSnapPreview] = useState(null);
178
+ const latestLayoutRef = useRef(void 0);
179
+ const lastReorderCursorRef = useRef(null);
180
+ const resizeBaselineRef = useRef(null);
181
+ const captureLayoutSnapshotRef = useRef(() => {});
182
+ const childrenCacheRef = useRef(/* @__PURE__ */ new Map());
183
+ const [gridRoot, setGridRoot] = useState(null);
184
+ const [containerWidth, setContainerWidth] = useState(0);
185
+ const [containerHeight, setContainerHeight] = useState(0);
186
+ const [gapPx, setGapPx] = useState(FALLBACK_GAP_PX);
187
+ const resizeObserverRef = useResizeObserver(([{ contentRect }]) => {
188
+ setContainerWidth(contentRect.width);
189
+ setContainerHeight(contentRect.height);
190
+ });
191
+ const mergedGridRef = useMergeRefs([
192
+ setGridRoot,
193
+ resizeObserverRef,
194
+ ref
195
+ ]);
196
+ useLayoutEffect(() => {
197
+ if (!gridRoot) return;
198
+ const { width, height } = gridRoot.getBoundingClientRect();
199
+ if (width > 0) setContainerWidth(width);
200
+ if (height > 0) setContainerHeight(height);
201
+ const parsed = Number.parseFloat(window.getComputedStyle(gridRoot).columnGap);
202
+ if (Number.isFinite(parsed) && parsed > 0) setGapPx(parsed);
203
+ }, [gridRoot]);
204
+ const effectiveColumns = useMemo(() => resolveColumnCount({
205
+ columns,
206
+ minColumnWidth
207
+ }, containerWidth, gapPx, DEFAULT_COLUMNS), [
208
+ minColumnWidth,
209
+ gapPx,
210
+ containerWidth,
211
+ columns
212
+ ]);
213
+ const columnWidth = (containerWidth - (effectiveColumns - 1) * gapPx) / effectiveColumns;
214
+ const minResizeWidthPx = gridSpanToPixelSize(1, 1, columnWidth, gapPx, null).widthPx;
215
+ const rowHeightPx = typeof rowHeight === "number" ? rowHeight : null;
216
+ const minResizeHeightPx = rowHeightPx === null ? void 0 : gridSpanToPixelSize(1, 1, columnWidth, gapPx, rowHeightPx).heightPx ?? void 0;
217
+ const spanBoundsByKey = useSpanBounds(itemLimits, columnWidth, gapPx, rowHeightPx, effectiveColumns);
218
+ const resizeLimitsByKey = useResizePixelLimits(spanBoundsByKey, columnWidth, gapPx, rowHeightPx);
219
+ const sourceLayout = temporaryLayout ?? layout;
220
+ const activeLayout = useMemo(() => {
221
+ if (spanBoundsByKey.size === 0) return sourceLayout;
222
+ let changed = false;
223
+ const bounded = sourceLayout.map((item) => {
224
+ const bounds = spanBoundsByKey.get(item.key);
225
+ if (!bounds) return item;
226
+ const width = typeof item.width === "number" ? clampSpan(item.width, bounds.minWidth, bounds.maxWidth) : item.width;
227
+ const height = clampSpan(item.height ?? 1, bounds.minHeight, bounds.maxHeight);
228
+ if (width === item.width && height === (item.height ?? 1)) return item;
229
+ changed = true;
230
+ return {
231
+ ...item,
232
+ width,
233
+ height
234
+ };
235
+ });
236
+ return changed ? bounded : sourceLayout;
237
+ }, [sourceLayout, spanBoundsByKey]);
238
+ const layoutMap = useMemo(() => {
239
+ const map = /* @__PURE__ */ new Map();
240
+ activeLayout.forEach((item) => map.set(item.key, item));
241
+ return map;
242
+ }, [activeLayout]);
243
+ const layoutKeys = useMemo(() => new Set(layout.map((item) => item.key)), [layout]);
244
+ const items = useMemo(() => activeLayout.map((item, index) => ({
245
+ item,
246
+ index
247
+ })).sort((a, b) => (a.item.order ?? a.index) - (b.item.order ?? b.index)).map(({ item }) => item.key), [activeLayout]);
248
+ const resolvedItemMap = useMemo(() => {
249
+ const fillWidths = resolveFillWidths(items, layoutMap, effectiveColumns, spanBoundsByKey);
250
+ if (fillWidths.size === 0) return layoutMap;
251
+ const map = /* @__PURE__ */ new Map();
252
+ for (const [key, item] of layoutMap) {
253
+ const fillW = fillWidths.get(key);
254
+ map.set(key, fillW !== void 0 ? {
255
+ ...item,
256
+ width: fillW
257
+ } : item);
258
+ }
259
+ return map;
260
+ }, [
261
+ items,
262
+ layoutMap,
263
+ effectiveColumns,
264
+ spanBoundsByKey
265
+ ]);
266
+ const [childrenMap, actionableAreaMap, remaining, renderedByKey] = useMemo(() => {
267
+ const childMap = /* @__PURE__ */ new Map();
268
+ const actionableMap = /* @__PURE__ */ new Map();
269
+ const rest = [];
270
+ const byKey = /* @__PURE__ */ new Map();
271
+ Children.forEach(children, (child) => {
272
+ if (!isValidElement(child)) {
273
+ rest.push(child);
274
+ return;
275
+ }
276
+ const key = child.key?.toString();
277
+ if (!key) {
278
+ rest.push(child);
279
+ return;
280
+ }
281
+ const typedChild = child;
282
+ const { actionableArea } = typedChild.props;
283
+ const stripped = actionableArea !== void 0 ? cloneElement(typedChild, { actionableArea: void 0 }) : child;
284
+ byKey.set(key, stripped);
285
+ if (layoutKeys.has(key)) {
286
+ if (actionableArea !== void 0) actionableMap.set(key, actionableArea);
287
+ childMap.set(key, stripped);
288
+ } else rest.push(child);
289
+ });
290
+ return [
291
+ childMap,
292
+ actionableMap,
293
+ rest,
294
+ byKey
295
+ ];
296
+ }, [children, layoutKeys]);
297
+ useLayoutEffect(() => {
298
+ for (const [key, child] of renderedByKey) childrenCacheRef.current.set(key, child);
299
+ }, [renderedByKey]);
300
+ const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }));
301
+ const handleDragStart = useEvent((event) => {
302
+ setActiveId(String(event.active.id));
303
+ lastReorderCursorRef.current = null;
304
+ });
305
+ const handleDragCancel = useEvent(() => {
306
+ setActiveId(null);
307
+ latestLayoutRef.current = void 0;
308
+ lastReorderCursorRef.current = null;
309
+ resizeBaselineRef.current = null;
310
+ setIsResizing(false);
311
+ setResizeSnapPreview(null);
312
+ setTemporaryLayout(void 0);
313
+ });
314
+ const handleDragMove = useEvent((event) => {
315
+ const { active, over } = event;
316
+ if (!over || active.id === over.id) return;
317
+ const activeRect = active.rect.current.translated;
318
+ if (!activeRect) return;
319
+ const activeCenterX = activeRect.left + activeRect.width / 2;
320
+ const activeCenterY = activeRect.top + activeRect.height / 2;
321
+ const lastCursor = lastReorderCursorRef.current;
322
+ if (lastCursor) {
323
+ const dx = activeCenterX - lastCursor.x;
324
+ const dy = activeCenterY - lastCursor.y;
325
+ if (dx * dx + dy * dy < 100) return;
326
+ }
327
+ const insertAfter = activeCenterX > over.rect.left + over.rect.width / 2;
328
+ const currentIndex = items.indexOf(String(active.id));
329
+ const overIndex = items.indexOf(String(over.id));
330
+ let newIndex;
331
+ if (insertAfter) newIndex = currentIndex > overIndex ? overIndex + 1 : overIndex;
332
+ else newIndex = currentIndex > overIndex ? overIndex : overIndex - 1;
333
+ newIndex = Math.max(0, Math.min(newIndex, items.length - 1));
334
+ if (newIndex === currentIndex) return;
335
+ const updatedItems = arrayMoveWithPinned(items, currentIndex, newIndex, (key) => layoutMap.get(key)?.draggable === false);
336
+ if (updatedItems.every((key, index) => key === items[index])) return;
337
+ const updatedLayout = (latestLayoutRef.current ?? layout).map((item) => ({
338
+ ...item,
339
+ order: updatedItems.indexOf(item.key)
340
+ }));
341
+ lastReorderCursorRef.current = {
342
+ x: activeCenterX,
343
+ y: activeCenterY
344
+ };
345
+ latestLayoutRef.current = updatedLayout;
346
+ captureLayoutSnapshotRef.current();
347
+ setTemporaryLayout(updatedLayout);
348
+ onPreviewLayout?.(updatedLayout);
349
+ });
350
+ const persistTemporaryLayout = useEvent(() => {
351
+ const latest = latestLayoutRef.current;
352
+ latestLayoutRef.current = void 0;
353
+ resizeBaselineRef.current = null;
354
+ setIsResizing(false);
355
+ setResizeSnapPreview(null);
356
+ if (!onChangeLayout || !latest) {
357
+ setTemporaryLayout(void 0);
358
+ return;
359
+ }
360
+ onChangeLayout(latest);
361
+ setTemporaryLayout(void 0);
362
+ });
363
+ const handleResize = useEvent((id, delta) => {
364
+ if (!editMode) return;
365
+ if (!isResizing) setIsResizing(true);
366
+ const relativeDelta = {
367
+ width: Math.round(delta.width / (columnWidth + gapPx)),
368
+ height: rowHeight === "auto" ? 0 : Math.round(delta.height / (rowHeight + gapPx))
369
+ };
370
+ const bounds = spanBoundsByKey.get(id);
371
+ if (!resizeBaselineRef.current) {
372
+ const baseItem = layoutMap.get(id);
373
+ const resolvedItem = resolvedItemMap.get(id);
374
+ let baseWidth;
375
+ if (baseItem?.width === "full") baseWidth = bounds?.maxWidth ?? effectiveColumns;
376
+ else if (baseItem?.width === "fill") baseWidth = typeof resolvedItem?.width === "number" ? resolvedItem.width : 1;
377
+ else baseWidth = baseItem?.width ?? 1;
378
+ resizeBaselineRef.current = {
379
+ width: baseWidth,
380
+ height: baseItem?.height ?? 1
381
+ };
382
+ }
383
+ const baseline = resizeBaselineRef.current;
384
+ const newWidth = clampSpan(baseline.width + relativeDelta.width, bounds?.minWidth ?? 1, bounds?.maxWidth ?? effectiveColumns);
385
+ const newHeight = clampSpan(baseline.height + relativeDelta.height, bounds?.minHeight ?? 1, bounds?.maxHeight ?? Infinity);
386
+ setResizeSnapPreview({
387
+ id,
388
+ snap: gridSpanToPixelSize(newWidth, newHeight, columnWidth, gapPx, rowHeightPx)
389
+ });
390
+ const currentItem = latestLayoutRef.current?.find((item) => item.key === id) ?? layoutMap.get(id);
391
+ if (currentItem && currentItem.width === newWidth && (currentItem.height ?? 1) === newHeight) return;
392
+ const updatedLayout = (latestLayoutRef.current ?? layout).map((item) => item.key === id ? {
393
+ ...item,
394
+ width: newWidth,
395
+ height: newHeight
396
+ } : item);
397
+ latestLayoutRef.current = updatedLayout;
398
+ captureLayoutSnapshotRef.current();
399
+ setTemporaryLayout(updatedLayout);
400
+ onPreviewLayout?.(updatedLayout);
401
+ });
402
+ const activeClone = activeId ? childrenMap.get(activeId) : null;
403
+ const DragPreview = renderDragPreview;
404
+ const dragOverlayContent = activeId && activeClone ? /* @__PURE__ */ jsx("div", {
405
+ className: grid_module_default["drag-preview-frame"],
406
+ children: /* @__PURE__ */ jsx("div", {
407
+ className: grid_module_default["drag-preview-frame__lift"],
408
+ children: DragPreview ? /* @__PURE__ */ jsx(DragPreview, {
409
+ itemId: activeId,
410
+ children: activeClone
411
+ }) : activeClone
412
+ })
413
+ }) : null;
414
+ const Overlay = renderGridOverlay ?? GridOverlay;
415
+ const overlayRowHeight = typeof rowHeight === "number" ? rowHeight : void 0;
416
+ const overlayRows = useMemo(() => {
417
+ if (overlayRowHeight === void 0 || containerHeight <= 0) return;
418
+ const rowTile = overlayRowHeight + gapPx;
419
+ return Math.max(1, Math.floor((containerHeight + gapPx) / rowTile));
420
+ }, [
421
+ overlayRowHeight,
422
+ containerHeight,
423
+ gapPx
424
+ ]);
425
+ const gridOverlay = useMemo(() => /* @__PURE__ */ jsx(Overlay, {
426
+ columns: effectiveColumns,
427
+ rowHeight: overlayRowHeight,
428
+ rows: overlayRows,
429
+ isActive: editMode
430
+ }), [
431
+ Overlay,
432
+ editMode,
433
+ effectiveColumns,
434
+ overlayRowHeight,
435
+ overlayRows
436
+ ]);
437
+ const layoutFingerprint = useMemo(() => getLayoutFingerprint([...resolvedItemMap.values()]), [resolvedItemMap]);
438
+ const excludeLayoutAnimationKey = activeId ?? (isResizing ? resizeSnapPreview?.id : null);
439
+ const { captureLayoutSnapshot, getPositionsBeforeLastChange } = useLayoutShiftAnimation({
440
+ container: gridRoot,
441
+ enabled: editMode,
442
+ layoutFingerprint,
443
+ excludeItemKey: excludeLayoutAnimationKey
444
+ });
445
+ const { exitingItems, clearExitingItem } = useItemExitAnimation({
446
+ container: gridRoot,
447
+ enabled: editMode,
448
+ layoutKeys,
449
+ getPositionsBeforeLastChange,
450
+ childrenCacheRef
451
+ });
452
+ const layoutAnimating = editMode;
453
+ useLayoutEffect(() => {
454
+ captureLayoutSnapshotRef.current = captureLayoutSnapshot;
455
+ }, [captureLayoutSnapshot]);
456
+ return /* @__PURE__ */ jsxs(DndContext, {
457
+ sensors,
458
+ onDragStart: handleDragStart,
459
+ onDragCancel: handleDragCancel,
460
+ onDragMove: handleDragMove,
461
+ onDragEnd: () => {
462
+ persistTemporaryLayout();
463
+ lastReorderCursorRef.current = null;
464
+ setActiveId(null);
465
+ },
466
+ children: [/* @__PURE__ */ jsx(SortableContext, {
467
+ items,
468
+ strategy: NO_SORT_STRATEGY,
469
+ children: /* @__PURE__ */ jsxs("div", {
470
+ ...divProps,
471
+ ref: mergedGridRef,
472
+ className: clsx(grid_module_default.grid, layoutAnimating && layout_shift_animation_module_default["layout-animating"], className),
473
+ "data-wp-grid-dragging": activeId || void 0,
474
+ "data-wp-grid-resizing": isResizing || void 0,
475
+ style: {
476
+ ...style,
477
+ gridTemplateColumns: `repeat(${effectiveColumns}, minmax(0, 1fr))`,
478
+ gridAutoRows: rowHeight
479
+ },
480
+ children: [
481
+ gridOverlay,
482
+ items.map((id) => {
483
+ const limitsPx = resizeLimitsByKey.get(id);
484
+ return /* @__PURE__ */ jsx(GridItem, {
485
+ item: resolvedItemMap.get(id),
486
+ maxColumns: spanBoundsByKey.get(id)?.maxWidth ?? effectiveColumns,
487
+ disabled: !editMode,
488
+ draggable: layoutMap.get(id)?.draggable !== false,
489
+ resizable: layoutMap.get(id)?.resizable !== false,
490
+ verticalResizable: rowHeight !== "auto",
491
+ interacting: activeId !== null || isResizing,
492
+ dragging: activeId !== null,
493
+ onResize: handleResize,
494
+ onResizeEnd: persistTemporaryLayout,
495
+ resizeSnapPreview: resizeSnapPreview?.id === id ? resizeSnapPreview.snap : null,
496
+ minResizeWidthPx: limitsPx?.minWidthPx ?? minResizeWidthPx,
497
+ minResizeHeightPx: limitsPx?.minHeightPx ?? minResizeHeightPx,
498
+ maxResizeWidthPx: limitsPx?.maxWidthPx,
499
+ maxResizeHeightPx: limitsPx?.maxHeightPx ?? void 0,
500
+ actionableArea: actionableAreaMap.get(id),
501
+ renderResizeHandle,
502
+ children: childrenMap.get(id)
503
+ }, id);
504
+ }),
505
+ remaining,
506
+ exitingItems.map(({ key, rect, child }) => /* @__PURE__ */ jsx(ItemExitOverlay, {
507
+ itemKey: key,
508
+ rect,
509
+ onAnimationEnd: () => clearExitingItem(key),
510
+ children: child
511
+ }, `exiting-${key}`))
512
+ ]
513
+ })
514
+ }), /* @__PURE__ */ jsx(DragOverlay, {
515
+ dropAnimation: dashboardDragDropAnimation,
516
+ children: dragOverlayContent
517
+ })]
518
+ });
519
+ });
520
+ export { DashboardGrid };
521
+
522
+ //# sourceMappingURL=index.mjs.map