panelgrid 0.4.0 → 0.4.2
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/dist/PanelGridRenderer.cjs +1 -1
- package/dist/PanelGridRenderer.cjs.map +1 -1
- package/dist/PanelGridRenderer.mjs +1 -1
- package/dist/PanelGridRenderer.mjs.map +1 -1
- package/dist/helpers/rearrangement.cjs +34 -8
- package/dist/helpers/rearrangement.cjs.map +1 -1
- package/dist/helpers/rearrangement.mjs +34 -8
- package/dist/helpers/rearrangement.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -64,7 +64,7 @@ function PanelGridRenderer({ children: ItemComponent }) {
|
|
|
64
64
|
"data-pg-y": y,
|
|
65
65
|
"data-pg-w": w,
|
|
66
66
|
"data-pg-h": h,
|
|
67
|
-
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ItemComponent, { id: key }), resizeHandlePositions.map((pos) => {
|
|
67
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ItemComponent, { id: key }), resizeHandleProps && resizeHandlePositions.map((pos) => {
|
|
68
68
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
69
69
|
className: `panelgrid-resize-handle panelgrid-resize-handle--${pos}`,
|
|
70
70
|
...resizeHandleProps,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PanelGridRenderer.cjs","names":["usePanelGridState","usePanelGridControls","getGridRowCount"],"sources":["../src/PanelGridRenderer.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentType } from \"react\";\nimport { useLayoutEffect, useRef } from \"react\";\nimport { getGridRowCount } from \"./helpers/gridCalculations\";\nimport { usePanelGridControls, usePanelGridState } from \"./PanelGridProvider\";\nimport type { PanelId } from \"./types\";\n\ninterface PanelGridRendererProps {\n children: ComponentType<{ id: PanelId }>;\n}\n\nexport function PanelGridRenderer({ children: ItemComponent }: PanelGridRendererProps) {\n const { panels, columnCount, gap, baseSize, resizeHandlePositions, ghostPanelRef } = usePanelGridState();\n const { setBaseSize } = usePanelGridControls();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const rowCount = getGridRowCount(\n panels.map(({ panelProps: p }) => ({\n id: p.key,\n x: p.positionData.x,\n y: p.positionData.y,\n w: p.positionData.w,\n h: p.positionData.h,\n }))\n );\n const count = Math.max(columnCount * (rowCount + 1), columnCount * columnCount);\n\n useLayoutEffect(() => {\n if (!containerRef.current) return;\n const observer = new ResizeObserver((entries) => {\n const [entry] = entries;\n const rect = entry.contentRect;\n const baseSize = Math.floor((rect.width - gap * (columnCount - 1)) / columnCount);\n setBaseSize(baseSize);\n });\n observer.observe(containerRef.current);\n return () => observer.disconnect();\n }, [columnCount, gap, setBaseSize]);\n\n return (\n <div\n className=\"panelgrid-renderer\"\n style={{\n \"--column-count\": `${columnCount}`,\n \"--gap\": `${gap}px`,\n opacity: baseSize ? 1 : 0,\n }}\n ref={containerRef}\n >\n {Array.from({ length: count }).map((_, i) => {\n return <div key={i} className=\"panelgrid-panel-placeholder\" />;\n })}\n\n <div className=\"panelgrid-panel-ghost\" ref={ghostPanelRef}></div>\n\n {panels.map((panel) => {\n const { panelProps, resizeHandleProps } = panel;\n const { key, lockSize, style, positionData, ref, onMouseDown } = panelProps;\n\n const className = lockSize ? \"panelgrid-panel panelgrid-panel--size-locked\" : \"panelgrid-panel\";\n const { x, y, w, h } = positionData;\n\n return (\n <div\n key={key}\n className={className}\n style={style}\n ref={ref}\n onMouseDown={onMouseDown}\n data-panel-id={key}\n data-pg-x={x}\n data-pg-y={y}\n data-pg-w={w}\n data-pg-h={h}\n >\n <ItemComponent id={key} />\n {resizeHandlePositions.map((pos) => {\n
|
|
1
|
+
{"version":3,"file":"PanelGridRenderer.cjs","names":["usePanelGridState","usePanelGridControls","getGridRowCount"],"sources":["../src/PanelGridRenderer.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentType } from \"react\";\nimport { useLayoutEffect, useRef } from \"react\";\nimport { getGridRowCount } from \"./helpers/gridCalculations\";\nimport { usePanelGridControls, usePanelGridState } from \"./PanelGridProvider\";\nimport type { PanelId } from \"./types\";\n\ninterface PanelGridRendererProps {\n children: ComponentType<{ id: PanelId }>;\n}\n\nexport function PanelGridRenderer({ children: ItemComponent }: PanelGridRendererProps) {\n const { panels, columnCount, gap, baseSize, resizeHandlePositions, ghostPanelRef } = usePanelGridState();\n const { setBaseSize } = usePanelGridControls();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const rowCount = getGridRowCount(\n panels.map(({ panelProps: p }) => ({\n id: p.key,\n x: p.positionData.x,\n y: p.positionData.y,\n w: p.positionData.w,\n h: p.positionData.h,\n }))\n );\n const count = Math.max(columnCount * (rowCount + 1), columnCount * columnCount);\n\n useLayoutEffect(() => {\n if (!containerRef.current) return;\n const observer = new ResizeObserver((entries) => {\n const [entry] = entries;\n const rect = entry.contentRect;\n const baseSize = Math.floor((rect.width - gap * (columnCount - 1)) / columnCount);\n setBaseSize(baseSize);\n });\n observer.observe(containerRef.current);\n return () => observer.disconnect();\n }, [columnCount, gap, setBaseSize]);\n\n return (\n <div\n className=\"panelgrid-renderer\"\n style={{\n \"--column-count\": `${columnCount}`,\n \"--gap\": `${gap}px`,\n opacity: baseSize ? 1 : 0,\n }}\n ref={containerRef}\n >\n {Array.from({ length: count }).map((_, i) => {\n return <div key={i} className=\"panelgrid-panel-placeholder\" />;\n })}\n\n <div className=\"panelgrid-panel-ghost\" ref={ghostPanelRef}></div>\n\n {panels.map((panel) => {\n const { panelProps, resizeHandleProps } = panel;\n const { key, lockSize, style, positionData, ref, onMouseDown } = panelProps;\n\n const className = lockSize ? \"panelgrid-panel panelgrid-panel--size-locked\" : \"panelgrid-panel\";\n const { x, y, w, h } = positionData;\n\n return (\n <div\n key={key}\n className={className}\n style={style}\n ref={ref}\n onMouseDown={onMouseDown}\n data-panel-id={key}\n data-pg-x={x}\n data-pg-y={y}\n data-pg-w={w}\n data-pg-h={h}\n >\n <ItemComponent id={key} />\n {resizeHandleProps &&\n resizeHandlePositions.map((pos) => {\n return (\n <span\n key={pos}\n className={`panelgrid-resize-handle panelgrid-resize-handle--${pos}`}\n {...resizeHandleProps}\n data-pg-resize-handle={pos}\n />\n );\n })}\n </div>\n );\n })}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,kBAAkB,EAAE,UAAU,iBAAyC;CACrF,MAAM,EAAE,QAAQ,aAAa,KAAK,UAAU,uBAAuB,kBAAkBA,6CAAmB;CACxG,MAAM,EAAE,gBAAgBC,gDAAsB;CAC9C,MAAM,iCAA6C,KAAK;CACxD,MAAM,WAAWC,yCACf,OAAO,KAAK,EAAE,YAAY,SAAS;EACjC,IAAI,EAAE;EACN,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EACnB,EAAE,CACJ;CACD,MAAM,QAAQ,KAAK,IAAI,eAAe,WAAW,IAAI,cAAc,YAAY;AAE/E,kCAAsB;AACpB,MAAI,CAAC,aAAa,QAAS;EAC3B,MAAM,WAAW,IAAI,gBAAgB,YAAY;GAC/C,MAAM,CAAC,SAAS;GAChB,MAAM,OAAO,MAAM;AAEnB,eADiB,KAAK,OAAO,KAAK,QAAQ,OAAO,cAAc,MAAM,YAAY,CAC5D;IACrB;AACF,WAAS,QAAQ,aAAa,QAAQ;AACtC,eAAa,SAAS,YAAY;IACjC;EAAC;EAAa;EAAK;EAAY,CAAC;AAEnC,QACE,4CAAC;EACC,WAAU;EACV,OAAO;GACL,kBAAkB,GAAG;GACrB,SAAS,GAAG,IAAI;GAChB,SAAS,WAAW,IAAI;GACzB;EACD,KAAK;;GAEJ,MAAM,KAAK,EAAE,QAAQ,OAAO,CAAC,CAAC,KAAK,GAAG,MAAM;AAC3C,WAAO,2CAAC,SAAY,WAAU,iCAAb,EAA6C;KAC9D;GAEF,2CAAC;IAAI,WAAU;IAAwB,KAAK;KAAqB;GAEhE,OAAO,KAAK,UAAU;IACrB,MAAM,EAAE,YAAY,sBAAsB;IAC1C,MAAM,EAAE,KAAK,UAAU,OAAO,cAAc,KAAK,gBAAgB;IAEjE,MAAM,YAAY,WAAW,iDAAiD;IAC9E,MAAM,EAAE,GAAG,GAAG,GAAG,MAAM;AAEvB,WACE,4CAAC;KAEY;KACJ;KACF;KACQ;KACb,iBAAe;KACf,aAAW;KACX,aAAW;KACX,aAAW;KACX,aAAW;gBAEX,2CAAC,iBAAc,IAAI,MAAO,EACzB,qBACC,sBAAsB,KAAK,QAAQ;AACjC,aACE,2CAAC;OAEC,WAAW,oDAAoD;OAC/D,GAAI;OACJ,yBAAuB;SAHlB,IAIL;OAEJ;OAtBC,IAuBD;KAER;;GACE"}
|
|
@@ -64,7 +64,7 @@ function PanelGridRenderer({ children: ItemComponent }) {
|
|
|
64
64
|
"data-pg-y": y,
|
|
65
65
|
"data-pg-w": w,
|
|
66
66
|
"data-pg-h": h,
|
|
67
|
-
children: [/* @__PURE__ */ jsx(ItemComponent, { id: key }), resizeHandlePositions.map((pos) => {
|
|
67
|
+
children: [/* @__PURE__ */ jsx(ItemComponent, { id: key }), resizeHandleProps && resizeHandlePositions.map((pos) => {
|
|
68
68
|
return /* @__PURE__ */ jsx("span", {
|
|
69
69
|
className: `panelgrid-resize-handle panelgrid-resize-handle--${pos}`,
|
|
70
70
|
...resizeHandleProps,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PanelGridRenderer.mjs","names":[],"sources":["../src/PanelGridRenderer.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentType } from \"react\";\nimport { useLayoutEffect, useRef } from \"react\";\nimport { getGridRowCount } from \"./helpers/gridCalculations\";\nimport { usePanelGridControls, usePanelGridState } from \"./PanelGridProvider\";\nimport type { PanelId } from \"./types\";\n\ninterface PanelGridRendererProps {\n children: ComponentType<{ id: PanelId }>;\n}\n\nexport function PanelGridRenderer({ children: ItemComponent }: PanelGridRendererProps) {\n const { panels, columnCount, gap, baseSize, resizeHandlePositions, ghostPanelRef } = usePanelGridState();\n const { setBaseSize } = usePanelGridControls();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const rowCount = getGridRowCount(\n panels.map(({ panelProps: p }) => ({\n id: p.key,\n x: p.positionData.x,\n y: p.positionData.y,\n w: p.positionData.w,\n h: p.positionData.h,\n }))\n );\n const count = Math.max(columnCount * (rowCount + 1), columnCount * columnCount);\n\n useLayoutEffect(() => {\n if (!containerRef.current) return;\n const observer = new ResizeObserver((entries) => {\n const [entry] = entries;\n const rect = entry.contentRect;\n const baseSize = Math.floor((rect.width - gap * (columnCount - 1)) / columnCount);\n setBaseSize(baseSize);\n });\n observer.observe(containerRef.current);\n return () => observer.disconnect();\n }, [columnCount, gap, setBaseSize]);\n\n return (\n <div\n className=\"panelgrid-renderer\"\n style={{\n \"--column-count\": `${columnCount}`,\n \"--gap\": `${gap}px`,\n opacity: baseSize ? 1 : 0,\n }}\n ref={containerRef}\n >\n {Array.from({ length: count }).map((_, i) => {\n return <div key={i} className=\"panelgrid-panel-placeholder\" />;\n })}\n\n <div className=\"panelgrid-panel-ghost\" ref={ghostPanelRef}></div>\n\n {panels.map((panel) => {\n const { panelProps, resizeHandleProps } = panel;\n const { key, lockSize, style, positionData, ref, onMouseDown } = panelProps;\n\n const className = lockSize ? \"panelgrid-panel panelgrid-panel--size-locked\" : \"panelgrid-panel\";\n const { x, y, w, h } = positionData;\n\n return (\n <div\n key={key}\n className={className}\n style={style}\n ref={ref}\n onMouseDown={onMouseDown}\n data-panel-id={key}\n data-pg-x={x}\n data-pg-y={y}\n data-pg-w={w}\n data-pg-h={h}\n >\n <ItemComponent id={key} />\n {resizeHandlePositions.map((pos) => {\n
|
|
1
|
+
{"version":3,"file":"PanelGridRenderer.mjs","names":[],"sources":["../src/PanelGridRenderer.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentType } from \"react\";\nimport { useLayoutEffect, useRef } from \"react\";\nimport { getGridRowCount } from \"./helpers/gridCalculations\";\nimport { usePanelGridControls, usePanelGridState } from \"./PanelGridProvider\";\nimport type { PanelId } from \"./types\";\n\ninterface PanelGridRendererProps {\n children: ComponentType<{ id: PanelId }>;\n}\n\nexport function PanelGridRenderer({ children: ItemComponent }: PanelGridRendererProps) {\n const { panels, columnCount, gap, baseSize, resizeHandlePositions, ghostPanelRef } = usePanelGridState();\n const { setBaseSize } = usePanelGridControls();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const rowCount = getGridRowCount(\n panels.map(({ panelProps: p }) => ({\n id: p.key,\n x: p.positionData.x,\n y: p.positionData.y,\n w: p.positionData.w,\n h: p.positionData.h,\n }))\n );\n const count = Math.max(columnCount * (rowCount + 1), columnCount * columnCount);\n\n useLayoutEffect(() => {\n if (!containerRef.current) return;\n const observer = new ResizeObserver((entries) => {\n const [entry] = entries;\n const rect = entry.contentRect;\n const baseSize = Math.floor((rect.width - gap * (columnCount - 1)) / columnCount);\n setBaseSize(baseSize);\n });\n observer.observe(containerRef.current);\n return () => observer.disconnect();\n }, [columnCount, gap, setBaseSize]);\n\n return (\n <div\n className=\"panelgrid-renderer\"\n style={{\n \"--column-count\": `${columnCount}`,\n \"--gap\": `${gap}px`,\n opacity: baseSize ? 1 : 0,\n }}\n ref={containerRef}\n >\n {Array.from({ length: count }).map((_, i) => {\n return <div key={i} className=\"panelgrid-panel-placeholder\" />;\n })}\n\n <div className=\"panelgrid-panel-ghost\" ref={ghostPanelRef}></div>\n\n {panels.map((panel) => {\n const { panelProps, resizeHandleProps } = panel;\n const { key, lockSize, style, positionData, ref, onMouseDown } = panelProps;\n\n const className = lockSize ? \"panelgrid-panel panelgrid-panel--size-locked\" : \"panelgrid-panel\";\n const { x, y, w, h } = positionData;\n\n return (\n <div\n key={key}\n className={className}\n style={style}\n ref={ref}\n onMouseDown={onMouseDown}\n data-panel-id={key}\n data-pg-x={x}\n data-pg-y={y}\n data-pg-w={w}\n data-pg-h={h}\n >\n <ItemComponent id={key} />\n {resizeHandleProps &&\n resizeHandlePositions.map((pos) => {\n return (\n <span\n key={pos}\n className={`panelgrid-resize-handle panelgrid-resize-handle--${pos}`}\n {...resizeHandleProps}\n data-pg-resize-handle={pos}\n />\n );\n })}\n </div>\n );\n })}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,kBAAkB,EAAE,UAAU,iBAAyC;CACrF,MAAM,EAAE,QAAQ,aAAa,KAAK,UAAU,uBAAuB,kBAAkB,mBAAmB;CACxG,MAAM,EAAE,gBAAgB,sBAAsB;CAC9C,MAAM,eAAe,OAA8B,KAAK;CACxD,MAAM,WAAW,gBACf,OAAO,KAAK,EAAE,YAAY,SAAS;EACjC,IAAI,EAAE;EACN,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EAClB,GAAG,EAAE,aAAa;EACnB,EAAE,CACJ;CACD,MAAM,QAAQ,KAAK,IAAI,eAAe,WAAW,IAAI,cAAc,YAAY;AAE/E,uBAAsB;AACpB,MAAI,CAAC,aAAa,QAAS;EAC3B,MAAM,WAAW,IAAI,gBAAgB,YAAY;GAC/C,MAAM,CAAC,SAAS;GAChB,MAAM,OAAO,MAAM;AAEnB,eADiB,KAAK,OAAO,KAAK,QAAQ,OAAO,cAAc,MAAM,YAAY,CAC5D;IACrB;AACF,WAAS,QAAQ,aAAa,QAAQ;AACtC,eAAa,SAAS,YAAY;IACjC;EAAC;EAAa;EAAK;EAAY,CAAC;AAEnC,QACE,qBAAC;EACC,WAAU;EACV,OAAO;GACL,kBAAkB,GAAG;GACrB,SAAS,GAAG,IAAI;GAChB,SAAS,WAAW,IAAI;GACzB;EACD,KAAK;;GAEJ,MAAM,KAAK,EAAE,QAAQ,OAAO,CAAC,CAAC,KAAK,GAAG,MAAM;AAC3C,WAAO,oBAAC,SAAY,WAAU,iCAAb,EAA6C;KAC9D;GAEF,oBAAC;IAAI,WAAU;IAAwB,KAAK;KAAqB;GAEhE,OAAO,KAAK,UAAU;IACrB,MAAM,EAAE,YAAY,sBAAsB;IAC1C,MAAM,EAAE,KAAK,UAAU,OAAO,cAAc,KAAK,gBAAgB;IAEjE,MAAM,YAAY,WAAW,iDAAiD;IAC9E,MAAM,EAAE,GAAG,GAAG,GAAG,MAAM;AAEvB,WACE,qBAAC;KAEY;KACJ;KACF;KACQ;KACb,iBAAe;KACf,aAAW;KACX,aAAW;KACX,aAAW;KACX,aAAW;gBAEX,oBAAC,iBAAc,IAAI,MAAO,EACzB,qBACC,sBAAsB,KAAK,QAAQ;AACjC,aACE,oBAAC;OAEC,WAAW,oDAAoD;OAC/D,GAAI;OACJ,yBAAuB;SAHlB,IAIL;OAEJ;OAtBC,IAuBD;KAER;;GACE"}
|
|
@@ -124,6 +124,7 @@ function rearrangePanelsInternal(movingPanel, allPanels, columnCount) {
|
|
|
124
124
|
panelMap.set(movingPanel.id, { ...movingPanel });
|
|
125
125
|
const queue = [{ ...movingPanel }];
|
|
126
126
|
const processed = /* @__PURE__ */ new Set();
|
|
127
|
+
const repositioned = /* @__PURE__ */ new Set();
|
|
127
128
|
const processCount = /* @__PURE__ */ new Map();
|
|
128
129
|
const MAX_PROCESS_COUNT = 10;
|
|
129
130
|
while (queue.length > 0) {
|
|
@@ -146,25 +147,50 @@ function rearrangePanelsInternal(movingPanel, allPanels, columnCount) {
|
|
|
146
147
|
if (panelA.y !== panelB.y) return panelA.y - panelB.y;
|
|
147
148
|
return panelA.x - panelB.x;
|
|
148
149
|
});
|
|
149
|
-
const pushedInIteration = /* @__PURE__ */ new Set();
|
|
150
150
|
for (const collidingId of sortedCollidingIds) {
|
|
151
151
|
const colliding = panelMap.get(collidingId);
|
|
152
152
|
if (!colliding) continue;
|
|
153
153
|
const newPos = findNewPosition(colliding, current, columnCount);
|
|
154
|
-
|
|
154
|
+
let candidate = {
|
|
155
155
|
...colliding,
|
|
156
156
|
x: newPos.x,
|
|
157
157
|
y: newPos.y
|
|
158
158
|
};
|
|
159
|
-
let
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
159
|
+
let needsPushDown = false;
|
|
160
|
+
let adjusted = true;
|
|
161
|
+
let adjustAttempts = 0;
|
|
162
|
+
while (adjusted && !needsPushDown && adjustAttempts < repositioned.size + 1) {
|
|
163
|
+
adjusted = false;
|
|
164
|
+
adjustAttempts++;
|
|
165
|
+
for (const repoId of repositioned) {
|
|
166
|
+
const repoPanel = panelMap.get(repoId);
|
|
167
|
+
if (!repoPanel || repoId === collidingId) continue;
|
|
168
|
+
if (!rectanglesOverlap(candidate, repoPanel)) continue;
|
|
169
|
+
const furtherX = repoPanel.x + repoPanel.w;
|
|
170
|
+
if (furtherX + candidate.w <= columnCount) {
|
|
171
|
+
candidate = {
|
|
172
|
+
...candidate,
|
|
173
|
+
x: furtherX
|
|
174
|
+
};
|
|
175
|
+
adjusted = true;
|
|
176
|
+
break;
|
|
177
|
+
} else {
|
|
178
|
+
needsPushDown = true;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (needsPushDown) {
|
|
184
|
+
const pushDown = current.y + current.h - colliding.y;
|
|
185
|
+
candidate = {
|
|
186
|
+
...candidate,
|
|
187
|
+
x: colliding.x,
|
|
188
|
+
y: colliding.y + (pushDown > 0 ? pushDown : 1)
|
|
189
|
+
};
|
|
163
190
|
}
|
|
164
|
-
if (wouldCollideWithPushed) continue;
|
|
165
191
|
panelMap.set(collidingId, candidate);
|
|
166
192
|
queue.push(candidate);
|
|
167
|
-
|
|
193
|
+
repositioned.add(collidingId);
|
|
168
194
|
}
|
|
169
195
|
panelMap.set(current.id, current);
|
|
170
196
|
processed.add(current.id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rearrangement.cjs","names":["queue: PanelCoordinate[]","candidate: PanelCoordinate"],"sources":["../../src/helpers/rearrangement.ts"],"sourcesContent":["import type { PanelCoordinate, PanelId } from \"../types\";\n\n/**\n * Check if two rectangles overlap using AABB (Axis-Aligned Bounding Box) test\n * 2つの矩形が重なっているかをAABBテストで判定\n */\nexport function rectanglesOverlap(\n a: { x: number; y: number; w: number; h: number },\n b: { x: number; y: number; w: number; h: number }\n): boolean {\n return !(\n (\n a.x + a.w <= b.x || // a is to the left of b\n b.x + b.w <= a.x || // b is to the left of a\n a.y + a.h <= b.y || // a is above b\n b.y + b.h <= a.y\n ) // b is above a\n );\n}\n\n/**\n * Detect all panels that collide with the given panel\n * 指定されたパネルと衝突する全てのパネルを検出\n */\nexport function detectCollisions(panel: PanelCoordinate, panelMap: Map<PanelId, PanelCoordinate>): PanelId[] {\n const collisions = new Set<PanelId>();\n\n for (const [id, other] of panelMap) {\n if (id === panel.id) continue;\n\n if (rectanglesOverlap(panel, other)) {\n collisions.add(id);\n }\n }\n\n return Array.from(collisions);\n}\n\n/**\n * Check if a panel at the given position would collide with any existing panels\n * 指定された位置にパネルを配置した場合に衝突があるかをチェック\n */\nexport function hasCollision(\n candidate: { x: number; y: number; w: number; h: number },\n excludeId: PanelId,\n panelMap: Map<PanelId, PanelCoordinate>\n): boolean {\n for (const [id, panel] of panelMap) {\n if (id === excludeId) continue;\n if (rectanglesOverlap(candidate, panel)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calculate the minimum distance to push a panel to avoid collision\n * パネルを押しのけるための最小距離を計算\n */\nfunction calculatePushDistance(\n pusher: PanelCoordinate,\n pushed: PanelCoordinate,\n columnCount: number\n): { direction: \"right\" | \"down\"; distance: number } | null {\n // Calculate how far to push horizontally (to the right)\n // 横方向(右)にどれだけ押すか計算\n const pushRight = pusher.x + pusher.w - pushed.x;\n const canPushRight = pushed.x + pushed.w + pushRight <= columnCount;\n\n // Calculate how far to push vertically (down)\n // 縦方向(下)にどれだけ押すか計算\n const pushDown = pusher.y + pusher.h - pushed.y;\n\n // Priority 1: Horizontal push if possible\n // 優先順位1: 可能なら横方向に押す\n if (canPushRight && pushRight > 0) {\n return { direction: \"right\", distance: pushRight };\n }\n\n // Priority 2: Vertical push\n // 優先順位2: 縦方向に押す\n if (pushDown > 0) {\n return { direction: \"down\", distance: pushDown };\n }\n\n return null;\n}\n\n/**\n * Find a new position for a panel by pushing it away from the colliding panel\n * Priority: horizontal (right) first, then vertical (down)\n * 衝突したパネルを押しのける方向に移動させる\n * 優先順位: 横方向(右)→縦方向(下)\n */\nexport function findNewPosition(\n panel: PanelCoordinate,\n pusher: PanelCoordinate,\n columnCount: number\n): { x: number; y: number } {\n const pushInfo = calculatePushDistance(pusher, panel, columnCount);\n\n if (!pushInfo) {\n // No push needed or can't determine direction\n // Fallback: move down\n return { x: panel.x, y: panel.y + 1 };\n }\n\n if (pushInfo.direction === \"right\") {\n // Push horizontally to the right\n // 横方向(右)に押す\n const newX = panel.x + pushInfo.distance;\n if (newX + panel.w <= columnCount) {\n return { x: newX, y: panel.y };\n }\n // Can't fit horizontally, push down instead\n // 横方向に入らない場合は下に押す\n }\n\n // Push vertically down\n // 縦方向(下)に押す\n return { x: panel.x, y: panel.y + pushInfo.distance };\n}\n\n/**\n * Constrain a panel to stay within grid boundaries\n * パネルをグリッド境界内に制約\n */\nfunction constrainToGrid(panel: PanelCoordinate, columnCount: number): PanelCoordinate {\n // Ensure x + w doesn't exceed columnCount\n // x + w が columnCount を超えないようにする\n const maxX = Math.max(0, columnCount - panel.w);\n const constrainedX = Math.max(0, Math.min(panel.x, maxX));\n\n // Ensure y is non-negative\n // y が負にならないようにする\n const constrainedY = Math.max(0, panel.y);\n\n return {\n ...panel,\n x: constrainedX,\n y: constrainedY,\n };\n}\n\n/**\n * Rearrange panels to resolve collisions when a panel is moved or resized\n * Panels are moved horizontally first, then vertically if needed\n * For compound resizes (both width and height change), uses two-phase processing\n * パネルの移動・リサイズ時に衝突を解決するようにパネルを再配置\n * 横方向を優先し、必要に応じて縦方向に移動\n * 幅と高さが同時に変更される場合は、二段階処理を使用\n */\nexport function rearrangePanels(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Constrain the moving panel to grid boundaries\n // 移動中のパネルをグリッド境界内に制約\n const constrainedMovingPanel = constrainToGrid(movingPanel, columnCount);\n\n // Check if this is a compound resize (both width and height changed)\n // 幅と高さの両方が変更されたかチェック\n const originalPanel = allPanels.find((p) => p.id === movingPanel.id);\n if (originalPanel) {\n const widthChanged = originalPanel.w !== constrainedMovingPanel.w;\n const heightChanged = originalPanel.h !== constrainedMovingPanel.h;\n\n if (widthChanged && heightChanged) {\n // Two-phase processing: width first, then height\n // 二段階処理: 幅を先に、次に高さ\n\n // Phase 1: Apply width change only\n // フェーズ1: 幅の変更のみを適用\n const widthOnlyPanel = {\n ...constrainedMovingPanel,\n h: originalPanel.h, // Keep original height\n };\n const afterWidthChange = rearrangePanelsInternal(widthOnlyPanel, allPanels, columnCount);\n\n // Phase 2: Apply height change to the result\n // フェーズ2: 結果に高さの変更を適用\n const heightChangedPanel = {\n ...constrainedMovingPanel,\n // Use the new position if panel-1 was moved during width phase\n x: afterWidthChange.find((p) => p.id === movingPanel.id)?.x ?? constrainedMovingPanel.x,\n y: afterWidthChange.find((p) => p.id === movingPanel.id)?.y ?? constrainedMovingPanel.y,\n };\n return rearrangePanelsInternal(heightChangedPanel, afterWidthChange, columnCount);\n }\n }\n\n // Single dimension change or move - use normal processing\n // 単一次元の変更または移動 - 通常の処理を使用\n return rearrangePanelsInternal(constrainedMovingPanel, allPanels, columnCount);\n}\n\n/**\n * Internal implementation of panel rearrangement\n * パネル再配置の内部実装\n */\nfunction rearrangePanelsInternal(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Create a map for fast panel lookup\n // パネルIDから座標への高速マップを作成\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, { ...panel });\n }\n\n // Update the moving panel's position in the map\n // 移動中のパネルの位置をマップに反映\n panelMap.set(movingPanel.id, { ...movingPanel });\n\n // Queue for processing panels that need to be repositioned\n // 再配置が必要なパネルの処理キュー\n const queue: PanelCoordinate[] = [{ ...movingPanel }];\n\n // Track processed panels to avoid reprocessing unnecessarily\n // 不要な再処理を避けるため処理済みパネルを追跡\n const processed = new Set<PanelId>();\n\n // Track processing count to prevent infinite loops\n // 無限ループを防ぐため処理回数を追跡\n const processCount = new Map<PanelId, number>();\n const MAX_PROCESS_COUNT = 10;\n\n // Process panels until no more collisions\n // 衝突がなくなるまでパネルを処理\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n // Safety check: prevent infinite loops\n // 安全チェック: 無限ループを防止\n const count = processCount.get(current.id) || 0;\n if (count >= MAX_PROCESS_COUNT) continue;\n processCount.set(current.id, count + 1);\n\n // Skip if the position in queue doesn't match current position in map (outdated entry)\n // キューの位置がマップの現在位置と一致しない場合はスキップ(古いエントリ)\n const currentInMap = panelMap.get(current.id);\n if (currentInMap && (currentInMap.x !== current.x || currentInMap.y !== current.y)) {\n continue;\n }\n\n // Skip if already processed at this position\n // この位置で既に処理済みの場合はスキップ\n if (processed.has(current.id)) {\n continue;\n }\n\n // Detect collisions with current panel position\n // 現在のパネル位置での衝突を検出\n const collidingIds = detectCollisions(current, panelMap);\n\n if (collidingIds.length === 0) {\n panelMap.set(current.id, current);\n processed.add(current.id);\n continue;\n }\n\n // Sort colliding panels by position (top-left to bottom-right) for consistent processing\n // 一貫した処理のため、衝突パネルを位置順(左上から右下)にソート\n const sortedCollidingIds = collidingIds.sort((a, b) => {\n const panelA = panelMap.get(a)!;\n const panelB = panelMap.get(b)!;\n if (panelA.y !== panelB.y) return panelA.y - panelB.y;\n return panelA.x - panelB.x;\n });\n\n // Track panels pushed in this iteration to detect secondary collisions\n // この反復で押されたパネルを追跡し、二次衝突を検出\n const pushedInIteration = new Set<PanelId>();\n\n // Resolve collisions by pushing colliding panels\n // 衝突したパネルを押しのけて衝突を解決\n for (const collidingId of sortedCollidingIds) {\n const colliding = panelMap.get(collidingId);\n if (!colliding) continue;\n\n // Calculate new position for the colliding panel\n // 衝突パネルの新しい位置を計算\n const newPos = findNewPosition(colliding, current, columnCount);\n const candidate = { ...colliding, x: newPos.x, y: newPos.y };\n\n // Check if this would collide with a panel we just pushed in this same iteration\n // 同じ反復内で押したパネルと衝突するかチェック\n let wouldCollideWithPushed = false;\n for (const pushedId of pushedInIteration) {\n const pushedPanel = panelMap.get(pushedId)!;\n if (rectanglesOverlap(candidate, pushedPanel)) {\n wouldCollideWithPushed = true;\n break;\n }\n }\n\n if (wouldCollideWithPushed) {\n // Skip pushing this panel to avoid creating secondary collisions\n // Let the queue handle it in a subsequent iteration\n continue;\n }\n\n // Update panel map and add to queue for further processing\n // パネルマップを更新し、さらなる処理のためキューに追加\n panelMap.set(collidingId, candidate);\n queue.push(candidate);\n pushedInIteration.add(collidingId);\n }\n\n panelMap.set(current.id, current);\n processed.add(current.id);\n }\n\n // Return the rearranged panels\n // 再配置後のパネルを返す\n return Array.from(panelMap.values());\n}\n\n/**\n * Find a new position for a panel to be added\n * 追加するパネルの新しい位置を見つける\n */\nexport function findNewPositionToAddPanel(\n panelToAdd: Partial<PanelCoordinate>,\n allPanels: PanelCoordinate[],\n columnCount: number\n): { x: number; y: number } {\n const id = panelToAdd.id || Math.random().toString(36).substring(2, 15);\n const w = panelToAdd.w || 1;\n const h = panelToAdd.h || 1;\n\n // Create a map for fast panel lookup\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, panel);\n }\n\n // Calculate maximum row based on existing panels\n // Add some buffer rows to ensure we can find a position\n const maxExistingY = allPanels.length > 0 ? Math.max(...allPanels.map((p) => p.y + p.h)) : 0;\n const MAX_ROWS = Math.max(maxExistingY + 100, 1000);\n\n // Try to find a position starting from top-left\n for (let y = 0; y < MAX_ROWS; y++) {\n for (let x = 0; x <= columnCount - w; x++) {\n const candidate: PanelCoordinate = {\n id,\n x,\n y,\n w,\n h,\n };\n\n // Check if this position has any collisions\n if (!hasCollision(candidate, candidate.id, panelMap)) {\n return { x, y };\n }\n }\n }\n\n // Fallback: if no position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AS,IAAI,aAAa,UAAU;AACpC,SAAM,KAAK,UAAU;AACrB,qBAAkB,IAAI,YAAY;;AAGpC,WAAS,IAAI,QAAQ,IAAI,QAAQ;AACjC,YAAU,IAAI,QAAQ,GAAG;;AAK3B,QAAO,MAAM,KAAK,SAAS,QAAQ,CAAC;;;;;;AAOtC,SAAgB,0BACd,YACA,WACA,aAC0B;CAC1B,MAAM,KAAK,WAAW,MAAM,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,GAAG,GAAG;CACvE,MAAM,IAAI,WAAW,KAAK;CAC1B,MAAM,IAAI,WAAW,KAAK;CAG1B,MAAM,2BAAW,IAAI,KAA+B;AACpD,MAAK,MAAM,SAAS,UAClB,UAAS,IAAI,MAAM,IAAI,MAAM;CAK/B,MAAM,eAAe,UAAU,SAAS,IAAI,KAAK,IAAI,GAAG,UAAU,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG;CAC3F,MAAM,WAAW,KAAK,IAAI,eAAe,KAAK,IAAK;AAGnD,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAC5B,MAAK,IAAI,IAAI,GAAG,KAAK,cAAc,GAAG,KAAK;EACzC,MAAMC,YAA6B;GACjC;GACA;GACA;GACA;GACA;GACD;AAGD,MAAI,CAAC,aAAa,WAAW,UAAU,IAAI,SAAS,CAClD,QAAO;GAAE;GAAG;GAAG;;AAMrB,QAAO;EAAE,GAAG;EAAG,GAAG;EAAc"}
|
|
1
|
+
{"version":3,"file":"rearrangement.cjs","names":["queue: PanelCoordinate[]","candidate: PanelCoordinate"],"sources":["../../src/helpers/rearrangement.ts"],"sourcesContent":["import type { PanelCoordinate, PanelId } from \"../types\";\n\n/**\n * Check if two rectangles overlap using AABB (Axis-Aligned Bounding Box) test\n * 2つの矩形が重なっているかをAABBテストで判定\n */\nexport function rectanglesOverlap(\n a: { x: number; y: number; w: number; h: number },\n b: { x: number; y: number; w: number; h: number }\n): boolean {\n return !(\n (\n a.x + a.w <= b.x || // a is to the left of b\n b.x + b.w <= a.x || // b is to the left of a\n a.y + a.h <= b.y || // a is above b\n b.y + b.h <= a.y\n ) // b is above a\n );\n}\n\n/**\n * Detect all panels that collide with the given panel\n * 指定されたパネルと衝突する全てのパネルを検出\n */\nexport function detectCollisions(panel: PanelCoordinate, panelMap: Map<PanelId, PanelCoordinate>): PanelId[] {\n const collisions = new Set<PanelId>();\n\n for (const [id, other] of panelMap) {\n if (id === panel.id) continue;\n\n if (rectanglesOverlap(panel, other)) {\n collisions.add(id);\n }\n }\n\n return Array.from(collisions);\n}\n\n/**\n * Check if a panel at the given position would collide with any existing panels\n * 指定された位置にパネルを配置した場合に衝突があるかをチェック\n */\nexport function hasCollision(\n candidate: { x: number; y: number; w: number; h: number },\n excludeId: PanelId,\n panelMap: Map<PanelId, PanelCoordinate>\n): boolean {\n for (const [id, panel] of panelMap) {\n if (id === excludeId) continue;\n if (rectanglesOverlap(candidate, panel)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calculate the minimum distance to push a panel to avoid collision\n * パネルを押しのけるための最小距離を計算\n */\nfunction calculatePushDistance(\n pusher: PanelCoordinate,\n pushed: PanelCoordinate,\n columnCount: number\n): { direction: \"right\" | \"down\"; distance: number } | null {\n // Calculate how far to push horizontally (to the right)\n // 横方向(右)にどれだけ押すか計算\n const pushRight = pusher.x + pusher.w - pushed.x;\n const canPushRight = pushed.x + pushed.w + pushRight <= columnCount;\n\n // Calculate how far to push vertically (down)\n // 縦方向(下)にどれだけ押すか計算\n const pushDown = pusher.y + pusher.h - pushed.y;\n\n // Priority 1: Horizontal push if possible\n // 優先順位1: 可能なら横方向に押す\n if (canPushRight && pushRight > 0) {\n return { direction: \"right\", distance: pushRight };\n }\n\n // Priority 2: Vertical push\n // 優先順位2: 縦方向に押す\n if (pushDown > 0) {\n return { direction: \"down\", distance: pushDown };\n }\n\n return null;\n}\n\n/**\n * Find a new position for a panel by pushing it away from the colliding panel\n * Priority: horizontal (right) first, then vertical (down)\n * 衝突したパネルを押しのける方向に移動させる\n * 優先順位: 横方向(右)→縦方向(下)\n */\nexport function findNewPosition(\n panel: PanelCoordinate,\n pusher: PanelCoordinate,\n columnCount: number\n): { x: number; y: number } {\n const pushInfo = calculatePushDistance(pusher, panel, columnCount);\n\n if (!pushInfo) {\n // No push needed or can't determine direction\n // Fallback: move down\n return { x: panel.x, y: panel.y + 1 };\n }\n\n if (pushInfo.direction === \"right\") {\n // Push horizontally to the right\n // 横方向(右)に押す\n const newX = panel.x + pushInfo.distance;\n if (newX + panel.w <= columnCount) {\n return { x: newX, y: panel.y };\n }\n // Can't fit horizontally, push down instead\n // 横方向に入らない場合は下に押す\n }\n\n // Push vertically down\n // 縦方向(下)に押す\n return { x: panel.x, y: panel.y + pushInfo.distance };\n}\n\n/**\n * Constrain a panel to stay within grid boundaries\n * パネルをグリッド境界内に制約\n */\nfunction constrainToGrid(panel: PanelCoordinate, columnCount: number): PanelCoordinate {\n // Ensure x + w doesn't exceed columnCount\n // x + w が columnCount を超えないようにする\n const maxX = Math.max(0, columnCount - panel.w);\n const constrainedX = Math.max(0, Math.min(panel.x, maxX));\n\n // Ensure y is non-negative\n // y が負にならないようにする\n const constrainedY = Math.max(0, panel.y);\n\n return {\n ...panel,\n x: constrainedX,\n y: constrainedY,\n };\n}\n\n/**\n * Rearrange panels to resolve collisions when a panel is moved or resized\n * Panels are moved horizontally first, then vertically if needed\n * For compound resizes (both width and height change), uses two-phase processing\n * パネルの移動・リサイズ時に衝突を解決するようにパネルを再配置\n * 横方向を優先し、必要に応じて縦方向に移動\n * 幅と高さが同時に変更される場合は、二段階処理を使用\n */\nexport function rearrangePanels(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Constrain the moving panel to grid boundaries\n // 移動中のパネルをグリッド境界内に制約\n const constrainedMovingPanel = constrainToGrid(movingPanel, columnCount);\n\n // Check if this is a compound resize (both width and height changed)\n // 幅と高さの両方が変更されたかチェック\n const originalPanel = allPanels.find((p) => p.id === movingPanel.id);\n if (originalPanel) {\n const widthChanged = originalPanel.w !== constrainedMovingPanel.w;\n const heightChanged = originalPanel.h !== constrainedMovingPanel.h;\n\n if (widthChanged && heightChanged) {\n // Two-phase processing: width first, then height\n // 二段階処理: 幅を先に、次に高さ\n\n // Phase 1: Apply width change only\n // フェーズ1: 幅の変更のみを適用\n const widthOnlyPanel = {\n ...constrainedMovingPanel,\n h: originalPanel.h, // Keep original height\n };\n const afterWidthChange = rearrangePanelsInternal(widthOnlyPanel, allPanels, columnCount);\n\n // Phase 2: Apply height change to the result\n // フェーズ2: 結果に高さの変更を適用\n const heightChangedPanel = {\n ...constrainedMovingPanel,\n // Use the new position if panel-1 was moved during width phase\n x: afterWidthChange.find((p) => p.id === movingPanel.id)?.x ?? constrainedMovingPanel.x,\n y: afterWidthChange.find((p) => p.id === movingPanel.id)?.y ?? constrainedMovingPanel.y,\n };\n return rearrangePanelsInternal(heightChangedPanel, afterWidthChange, columnCount);\n }\n }\n\n // Single dimension change or move - use normal processing\n // 単一次元の変更または移動 - 通常の処理を使用\n return rearrangePanelsInternal(constrainedMovingPanel, allPanels, columnCount);\n}\n\n/**\n * Internal implementation of panel rearrangement\n * パネル再配置の内部実装\n */\nfunction rearrangePanelsInternal(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Create a map for fast panel lookup\n // パネルIDから座標への高速マップを作成\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, { ...panel });\n }\n\n // Update the moving panel's position in the map\n // 移動中のパネルの位置をマップに反映\n panelMap.set(movingPanel.id, { ...movingPanel });\n\n // Queue for processing panels that need to be repositioned\n // 再配置が必要なパネルの処理キュー\n const queue: PanelCoordinate[] = [{ ...movingPanel }];\n\n // Track processed panels to avoid reprocessing unnecessarily\n // 不要な再処理を避けるため処理済みパネルを追跡\n const processed = new Set<PanelId>();\n\n // Track all panels that have been repositioned across all queue iterations\n // 全キュー反復を通じて再配置されたパネルを追跡\n const repositioned = new Set<PanelId>();\n\n // Track processing count to prevent infinite loops\n // 無限ループを防ぐため処理回数を追跡\n const processCount = new Map<PanelId, number>();\n const MAX_PROCESS_COUNT = 10;\n\n // Process panels until no more collisions\n // 衝突がなくなるまでパネルを処理\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n // Safety check: prevent infinite loops\n // 安全チェック: 無限ループを防止\n const count = processCount.get(current.id) || 0;\n if (count >= MAX_PROCESS_COUNT) continue;\n processCount.set(current.id, count + 1);\n\n // Skip if the position in queue doesn't match current position in map (outdated entry)\n // キューの位置がマップの現在位置と一致しない場合はスキップ(古いエントリ)\n const currentInMap = panelMap.get(current.id);\n if (currentInMap && (currentInMap.x !== current.x || currentInMap.y !== current.y)) {\n continue;\n }\n\n // Skip if already processed at this position\n // この位置で既に処理済みの場合はスキップ\n if (processed.has(current.id)) {\n continue;\n }\n\n // Detect collisions with current panel position\n // 現在のパネル位置での衝突を検出\n const collidingIds = detectCollisions(current, panelMap);\n\n if (collidingIds.length === 0) {\n panelMap.set(current.id, current);\n processed.add(current.id);\n continue;\n }\n\n // Sort colliding panels by position (top-left to bottom-right) for consistent processing\n // 一貫した処理のため、衝突パネルを位置順(左上から右下)にソート\n const sortedCollidingIds = collidingIds.sort((a, b) => {\n const panelA = panelMap.get(a)!;\n const panelB = panelMap.get(b)!;\n if (panelA.y !== panelB.y) return panelA.y - panelB.y;\n return panelA.x - panelB.x;\n });\n\n // Resolve collisions by pushing colliding panels\n // 衝突したパネルを押しのけて衝突を解決\n for (const collidingId of sortedCollidingIds) {\n const colliding = panelMap.get(collidingId);\n if (!colliding) continue;\n\n // Calculate new position for the colliding panel\n // 衝突パネルの新しい位置を計算\n const newPos = findNewPosition(colliding, current, columnCount);\n let candidate = { ...colliding, x: newPos.x, y: newPos.y };\n\n // Check if candidate overlaps with any previously repositioned panel\n // Re-validate after each adjustment to catch multi-overlap scenarios\n // 候補位置が既に再配置されたパネルと重なる場合、さらに右に押す。無理なら下に押す\n // 各調整後に再検証し、複数の重なりシナリオに対応\n let needsPushDown = false;\n let adjusted = true;\n let adjustAttempts = 0;\n while (adjusted && !needsPushDown && adjustAttempts < repositioned.size + 1) {\n adjusted = false;\n adjustAttempts++;\n for (const repoId of repositioned) {\n const repoPanel = panelMap.get(repoId);\n if (!repoPanel || repoId === collidingId) continue;\n if (!rectanglesOverlap(candidate, repoPanel)) continue;\n\n const furtherX = repoPanel.x + repoPanel.w;\n if (furtherX + candidate.w <= columnCount) {\n candidate = { ...candidate, x: furtherX };\n adjusted = true;\n break; // Restart loop to re-validate against all repositioned panels\n } else {\n needsPushDown = true;\n break;\n }\n }\n }\n\n if (needsPushDown) {\n const pushDown = current.y + current.h - colliding.y;\n candidate = { ...candidate, x: colliding.x, y: colliding.y + (pushDown > 0 ? pushDown : 1) };\n }\n\n // Update panel map and add to queue for further processing\n // パネルマップを更新し、さらなる処理のためキューに追加\n panelMap.set(collidingId, candidate);\n queue.push(candidate);\n repositioned.add(collidingId);\n }\n\n panelMap.set(current.id, current);\n processed.add(current.id);\n }\n\n // Return the rearranged panels\n // 再配置後のパネルを返す\n return Array.from(panelMap.values());\n}\n\n/**\n * Find a new position for a panel to be added\n * 追加するパネルの新しい位置を見つける\n */\nexport function findNewPositionToAddPanel(\n panelToAdd: Partial<PanelCoordinate>,\n allPanels: PanelCoordinate[],\n columnCount: number\n): { x: number; y: number } {\n const id = panelToAdd.id || Math.random().toString(36).substring(2, 15);\n const w = panelToAdd.w || 1;\n const h = panelToAdd.h || 1;\n\n // Create a map for fast panel lookup\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, panel);\n }\n\n // Calculate maximum row based on existing panels\n // Add some buffer rows to ensure we can find a position\n const maxExistingY = allPanels.length > 0 ? Math.max(...allPanels.map((p) => p.y + p.h)) : 0;\n const MAX_ROWS = Math.max(maxExistingY + 100, 1000);\n\n // Try to find a position starting from top-left\n for (let y = 0; y < MAX_ROWS; y++) {\n for (let x = 0; x <= columnCount - w; x++) {\n const candidate: PanelCoordinate = {\n id,\n x,\n y,\n w,\n h,\n };\n\n // Check if this position has any collisions\n if (!hasCollision(candidate, candidate.id, panelMap)) {\n return { x, y };\n }\n }\n }\n\n // Fallback: if no position found, place at the bottom\n return { x: 0, y: maxExistingY };\n}\n"],"mappings":";;;;;;AAMA,SAAgB,kBACd,GACA,GACS;AACT,QAAO,EAEH,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE;;;;;;AASrB,SAAgB,iBAAiB,OAAwB,UAAoD;CAC3G,MAAM,6BAAa,IAAI,KAAc;AAErC,MAAK,MAAM,CAAC,IAAI,UAAU,UAAU;AAClC,MAAI,OAAO,MAAM,GAAI;AAErB,MAAI,kBAAkB,OAAO,MAAM,CACjC,YAAW,IAAI,GAAG;;AAItB,QAAO,MAAM,KAAK,WAAW;;;;;;AAO/B,SAAgB,aACd,WACA,WACA,UACS;AACT,MAAK,MAAM,CAAC,IAAI,UAAU,UAAU;AAClC,MAAI,OAAO,UAAW;AACtB,MAAI,kBAAkB,WAAW,MAAM,CACrC,QAAO;;AAGX,QAAO;;;;;;AAOT,SAAS,sBACP,QACA,QACA,aAC0D;CAG1D,MAAM,YAAY,OAAO,IAAI,OAAO,IAAI,OAAO;CAC/C,MAAM,eAAe,OAAO,IAAI,OAAO,IAAI,aAAa;CAIxD,MAAM,WAAW,OAAO,IAAI,OAAO,IAAI,OAAO;AAI9C,KAAI,gBAAgB,YAAY,EAC9B,QAAO;EAAE,WAAW;EAAS,UAAU;EAAW;AAKpD,KAAI,WAAW,EACb,QAAO;EAAE,WAAW;EAAQ,UAAU;EAAU;AAGlD,QAAO;;;;;;;;AAST,SAAgB,gBACd,OACA,QACA,aAC0B;CAC1B,MAAM,WAA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,EAAE,CAAC,GAAG;CAC3F,MAAM,WAAW,KAAK,IAAI,eAAe,KAAK,IAAK;AAGnD,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAC5B,MAAK,IAAI,IAAI,GAAG,KAAK,cAAc,GAAG,KAAK;EACzC,MAAMC,YAA6B;GACjC;GACA;GACA;GACA;GACA;GACD;AAGD,MAAI,CAAC,aAAa,WAAW,UAAU,IAAI,SAAS,CAClD,QAAO;GAAE;GAAG;GAAG;;AAMrB,QAAO;EAAE,GAAG;EAAG,GAAG;EAAc"}
|
|
@@ -123,6 +123,7 @@ function rearrangePanelsInternal(movingPanel, allPanels, columnCount) {
|
|
|
123
123
|
panelMap.set(movingPanel.id, { ...movingPanel });
|
|
124
124
|
const queue = [{ ...movingPanel }];
|
|
125
125
|
const processed = /* @__PURE__ */ new Set();
|
|
126
|
+
const repositioned = /* @__PURE__ */ new Set();
|
|
126
127
|
const processCount = /* @__PURE__ */ new Map();
|
|
127
128
|
const MAX_PROCESS_COUNT = 10;
|
|
128
129
|
while (queue.length > 0) {
|
|
@@ -145,25 +146,50 @@ function rearrangePanelsInternal(movingPanel, allPanels, columnCount) {
|
|
|
145
146
|
if (panelA.y !== panelB.y) return panelA.y - panelB.y;
|
|
146
147
|
return panelA.x - panelB.x;
|
|
147
148
|
});
|
|
148
|
-
const pushedInIteration = /* @__PURE__ */ new Set();
|
|
149
149
|
for (const collidingId of sortedCollidingIds) {
|
|
150
150
|
const colliding = panelMap.get(collidingId);
|
|
151
151
|
if (!colliding) continue;
|
|
152
152
|
const newPos = findNewPosition(colliding, current, columnCount);
|
|
153
|
-
|
|
153
|
+
let candidate = {
|
|
154
154
|
...colliding,
|
|
155
155
|
x: newPos.x,
|
|
156
156
|
y: newPos.y
|
|
157
157
|
};
|
|
158
|
-
let
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
158
|
+
let needsPushDown = false;
|
|
159
|
+
let adjusted = true;
|
|
160
|
+
let adjustAttempts = 0;
|
|
161
|
+
while (adjusted && !needsPushDown && adjustAttempts < repositioned.size + 1) {
|
|
162
|
+
adjusted = false;
|
|
163
|
+
adjustAttempts++;
|
|
164
|
+
for (const repoId of repositioned) {
|
|
165
|
+
const repoPanel = panelMap.get(repoId);
|
|
166
|
+
if (!repoPanel || repoId === collidingId) continue;
|
|
167
|
+
if (!rectanglesOverlap(candidate, repoPanel)) continue;
|
|
168
|
+
const furtherX = repoPanel.x + repoPanel.w;
|
|
169
|
+
if (furtherX + candidate.w <= columnCount) {
|
|
170
|
+
candidate = {
|
|
171
|
+
...candidate,
|
|
172
|
+
x: furtherX
|
|
173
|
+
};
|
|
174
|
+
adjusted = true;
|
|
175
|
+
break;
|
|
176
|
+
} else {
|
|
177
|
+
needsPushDown = true;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (needsPushDown) {
|
|
183
|
+
const pushDown = current.y + current.h - colliding.y;
|
|
184
|
+
candidate = {
|
|
185
|
+
...candidate,
|
|
186
|
+
x: colliding.x,
|
|
187
|
+
y: colliding.y + (pushDown > 0 ? pushDown : 1)
|
|
188
|
+
};
|
|
162
189
|
}
|
|
163
|
-
if (wouldCollideWithPushed) continue;
|
|
164
190
|
panelMap.set(collidingId, candidate);
|
|
165
191
|
queue.push(candidate);
|
|
166
|
-
|
|
192
|
+
repositioned.add(collidingId);
|
|
167
193
|
}
|
|
168
194
|
panelMap.set(current.id, current);
|
|
169
195
|
processed.add(current.id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rearrangement.mjs","names":["queue: PanelCoordinate[]","candidate: PanelCoordinate"],"sources":["../../src/helpers/rearrangement.ts"],"sourcesContent":["import type { PanelCoordinate, PanelId } from \"../types\";\n\n/**\n * Check if two rectangles overlap using AABB (Axis-Aligned Bounding Box) test\n * 2つの矩形が重なっているかをAABBテストで判定\n */\nexport function rectanglesOverlap(\n a: { x: number; y: number; w: number; h: number },\n b: { x: number; y: number; w: number; h: number }\n): boolean {\n return !(\n (\n a.x + a.w <= b.x || // a is to the left of b\n b.x + b.w <= a.x || // b is to the left of a\n a.y + a.h <= b.y || // a is above b\n b.y + b.h <= a.y\n ) // b is above a\n );\n}\n\n/**\n * Detect all panels that collide with the given panel\n * 指定されたパネルと衝突する全てのパネルを検出\n */\nexport function detectCollisions(panel: PanelCoordinate, panelMap: Map<PanelId, PanelCoordinate>): PanelId[] {\n const collisions = new Set<PanelId>();\n\n for (const [id, other] of panelMap) {\n if (id === panel.id) continue;\n\n if (rectanglesOverlap(panel, other)) {\n collisions.add(id);\n }\n }\n\n return Array.from(collisions);\n}\n\n/**\n * Check if a panel at the given position would collide with any existing panels\n * 指定された位置にパネルを配置した場合に衝突があるかをチェック\n */\nexport function hasCollision(\n candidate: { x: number; y: number; w: number; h: number },\n excludeId: PanelId,\n panelMap: Map<PanelId, PanelCoordinate>\n): boolean {\n for (const [id, panel] of panelMap) {\n if (id === excludeId) continue;\n if (rectanglesOverlap(candidate, panel)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calculate the minimum distance to push a panel to avoid collision\n * パネルを押しのけるための最小距離を計算\n */\nfunction calculatePushDistance(\n pusher: PanelCoordinate,\n pushed: PanelCoordinate,\n columnCount: number\n): { direction: \"right\" | \"down\"; distance: number } | null {\n // Calculate how far to push horizontally (to the right)\n // 横方向(右)にどれだけ押すか計算\n const pushRight = pusher.x + pusher.w - pushed.x;\n const canPushRight = pushed.x + pushed.w + pushRight <= columnCount;\n\n // Calculate how far to push vertically (down)\n // 縦方向(下)にどれだけ押すか計算\n const pushDown = pusher.y + pusher.h - pushed.y;\n\n // Priority 1: Horizontal push if possible\n // 優先順位1: 可能なら横方向に押す\n if (canPushRight && pushRight > 0) {\n return { direction: \"right\", distance: pushRight };\n }\n\n // Priority 2: Vertical push\n // 優先順位2: 縦方向に押す\n if (pushDown > 0) {\n return { direction: \"down\", distance: pushDown };\n }\n\n return null;\n}\n\n/**\n * Find a new position for a panel by pushing it away from the colliding panel\n * Priority: horizontal (right) first, then vertical (down)\n * 衝突したパネルを押しのける方向に移動させる\n * 優先順位: 横方向(右)→縦方向(下)\n */\nexport function findNewPosition(\n panel: PanelCoordinate,\n pusher: PanelCoordinate,\n columnCount: number\n): { x: number; y: number } {\n const pushInfo = calculatePushDistance(pusher, panel, columnCount);\n\n if (!pushInfo) {\n // No push needed or can't determine direction\n // Fallback: move down\n return { x: panel.x, y: panel.y + 1 };\n }\n\n if (pushInfo.direction === \"right\") {\n // Push horizontally to the right\n // 横方向(右)に押す\n const newX = panel.x + pushInfo.distance;\n if (newX + panel.w <= columnCount) {\n return { x: newX, y: panel.y };\n }\n // Can't fit horizontally, push down instead\n // 横方向に入らない場合は下に押す\n }\n\n // Push vertically down\n // 縦方向(下)に押す\n return { x: panel.x, y: panel.y + pushInfo.distance };\n}\n\n/**\n * Constrain a panel to stay within grid boundaries\n * パネルをグリッド境界内に制約\n */\nfunction constrainToGrid(panel: PanelCoordinate, columnCount: number): PanelCoordinate {\n // Ensure x + w doesn't exceed columnCount\n // x + w が columnCount を超えないようにする\n const maxX = Math.max(0, columnCount - panel.w);\n const constrainedX = Math.max(0, Math.min(panel.x, maxX));\n\n // Ensure y is non-negative\n // y が負にならないようにする\n const constrainedY = Math.max(0, panel.y);\n\n return {\n ...panel,\n x: constrainedX,\n y: constrainedY,\n };\n}\n\n/**\n * Rearrange panels to resolve collisions when a panel is moved or resized\n * Panels are moved horizontally first, then vertically if needed\n * For compound resizes (both width and height change), uses two-phase processing\n * パネルの移動・リサイズ時に衝突を解決するようにパネルを再配置\n * 横方向を優先し、必要に応じて縦方向に移動\n * 幅と高さが同時に変更される場合は、二段階処理を使用\n */\nexport function rearrangePanels(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Constrain the moving panel to grid boundaries\n // 移動中のパネルをグリッド境界内に制約\n const constrainedMovingPanel = constrainToGrid(movingPanel, columnCount);\n\n // Check if this is a compound resize (both width and height changed)\n // 幅と高さの両方が変更されたかチェック\n const originalPanel = allPanels.find((p) => p.id === movingPanel.id);\n if (originalPanel) {\n const widthChanged = originalPanel.w !== constrainedMovingPanel.w;\n const heightChanged = originalPanel.h !== constrainedMovingPanel.h;\n\n if (widthChanged && heightChanged) {\n // Two-phase processing: width first, then height\n // 二段階処理: 幅を先に、次に高さ\n\n // Phase 1: Apply width change only\n // フェーズ1: 幅の変更のみを適用\n const widthOnlyPanel = {\n ...constrainedMovingPanel,\n h: originalPanel.h, // Keep original height\n };\n const afterWidthChange = rearrangePanelsInternal(widthOnlyPanel, allPanels, columnCount);\n\n // Phase 2: Apply height change to the result\n // フェーズ2: 結果に高さの変更を適用\n const heightChangedPanel = {\n ...constrainedMovingPanel,\n // Use the new position if panel-1 was moved during width phase\n x: afterWidthChange.find((p) => p.id === movingPanel.id)?.x ?? constrainedMovingPanel.x,\n y: afterWidthChange.find((p) => p.id === movingPanel.id)?.y ?? constrainedMovingPanel.y,\n };\n return rearrangePanelsInternal(heightChangedPanel, afterWidthChange, columnCount);\n }\n }\n\n // Single dimension change or move - use normal processing\n // 単一次元の変更または移動 - 通常の処理を使用\n return rearrangePanelsInternal(constrainedMovingPanel, allPanels, columnCount);\n}\n\n/**\n * Internal implementation of panel rearrangement\n * パネル再配置の内部実装\n */\nfunction rearrangePanelsInternal(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Create a map for fast panel lookup\n // パネルIDから座標への高速マップを作成\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, { ...panel });\n }\n\n // Update the moving panel's position in the map\n // 移動中のパネルの位置をマップに反映\n panelMap.set(movingPanel.id, { ...movingPanel });\n\n // Queue for processing panels that need to be repositioned\n // 再配置が必要なパネルの処理キュー\n const queue: PanelCoordinate[] = [{ ...movingPanel }];\n\n // Track processed panels to avoid reprocessing unnecessarily\n // 不要な再処理を避けるため処理済みパネルを追跡\n const processed = new Set<PanelId>();\n\n // Track processing count to prevent infinite loops\n // 無限ループを防ぐため処理回数を追跡\n const processCount = new Map<PanelId, number>();\n const MAX_PROCESS_COUNT = 10;\n\n // Process panels until no more collisions\n // 衝突がなくなるまでパネルを処理\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n // Safety check: prevent infinite loops\n // 安全チェック: 無限ループを防止\n const count = processCount.get(current.id) || 0;\n if (count >= MAX_PROCESS_COUNT) continue;\n processCount.set(current.id, count + 1);\n\n // Skip if the position in queue doesn't match current position in map (outdated entry)\n // キューの位置がマップの現在位置と一致しない場合はスキップ(古いエントリ)\n const currentInMap = panelMap.get(current.id);\n if (currentInMap && (currentInMap.x !== current.x || currentInMap.y !== current.y)) {\n continue;\n }\n\n // Skip if already processed at this position\n // この位置で既に処理済みの場合はスキップ\n if (processed.has(current.id)) {\n continue;\n }\n\n // Detect collisions with current panel position\n // 現在のパネル位置での衝突を検出\n const collidingIds = detectCollisions(current, panelMap);\n\n if (collidingIds.length === 0) {\n panelMap.set(current.id, current);\n processed.add(current.id);\n continue;\n }\n\n // Sort colliding panels by position (top-left to bottom-right) for consistent processing\n // 一貫した処理のため、衝突パネルを位置順(左上から右下)にソート\n const sortedCollidingIds = collidingIds.sort((a, b) => {\n const panelA = panelMap.get(a)!;\n const panelB = panelMap.get(b)!;\n if (panelA.y !== panelB.y) return panelA.y - panelB.y;\n return panelA.x - panelB.x;\n });\n\n // Track panels pushed in this iteration to detect secondary collisions\n // この反復で押されたパネルを追跡し、二次衝突を検出\n const pushedInIteration = new Set<PanelId>();\n\n // Resolve collisions by pushing colliding panels\n // 衝突したパネルを押しのけて衝突を解決\n for (const collidingId of sortedCollidingIds) {\n const colliding = panelMap.get(collidingId);\n if (!colliding) continue;\n\n // Calculate new position for the colliding panel\n // 衝突パネルの新しい位置を計算\n const newPos = findNewPosition(colliding, current, columnCount);\n const candidate = { ...colliding, x: newPos.x, y: newPos.y };\n\n // Check if this would collide with a panel we just pushed in this same iteration\n // 同じ反復内で押したパネルと衝突するかチェック\n let wouldCollideWithPushed = false;\n for (const pushedId of pushedInIteration) {\n const pushedPanel = panelMap.get(pushedId)!;\n if (rectanglesOverlap(candidate, pushedPanel)) {\n wouldCollideWithPushed = true;\n break;\n }\n }\n\n if (wouldCollideWithPushed) {\n // Skip pushing this panel to avoid creating secondary collisions\n // Let the queue handle it in a subsequent iteration\n continue;\n }\n\n // Update panel map and add to queue for further processing\n // パネルマップを更新し、さらなる処理のためキューに追加\n panelMap.set(collidingId, candidate);\n queue.push(candidate);\n pushedInIteration.add(collidingId);\n }\n\n panelMap.set(current.id, current);\n processed.add(current.id);\n }\n\n // Return the rearranged panels\n // 再配置後のパネルを返す\n return Array.from(panelMap.values());\n}\n\n/**\n * Find a new position for a panel to be added\n * 追加するパネルの新しい位置を見つける\n */\nexport function findNewPositionToAddPanel(\n panelToAdd: Partial<PanelCoordinate>,\n allPanels: PanelCoordinate[],\n columnCount: number\n): { x: number; y: number } {\n const id = panelToAdd.id || Math.random().toString(36).substring(2, 15);\n const w = panelToAdd.w || 1;\n const h = panelToAdd.h || 1;\n\n // Create a map for fast panel lookup\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, panel);\n }\n\n // Calculate maximum row based on existing panels\n // Add some buffer rows to ensure we can find a position\n const maxExistingY = allPanels.length > 0 ? Math.max(...allPanels.map((p) => p.y + p.h)) : 0;\n const MAX_ROWS = Math.max(maxExistingY + 100, 1000);\n\n // Try to find a position starting from top-left\n for (let y = 0; y < MAX_ROWS; y++) {\n for (let x = 0; x <= columnCount - w; x++) {\n const candidate: PanelCoordinate = {\n id,\n x,\n y,\n w,\n h,\n };\n\n // Check if this position has any collisions\n if (!hasCollision(candidate, candidate.id, panelMap)) {\n return { x, y };\n }\n }\n }\n\n // Fallback: if no position found, place at the bottom\n return { x: 0, y: maxExistingY };\n}\n"],"mappings":";;;;;AAMA,SAAgB,kBACd,GACA,GACS;AAC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S,IAAI,QAAQ,IAAI,QAAQ;AACjC,YAAU,IAAI,QAAQ,GAAG;;AAK3B,QAAO,MAAM,KAAK,SAAS,QAAQ,CAAC;;;;;;AAOtC,SAAgB,0BACd,YACA,WACA,aAC0B;CAC1B,MAAM,KAAK,WAAW,MAAM,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,GAAG,GAAG;CACvE,MAAM,IAAI,WAAW,KAAK;CAC1B,MAAM,IAAI,WAAW,KAAK;CAG1B,MAAM,2BAAW,IAAI,KAA+B;AACpD,MAAK,MAAM,SAAS,UAClB,UAAS,IAAI,MAAM,IAAI,MAAM;CAK/B,MAAM,eAAe,UAAU,SAAS,IAAI,KAAK,IAAI,GAAG,UAAU,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG;CAC3F,MAAM,WAAW,KAAK,IAAI,eAAe,KAAK,IAAK;AAGnD,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAC5B,MAAK,IAAI,IAAI,GAAG,KAAK,cAAc,GAAG,KAAK;EACzC,MAAMC,YAA6B;GACjC;GACA;GACA;GACA;GACA;GACD;AAGD,MAAI,CAAC,aAAa,WAAW,UAAU,IAAI,SAAS,CAClD,QAAO;GAAE;GAAG;GAAG;;AAMrB,QAAO;EAAE,GAAG;EAAG,GAAG;EAAc"}
|
|
1
|
+
{"version":3,"file":"rearrangement.mjs","names":["queue: PanelCoordinate[]","candidate: PanelCoordinate"],"sources":["../../src/helpers/rearrangement.ts"],"sourcesContent":["import type { PanelCoordinate, PanelId } from \"../types\";\n\n/**\n * Check if two rectangles overlap using AABB (Axis-Aligned Bounding Box) test\n * 2つの矩形が重なっているかをAABBテストで判定\n */\nexport function rectanglesOverlap(\n a: { x: number; y: number; w: number; h: number },\n b: { x: number; y: number; w: number; h: number }\n): boolean {\n return !(\n (\n a.x + a.w <= b.x || // a is to the left of b\n b.x + b.w <= a.x || // b is to the left of a\n a.y + a.h <= b.y || // a is above b\n b.y + b.h <= a.y\n ) // b is above a\n );\n}\n\n/**\n * Detect all panels that collide with the given panel\n * 指定されたパネルと衝突する全てのパネルを検出\n */\nexport function detectCollisions(panel: PanelCoordinate, panelMap: Map<PanelId, PanelCoordinate>): PanelId[] {\n const collisions = new Set<PanelId>();\n\n for (const [id, other] of panelMap) {\n if (id === panel.id) continue;\n\n if (rectanglesOverlap(panel, other)) {\n collisions.add(id);\n }\n }\n\n return Array.from(collisions);\n}\n\n/**\n * Check if a panel at the given position would collide with any existing panels\n * 指定された位置にパネルを配置した場合に衝突があるかをチェック\n */\nexport function hasCollision(\n candidate: { x: number; y: number; w: number; h: number },\n excludeId: PanelId,\n panelMap: Map<PanelId, PanelCoordinate>\n): boolean {\n for (const [id, panel] of panelMap) {\n if (id === excludeId) continue;\n if (rectanglesOverlap(candidate, panel)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calculate the minimum distance to push a panel to avoid collision\n * パネルを押しのけるための最小距離を計算\n */\nfunction calculatePushDistance(\n pusher: PanelCoordinate,\n pushed: PanelCoordinate,\n columnCount: number\n): { direction: \"right\" | \"down\"; distance: number } | null {\n // Calculate how far to push horizontally (to the right)\n // 横方向(右)にどれだけ押すか計算\n const pushRight = pusher.x + pusher.w - pushed.x;\n const canPushRight = pushed.x + pushed.w + pushRight <= columnCount;\n\n // Calculate how far to push vertically (down)\n // 縦方向(下)にどれだけ押すか計算\n const pushDown = pusher.y + pusher.h - pushed.y;\n\n // Priority 1: Horizontal push if possible\n // 優先順位1: 可能なら横方向に押す\n if (canPushRight && pushRight > 0) {\n return { direction: \"right\", distance: pushRight };\n }\n\n // Priority 2: Vertical push\n // 優先順位2: 縦方向に押す\n if (pushDown > 0) {\n return { direction: \"down\", distance: pushDown };\n }\n\n return null;\n}\n\n/**\n * Find a new position for a panel by pushing it away from the colliding panel\n * Priority: horizontal (right) first, then vertical (down)\n * 衝突したパネルを押しのける方向に移動させる\n * 優先順位: 横方向(右)→縦方向(下)\n */\nexport function findNewPosition(\n panel: PanelCoordinate,\n pusher: PanelCoordinate,\n columnCount: number\n): { x: number; y: number } {\n const pushInfo = calculatePushDistance(pusher, panel, columnCount);\n\n if (!pushInfo) {\n // No push needed or can't determine direction\n // Fallback: move down\n return { x: panel.x, y: panel.y + 1 };\n }\n\n if (pushInfo.direction === \"right\") {\n // Push horizontally to the right\n // 横方向(右)に押す\n const newX = panel.x + pushInfo.distance;\n if (newX + panel.w <= columnCount) {\n return { x: newX, y: panel.y };\n }\n // Can't fit horizontally, push down instead\n // 横方向に入らない場合は下に押す\n }\n\n // Push vertically down\n // 縦方向(下)に押す\n return { x: panel.x, y: panel.y + pushInfo.distance };\n}\n\n/**\n * Constrain a panel to stay within grid boundaries\n * パネルをグリッド境界内に制約\n */\nfunction constrainToGrid(panel: PanelCoordinate, columnCount: number): PanelCoordinate {\n // Ensure x + w doesn't exceed columnCount\n // x + w が columnCount を超えないようにする\n const maxX = Math.max(0, columnCount - panel.w);\n const constrainedX = Math.max(0, Math.min(panel.x, maxX));\n\n // Ensure y is non-negative\n // y が負にならないようにする\n const constrainedY = Math.max(0, panel.y);\n\n return {\n ...panel,\n x: constrainedX,\n y: constrainedY,\n };\n}\n\n/**\n * Rearrange panels to resolve collisions when a panel is moved or resized\n * Panels are moved horizontally first, then vertically if needed\n * For compound resizes (both width and height change), uses two-phase processing\n * パネルの移動・リサイズ時に衝突を解決するようにパネルを再配置\n * 横方向を優先し、必要に応じて縦方向に移動\n * 幅と高さが同時に変更される場合は、二段階処理を使用\n */\nexport function rearrangePanels(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Constrain the moving panel to grid boundaries\n // 移動中のパネルをグリッド境界内に制約\n const constrainedMovingPanel = constrainToGrid(movingPanel, columnCount);\n\n // Check if this is a compound resize (both width and height changed)\n // 幅と高さの両方が変更されたかチェック\n const originalPanel = allPanels.find((p) => p.id === movingPanel.id);\n if (originalPanel) {\n const widthChanged = originalPanel.w !== constrainedMovingPanel.w;\n const heightChanged = originalPanel.h !== constrainedMovingPanel.h;\n\n if (widthChanged && heightChanged) {\n // Two-phase processing: width first, then height\n // 二段階処理: 幅を先に、次に高さ\n\n // Phase 1: Apply width change only\n // フェーズ1: 幅の変更のみを適用\n const widthOnlyPanel = {\n ...constrainedMovingPanel,\n h: originalPanel.h, // Keep original height\n };\n const afterWidthChange = rearrangePanelsInternal(widthOnlyPanel, allPanels, columnCount);\n\n // Phase 2: Apply height change to the result\n // フェーズ2: 結果に高さの変更を適用\n const heightChangedPanel = {\n ...constrainedMovingPanel,\n // Use the new position if panel-1 was moved during width phase\n x: afterWidthChange.find((p) => p.id === movingPanel.id)?.x ?? constrainedMovingPanel.x,\n y: afterWidthChange.find((p) => p.id === movingPanel.id)?.y ?? constrainedMovingPanel.y,\n };\n return rearrangePanelsInternal(heightChangedPanel, afterWidthChange, columnCount);\n }\n }\n\n // Single dimension change or move - use normal processing\n // 単一次元の変更または移動 - 通常の処理を使用\n return rearrangePanelsInternal(constrainedMovingPanel, allPanels, columnCount);\n}\n\n/**\n * Internal implementation of panel rearrangement\n * パネル再配置の内部実装\n */\nfunction rearrangePanelsInternal(\n movingPanel: PanelCoordinate,\n allPanels: PanelCoordinate[],\n columnCount: number\n): PanelCoordinate[] {\n // Create a map for fast panel lookup\n // パネルIDから座標への高速マップを作成\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, { ...panel });\n }\n\n // Update the moving panel's position in the map\n // 移動中のパネルの位置をマップに反映\n panelMap.set(movingPanel.id, { ...movingPanel });\n\n // Queue for processing panels that need to be repositioned\n // 再配置が必要なパネルの処理キュー\n const queue: PanelCoordinate[] = [{ ...movingPanel }];\n\n // Track processed panels to avoid reprocessing unnecessarily\n // 不要な再処理を避けるため処理済みパネルを追跡\n const processed = new Set<PanelId>();\n\n // Track all panels that have been repositioned across all queue iterations\n // 全キュー反復を通じて再配置されたパネルを追跡\n const repositioned = new Set<PanelId>();\n\n // Track processing count to prevent infinite loops\n // 無限ループを防ぐため処理回数を追跡\n const processCount = new Map<PanelId, number>();\n const MAX_PROCESS_COUNT = 10;\n\n // Process panels until no more collisions\n // 衝突がなくなるまでパネルを処理\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n // Safety check: prevent infinite loops\n // 安全チェック: 無限ループを防止\n const count = processCount.get(current.id) || 0;\n if (count >= MAX_PROCESS_COUNT) continue;\n processCount.set(current.id, count + 1);\n\n // Skip if the position in queue doesn't match current position in map (outdated entry)\n // キューの位置がマップの現在位置と一致しない場合はスキップ(古いエントリ)\n const currentInMap = panelMap.get(current.id);\n if (currentInMap && (currentInMap.x !== current.x || currentInMap.y !== current.y)) {\n continue;\n }\n\n // Skip if already processed at this position\n // この位置で既に処理済みの場合はスキップ\n if (processed.has(current.id)) {\n continue;\n }\n\n // Detect collisions with current panel position\n // 現在のパネル位置での衝突を検出\n const collidingIds = detectCollisions(current, panelMap);\n\n if (collidingIds.length === 0) {\n panelMap.set(current.id, current);\n processed.add(current.id);\n continue;\n }\n\n // Sort colliding panels by position (top-left to bottom-right) for consistent processing\n // 一貫した処理のため、衝突パネルを位置順(左上から右下)にソート\n const sortedCollidingIds = collidingIds.sort((a, b) => {\n const panelA = panelMap.get(a)!;\n const panelB = panelMap.get(b)!;\n if (panelA.y !== panelB.y) return panelA.y - panelB.y;\n return panelA.x - panelB.x;\n });\n\n // Resolve collisions by pushing colliding panels\n // 衝突したパネルを押しのけて衝突を解決\n for (const collidingId of sortedCollidingIds) {\n const colliding = panelMap.get(collidingId);\n if (!colliding) continue;\n\n // Calculate new position for the colliding panel\n // 衝突パネルの新しい位置を計算\n const newPos = findNewPosition(colliding, current, columnCount);\n let candidate = { ...colliding, x: newPos.x, y: newPos.y };\n\n // Check if candidate overlaps with any previously repositioned panel\n // Re-validate after each adjustment to catch multi-overlap scenarios\n // 候補位置が既に再配置されたパネルと重なる場合、さらに右に押す。無理なら下に押す\n // 各調整後に再検証し、複数の重なりシナリオに対応\n let needsPushDown = false;\n let adjusted = true;\n let adjustAttempts = 0;\n while (adjusted && !needsPushDown && adjustAttempts < repositioned.size + 1) {\n adjusted = false;\n adjustAttempts++;\n for (const repoId of repositioned) {\n const repoPanel = panelMap.get(repoId);\n if (!repoPanel || repoId === collidingId) continue;\n if (!rectanglesOverlap(candidate, repoPanel)) continue;\n\n const furtherX = repoPanel.x + repoPanel.w;\n if (furtherX + candidate.w <= columnCount) {\n candidate = { ...candidate, x: furtherX };\n adjusted = true;\n break; // Restart loop to re-validate against all repositioned panels\n } else {\n needsPushDown = true;\n break;\n }\n }\n }\n\n if (needsPushDown) {\n const pushDown = current.y + current.h - colliding.y;\n candidate = { ...candidate, x: colliding.x, y: colliding.y + (pushDown > 0 ? pushDown : 1) };\n }\n\n // Update panel map and add to queue for further processing\n // パネルマップを更新し、さらなる処理のためキューに追加\n panelMap.set(collidingId, candidate);\n queue.push(candidate);\n repositioned.add(collidingId);\n }\n\n panelMap.set(current.id, current);\n processed.add(current.id);\n }\n\n // Return the rearranged panels\n // 再配置後のパネルを返す\n return Array.from(panelMap.values());\n}\n\n/**\n * Find a new position for a panel to be added\n * 追加するパネルの新しい位置を見つける\n */\nexport function findNewPositionToAddPanel(\n panelToAdd: Partial<PanelCoordinate>,\n allPanels: PanelCoordinate[],\n columnCount: number\n): { x: number; y: number } {\n const id = panelToAdd.id || Math.random().toString(36).substring(2, 15);\n const w = panelToAdd.w || 1;\n const h = panelToAdd.h || 1;\n\n // Create a map for fast panel lookup\n const panelMap = new Map<PanelId, PanelCoordinate>();\n for (const panel of allPanels) {\n panelMap.set(panel.id, panel);\n }\n\n // Calculate maximum row based on existing panels\n // Add some buffer rows to ensure we can find a position\n const maxExistingY = allPanels.length > 0 ? Math.max(...allPanels.map((p) => p.y + p.h)) : 0;\n const MAX_ROWS = Math.max(maxExistingY + 100, 1000);\n\n // Try to find a position starting from top-left\n for (let y = 0; y < MAX_ROWS; y++) {\n for (let x = 0; x <= columnCount - w; x++) {\n const candidate: PanelCoordinate = {\n id,\n x,\n y,\n w,\n h,\n };\n\n // Check if this position has any collisions\n if (!hasCollision(candidate, candidate.id, panelMap)) {\n return { x, y };\n }\n }\n }\n\n // Fallback: if no position found, place at the bottom\n return { x: 0, y: maxExistingY };\n}\n"],"mappings":";;;;;AAMA,SAAgB,kBACd,GACA,GACS;AACT,QAAO,EAEH,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE,KACf,EAAE,IAAI,EAAE,KAAK,EAAE;;;;;;AASrB,SAAgB,iBAAiB,OAAwB,UAAoD;CAC3G,MAAM,6BAAa,IAAI,KAAc;AAErC,MAAK,MAAM,CAAC,IAAI,UAAU,UAAU;AAClC,MAAI,OAAO,MAAM,GAAI;AAErB,MAAI,kBAAkB,OAAO,MAAM,CACjC,YAAW,IAAI,GAAG;;AAItB,QAAO,MAAM,KAAK,WAAW;;;;;;AAO/B,SAAgB,aACd,WACA,WACA,UACS;AACT,MAAK,MAAM,CAAC,IAAI,UAAU,UAAU;AAClC,MAAI,OAAO,UAAW;AACtB,MAAI,kBAAkB,WAAW,MAAM,CACrC,QAAO;;AAGX,QAAO;;;;;;AAOT,SAAS,sBACP,QACA,QACA,aAC0D;CAG1D,MAAM,YAAY,OAAO,IAAI,OAAO,IAAI,OAAO;CAC/C,MAAM,eAAe,OAAO,IAAI,OAAO,IAAI,aAAa;CAIxD,MAAM,WAAW,OAAO,IAAI,OAAO,IAAI,OAAO;AAI9C,KAAI,gBAAgB,YAAY,EAC9B,QAAO;EAAE,WAAW;EAAS,UAAU;EAAW;AAKpD,KAAI,WAAW,EACb,QAAO;EAAE,WAAW;EAAQ,UAAU;EAAU;AAGlD,QAAO;;;;;;;;AAST,SAAgB,gBACd,OACA,QACA,aAC0B;CAC1B,MAAM,WAAW,sBAAsB,QAAQ,OAAO,YAAY;AAElE,KAAI,CAAC,SAGH,QAAO;EAAE,GAAG,MAAM;EAAG,G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