OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): tiles switch to their table and snap to a finer grid (#548)
Carl-Gerhard Lindesvärdf1c5d3699d04
diff --git a/apps/start/e2e/verify-b-interactions.spec.ts b/apps/start/e2e/verify-b-interactions.spec.tsindex 257542e88..772e255ca 100644--- a/apps/start/e2e/verify-b-interactions.spec.ts+++ b/apps/start/e2e/verify-b-interactions.spec.ts@@ -230,11 +230,11 @@ test('dashboard grid: drag, resize, persist, reset layout', async ({const resized = await boxes();expect(resized.one?.height ?? 0).toBeGreaterThan(initial.one.height + 80);- // --- drag card two by its handle to the left column- const grip = two.locator('.drag-handle').first();+ // --- drag card two by its header to the left column+ const grip = two.locator('.tile-header').first();const gripBox = await grip.boundingBox();if (!gripBox) {- throw new Error('no drag handle');+ throw new Error('no tile header');}saved = layoutSaved();await page.mouse.move(@@ -268,6 +268,26 @@ test('dashboard grid: drag, resize, persist, reset layout', async ({Math.round(dragged.two?.y ?? 0));+ // --- switch a tile to its table: same size, and it stays a table+ const displaySaved = page.waitForResponse((response) =>+ response.url().includes('/trpc/report.updateDisplay')+ );+ await two.hover();+ await two.getByRole('button', { name: 'Show table' }).click();+ expect((await displaySaved).status()).toBe(200);+ const tableView = two.locator('[data-tile-view="table"]');+ await expect(tableView.locator('[data-report-table]')).toBeVisible();+ const asTable = await two.boundingBox();+ expect(Math.round(asTable?.height ?? 0)).toBe(+ Math.round(reloaded.two?.height ?? 0)+ );+ await shot(page, 'item13-grid-table-view');+ await page.reload();+ await expect(tableView).toBeVisible({ timeout: 30_000 });+ await two.hover();+ await two.getByRole('button', { name: 'Show chart' }).click();+ await expect(tableView).toHaveCount(0);+// --- reset layoutawait page.locator('button:has(svg.lucide-ellipsis)').first().click();await page.getByRole('menuitem', { name: 'Reset layout' }).click();diff --git a/apps/start/src/components/charts/bar-x-axis.tsx b/apps/start/src/components/charts/bar-x-axis.tsxindex 105c2e473..34fdece42 100644--- a/apps/start/src/components/charts/bar-x-axis.tsx+++ b/apps/start/src/components/charts/bar-x-axis.tsx@@ -18,6 +18,8 @@ export interface BarXAxisProps {interface BarXAxisLabelProps {label: string;x: number;+ /** The label's band; a longer label is cut off instead of overlapping its neighbours. */+ maxWidth: number;crosshairX: number | null;isHovering: boolean;tickerHalfWidth: number;@@ -26,6 +28,7 @@ interface BarXAxisLabelProps {function BarXAxisLabel({label,x,+ maxWidth,crosshairX,isHovering,tickerHalfWidth,@@ -43,22 +46,24 @@ function BarXAxisLabel({}}- // Zero-width container approach for perfect centering+ // Centred on x and as wide as the label may be, so a long label truncates+ // instead of overlapping its neighbours.return (<divclassName="absolute"style={{- left: x,+ left: x - maxWidth / 2,bottom: 12,- width: 0,+ width: maxWidth,display: 'flex',justifyContent: 'center',}}><motion.spananimate={{ opacity }}- className={cn('whitespace-nowrap text-chart-label text-xs')}+ className={cn('truncate whitespace-nowrap text-chart-label text-xs')}initial={{ opacity: 1 }}+ title={label}transition={{ duration: 0.4, ease: 'easeInOut' }}>{label}@@ -128,6 +133,10 @@ const BarXAxisInner = memo(function BarXAxisInner({maxLabels,]);+ // Each shown label may take the bands of the labels skipped next to it.+ const labelWidth =+ (bandWidth ?? 0) *+ Math.max(1, data.length / Math.max(1, labelsToShow.length));const isHovering = tooltipData !== null;const crosshairX = tooltipData ? tooltipData.x + margin.left : null;@@ -139,6 +148,7 @@ const BarXAxisInner = memo(function BarXAxisInner({isHovering={isHovering}key={`${item.label}-${item.x}`}label={item.label}+ maxWidth={labelWidth}tickerHalfWidth={tickerHalfWidth}x={item.x}/>diff --git a/apps/start/src/components/charts/funnel-chart.tsx b/apps/start/src/components/charts/funnel-chart.tsxindex 5e59684be..1b15b5138 100644--- a/apps/start/src/components/charts/funnel-chart.tsx+++ b/apps/start/src/components/charts/funnel-chart.tsx@@ -634,7 +634,10 @@ function SegmentLabel({</span>);const labelEl = showLabels && (- <span className="whitespace-nowrap font-medium text-muted-foreground text-xs">+ <span+ className="min-w-0 max-w-full truncate whitespace-nowrap px-1 font-medium text-muted-foreground text-xs"+ title={stage.label}+ >{stage.label}</span>);@@ -663,7 +666,7 @@ function SegmentLabel({<div className="flex flex-1 items-center justify-center">{pctEl}</div>- <div className="flex h-[16%] items-start justify-center pt-1">+ <div className="flex h-[16%] w-full min-w-0 items-start justify-center pt-1">{labelEl}</div></>@@ -726,7 +729,7 @@ function SegmentLabel({><divclassName={cn(- 'flex gap-1.5',+ 'flex min-w-0 max-w-full gap-1.5',isVerticalStack? cn('flex-col', itemsMap[isHorizontal ? 'center' : align]): cn('flex-row', itemsMap.center)diff --git a/apps/start/src/components/dashboard-grid.tsx b/apps/start/src/components/dashboard-grid.tsxindex 41087e921..9762cdfa5 100644--- a/apps/start/src/components/dashboard-grid.tsx+++ b/apps/start/src/components/dashboard-grid.tsx@@ -1,6 +1,19 @@import type { IServiceReport } from '@openpanel/core';-import { type ReactNode, useEffect, useMemo, useState } from 'react';import {+ GRID_COLUMNS,+ GRID_GAP,+ GRID_ROW_HEIGHT,+} from '@openpanel/core/modules/report/report.constants';+import {+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import {+ type EventCallback,GridLayout,type GridLayoutProps,type Layout,@@ -10,14 +23,33 @@ import {verticalCompactor,} from 'react-grid-layout';+export {+ GRID_COLUMNS,+ GRID_GAP,+ GRID_ROW_HEIGHT,+} from '@openpanel/core/modules/report/report.constants';export type { Layout, LayoutItem } from 'react-grid-layout';-export const GRID_COLUMNS = 12;-export const GRID_ROW_HEIGHT = 100;-export const GRID_GAP = 16;-export const TILE_MIN_SIZE = { minW: 3, minH: 3 } as const;-const RESIZE_HANDLES: readonly ResizeHandleAxis[] = ['se', 'sw', 'ne', 'nw'];-const TILE_DEFAULT_SIZE = { w: 6, h: 4 } as const;+export const TILE_MIN_SIZE = { minW: 6, minH: 6 } as const;+const RESIZE_HANDLES: readonly ResizeHandleAxis[] = [+ 'n',+ 'e',+ 's',+ 'w',+ 'ne',+ 'nw',+ 'se',+ 'sw',+];+// The whole header drags the tile; its controls keep their clicks.+const DRAG_HANDLE = '.tile-header';+const DRAG_CANCEL =+ 'button, a, input, textarea, select, [role="menu"], [role="menuitem"]';+// Within this distance of the viewport's top or bottom a gesture scrolls the+// page, up to the max speed (px per frame) at the very edge.+const AUTO_SCROLL_EDGE = 80;+const AUTO_SCROLL_MAX_SPEED = 18;+const TILE_DEFAULT_SIZE = { w: 12, h: 8 } as const;// Narrower than this and tiles stack in one column with no drag, since a// drag would hijack scrolling on a phone.const SINGLE_COLUMN_MAX_WIDTH = 640;@@ -26,18 +58,35 @@ export type DashboardReport = NonNullable<IServiceReport>;/** What placing a report on the grid needs; the dashboards list has reports in a lighter shape than the editor. */export interface LayoutSource {id: string;- layout?: Pick<LayoutItem, 'x' | 'y' | 'w' | 'h'> | null;+ layout?:+ | (Pick<LayoutItem, 'x' | 'y' | 'w' | 'h'> & { gridColumns?: number })+ | null;}export function toLayout(reports: LayoutSource[]): Layout {- return reports.map((report, index) => ({- i: report.id,- x: report.layout?.x ?? (index % 2) * TILE_DEFAULT_SIZE.w,- y: report.layout?.y ?? Math.floor(index / 2) * TILE_DEFAULT_SIZE.h,- w: report.layout?.w ?? TILE_DEFAULT_SIZE.w,- h: report.layout?.h ?? TILE_DEFAULT_SIZE.h,- ...TILE_MIN_SIZE,- }));+ return reports.map((report, index) => {+ const saved = report.layout;+ if (!saved) {+ return {+ i: report.id,+ x: (index % 2) * TILE_DEFAULT_SIZE.w,+ y: Math.floor(index / 2) * TILE_DEFAULT_SIZE.h,+ ...TILE_DEFAULT_SIZE,+ ...TILE_MIN_SIZE,+ };+ }+ // A layout not yet moved by the grid migration is drawn at the same size+ // on the finer grid; its next save stores it in the new units.+ const scale = GRID_COLUMNS / (saved.gridColumns ?? GRID_COLUMNS);+ return {+ i: report.id,+ x: saved.x * scale,+ y: saved.y * scale,+ w: saved.w * scale,+ h: saved.h * scale,+ ...TILE_MIN_SIZE,+ };+ });}function toSingleColumn(layout: Layout): Layout {@@ -56,16 +105,186 @@ export function isSameTilePosition(a: TilePosition, b: TilePosition) {return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;}-// The grid owns the layout while the user drags; saved positions only seed it.+/**+ * The grid owns the layout while the user drags; saved positions only seed it.+ * A new set of reports re-seeds it during render rather than in an effect, so+ * a tile added to a mounted grid arrives together with its layout entry. With+ * an effect the grid first saw the tile without one, placed it itself, and the+ * two layouts overwrote each other until React stopped the update loop.+ */export function useDashboardLayout(reports: DashboardReport[]) {const savedLayout = useMemo(() => toLayout(reports), [reports]);- const [layout, setLayout] = useState(savedLayout);+ const [state, setState] = useState({+ seed: savedLayout,+ layout: savedLayout,+ });+ if (state.seed !== savedLayout) {+ setState({ seed: savedLayout, layout: savedLayout });+ }+ const setLayout = useCallback(+ (layout: Layout) => setState((current) => ({ ...current, layout })),+ []+ );++ return [+ state.seed === savedLayout ? state.layout : savedLayout,+ setLayout,+ ] as const;+}++function hasScrollingAncestor(element: HTMLElement | null) {+ for (let node = element?.parentElement; node; node = node.parentElement) {+ const { overflowY } = getComputedStyle(node);+ const scrolls = overflowY === 'auto' || overflowY === 'scroll';+ if (scrolls && node.scrollHeight > node.clientHeight) {+ return true;+ }+ }+ return false;+}++function edgeScrollSpeed(pointerY: number) {+ const fromBottom = window.innerHeight - pointerY;+ if (pointerY < AUTO_SCROLL_EDGE) {+ return -AUTO_SCROLL_MAX_SPEED * (1 - pointerY / AUTO_SCROLL_EDGE);+ }+ if (fromBottom < AUTO_SCROLL_EDGE) {+ return AUTO_SCROLL_MAX_SPEED * (1 - fromBottom / AUTO_SCROLL_EDGE);+ }+ return 0;+}++/**+ * Scrolls the page while the pointer rests near the viewport edge; returns a+ * stop function. react-grid-layout already edge-scrolls an overflowing+ * ancestor, but not the page itself, which is what scrolls a dashboard.+ */+function startEdgeScroll(container: HTMLElement | null) {+ if (hasScrollingAncestor(container)) {+ return () => undefined;+ }+ let pointer: { x: number; y: number } | null = null;+ let frame = 0;+ const trackPointer = (event: MouseEvent) => {+ if (event.isTrusted) {+ pointer = { x: event.clientX, y: event.clientY };+ }+ };+ const tick = () => {+ const speed = pointer ? edgeScrollSpeed(pointer.y) : 0;+ if (pointer && speed !== 0) {+ window.scrollBy(0, speed);+ // The grid only moves the tile on pointer moves, so replay the resting+ // pointer to keep the tile under it while the page scrolls.+ document.dispatchEvent(+ new MouseEvent('mousemove', {+ bubbles: true,+ clientX: pointer.x,+ clientY: pointer.y,+ })+ );+ }+ frame = requestAnimationFrame(tick);+ };+ document.addEventListener('mousemove', trackPointer);+ frame = requestAnimationFrame(tick);+ return () => {+ cancelAnimationFrame(frame);+ document.removeEventListener('mousemove', trackPointer);+ };+}++// A drag reports the tile itself, a resize reports the handle inside it.+function tileOf(element: HTMLElement | null) {+ return element?.closest<HTMLElement>('.react-grid-item') ?? null;+}++function tileBodyOf(tile: HTMLElement | null) {+ return tile?.querySelector<HTMLElement>('[data-tile-body]') ?? null;+}++/**+ * What a drag or resize does besides moving the tile: scroll at the viewport+ * edge, show the size the tile will snap to, and hold the chart at its+ * starting size so it renders once on release instead of every frame.+ */+function useGestureEffects(+ containerRef: React.RefObject<HTMLDivElement | null>,+ {+ onDragStop,+ onResizeStop,+ }: Pick<GridLayoutProps, 'onDragStop' | 'onResizeStop'>+) {+ const stopEdgeScroll = useRef<(() => void) | null>(null);+ // Set once a gesture has passed the drag threshold, so a plain click on a+ // tile's title is never treated as the start of one.+ const begin = useCallback(() => {+ stopEdgeScroll.current?.();+ stopEdgeScroll.current = startEdgeScroll(containerRef.current);+ containerRef.current?.setAttribute('data-gesture', '');+ }, [containerRef]);+ const end = useCallback(() => {+ stopEdgeScroll.current?.();+ stopEdgeScroll.current = null;+ containerRef.current?.removeAttribute('data-gesture');+ }, [containerRef]);+ useEffect(() => end, [end]);- useEffect(() => {- setLayout(savedLayout);- }, [savedLayout]);+ const handleDragStart = useCallback<EventCallback>(() => begin(), [begin]);+ const handleDragStop = useCallback<EventCallback>(+ (...args) => {+ end();+ onDragStop?.(...args);+ },+ [end, onDragStop]+ );+ const handleResizeStart = useCallback<EventCallback>(+ (_layout, _oldItem, _newItem, _placeholder, _event, element) => {+ begin();+ const body = tileBodyOf(tileOf(element));+ if (body) {+ const { width, height } = body.getBoundingClientRect();+ body.style.flex = 'none';+ body.style.width = `${width}px`;+ body.style.height = `${height}px`;+ }+ },+ [begin]+ );+ const handleResize = useCallback<EventCallback>(+ (_layout, _oldItem, newItem, _placeholder, _event, element) => {+ const tile = tileOf(element);+ if (tile && newItem) {+ tile.dataset.tileSize = `${newItem.w} × ${newItem.h}`;+ }+ },+ []+ );+ const handleResizeStop = useCallback<EventCallback>(+ (...args) => {+ end();+ const tile = tileOf(args[5]);+ const body = tileBodyOf(tile);+ if (body) {+ body.style.flex = '';+ body.style.width = '';+ body.style.height = '';+ }+ if (tile) {+ delete tile.dataset.tileSize;+ }+ onResizeStop?.(...args);+ },+ [end, onResizeStop]+ );- return [layout, setLayout] as const;+ return {+ onDragStart: handleDragStart,+ onDragStop: handleDragStop,+ onResizeStart: handleResizeStart,+ onResize: handleResize,+ onResizeStop: handleResizeStop,+ };}export function DashboardGrid({@@ -87,22 +306,33 @@ export function DashboardGrid({() => (isSingleColumn ? toSingleColumn(layout) : layout),[isSingleColumn, layout]);+ const gesture = useGestureEffects(containerRef, {+ onDragStop,+ onResizeStop,+ });return (<div className="-m-4" ref={containerRef}>{mounted && (<GridLayoutcompactor={verticalCompactor}- dragConfig={{ enabled: canEdit, handle: '.drag-handle' }}+ dragConfig={{+ enabled: canEdit,+ handle: DRAG_HANDLE,+ cancel: DRAG_CANCEL,+ }}gridConfig={{cols: GRID_COLUMNS,rowHeight: GRID_ROW_HEIGHT,margin: [GRID_GAP, GRID_GAP],}}layout={gridLayout}- onDragStop={onDragStop}+ onDragStart={gesture.onDragStart}+ onDragStop={gesture.onDragStop}onLayoutChange={canEdit ? onLayoutChange : undefined}- onResizeStop={onResizeStop}+ onResize={gesture.onResize}+ onResizeStart={gesture.onResizeStart}+ onResizeStop={gesture.onResizeStop}resizeConfig={{ enabled: canEdit, handles: RESIZE_HANDLES }}width={width}>diff --git a/apps/start/src/components/dashboard-preview.tsx b/apps/start/src/components/dashboard-preview.tsxindex 192153aef..ac0a5ee8f 100644--- a/apps/start/src/components/dashboard-preview.tsx+++ b/apps/start/src/components/dashboard-preview.tsx@@ -33,11 +33,11 @@ export const CHART_TYPE_ICONS: Record<IChartType, LucideIcon> = {// Shown rows: a short dashboard still looks like a dashboard, a long one is cut// rather than shrunk to specks.-const MIN_ROWS = 6;-const MAX_ROWS = 14;+const MIN_ROWS = 12;+const MAX_ROWS = 28;// A tile shows its chart icon only when it is big enough to hold one.-const ICON_MIN_WIDTH_COLUMNS = 3;-const ICON_MIN_HEIGHT_ROWS = 2;+const ICON_MIN_WIDTH_COLUMNS = 6;+const ICON_MIN_HEIGHT_ROWS = 4;const ICON_SIZE = 14;function iconFor(chartType: IChartType | undefined) {diff --git a/apps/start/src/components/page-header.tsx b/apps/start/src/components/page-header.tsxindex 241ebf415..734d1222c 100644--- a/apps/start/src/components/page-header.tsx+++ b/apps/start/src/components/page-header.tsx@@ -24,7 +24,7 @@ export function PageHeader({)}{children}</div>- <div className="row gap-2">{actions}</div>+ <div className="row flex-wrap gap-2">{actions}</div></div>);}diff --git a/apps/start/src/components/report-chart/area/chart.tsx b/apps/start/src/components/report-chart/area/chart.tsxindex f06694627..e71f547a3 100644--- a/apps/start/src/components/report-chart/area/chart.tsx+++ b/apps/start/src/components/report-chart/area/chart.tsx@@ -45,8 +45,8 @@ export function Chart({ data, series }: Props) {xDataKey="date"><Grid horizontal />- {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}- {!chart.hideXAxis && <XAxis />}+ {chart.showYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {chart.showXAxis && <XAxis numTicks={chart.xAxisTicks} />}{chart.previous &&series.map((serie) => (<Areadiff --git a/apps/start/src/components/report-chart/common/chart-size.ts b/apps/start/src/components/report-chart/common/chart-size.tsnew file mode 100644index 000000000..84fdb165d--- /dev/null+++ b/apps/start/src/components/report-chart/common/chart-size.ts@@ -0,0 +1,56 @@+import { useReportChartContext } from '../context';++export type ChartSizeTier = 'compact' | 'medium' | 'wide';++const COMPACT_MAX_WIDTH = 320;+const MEDIUM_MAX_WIDTH = 640;++const X_AXIS_TICKS = {+ compact: 3,+ medium: 4,+ wide: 5,+} satisfies Record<ChartSizeTier, number>;++const LEGEND_LIMIT = {+ compact: 0,+ medium: 3,+ wide: Number.POSITIVE_INFINITY,+} satisfies Record<ChartSizeTier, number>;++const EDGE_MARGIN = 12;+const Y_AXIS_WIDTH = 40;+const X_AXIS_HEIGHT = 28;++export function getSizeTier(width: number): ChartSizeTier {+ if (width < COMPACT_MAX_WIDTH) {+ return 'compact';+ }+ if (width < MEDIUM_MAX_WIDTH) {+ return 'medium';+ }+ return 'wide';+}++/** The axes, ticks and legend entries a chart has room for at its size. */+export function useChartChrome() {+ const {+ sizeTier,+ options: { hideXAxis, hideYAxis, hideLegend },+ } = useReportChartContext();+ // A compact tile spends its width on the data, not on Y labels.+ const showYAxis = !hideYAxis && sizeTier !== 'compact';+ const showXAxis = !hideXAxis;++ return {+ showXAxis,+ showYAxis,+ xAxisTicks: X_AXIS_TICKS[sizeTier],+ legendLimit: hideLegend ? 0 : LEGEND_LIMIT[sizeTier],+ margin: {+ top: EDGE_MARGIN,+ right: EDGE_MARGIN,+ bottom: showXAxis ? X_AXIS_HEIGHT : EDGE_MARGIN,+ left: showYAxis ? Y_AXIS_WIDTH : EDGE_MARGIN,+ },+ };+}diff --git a/apps/start/src/components/report-chart/common/chart-with-table.tsx b/apps/start/src/components/report-chart/common/chart-with-table.tsxindex 87ef0f4b6..f1f620e74 100644--- a/apps/start/src/components/report-chart/common/chart-with-table.tsx+++ b/apps/start/src/components/report-chart/common/chart-with-table.tsx@@ -3,7 +3,8 @@ import { AspectContainer } from '../aspect-container';import { useReportChartContext } from '../context';/**- * Where a report's pieces go: a dashboard tile, or any embed with `hideTable`,+ * Where a report's pieces go: a dashboard tile shows the chart or, switched+ * to its table view, the tables filling the tile; an embed with `hideTable`* is the chart alone; the editor and the share page get the summary, the* chart, and the tables under it.*/@@ -21,7 +22,7 @@ export function ChartWithTable({}) {const {layout,- options: { hideTable },+ options: { hideTable, view },} = useReportChartContext();const sizedChart = sizesItself ? (chart@@ -29,6 +30,17 @@ export function ChartWithTable({<AspectContainer>{chart}</AspectContainer>);+ if (layout === 'fill' && view === 'table') {+ return (+ <div+ className="col h-full min-h-0 gap-2 [--report-table-max-height:none] [&>.card]:rounded-none [&>.card]:border-0"+ data-tile-view="table"+ >+ {tables}+ </div>+ );+ }+if (layout === 'fill' || hideTable) {return sizedChart;}@@ -51,7 +63,7 @@ export function TableCard({children: ReactNode;}) {return (- <div className="card overflow-hidden">+ <div className="card flex min-h-0 flex-1 flex-col overflow-hidden">{title && <div className="border-b px-4 py-3 font-medium">{title}</div>}{children}</div>diff --git a/apps/start/src/components/report-chart/common/time-series.tsx b/apps/start/src/components/report-chart/common/time-series.tsxindex 6c34be7c2..846537f7d 100644--- a/apps/start/src/components/report-chart/common/time-series.tsx+++ b/apps/start/src/components/report-chart/common/time-series.tsx@@ -8,6 +8,7 @@ import {type ChartClickMenuHandle,type ChartClickMenuItem,} from './chart-click-menu';+import { useChartChrome } from './chart-size';import { getCurve } from './curve';import { SerieIcon } from './serie-icon';import { SerieName } from './serie-name';@@ -29,8 +30,6 @@ import { getChartColor } from '@/utils/theme';const TOOLTIP_SERIES_LIMIT = 3;const MARKERS_MAX_POINTS = 8;const PREVIOUS_PERIOD_OPACITY = '30%';-const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };-const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };/** Small point markers for sparse series; bklit's default ring is sized for hero charts. */export const POINT_MARKER = { radius: 3, strokeWidth: 0, ringGap: 0 };@@ -61,8 +60,8 @@ export function useTimeSeriesChart({breakdowns,},shareId,- options: { hideXAxis, hideYAxis },} = useReportChartContext();+ const chrome = useChartChrome();const trpc = useTRPC();const number = useNumber();const references = useQuery(@@ -184,12 +183,10 @@ export function useTimeSeriesChart({references: references.data,previous,interval,- hideXAxis,- hideYAxis,+ ...chrome,dashFromIndex,curve: getCurve(lineType),showMarkers: chartData.length <= MARKERS_MAX_POINTS,- margin: hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN,formatDateLabel,formatAxisValue: number.short,tooltipRows,@@ -225,16 +222,23 @@ export function TimeSeriesFrame({>{children}</div>- {series.length > 1 && <SeriesLegend series={series} />}+ <SeriesLegend series={series} /></div></ChartClickMenu>);}function SeriesLegend({ series }: { series: IVisibleSeries }) {+ const { legendLimit } = useChartChrome();+ const hasRoom = legendLimit > 0;+ if (series.length < 2 || !hasRoom) {+ return null;+ }+ const shown = series.slice(0, legendLimit);+ const hiddenCount = series.length - shown.length;return (<div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">- {series.map((serie) => (+ {shown.map((serie) => (<divclassName="flex items-center gap-1"key={serie.id}@@ -244,6 +248,9 @@ function SeriesLegend({ series }: { series: IVisibleSeries }) {<SerieName className="font-semibold" name={serie.names} /></div>))}+ {hiddenCount > 0 && (+ <div className="text-muted-foreground">+{hiddenCount} more</div>+ )}</div>);}diff --git a/apps/start/src/components/report-chart/context.tsx b/apps/start/src/components/report-chart/context.tsxindex ac3f7672f..b050a91b4 100644--- a/apps/start/src/components/report-chart/context.tsx+++ b/apps/start/src/components/report-chart/context.tsx@@ -4,6 +4,7 @@ import type {} from '@openpanel/core/modules/report/report.constants';import isEqual from 'lodash.isequal';import { createContext, useContext, useEffect, useMemo, useState } from 'react';+import type { ChartSizeTier } from './common/chart-size';export interface ReportChartContextType {options: Partial<{@@ -11,6 +12,8 @@ export interface ReportChartContextType {hideLegend: boolean;/** Show the chart alone, without the series tables an editor shows under it. */hideTable: boolean;+ /** A dashboard tile's choice between its chart and its table. */+ view: 'chart' | 'table';hideXAxis: boolean;hideYAxis: boolean;aspectRatio: number;@@ -25,6 +28,8 @@ export interface ReportChartContextType {// `fill` takes the parent's height (a dashboard tile); `aspect` sizes the// chart from its width (the editor, chat, modals, share pages).layout: 'fill' | 'aspect';+ /** From the chart's measured width; decides axes, ticks and legend size. */+ sizeTier: ChartSizeTier;shareId?: string;reportId?: string;}diff --git a/apps/start/src/components/report-chart/conversion/chart.tsx b/apps/start/src/components/report-chart/conversion/chart.tsxindex 2b6bd7b3a..53cde0740 100644--- a/apps/start/src/components/report-chart/conversion/chart.tsx+++ b/apps/start/src/components/report-chart/conversion/chart.tsx@@ -1,6 +1,7 @@import { average, round } from '@openpanel/shared';import { useQuery } from '@tanstack/react-query';import { useCallback, useMemo } from 'react';+import { useChartChrome } from '../common/chart-size';import { getCurve } from '../common/curve';import { PointClick } from '../common/point-click';import { SerieIcon } from '../common/serie-icon';@@ -25,8 +26,6 @@ import type { RouterOutputs } from '@/trpc/client';import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';-const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };-const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };const MARKERS_MAX_POINTS = 30;const PERCENT_DOMAIN: [number, number] = [0, 100];@@ -45,8 +44,8 @@ export function Chart({report: { interval, projectId, startDate, endDate, range, lineType },isEditMode,shareId,- options: { hideXAxis, hideYAxis },} = useReportChartContext();+ const chrome = useChartChrome();const number = useNumber();const trpc = useTRPC();const references = useQuery(@@ -132,16 +131,16 @@ export function Chart({className="h-full"data={chartData}formatDateLabel={formatDateLabel}- margin={hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN}+ margin={chrome.margin}style={{ touchAction: 'pan-y' }}xDataKey="date"yDomain={PERCENT_DOMAIN}><Grid horizontal />- {!hideYAxis && (+ {chrome.showYAxis && (<YAxis formatValue={(value) => `${number.short(value)}%`} />)}- {!hideXAxis && <XAxis />}+ {chrome.showXAxis && <XAxis numTicks={chrome.xAxisTicks} />}{series.map((serie) => (<Lineanimate={false}@@ -191,9 +190,9 @@ export function Chart({Average ({round(averageRate, 2)}%)</div></div>- {series.length > 1 && (+ {series.length > 1 && chrome.legendLimit > 0 && (<div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">- {series.map((serie) => (+ {series.slice(0, chrome.legendLimit).map((serie) => (<divclassName="flex items-center gap-1"key={serie.id}@@ -203,6 +202,11 @@ export function Chart({<SerieName className="font-semibold" name={seriesNames(serie)} /></div>))}+ {series.length > chrome.legendLimit && (+ <div className="text-muted-foreground">+ +{series.length - chrome.legendLimit} more+ </div>+ )}</div>)}</div>diff --git a/apps/start/src/components/report-chart/funnel/steps-chart.tsx b/apps/start/src/components/report-chart/funnel/steps-chart.tsxindex 514801c85..c30c58ac4 100644--- a/apps/start/src/components/report-chart/funnel/steps-chart.tsx+++ b/apps/start/src/components/report-chart/funnel/steps-chart.tsx@@ -1,5 +1,6 @@import { useMemo } from 'react';import { getPreviousMetric } from '../../../utils/previous-metric';+import { useChartChrome } from '../common/chart-size';import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';import { SerieIcon } from '../common/serie-icon';import { SerieName } from '../common/serie-name';@@ -21,7 +22,6 @@ import { getChartColor } from '@/utils/theme';type FunnelData = RouterOutputs['chart']['funnel'];type Funnel = FunnelData['current'][number];-const BREAKDOWN_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };const BREAKDOWN_BAR_GAP = 0.25;export function Chart({@@ -124,6 +124,7 @@ function BreakdownBars({visibleBreakdowns: Funnel[];}) {const number = useNumber();+ const chrome = useChartChrome();const breakdowns = useMemo(() =>visibleBreakdowns.map((breakdown, visibleIndex) => {@@ -177,12 +178,12 @@ function BreakdownBars({barGap={BREAKDOWN_BAR_GAP}className="h-full"data={rows}- margin={BREAKDOWN_MARGIN}+ margin={chrome.margin}xDataKey="name"><Grid horizontal />- <YAxis formatValue={(value) => `${value}%`} />- <BarXAxis />+ {chrome.showYAxis && <YAxis formatValue={(value) => `${value}%`} />}+ {chrome.showXAxis && <BarXAxis />}{breakdowns.map((breakdown) => (<Baranimate={false}@@ -198,9 +199,9 @@ function BreakdownBars({/></BarChart></div>- {breakdowns.length > 1 && (+ {breakdowns.length > 1 && chrome.legendLimit > 0 && (<div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">- {breakdowns.map((breakdown) => (+ {breakdowns.slice(0, chrome.legendLimit).map((breakdown) => (<divclassName="flex items-center gap-1"key={breakdown.key}@@ -210,6 +211,11 @@ function BreakdownBars({<SerieName className="font-semibold" name={breakdown.names} /></div>))}+ {breakdowns.length > chrome.legendLimit && (+ <div className="text-muted-foreground">+ +{breakdowns.length - chrome.legendLimit} more+ </div>+ )}</div>)}</div>diff --git a/apps/start/src/components/report-chart/histogram/chart.tsx b/apps/start/src/components/report-chart/histogram/chart.tsxindex 62a263449..4b00fc3f1 100644--- a/apps/start/src/components/report-chart/histogram/chart.tsx+++ b/apps/start/src/components/report-chart/histogram/chart.tsx@@ -52,8 +52,8 @@ export function Chart({ data, series }: Props) {xDataKey="date"><Grid horizontal />- {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}- {!chart.hideXAxis && <XAxis />}+ {chart.showYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {chart.showXAxis && <XAxis numTicks={chart.xAxisTicks} />}{showPreviousBars &&series.map((serie) => (<SeriesBardiff --git a/apps/start/src/components/report-chart/index.tsx b/apps/start/src/components/report-chart/index.tsxindex 92e7fbfa2..ae6a4ddb4 100644--- a/apps/start/src/components/report-chart/index.tsx+++ b/apps/start/src/components/report-chart/index.tsx@@ -1,8 +1,9 @@import { mergeDeepRight } from 'ramda';-import { type RefObject, useEffect, useRef } from 'react';+import { type RefObject, useCallback, useEffect, useRef } from 'react';import { useInViewport } from 'react-in-viewport';import { ReportAreaChart } from './area';import { ReportBarChart } from './bar';+import { getSizeTier } from './common/chart-size';import type { ReportChartProps } from './context';import { ReportChartProvider } from './context';import { ReportConversionChart } from './conversion';@@ -14,6 +15,7 @@ import { ReportMetricChart } from './metric';import { ReportPieChart } from './pie';import { ReportRetentionChart } from './retention';import { ReportSankeyChart } from './sankey';+import { useElementSize } from '@/hooks/use-element-size';import { cn } from '@/utils/cn';export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {@@ -35,6 +37,17 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {const loaded = lazy ? once.current || inViewport : true;+ const [measureRef, size] = useElementSize();+ const setRootRef = useCallback(+ (element: HTMLDivElement | null) => {+ ref.current = element;+ return measureRef(element);+ },+ [measureRef]+ );+ // Before the first measurement the chart renders with full chrome.+ const sizeTier = size.width > 0 ? getSizeTier(size.width) : 'wide';+const renderReportChart = () => {switch (props.report.chartType) {case 'linear':@@ -67,7 +80,7 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {return (<divclassName={cn('w-full', props.layout === 'fill' && 'h-full min-h-0')}- ref={ref}+ ref={setRootRef}><ReportChartProvider{...mergeDeepRight(@@ -75,6 +88,7 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {props)}isLazyLoading={!loaded}+ sizeTier={sizeTier}>{renderReportChart()}</ReportChartProvider>diff --git a/apps/start/src/components/report-chart/line/chart.tsx b/apps/start/src/components/report-chart/line/chart.tsxindex 3d8562378..fe2d1d77c 100644--- a/apps/start/src/components/report-chart/line/chart.tsx+++ b/apps/start/src/components/report-chart/line/chart.tsx@@ -37,8 +37,8 @@ export function Chart({ data, series }: Props) {xDataKey="date"><Grid horizontal />- {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}- {!chart.hideXAxis && <XAxis />}+ {chart.showYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {chart.showXAxis && <XAxis numTicks={chart.xAxisTicks} />}{chart.previous &&series.map((serie) => (<Linediff --git a/apps/start/src/components/report-chart/pie/chart.tsx b/apps/start/src/components/report-chart/pie/chart.tsxindex 15fc2868e..91e072433 100644--- a/apps/start/src/components/report-chart/pie/chart.tsx+++ b/apps/start/src/components/report-chart/pie/chart.tsx@@ -1,5 +1,6 @@import { round } from '@openpanel/shared';import { useMemo, useState } from 'react';+import { useChartChrome } from '../common/chart-size';import { getLabelNames } from '../common/label-names';import { SerieIcon } from '../common/serie-icon';import { SerieName } from '../common/serie-name';@@ -25,6 +26,8 @@ interface Props {export function Chart({ series }: Props) {const { isEditMode } = useReportChartContext();+ const { legendLimit } = useChartChrome();+ const showLegend = legendLimit > 0;const number = useNumber();const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);const [frameRef, frame] = useElementSize();@@ -43,7 +46,10 @@ export function Chart({ series }: Props) {}));}, [series]);- const isSideLegend = frame.width > frame.height * SIDE_LEGEND_RATIO;+ const legendSlices = slices.slice(0, legendLimit);+ const hiddenSliceCount = slices.length - legendSlices.length;+ const isSideLegend =+ showLegend && frame.width > frame.height * SIDE_LEGEND_RATIO;const pieSize = Math.min(pieBox.width, pieBox.height);const innerRadius = Math.max(0,@@ -98,45 +104,52 @@ export function Chart({ series }: Props) {</div>)}</div>- <ul- className={cn(- 'col min-h-0 shrink-0 gap-0.5 overflow-y-auto text-sm',- isSideLegend ? 'w-1/2 max-w-72' : 'max-h-[40%] w-full'- )}- >- {slices.map((slice, index) => (- <li key={slice.id}>- <button- className={cn(- 'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left transition-opacity',- hoveredIndex !== null &&- hoveredIndex !== index &&- 'opacity-50'- )}- onBlur={() => setHoveredIndex(null)}- onFocus={() => setHoveredIndex(index)}- onMouseEnter={() => setHoveredIndex(index)}- onMouseLeave={() => setHoveredIndex(null)}- type="button"- >- <span- className="size-2.5 shrink-0 rounded-full"- style={{ background: slice.color }}- />- <SerieIcon name={slice.names} />- <div className="min-w-0 flex-1 overflow-hidden whitespace-nowrap">- <SerieName name={slice.names} />- </div>- <span className="font-mono font-semibold">- {number.short(slice.value)}- </span>- <span className="w-12 text-right font-mono text-muted-foreground">- {slice.share}%- </span>- </button>- </li>- ))}- </ul>+ {showLegend && (+ <ul+ className={cn(+ 'col min-h-0 shrink-0 gap-0.5 overflow-y-auto text-sm',+ isSideLegend ? 'w-1/2 max-w-72' : 'max-h-[40%] w-full'+ )}+ >+ {legendSlices.map((slice, index) => (+ <li key={slice.id}>+ <button+ className={cn(+ 'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left transition-opacity',+ hoveredIndex !== null &&+ hoveredIndex !== index &&+ 'opacity-50'+ )}+ onBlur={() => setHoveredIndex(null)}+ onFocus={() => setHoveredIndex(index)}+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ type="button"+ >+ <span+ className="size-2.5 shrink-0 rounded-full"+ style={{ background: slice.color }}+ />+ <SerieIcon name={slice.names} />+ <div className="min-w-0 flex-1 overflow-hidden whitespace-nowrap">+ <SerieName name={slice.names} />+ </div>+ <span className="font-mono font-semibold">+ {number.short(slice.value)}+ </span>+ <span className="w-12 text-right font-mono text-muted-foreground">+ {slice.share}%+ </span>+ </button>+ </li>+ ))}+ {hiddenSliceCount > 0 && (+ <li className="px-1.5 py-1 text-muted-foreground text-xs">+ +{hiddenSliceCount} more+ </li>+ )}+ </ul>+ )}</div></div>);diff --git a/apps/start/src/components/report-chart/retention/chart.tsx b/apps/start/src/components/report-chart/retention/chart.tsxindex 1040ed94a..9c38399d6 100644--- a/apps/start/src/components/report-chart/retention/chart.tsx+++ b/apps/start/src/components/report-chart/retention/chart.tsx@@ -1,6 +1,7 @@import { average, round } from '@openpanel/shared';import { curveMonotoneX } from 'd3-shape';import { useCallback, useMemo } from 'react';+import { useChartChrome } from '../common/chart-size';import { useReportChartContext } from '../context';import { Area, AreaChart } from '@/components/charts/area-chart';import { Grid } from '@/components/charts/grid';@@ -16,8 +17,6 @@ import { getChartColor } from '@/utils/theme';// bklit's x axis is a time axis; periods since the cohort start are laid out// as consecutive days from the epoch and read back by the axis formatter.const PERIOD_MS = 86_400_000;-const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };-const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };const RETENTION_COLOR = getChartColor(0);const AVERAGE_COLOR = getChartColor(1);@@ -41,8 +40,8 @@ export function Chart({ data }: Props) {const {report: { interval },isEditMode,- options: { hideXAxis, hideYAxis },} = useReportChartContext();+ const chrome = useChartChrome();const number = useNumber();const averageRow = data[0];const averageRate = average(averageRow?.percentages ?? [], true) * 100;@@ -75,13 +74,13 @@ export function Chart({ data }: Props) {className="h-full"data={points}formatDateLabel={formatPeriod}- margin={hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN}+ margin={chrome.margin}style={{ touchAction: 'pan-y' }}xDataKey="date"><Grid horizontal />- {!hideYAxis && <YAxis formatValue={(value) => `${value}%`} />}- {!hideXAxis && <XAxis />}+ {chrome.showYAxis && <YAxis formatValue={(value) => `${value}%`} />}+ {chrome.showXAxis && <XAxis numTicks={chrome.xAxisTicks} />}<Areaanimate={false}curve={curveMonotoneX}diff --git a/apps/start/src/components/report-table/report-data-table.tsx b/apps/start/src/components/report-table/report-data-table.tsxindex 25bc9e6ad..5b116f0ad 100644--- a/apps/start/src/components/report-table/report-data-table.tsx+++ b/apps/start/src/components/report-table/report-data-table.tsx@@ -32,6 +32,8 @@ import { cn } from '@/utils/cn';export const ROW_HEIGHT = 40;const HEADER_HEIGHT = 32;const MAX_TABLE_HEIGHT = 600;+// A dashboard tile lifts the cap and lets the table fill the tile instead.+const MAX_TABLE_HEIGHT_VAR = `var(--report-table-max-height, ${MAX_TABLE_HEIGHT}px)`;// Below this many rows the DOM is small enough to render whole.const VIRTUALIZE_FROM = 40;const VIRTUAL_OVERSCAN = 8;@@ -208,7 +210,7 @@ export function ReportDataTable<Row>({};return (- <div className={cn('col', className)} data-report-table>+ <div className={cn('col min-h-0 flex-1', className)} data-report-table><ToolbaronDownload={csvFilename@@ -229,9 +231,9 @@ export function ReportDataTable<Row>({search={search}/><div- className="scrollbar-thin relative overflow-auto"+ className="scrollbar-thin relative min-h-0 flex-1 overflow-auto"ref={scrollRef}- style={{ maxHeight: MAX_TABLE_HEIGHT }}+ style={{ maxHeight: MAX_TABLE_HEIGHT_VAR }}><divclassName="sticky top-0 z-20 flex min-w-full border-border border-b bg-card"@@ -361,9 +363,9 @@ function Toolbar({return null;}return (- <div className="flex items-center gap-2 border-border border-b p-2">+ <div className="flex flex-wrap items-center gap-2 border-border border-b p-2">{onSearch && (- <div className="relative flex-1 md:max-w-xs">+ <div className="relative min-w-32 flex-1 md:max-w-xs"><SearchIcon className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" /><InputclassName="pl-8"diff --git a/apps/start/src/components/report/report-item.tsx b/apps/start/src/components/report/report-item.tsxindex 29de23ea4..51d0182a1 100644--- a/apps/start/src/components/report/report-item.tsx+++ b/apps/start/src/components/report/report-item.tsx@@ -1,11 +1,17 @@-import { timeWindows } from '@openpanel/core/modules/report/report.constants';+import {+ type IReportDisplay,+ timeWindows,+} from '@openpanel/core/modules/report/report.constants';import { useRouter } from '@tanstack/react-router';import {+ ChartLineIcon,CopyIcon,LayoutPanelTopIcon,MoreHorizontal,+ TableIcon,Trash,} from 'lucide-react';+import { useState } from 'react';import { ReportChart } from '@/components/report-chart';import {DropdownMenu,@@ -16,6 +22,40 @@ import {} from '@/components/ui/dropdown-menu';import { cn } from '@/utils/cn';+type TileView = IReportDisplay['view'];++/** Shown on hover (always on touch): switches the tile between chart and table. */+function TileViewToggle({+ chartType,+ view,+ onChange,+}: {+ chartType: string;+ view: TileView;+ onChange: (view: TileView) => void;+}) {+ // A metric tile is already its numbers; it has no table.+ if (chartType === 'metric') {+ return null;+ }+ const isTable = view === 'table';+ const label = isTable ? 'Show chart' : 'Show table';+ return (+ <button+ aria-label={label}+ className="flex h-8 w-8 items-center justify-center rounded opacity-0 transition-opacity hover:border focus-visible:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100"+ onClick={(event) => {+ event.stopPropagation();+ onChange(isTable ? 'chart' : 'table');+ }}+ title={label}+ type="button"+ >+ {isTable ? <ChartLineIcon size={16} /> : <TableIcon size={16} />}+ </button>+ );+}+export function ReportItemSkeleton() {return (<div className="card flex h-full animate-pulse flex-col">@@ -45,6 +85,7 @@ export function ReportItem({onDelete,onDuplicate,onMove,+ onViewChange,}: {report: any;organizationId: string;@@ -56,13 +97,15 @@ export function ReportItem({onDelete: (reportId: string) => void;onDuplicate: (reportId: string) => void;onMove?: (reportId: string) => void;+ onViewChange: (reportId: string, view: TileView) => void;}) {const router = useRouter();const chartRange = report.range;+ const view: TileView = report.display?.view ?? 'chart';return (- <div className="card flex h-full flex-col">- <div className="flex items-center justify-between border-border border-b p-4 leading-none hover:bg-muted/50 [&_svg]:hover:opacity-100">+ <div className="card group flex h-full flex-col">+ <div className="tile-header flex items-center justify-between border-border border-b p-4 leading-none hover:bg-muted/50 [&_svg]:hover:opacity-100"><divclassName="-m-4 flex-1 cursor-pointer p-4"onClick={(event) => {@@ -124,22 +167,11 @@ export function ReportItem({)}</div><div className="flex items-center gap-2">- <div className="drag-handle cursor-move rounded p-2 hover:bg-muted">- <svg- className="opacity-30 hover:opacity-100"- fill="currentColor"- height="16"- viewBox="0 0 16 16"- width="16"- >- <circle cx="4" cy="4" r="1.5" />- <circle cx="4" cy="8" r="1.5" />- <circle cx="4" cy="12" r="1.5" />- <circle cx="12" cy="4" r="1.5" />- <circle cx="12" cy="8" r="1.5" />- <circle cx="12" cy="12" r="1.5" />- </svg>- </div>+ <TileViewToggle+ chartType={report.chartType}+ onChange={(next) => onViewChange(report.id, next)}+ view={view}+ /><DropdownMenu><DropdownMenuTrigger className="flex h-8 w-8 items-center justify-center rounded hover:border"><MoreHorizontal size={16} />@@ -186,9 +218,11 @@ export function ReportItem({'min-h-0 flex-1 overflow-hidden p-4',report.chartType === 'metric' && 'p-0')}+ data-tile-body><ReportChartlayout="fill"+ options={{ view }}report={{...report,range: range ?? report.range,@@ -218,9 +252,11 @@ export function ReportItemReadOnly({interval: any;}) {const chartRange = report.range;+ // A share page viewer can switch the view but never saves it.+ const [view, setView] = useState<TileView>(report.display?.view ?? 'chart');return (- <div className="card flex h-full flex-col">+ <div className="card group flex h-full flex-col"><div className="flex items-center justify-between border-border border-b p-4 leading-none"><div className="flex-1"><div className="font-medium">{report.name}</div>@@ -249,6 +285,11 @@ export function ReportItemReadOnly({</div>)}</div>+ <TileViewToggle+ chartType={report.chartType}+ onChange={setView}+ view={view}+ /></div><divclassName={cn(@@ -258,6 +299,7 @@ export function ReportItemReadOnly({><ReportChartlayout="fill"+ options={{ view }}report={{...report,range: range ?? report.range,diff --git a/apps/start/src/hooks/use-tile-views.ts b/apps/start/src/hooks/use-tile-views.tsnew file mode 100644index 000000000..c416caaa4--- /dev/null+++ b/apps/start/src/hooks/use-tile-views.ts@@ -0,0 +1,89 @@+import type { IReportDisplay } from '@openpanel/core/modules/report/report.constants';+import { useMutation, useQueryClient } from '@tanstack/react-query';+import { TRPCClientError } from '@trpc/client';+import { useCallback, useRef, useState } from 'react';+import { handleErrorToastOptions, useTRPC } from '@/integrations/trpc/react';++type TileView = IReportDisplay['view'];++/**+ * The chart/table view of a dashboard's tiles. A switch shows at once and is+ * saved behind it, one save per report at a time, so the last choice is the+ * one stored. A member who may not save keeps their choices for the visit.+ */+export function useTileViews({+ dashboardId,+ projectId,+}: {+ dashboardId: string;+ projectId: string;+}) {+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const [unsavedViews, setUnsavedViews] = useState<Record<string, TileView>>(+ {}+ );+ // A report with a save in flight maps to the view to save after it, if any.+ const queuedViews = useRef(new Map<string, TileView | undefined>());+ const canSave = useRef(true);+ const { mutateAsync: saveDisplay } = useMutation(+ trpc.report.updateDisplay.mutationOptions()+ );++ const changeView = useCallback(+ (reportId: string, view: TileView) => {+ const reportsQueryKey = trpc.report.list.queryKey({+ dashboardId,+ projectId,+ });+ const forgetUnsaved = () =>+ setUnsavedViews(({ [reportId]: _saved, ...rest }) => rest);++ async function saveView(next: TileView): Promise<void> {+ try {+ await saveDisplay({ reportId, display: { view: next } });+ } catch (error) {+ queuedViews.current.delete(reportId);+ if (!(error instanceof TRPCClientError)) {+ throw error;+ }+ if (error.data?.code === 'FORBIDDEN') {+ canSave.current = false;+ return;+ }+ handleErrorToastOptions({})(error);+ forgetUnsaved();+ return;+ }+ queryClient.setQueryData(reportsQueryKey, (current) =>+ current?.map((report) =>+ report.id === reportId+ ? { ...report, display: { view: next } }+ : report+ )+ );+ const queued = queuedViews.current.get(reportId);+ if (queued) {+ queuedViews.current.set(reportId, undefined);+ return saveView(queued);+ }+ queuedViews.current.delete(reportId);+ forgetUnsaved();+ }++ setUnsavedViews((current) => ({ ...current, [reportId]: view }));+ if (!canSave.current) {+ return;+ }+ if (queuedViews.current.has(reportId)) {+ queuedViews.current.set(reportId, view);+ return;+ }+ queuedViews.current.set(reportId, undefined);+ saveView(view);+ },+ [trpc, queryClient, saveDisplay, dashboardId, projectId]+ );++ return { unsavedViews, changeView };+}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsxindex 783acaffe..8cc00c594 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx@@ -39,6 +39,7 @@ import {} from '@/components/ui/dropdown-menu';import { Input } from '@/components/ui/input';import { useDashboardPageContext } from '@/hooks/use-page-context-helpers';+import { useTileViews } from '@/hooks/use-tile-views';import { handleErrorToastOptions, useTRPC } from '@/integrations/trpc/react';import { pushModal, showConfirm } from '@/modals';import { createProjectTitle } from '@/utils/title';@@ -178,6 +179,7 @@ function Component() {}));+ const { unsavedViews, changeView } = useTileViews({ dashboardId, projectId });const resetLayout = useMutation(trpc.report.resetLayout.mutationOptions({onError: handleErrorToastOptions({}),@@ -241,24 +243,33 @@ function Component() {);const tiles = useMemo(() =>- filteredReports.map((report) => (- <div key={report.id}>- <ReportItem- endDate={endDate}- interval={interval}- onDelete={(reportId) => deleteReport({ reportId })}- onDuplicate={(reportId) => duplicateReport({ reportId })}- onMove={moveReport}- organizationId={organizationId}- projectId={projectId}- range={range}- report={report}- startDate={startDate}- />- </div>- )),+ filteredReports.map((report) => {+ const unsavedView = unsavedViews[report.id];+ return (+ <div key={report.id}>+ <ReportItem+ endDate={endDate}+ interval={interval}+ onDelete={(reportId) => deleteReport({ reportId })}+ onDuplicate={(reportId) => duplicateReport({ reportId })}+ onMove={moveReport}+ onViewChange={changeView}+ organizationId={organizationId}+ projectId={projectId}+ range={range}+ report={+ unsavedView+ ? { ...report, display: { view: unsavedView } }+ : report+ }+ startDate={startDate}+ />+ </div>+ );+ }),[filteredReports,+ unsavedViews,endDate,interval,range,@@ -268,6 +279,7 @@ function Component() {deleteReport,duplicateReport,moveReport,+ changeView,]);diff --git a/apps/start/src/styles.css b/apps/start/src/styles.cssindex 7cc6ebd2a..5a5979c03 100644--- a/apps/start/src/styles.css+++ b/apps/start/src/styles.css@@ -560,13 +560,94 @@ button {/* While a tile moves, nothing under the pointer reacts: no chart tooltips,no hover states, no text selection. The gesture itself runs on document- listeners, so the tiles need no pointer events until it ends. */-.react-grid-layout:has(.react-draggable-dragging, .resizing) .react-grid-item- > * {+ listeners, so the tiles need no pointer events until it ends.+ `data-gesture` is set once a drag passes its threshold; the library marks+ the tile as dragging on mouse-down, which would swallow a click on the title. */+[data-gesture] .react-grid-item > * {pointer-events: none;user-select: none;}-html:has(.react-grid-item.react-draggable-dragging),-.react-grid-item.react-draggable-dragging {+html:has([data-gesture] .react-grid-item.react-draggable-dragging),+[data-gesture] .react-grid-item.react-draggable-dragging {cursor: grabbing;}++/* The dragged tile lifts off the grid. */+[data-gesture] .react-grid-item.react-draggable-dragging > * {+ transform: scale(1.02);+ box-shadow: 0 16px 40px -12px rgb(0 0 0 / 0.35);+ transition: transform 120ms cubic-bezier(0.2, 0, 0, 1);+}+@media (prefers-reduced-motion: reduce) {+ [data-gesture] .react-grid-item.react-draggable-dragging > * {+ transform: none;+ }+}++/* Edges resize along one axis through invisible 8px strips; the corners keep+ the library's grip. */+.react-grid-item > .react-resizable-handle.react-resizable-handle-n,+.react-grid-item > .react-resizable-handle.react-resizable-handle-s,+.react-grid-item > .react-resizable-handle.react-resizable-handle-e,+.react-grid-item > .react-resizable-handle.react-resizable-handle-w {+ margin: 0;+ transform: none;+ background: none;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-n::after,+.react-grid-item > .react-resizable-handle.react-resizable-handle-s::after,+.react-grid-item > .react-resizable-handle.react-resizable-handle-e::after,+.react-grid-item > .react-resizable-handle.react-resizable-handle-w::after {+ display: none;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-n,+.react-grid-item > .react-resizable-handle.react-resizable-handle-s {+ left: 20px;+ right: 20px;+ width: auto;+ height: 8px;+ cursor: ns-resize;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-n {+ top: -4px;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-s {+ bottom: -4px;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-e,+.react-grid-item > .react-resizable-handle.react-resizable-handle-w {+ top: 20px;+ bottom: 20px;+ width: 8px;+ height: auto;+ cursor: ew-resize;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-e {+ right: -4px;+}+.react-grid-item > .react-resizable-handle.react-resizable-handle-w {+ left: -4px;+}++/* While resizing, the chart keeps its starting size (dimmed and clipped) and+ the tile shows the size it will snap to. */+.react-grid-item.resizing {+ overflow: hidden;+}+.react-grid-item.resizing [data-tile-body] {+ opacity: 0.5;+}+.react-grid-item.resizing[data-tile-size]::after {+ content: attr(data-tile-size);+ position: absolute;+ right: 12px;+ bottom: 12px;+ padding: 2px 8px;+ border-radius: 9999px;+ background: var(--foreground);+ color: var(--background);+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ font-weight: 600;+ pointer-events: none;+}diff --git a/bklit-issues.md b/bklit-issues.mdindex 664f1769b..4c68fb816 100644--- a/bklit-issues.md+++ b/bklit-issues.md@@ -25,6 +25,9 @@ Last synced from the registry on 2026-10-15. Fetch every item (and its `registry| 22 | no stacked areas | **open**: re-apply `baselineKey` in `area.tsx` || 23 | sankey links have no gap | **open**: re-apply `linkGap` in `sankey/sankey-link.tsx` || 24 | no fixed y domain (percent axes reach 120%) | **open**: re-apply `yDomain` in `time-series-chart-shell.tsx` / `line-chart.tsx` |+| 25 | no per-axis domain, no reversed axis, `SeriesBar` ignores `yAxisId` | **open**: re-apply `yDomains` / `yReversed` in `time-series-chart-shell.tsx`, `composed-chart.tsx`, `line-chart.tsx`, `y-axis-scales.ts`, `y-domain-utils.ts`, and `yAxisId` in `series-bar.tsx` |+| 26 | dashed tail overlaps the solid stroke on steep curves | **open**: re-apply the clip-based `dash-tail-stroke.tsx` |+| 27 | funnel stage and bar-axis labels overlap their neighbours | **open**: re-apply the truncation in `funnel-chart.tsx` and `bar-x-axis.tsx` |`chart-loading-label.tsx` imports `../components/shimmering-text`, which does not resolve with the registry's own targets; it is patched to `../shimmering-text`.@@ -655,3 +658,57 @@ A chart of percentages tops out at 120%, which reads as if conversion could exce`TimeSeriesChartInner` and `LineChart` take `yDomain?: [number, number]`, used as is when set. The conversion report passes `[0, 100]`.`shadcn add` reverts.++---++## 25. One y domain for every axis, no reversed axis++**Symptom**++A small chart with two series of different size (clicks and impressions, sessions and revenue) flattens the smaller one, and search position, where 1 is best, draws upside down.++**Cause**++`ComposedChart` and `LineChart` take one fixed `yDomain` at most, `SeriesBar` always uses the primary scale, and every scale maps the smallest value to the bottom.++**Fix (applied locally)**++`TimeSeriesChartInner` and `ComposedChart` take `yDomains?: Record<yAxisId, [number, number]>`; `LineChart` takes `yReversed`, passed through to `buildYScalesFromDomains(..., reversed)`. `SeriesBar` takes `yAxisId` and reads `useYScale(yAxisId)`, and `ComposedChart` registers the axis id of every `Line`, `Area` and `SeriesBar`. The project card and GSC position chart use these.++`shadcn add` reverts.++---++## 26. The dashed tail overlaps the solid stroke on steep curves++**Symptom**++When the last days of a line rise steeply, the solid line runs up the rise on top of the dashed tail.++**Cause**++`DashTailStroke` split the path by length, with the length at the dash start estimated as `dashFromIndex / (n - 1) * totalLength`. That assumes every day's stretch of curve is equally long; a flat line followed by a spike breaks it.++**Fix (applied locally)**++Both halves draw the full path, each clipped at the dash start x: the solid head to its left, the dashed tail to its right. `findPathLengthAtX` and the length estimate are gone.++`shadcn add` reverts.++---++## 27. Funnel stage and bar-axis labels overlap their neighbours++**Symptom**++In a narrow tile, long step names (`signup_completed`, `first_event_received`) under a funnel or a grouped bar chart run into each other.++**Cause**++The labels are `whitespace-nowrap` with no width limit.++**Fix (applied locally)**++Funnel stage labels truncate to their segment (`max-w-full truncate` in a full-width cell); `BarXAxis` labels truncate to the bands they cover. Both carry the full name as `title`.++`shadcn add` reverts.diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.tsindex 21b12cdbc..042344ba3 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts@@ -8,6 +8,7 @@ import {mock,} from 'bun:test';import { z } from 'zod';+import { GRID_COLUMNS } from '../../../report/report.constants';const mockDb = {$transaction: mock(),@@ -599,8 +600,19 @@ describe('dashboard management behavior', () => {minH: 2,maxW: 8,maxH: 8,+ gridColumns: GRID_COLUMNS,+ },+ update: {+ x: 1,+ y: 2,+ w: 4,+ h: 3,+ minW: 2,+ minH: 2,+ maxW: 8,+ maxH: 8,+ gridColumns: GRID_COLUMNS,},- update: { x: 1, y: 2, w: 4, h: 3, minW: 2, minH: 2, maxW: 8, maxH: 8 },});});});diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.tsindex 489c3aad4..c91291b04 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts@@ -4,7 +4,11 @@ import type { CoreConfig } from '../../../../config';import type { ServiceDeps } from '../../../../services';import { getId } from '../../../../slug-id';import { getProjectById } from '../../../project/project.service';-import { zReport } from '../../../report/report.constants';+import {+ GRID_COLUMNS,+ GRID_ROW_HEIGHT,+ zReport,+} from '../../../report/report.constants';import { requireDashboard } from './dashboard-access';import { dashboardBaseUrl } from './dashboard-links';import {@@ -50,15 +54,19 @@ const reportSchema = zReport}});+const GRID_DESCRIPTION = `Grid units: ${GRID_COLUMNS} columns across the dashboard, rows ${GRID_ROW_HEIGHT}px tall. A half-width chart is w ${GRID_COLUMNS / 2}, h 8.`;+const zColumn = z.number().int().nonnegative().max(GRID_COLUMNS);+const zColumnSpan = z.number().int().positive().max(GRID_COLUMNS);+const layoutSchema = z.object({- x: z.number().int().nonnegative(),+ x: zColumn,y: z.number().int().nonnegative(),- w: z.number().int().positive(),+ w: zColumnSpan,h: z.number().int().positive(),- minW: z.number().int().positive().optional(),+ minW: zColumnSpan.optional(),minH: z.number().int().positive().optional(),- maxW: z.number().int().positive().optional(),+ maxW: zColumnSpan.optional(),maxH: z.number().int().positive().optional(),}).superRefine((layout, ctx) => {@@ -617,7 +625,9 @@ function registerDashboardWriteTools(.string().uuid().describe('The report ID whose layout should change'),- layout: layoutSchema.describe('The report grid layout'),+ layout: layoutSchema.describe(+ `The report grid layout. ${GRID_DESCRIPTION}`+ ),},async ({ projectId: inputProjectId, reportId, layout }) =>withErrorHandling(deps, async () => {@@ -626,8 +636,8 @@ function registerDashboardWriteTools(await requireReport(db, projectId, reportId);return db.reportLayout.upsert({where: { reportId },- create: { reportId, ...layout },- update: layout,+ create: { reportId, ...layout, gridColumns: GRID_COLUMNS },+ update: { ...layout, gridColumns: GRID_COLUMNS },});}));diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.tsindex 2f9b461d6..ae086f508 100644--- a/packages/core/src/modules/report/report.constants.ts+++ b/packages/core/src/modules/report/report.constants.ts@@ -7,6 +7,19 @@import { z } from 'zod';export const DEFAULT_ASPECT_RATIO = 0.5625;++// Dashboard grid units. With the 16px gap, 2 rows of 42px are exactly as tall+// as one row of the former 100px grid, and 24 columns line up with the former+// 12, which is what lets the layout migration keep every tile in place.+export const GRID_COLUMNS = 24;+export const GRID_ROW_HEIGHT = 42;+export const GRID_GAP = 16;+export const GRID_MAX_ROWS = 2000;++/** How a dashboard tile shows its report; every chart type but metric has a table. */+export const zReportDisplay = z.object({ view: z.enum(['chart', 'table']) });+export type IReportDisplay = z.infer<typeof zReportDisplay>;+export const DEFAULT_REPORT_DISPLAY: IReportDisplay = { view: 'chart' };export const NOT_SET_VALUE = '(not set)';export const timeWindows = {diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.tsindex fd5051d5d..6750dfd62 100644--- a/packages/core/src/modules/report/report.rpc.ts+++ b/packages/core/src/modules/report/report.rpc.ts@@ -10,15 +10,18 @@ import {type TrpcContext,} from '../../rpc/base';import { TRPCNotFoundError } from '../../rpc/errors';-import { zReport } from './report.constants';+import {+ GRID_COLUMNS,+ GRID_MAX_ROWS,+ zReport,+ zReportDisplay,+} from './report.constants';// Grid coordinates, so whole numbers inside the grid. A zero width or a// height in the tens of thousands is a client bug, not a layout.-const GRID_MAX_COLUMNS = 12;-const GRID_MAX_ROWS = 1000;-const zGridSpan = z.number().int().min(1).max(GRID_MAX_COLUMNS);+const zGridSpan = z.number().int().min(1).max(GRID_COLUMNS);const zReportLayout = z.object({- x: z.number().int().min(0).max(GRID_MAX_COLUMNS),+ x: z.number().int().min(0).max(GRID_COLUMNS),y: z.number().int().min(0).max(GRID_MAX_ROWS),w: zGridSpan,h: z.number().int().min(1).max(GRID_MAX_ROWS),@@ -107,6 +110,18 @@ export const reportRouter = createTRPCRouter({return ctx.services.report.updateReport({ reportId, report });}),+ updateDisplay: protectedProcedure+ .input(z.object({ reportId: z.string(), display: zReportDisplay }))+ .mutation(async ({ input: { reportId, display }, ctx }) => {+ const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId: dbReport.projectId,+ level: 'write',+ });+ return ctx.services.report.updateReportDisplay({ reportId, display });+ }),+move: protectedProcedure.input(z.object({diff --git a/packages/core/src/modules/report/report.service.test.ts b/packages/core/src/modules/report/report.service.test.tsindex 7c223311a..657d1fb8c 100644--- a/packages/core/src/modules/report/report.service.test.ts+++ b/packages/core/src/modules/report/report.service.test.ts@@ -1,6 +1,10 @@import { describe, expect, it, mock } from 'bun:test';import type { ServiceDeps } from '../../services';-import type { IChartEventFilter, IChartEventItem } from './report.constants';+import {+ GRID_COLUMNS,+ type IChartEventFilter,+ type IChartEventItem,+} from './report.constants';import { transformFilter, updateReportLayouts } from './report.service';import { mergeGlobalFilters } from './src/series';@@ -139,8 +143,8 @@ describe('updateReportLayouts', () => {expect(upsert).toHaveBeenCalledTimes(2);expect(upsert).toHaveBeenCalledWith({where: { reportId: 'r2' },- create: { reportId: 'r2', ...layout, x: 6 },- update: { ...layout, x: 6 },+ create: { reportId: 'r2', ...layout, x: 6, gridColumns: GRID_COLUMNS },+ update: { ...layout, x: 6, gridColumns: GRID_COLUMNS },});});diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex 533ae89e0..e31b35fbd 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -23,7 +23,14 @@ import type {IReport,IReportOptions,} from './report.constants';-import { alphabetIds, lineTypes } from './report.constants';+import {+ alphabetIds,+ DEFAULT_REPORT_DISPLAY,+ GRID_COLUMNS,+ type IReportDisplay,+ lineTypes,+ zReportDisplay,+} from './report.constants';import { getChartStartEndDate } from './src/chart-dates';import { mergeGlobalFilters, onlyReportEvents } from './src/series';@@ -77,8 +84,10 @@ export function transformReport(): IReport & {id: string;layout?: ReportLayout | null;+ display: IReportDisplay;} {const options = report.options as IReportOptions | null | undefined;+ const display = zReportDisplay.safeParse(report.display);return {id: report.id,@@ -101,6 +110,7 @@ export function transformReport(unit: report.unit ?? undefined,layout: report.layout ?? undefined,options: options ?? undefined,+ display: display.success ? display.data : DEFAULT_REPORT_DISPLAY,visibleSeries: report.visibleSeries ?? undefined,startDate: report.startDate ?? undefined,endDate: report.endDate ?? undefined,@@ -276,6 +286,17 @@ export async function createReport(});}+export async function updateReportDisplay(+ deps: ServiceDeps,+ input: { reportId: string; display: IReportDisplay }+) {+ return deps.db.report.update({+ where: { id: input.reportId },+ data: { display: input.display },+ select: { id: true, display: true },+ });+}+export async function updateReport(deps: ServiceDeps,input: {@@ -414,8 +435,8 @@ export async function updateReportLayouts(input.items.map(({ reportId, layout }) =>db.reportLayout.upsert({where: { reportId },- create: { reportId, ...layout },- update: layout,+ create: { reportId, ...layout, gridColumns: GRID_COLUMNS },+ update: { ...layout, gridColumns: GRID_COLUMNS },})));@@ -503,6 +524,10 @@ export function createReportService(input: Parameters<typeof updateReportLayouts>[1]): ReturnType<typeof updateReportLayouts> =>updateReportLayouts(deps, input),+ updateReportDisplay: (+ input: Parameters<typeof updateReportDisplay>[1]+ ): ReturnType<typeof updateReportDisplay> =>+ updateReportDisplay(deps, input),getReportLayouts: (input: Parameters<typeof getReportLayouts>[1]): ReturnType<typeof getReportLayouts> => getReportLayouts(deps, input),diff --git a/packages/db/prisma/migrations/20261017120000_report_layout_grid_columns/migration.sql b/packages/db/prisma/migrations/20261017120000_report_layout_grid_columns/migration.sqlnew file mode 100644index 000000000..f60deec47--- /dev/null+++ b/packages/db/prisma/migrations/20261017120000_report_layout_grid_columns/migration.sql@@ -0,0 +1,9 @@+-- The grid each layout was saved on; existing rows are on the 12-column grid+-- until code migration 25 doubles them.+ALTER TABLE "report_layouts" ADD COLUMN "gridColumns" INTEGER NOT NULL DEFAULT 12;++-- Defaults in the 24-column grid units.+ALTER TABLE "report_layouts" ALTER COLUMN "w" SET DEFAULT 8,+ALTER COLUMN "h" SET DEFAULT 6,+ALTER COLUMN "minW" SET DEFAULT 4,+ALTER COLUMN "minH" SET DEFAULT 4;diff --git a/packages/db/prisma/migrations/20261017130000_report_display/migration.sql b/packages/db/prisma/migrations/20261017130000_report_display/migration.sqlnew file mode 100644index 000000000..13122e530--- /dev/null+++ b/packages/db/prisma/migrations/20261017130000_report_display/migration.sql@@ -0,0 +1,2 @@+-- How a dashboard tile shows the report: { "view": "chart" | "table" }.+ALTER TABLE "reports" ADD COLUMN "display" JSONB;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex ab7777c7c..ee418c502 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -445,6 +445,8 @@ model Report {funnelWindow Float?/// [IReportOptions]options Json?+ /// How a dashboard tile shows the report: { view: 'chart' | 'table' }+ display Json?visibleSeries String[]startDate String?endDate String?@@ -465,15 +467,19 @@ model ReportLayout {reportId String @unique @db.Uuidreport Report @relation(fields: [reportId], references: [id], onDelete: Cascade)- // Grid position and size+ // The grid the layout was saved on: 12 (× 100px rows) before code migration+ // 25, 24 (× 42px rows) after. Writers set it, so a row without it is old.+ gridColumns Int @default(12)++ // Grid position and size, in 24-column × 42px-row unitsx Int @default(0)y Int @default(0)- w Int @default(4)- h Int @default(3)+ w Int @default(8)+ h Int @default(6)// Optional: store additional layout preferences- minW Int? @default(2)- minH Int? @default(2)+ minW Int? @default(4)+ minH Int? @default(4)maxW Int?maxH Int?diff --git a/packages/db/src/code-migrations/25-dashboard-grid-24-columns.ts b/packages/db/src/code-migrations/25-dashboard-grid-24-columns.tsnew file mode 100644index 000000000..044b248a1--- /dev/null+++ b/packages/db/src/code-migrations/25-dashboard-grid-24-columns.ts@@ -0,0 +1,53 @@+/**+ * Move dashboard layouts from the 12 × 100px grid to 24 columns × 42px rows.+ *+ * With the 16px gap, two 42px rows are exactly as tall as one 100px row, and+ * two of 24 columns exactly as wide as one of 12, so doubling every stored+ * position and size keeps each tile where it was, to the pixel.+ *+ * Only rows still marked `gridColumns = 12` are doubled, and they are marked+ * 24 in the same statement. A re-run changes nothing, and a tile saved on the+ * new grid before this ran is never doubled.+ *+ * pnpm with-env jiti ./src/code-migrations/25-dashboard-grid-24-columns.ts --dry+ */+import { db } from '../prisma-client';+import { getIsDry, printBoxMessage } from './helpers';++const OLD_GRID_COLUMNS = 12;+const NEW_GRID_COLUMNS = 24;++export async function up() {+ const oldLayouts = await db.reportLayout.count({+ where: { gridColumns: OLD_GRID_COLUMNS },+ });++ printBoxMessage('📋 Plan', [+ `Layouts on the ${OLD_GRID_COLUMNS}-column grid: ${oldLayouts}`,+ 'x, y, w, h and the min/max sizes are doubled for the 24-column grid',+ ]);++ if (oldLayouts === 0) {+ printBoxMessage('✅ Nothing to do', [+ `No layouts left on the ${OLD_GRID_COLUMNS}-column grid`,+ ]);+ return;+ }++ if (getIsDry()) {+ printBoxMessage('🕒 Dry run - nothing written', [+ `Would double ${oldLayouts} layout(s)`,+ ]);+ return;+ }++ const updated = await db.$executeRaw`+ UPDATE report_layouts+ SET x = x * 2, y = y * 2, w = w * 2, h = h * 2,+ "minW" = "minW" * 2, "minH" = "minH" * 2,+ "maxW" = "maxW" * 2, "maxH" = "maxH" * 2,+ "gridColumns" = ${NEW_GRID_COLUMNS}+ WHERE "gridColumns" = ${OLD_GRID_COLUMNS}`;++ printBoxMessage('✅ Done', [`Doubled ${updated} layout(s)`]);+}