Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Drop react draggable for dnd kit (#65268)

Fraser6845e31f38ee
diff --git a/.loki/reference/chrome_laptop_viz_PivotTable_Default.png b/.loki/reference/chrome_laptop_viz_PivotTable_Default.png
index 9e3dc719810..1073a0cfa01 100644
Binary files a/.loki/reference/chrome_laptop_viz_PivotTable_Default.png and b/.loki/reference/chrome_laptop_viz_PivotTable_Default.png differ
diff --git a/.loki/reference/chrome_laptop_viz_PivotTable_Embedding_Theme.png b/.loki/reference/chrome_laptop_viz_PivotTable_Embedding_Theme.png
index 8fd832a572f..e72e0c7c24c 100644
Binary files a/.loki/reference/chrome_laptop_viz_PivotTable_Embedding_Theme.png and b/.loki/reference/chrome_laptop_viz_PivotTable_Embedding_Theme.png differ
diff --git a/.loki/reference/chrome_laptop_viz_PivotTable_Horizontal_Scroll_43215.png b/.loki/reference/chrome_laptop_viz_PivotTable_Horizontal_Scroll_43215.png
index 5f5146fe740..7cd797d9770 100644
Binary files a/.loki/reference/chrome_laptop_viz_PivotTable_Horizontal_Scroll_43215.png and b/.loki/reference/chrome_laptop_viz_PivotTable_Horizontal_Scroll_43215.png differ
diff --git a/.loki/reference/chrome_laptop_viz_PivotTable_No_Outer_Horizontal_Scroll.png b/.loki/reference/chrome_laptop_viz_PivotTable_No_Outer_Horizontal_Scroll.png
index ecb0780ecd7..327eb2afa10 100644
Binary files a/.loki/reference/chrome_laptop_viz_PivotTable_No_Outer_Horizontal_Scroll.png and b/.loki/reference/chrome_laptop_viz_PivotTable_No_Outer_Horizontal_Scroll.png differ
diff --git a/.loki/reference/chrome_laptop_viz_PivotTable_Outer_Horizontal_Scroll.png b/.loki/reference/chrome_laptop_viz_PivotTable_Outer_Horizontal_Scroll.png
index bc458fe5767..f6557314fca 100644
Binary files a/.loki/reference/chrome_laptop_viz_PivotTable_Outer_Horizontal_Scroll.png and b/.loki/reference/chrome_laptop_viz_PivotTable_Outer_Horizontal_Scroll.png differ
diff --git a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js
index 4c9958b86ab..a973f3ac88a 100644
--- a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js
+++ b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js
@@ -1078,15 +1078,20 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {
// eslint-disable-next-line no-unsafe-element-filtering
cy.findAllByTestId("pivot-table-resize-handle").last();
- dragColumnHeader(leftHeaderColHandle(), -100);
- dragColumnHeader(totalHeaderColHandle(), 100);
-
+ H.moveDnDKitElement(leftHeaderColHandle(), {
+ horizontal: -100,
+ vertical: 0,
+ });
+ H.moveDnDKitElement(totalHeaderColHandle(), {
+ horizontal: 100,
+ vertical: 0,
+ });
cy.findByTestId("pivot-table").within(() => {
cy.findByText("User → Source").should(($headerTextEl) => {
expect(getCellWidth($headerTextEl)).equal(80); // min width is 80
});
cy.findByText("Row totals").should(($headerTextEl) => {
- expect(getCellWidth($headerTextEl)).equal(200);
+ expect(getCellWidth($headerTextEl)).equal(220);
});
});
@@ -1096,13 +1101,12 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {
});
cy.reload(); // reload to make sure the settings are persisted
-
cy.findByTestId("pivot-table").within(() => {
cy.findByText("User → Source").then(($headerTextEl) => {
expect(getCellWidth($headerTextEl)).equal(80);
});
cy.findByText("Row totals").then(($headerTextEl) => {
- expect(getCellWidth($headerTextEl)).equal(200);
+ expect(getCellWidth($headerTextEl)).equal(220);
});
});
});
@@ -1517,18 +1521,6 @@ function assertOnPivotFields() {
cy.findByText("18,760");
}
-function dragColumnHeader(el, xDistance = 50) {
- const HANDLE_WIDTH = xDistance > 0 ? 2 : -2;
- el.then(($el) => {
- const currentXPos = $el[0].getBoundingClientRect().x;
- el.trigger("mousedown", { which: 1 })
- .trigger("mousemove", {
- clientX: currentXPos + (xDistance + HANDLE_WIDTH),
- })
- .trigger("mouseup");
- });
-}
-
function openColumnSettings(columnName) {
H.sidebar()
.findByTestId(`draggable-item-${columnName}`)
diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx
index c61290f475b..2388ca38200 100644
--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTable.tsx
@@ -1,3 +1,5 @@
+import { DndContext } from "@dnd-kit/core";
+import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
import cx from "classnames";
import type * as React from "react";
import {
@@ -401,194 +403,202 @@ const PivotTableInner = forwardRef<HTMLDivElement, VisualizationProps>(
}
return (
- <PivotTableRoot
- ref={ref}
- shouldOverflow={shouldOverflow}
- shouldHideScrollbars={isEditing && isDashboard}
- isDashboard={isDashboard}
- data-testid="pivot-table"
- >
- <ScrollSync>
- {({ onScroll, scrollLeft, scrollTop }) => (
- <div className={cx(CS.fullHeight, CS.flex, CS.flexColumn)}>
- <div className={CS.flex} style={{ height: topHeaderHeight }}>
- {/* top left corner - displays left header columns */}
- <PivotTableTopLeftCellsContainer
- style={{
- width: leftHeaderWidth,
- }}
- >
- {rowIndexes.map((rowIndex: number, index: number) => (
- <Cell
- key={rowIndex}
- isEmphasized
- isBold
- isBorderedHeader
- isTransparent
- hasTopBorder={topHeaderRows > 1}
- value={getColumnTitle(rowIndex)}
- onResize={(newWidth: number) =>
- handleColumnResize("leftHeader", index, newWidth)
- }
- style={{
- flex: "0 0 auto",
- width:
- (leftHeaderWidths?.[index] ?? 0) +
- (index === 0 ? LEFT_HEADER_LEFT_SPACING : 0),
- ...(index === 0
- ? { paddingLeft: LEFT_HEADER_LEFT_SPACING }
- : {}),
- ...(index === rowIndexes.length - 1
- ? { borderRight: "none" }
- : {}),
- }}
- icon={
- // you can only collapse before the last column
- index < rowIndexes.length - 1 &&
- isColumnCollapsible(rowIndex) && (
- <RowToggleIcon
- value={index + 1}
- settings={settings}
- updateSettings={onUpdateVisualizationSettings}
- />
- )
- }
- />
- ))}
- </PivotTableTopLeftCellsContainer>
- {/* top header */}
- <Collection
- style={{ minWidth: `${topHeaderWidth}px` }}
- ref={topHeaderRef}
- className={CS.scrollHideAll}
- width={topHeaderWidth}
- height={topHeaderHeight}
- cellCount={topHeaderItems.length}
- cellRenderer={({ index, style, key }) => (
- <TopHeaderCell
- key={key}
- style={style}
- item={topHeaderItems[index]}
- getCellClickHandler={getCellClickHandler}
- onResize={(newWidth: number) =>
- handleColumnResize(
- "value",
- topHeaderItems[index].offset,
- newWidth,
- )
- }
- />
- )}
- cellSizeAndPositionGetter={({ index }) =>
- topHeaderCellSizeAndPositionGetter(
- topHeaderItems[index],
- topHeaderRows,
- valueHeaderWidths,
- )
- }
- onScroll={({ scrollLeft }) =>
- onScroll({ scrollLeft } as OnScrollParams)
- }
- scrollLeft={scrollLeft}
- />
- </div>
- <div className={cx(CS.flex, CS.flexFull)}>
- {/* left header */}
- <div style={{ width: leftHeaderWidth }}>
- <AutoSizer disableWidth nonce={window.MetabaseNonce}>
- {() => (
- <Collection
- ref={leftHeaderRef}
- className={CS.scrollHideAll}
- cellCount={leftHeaderItems.length}
- cellRenderer={({ index, style, key }) => (
- <LeftHeaderCell
- key={key}
- style={style}
- item={leftHeaderItems[index]}
- rowIndex={rowIndex}
- onUpdateVisualizationSettings={
- onUpdateVisualizationSettings
- }
- settings={settings}
- getCellClickHandler={getCellClickHandler}
- />
- )}
- cellSizeAndPositionGetter={({ index }) =>
- leftHeaderCellSizeAndPositionGetter(
- leftHeaderItems[index],
- leftHeaderWidths ?? [0],
- rowIndexes,
+ <DndContext modifiers={[restrictToHorizontalAxis]}>
+ <PivotTableRoot
+ ref={ref}
+ shouldOverflow={shouldOverflow}
+ shouldHideScrollbars={isEditing && isDashboard}
+ isDashboard={isDashboard}
+ data-testid="pivot-table"
+ >
+ <ScrollSync>
+ {({ onScroll, scrollLeft, scrollTop }) => (
+ <div className={cx(CS.fullHeight, CS.flex, CS.flexColumn)}>
+ <div className={CS.flex} style={{ height: topHeaderHeight }}>
+ {/* top left corner - displays left header columns */}
+ <PivotTableTopLeftCellsContainer
+ style={{
+ width: leftHeaderWidth,
+ }}
+ >
+ {rowIndexes.map((rowIndex: number, index: number) => (
+ <Cell
+ key={rowIndex}
+ isEmphasized
+ isBold
+ isBorderedHeader
+ isTransparent
+ hasTopBorder={topHeaderRows > 1}
+ value={getColumnTitle(rowIndex)}
+ onResize={(newWidth: number) =>
+ handleColumnResize("leftHeader", index, newWidth)
+ }
+ style={{
+ flex: "0 0 auto",
+ width:
+ (leftHeaderWidths?.[index] ?? 0) +
+ (index === 0 ? LEFT_HEADER_LEFT_SPACING : 0),
+ ...(index === 0
+ ? { paddingLeft: LEFT_HEADER_LEFT_SPACING }
+ : {}),
+ ...(index === rowIndexes.length - 1
+ ? { borderRight: "none" }
+ : {}),
+ }}
+ icon={
+ // you can only collapse before the last column
+ index < rowIndexes.length - 1 &&
+ isColumnCollapsible(rowIndex) && (
+ <RowToggleIcon
+ value={index + 1}
+ settings={settings}
+ updateSettings={onUpdateVisualizationSettings}
+ />
)
}
- width={leftHeaderWidth}
- height={bodyHeight - scrollBarOffsetSize()}
- scrollTop={scrollTop}
- onScroll={({ scrollTop }) =>
- onScroll({ scrollTop } as OnScrollParams)
+ />
+ ))}
+ </PivotTableTopLeftCellsContainer>
+ {/* top header */}
+ <Collection
+ style={{ minWidth: `${topHeaderWidth}px` }}
+ ref={topHeaderRef}
+ className={CS.scrollHideAll}
+ width={topHeaderWidth}
+ height={topHeaderHeight}
+ cellCount={topHeaderItems.length}
+ cellRenderer={({ index, style, key }) => (
+ <TopHeaderCell
+ key={key}
+ style={style}
+ item={topHeaderItems[index]}
+ getCellClickHandler={getCellClickHandler}
+ onResize={(newWidth: number) =>
+ handleColumnResize(
+ "value",
+ topHeaderItems[index].offset,
+ newWidth,
+ )
}
/>
)}
- </AutoSizer>
+ cellSizeAndPositionGetter={({ index }) =>
+ topHeaderCellSizeAndPositionGetter(
+ topHeaderItems[index],
+ topHeaderRows,
+ valueHeaderWidths,
+ )
+ }
+ onScroll={({ scrollLeft }) =>
+ onScroll({ scrollLeft } as OnScrollParams)
+ }
+ scrollLeft={scrollLeft}
+ />
</div>
- {/* pivot table body */}
- <div>
- <AutoSizer disableWidth nonce={window.MetabaseNonce}>
- {() => (
- <Grid
- aria-label={PIVOT_TABLE_BODY_LABEL}
- width={viewPortWidth - leftHeaderWidth}
- height={bodyHeight}
- rowCount={rowCount}
- columnCount={columnCount}
- rowHeight={CELL_HEIGHT}
- columnWidth={({ index }) => {
- const subColumnWidths = getCellWidthsForSection(
- valueHeaderWidths,
- valueIndexes,
- index,
- );
- return sumArray(subColumnWidths);
- }}
- estimatedColumnSize={DEFAULT_CELL_WIDTH}
- cellRenderer={({
- rowIndex,
- columnIndex,
- key,
- style,
- isScrolling,
- }) => {
- return (
- <BodyCell
+ <div className={cx(CS.flex, CS.flexFull)}>
+ {/* left header */}
+ <div style={{ width: leftHeaderWidth }}>
+ <AutoSizer disableWidth nonce={window.MetabaseNonce}>
+ {() => (
+ <Collection
+ ref={leftHeaderRef}
+ className={CS.scrollHideAll}
+ cellCount={leftHeaderItems.length}
+ cellRenderer={({ index, style, key }) => (
+ <LeftHeaderCell
key={key}
style={style}
- showTooltip={!isScrolling}
- rowSection={getRowSection(columnIndex, rowIndex)}
+ item={leftHeaderItems[index]}
+ rowIndex={rowIndex}
+ onUpdateVisualizationSettings={
+ onUpdateVisualizationSettings
+ }
+ settings={settings}
getCellClickHandler={getCellClickHandler}
- cellWidths={getCellWidthsForSection(
- valueHeaderWidths,
- valueIndexes,
- columnIndex,
- )}
/>
- );
- }}
- onScroll={({ scrollLeft, scrollTop }) =>
- onScroll({ scrollLeft, scrollTop } as OnScrollParams)
- }
- ref={gridRef}
- elementRef={gridContainerRef}
- scrollTop={scrollTop}
- scrollLeft={scrollLeft}
- />
- )}
- </AutoSizer>
+ )}
+ cellSizeAndPositionGetter={({ index }) =>
+ leftHeaderCellSizeAndPositionGetter(
+ leftHeaderItems[index],
+ leftHeaderWidths ?? [0],
+ rowIndexes,
+ )
+ }
+ width={leftHeaderWidth}
+ height={bodyHeight - scrollBarOffsetSize()}
+ scrollTop={scrollTop}
+ onScroll={({ scrollTop }) =>
+ onScroll({ scrollTop } as OnScrollParams)
+ }
+ />
+ )}
+ </AutoSizer>
+ </div>
+ {/* pivot table body */}
+ <div>
+ <AutoSizer disableWidth nonce={window.MetabaseNonce}>
+ {() => (
+ <Grid
+ aria-label={PIVOT_TABLE_BODY_LABEL}
+ width={viewPortWidth - leftHeaderWidth}
+ height={bodyHeight}
+ rowCount={rowCount}
+ columnCount={columnCount}
+ rowHeight={CELL_HEIGHT}
+ columnWidth={({ index }) => {
+ const subColumnWidths = getCellWidthsForSection(
+ valueHeaderWidths,
+ valueIndexes,
+ index,
+ );
+ return sumArray(subColumnWidths);
+ }}
+ estimatedColumnSize={DEFAULT_CELL_WIDTH}
+ cellRenderer={({
+ rowIndex,
+ columnIndex,
+ key,
+ style,
+ isScrolling,
+ }) => {
+ return (
+ <BodyCell
+ key={key}
+ style={style}
+ showTooltip={!isScrolling}
+ rowSection={getRowSection(
+ columnIndex,
+ rowIndex,
+ )}
+ getCellClickHandler={getCellClickHandler}
+ cellWidths={getCellWidthsForSection(
+ valueHeaderWidths,
+ valueIndexes,
+ columnIndex,
+ )}
+ />
+ );
+ }}
+ onScroll={({ scrollLeft, scrollTop }) =>
+ onScroll({
+ scrollLeft,
+ scrollTop,
+ } as OnScrollParams)
+ }
+ ref={gridRef}
+ elementRef={gridContainerRef}
+ scrollTop={scrollTop}
+ scrollLeft={scrollLeft}
+ />
+ )}
+ </AutoSizer>
+ </div>
</div>
</div>
- </div>
- )}
- </ScrollSync>
- </PivotTableRoot>
+ )}
+ </ScrollSync>
+ </PivotTableRoot>
+ </DndContext>
);
},
);
diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableCell.tsx b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableCell.tsx
index ad8adc37ff3..189cea4ecb6 100644
--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableCell.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableCell.tsx
@@ -1,7 +1,6 @@
+import { useDraggable } from "@dnd-kit/core";
import cx from "classnames";
-import * as React from "react";
-import type { ControlPosition, DraggableBounds } from "react-draggable";
-import Draggable from "react-draggable";
+import { useEffect, useId, useRef } from "react";
import { Ellipsified } from "metabase/common/components/Ellipsified";
import CS from "metabase/css/core/index.css";
@@ -26,22 +25,53 @@ interface CellProps {
hasTopBorder?: boolean;
onClick?: ((e: React.MouseEvent) => void) | undefined;
onResize?: (newWidth: number) => void;
+ showTooltip?: boolean;
}
-interface CellProps {
- value: React.ReactNode;
- style?: React.CSSProperties;
- icon?: React.ReactNode;
- backgroundColor?: string;
- isBody?: boolean;
- isBold?: boolean;
- isEmphasized?: boolean;
- isBorderedHeader?: boolean;
- isTransparent?: boolean;
- hasTopBorder?: boolean;
- onClick?: ((e: React.MouseEvent) => void) | undefined;
- onResize?: (newWidth: number) => void;
- showTooltip?: boolean;
+interface ResizableHandleProps {
+ id: string;
+ initialWidth: number;
+ onResizeEnd: (newWidth: number) => void;
+}
+
+function ResizableHandle({
+ id,
+ initialWidth,
+ onResizeEnd,
+}: ResizableHandleProps) {
+ const { attributes, listeners, setNodeRef, transform } = useDraggable({
+ id,
+ });
+
+ const prevTransformRef = useRef<{ x: number; y: number } | null>(null);
+
+ useEffect(() => {
+ const prevTransform = prevTransformRef.current;
+ prevTransformRef.current = transform;
+
+ if (prevTransform !== null && transform === null) {
+ const newWidth = Math.max(
+ RESIZE_HANDLE_WIDTH,
+ initialWidth + prevTransform.x,
+ );
+ onResizeEnd(newWidth);
+ }
+ }, [transform, initialWidth, onResizeEnd]);
+
+ const currentPosition = initialWidth + (transform ? transform.x : 0);
+
+ return (
+ <ResizeHandle
+ ref={setNodeRef}
+ data-testid="pivot-table-resize-handle"
+ style={{
+ left: `${currentPosition}px`,
+ cursor: "col-resize",
+ }}
+ {...listeners}
+ {...attributes}
+ />
+ );
}
export function Cell({
@@ -59,7 +89,7 @@ export function Cell({
onResize,
showTooltip = true,
}: CellProps) {
- const resizeHandleRef = React.useRef<HTMLDivElement | null>(null);
+ const cellId = useId();
return (
<PivotTableCell
@@ -90,26 +120,11 @@ export function Cell({
{icon && <div className={CS.pl1}>{icon}</div>}
</div>
{!!onResize && (
- <Draggable
- axis="x"
- enableUserSelectHack
- bounds={{ left: RESIZE_HANDLE_WIDTH } as DraggableBounds}
- position={
- {
- x: style?.width ?? 0,
- y: 0,
- } as ControlPosition
- }
- onStop={(e, { x }) => {
- onResize(x);
- }}
- nodeRef={resizeHandleRef}
- >
- <ResizeHandle
- data-testid="pivot-table-resize-handle"
- ref={resizeHandleRef}
- />
- </Draggable>
+ <ResizableHandle
+ id={`resize-handle-${cellId}`}
+ initialWidth={(style?.width as number) ?? 0}
+ onResizeEnd={onResize}
+ />
)}
</>
</PivotTableCell>
diff --git a/package.json b/package.json
index 0c076eda726..1d41a5e1e09 100644
--- a/package.json
+++ b/package.json
@@ -113,7 +113,6 @@
"react-dnd": "4",
"react-dnd-html5-backend": "4",
"react-dom": "^18.2.0",
- "react-draggable": "^4.4.5",
"react-dropzone": "^14.2.3",
"react-grid-layout": "^1.4.4",
"react-innertext": "^1.1.5",
diff --git a/yarn.lock b/yarn.lock
index c85c4c3d69e..d7ca0f9e585 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -8127,7 +8127,7 @@ classnames@^2.1.3:
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.3.2.tgz#351d813bf0137fcc6a76a16b88208d2560a0d924"
integrity sha512-CSbhY4cFEJRe6/GQzIk5qXZ4Jeg5pcsP7b5peFSDpffpe1cqjASH/n9UTjBwOp6XpMSTwQ8Za2K5V02ueA7Tmw==
-classnames@^2.2.5, classnames@^2.3.1:
+classnames@^2.3.1:
version "2.5.1"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.5.1.tgz#ba774c614be0f016da105c858e7159eae8e7687b"
integrity sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==
@@ -17989,15 +17989,7 @@ react-dom@^18.2.0:
loose-envify "^1.1.0"
scheduler "^0.23.0"
-react-draggable@^4.0.3:
- version "4.4.3"
- resolved "https://registry.yarnpkg.com/react-draggable/-/react-draggable-4.4.3.tgz#0727f2cae5813e36b0e4962bf11b2f9ef2b406f3"
- integrity sha512-jV4TE59MBuWm7gb6Ns3Q1mxX8Azffb7oTtDtBgFkxRvhDp38YAARmRplrj0+XGkhOJB5XziArX+4HUUABtyZ0w==
- dependencies:
- classnames "^2.2.5"
- prop-types "^15.6.0"
-
-react-draggable@^4.4.5:
+react-draggable@^4.0.3, react-draggable@^4.4.5:
version "4.4.6"
resolved "https://registry.yarnpkg.com/react-draggable/-/react-draggable-4.4.6.tgz#63343ee945770881ca1256a5b6fa5c9f5983fe1e"
integrity sha512-LtY5Xw1zTPqHkVmtM3X8MUOxNDOUhv/khTgBgrUvwaS064bwVvxT+q5El0uUFNx5IEPKXuRejr7UqLwBIg5pdw==