feat(webui): Apple-widgets dashboard editor — gallery drag in/out

Reworks the desktop overview edit UX from per-card show/hide toggles to an
Apple-widgets model:

- The grid shows only the widgets that are on it; hidden ones live in a new
  right-side 部件库 ("store") panel that slides in during edit mode.
- Add: drag a gallery tile onto the canvas (HTML5 DnD) — dropped at the cursor
  cell, driven entirely through React state.
- Remove ("hide"): drag a card back onto the gallery (gridstack `removable`).
  Move/resize/remove all funnel through one onChange writer that derives removal
  from a block's absence in the grid snapshot — no separate handler, no state
  race.
- Card affordance: the big top "notch" bar is gone. Edit mode now shows two
  small square corner icons — a subtle semi-transparent drag hint (top-left, the
  whole card stays draggable) and the settings gear (top-right, configurable
  widgets only). The eye toggle is removed.

Mobile is unchanged (single-column reorder panel) — the gallery drag UX is
desktop-only by design.
This commit is contained in:
DrSmoothl committed 2026-06-16 14:57:39 +08:00
1 parent 2913a7a19b
commit fb567177b4
2 files changed
+174 -72

No files matched your search

@@ -1,7 +1,7 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { GridStack, type GridStackWidget } from 'gridstack';
import { Eye, EyeOff, GripVertical, Settings2 } from 'lucide-react';
import { GripVertical, Settings2 } from 'lucide-react';
import 'gridstack/dist/gridstack.css';
import { GRID_CELL_HEIGHT, GRID_MARGIN, minSizeOf } from '@/lib/dashboard-layout';
import { cn } from '@/lib/utils';
@@ -9,21 +9,31 @@ import type { UiLayoutItem } from '@/types';
export interface GridCoord { id: string; x: number; y: number; w: number; h: number }
/** dataTransfer key carrying the dragged gallery widget id (HTML5 add). */
export const WIDGET_DRAG_TYPE = 'text/plain';
interface DashboardGridProps {
/** Blocks to render — visible-only in view mode, ALL (incl. hidden) in edit
* mode so hidden widgets show as re-enableable ghosts. Each has x/y/w/h. */
/** Visible widgets only — each carries x/y/w/h. Hidden widgets live in the
* gallery, not the grid (Apple-widgets model: presence = shown). */
blocks: UiLayoutItem[];
editing: boolean;
/** Column count — 12 on desktop, 1 on narrow screens (auto single-column). */
cols: number;
/** Fired (debounced upstream) after a drag/resize settles. */
/**
* Fired (debounced upstream) after a drag/resize/remove settles, with the
* grid's current visible set. The consumer derives removal from absence: a
* block that was visible but is no longer in `coords` was dragged out.
*/
onChange: (coords: GridCoord[]) => void;
renderWidget: (block: UiLayoutItem) => ReactNode;
// ── edit overlay ──
labelFor: (id: string) => string;
configurableIds: ReadonlySet<string>;
onToggleVisible: (id: string) => void;
onConfigOpen: (id: string) => void;
/** CSS selector for the gallery drop-zone; dragging a card onto it removes
* the widget from the grid (gridstack `removable`). Edit mode only. */
removableSelector?: string;
/** Add a widget dropped from the gallery at the computed grid cell (HTML5
* drag-and-drop, driven entirely through React state). */
onAdd?: (id: string, x: number, y: number) => void;
}
/**
@@ -33,10 +43,15 @@ interface DashboardGridProps {
* when the visible widget SET or the edit mode changes — never on a pure
* coord change (gridstack already moved the item; the coord round-trips back
* through `onChange` → state and matches what gridstack has).
*
* Add/remove are NOT done through gridstack's external drag-in: instead the
* gallery drives React state (add = HTML5 drop here; remove = drag onto the
* gallery via `removable`). Both funnel through the single `onChange` writer,
* which reads the post-mutation grid snapshot — so there's no state race.
*/
export function DashboardGrid({
blocks, editing, cols, onChange, renderWidget,
labelFor, configurableIds, onToggleVisible, onConfigOpen,
configurableIds, onConfigOpen, removableSelector, onAdd,
}: DashboardGridProps) {
const elRef = useRef<HTMLDivElement | null>(null);
const gridRef = useRef<GridStack | null>(null);
@@ -63,11 +78,9 @@ export function DashboardGrid({
float: true, // free placement — items stay where dropped (no auto-compact)
disableDrag: !editing,
disableResize: !editing,
// Default handle (.grid-stack-item-content) = the whole card is a drag
// target in edit mode — forgiving + discoverable. The card body is
// pointer-events-none in edit mode so widget controls don't fire, and
// the eye/gear are <button>s which gridstack's skipMouseDown excludes
// from dragging. The overlay's grip + "拖动" label is the visual cue.
// Drag a card onto the gallery to remove it (edit mode only). The whole
// card is the drag target; the corner icons are just hints.
removable: editing && removableSelector ? removableSelector : false,
},
host,
);
@@ -85,7 +98,9 @@ export function DashboardGrid({
setContentEls(els);
// Attach AFTER the initial programmatic build so we don't persist the
// (unchanged) starting layout back to the server on mount.
// (unchanged) starting layout back to the server on mount. `change` covers
// move/resize; `removed` covers a drag-to-gallery — both re-read the
// snapshot, and the consumer treats any now-absent visible block as removed.
const persist = () => {
const saved = grid.save(false) as GridStackWidget[];
onChangeRef.current(
@@ -95,64 +110,72 @@ export function DashboardGrid({
);
};
grid.on('change', persist);
grid.on('removed', persist);
return () => {
grid.off('change');
grid.off('removed');
grid.destroy(false); // tear down gridstack, keep the React-owned container
// Remove the item DOM gridstack created (React never owned these).
host.replaceChildren();
gridRef.current = null;
setContentEls({});
};
}, [idKey, editing, cols]);
}, [idKey, editing, cols, removableSelector]);
// HTML5 drop from the gallery → add at the computed grid cell.
const onDrop = (e: React.DragEvent) => {
if (!editing || !onAdd) return;
e.preventDefault();
const id = e.dataTransfer.getData(WIDGET_DRAG_TYPE);
const host = elRef.current;
if (!id || !host) return;
const rect = host.getBoundingClientRect();
const colW = rect.width / cols || 1;
const x = Math.max(0, Math.min(cols - 1, Math.floor((e.clientX - rect.left) / colW)));
const y = Math.max(0, Math.floor((e.clientY - rect.top) / (GRID_CELL_HEIGHT + GRID_MARGIN)));
onAdd(id, x, y);
};
return (
<div ref={elRef} className="grid-stack -mx-1">
<div
ref={elRef}
className="grid-stack -mx-1"
onDragOver={(e) => { if (editing && onAdd) e.preventDefault(); }}
onDrop={onDrop}
>
{blocks.map((b) => {
const target = contentEls[b.id];
if (!target) return null;
const hidden = editing && !b.visible;
return createPortal(
<div className="relative h-full w-full">
{editing && (
<div className="pointer-events-auto absolute inset-x-0 top-0 z-20 flex items-center gap-1 rounded-t-xl border-b border-border/50 bg-background/70 px-1.5 py-1 backdrop-blur-sm">
<div
className="widget-drag-handle flex flex-1 cursor-grab items-center gap-1 rounded px-1 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-accent/50 active:cursor-grabbing"
title="拖动调整位置"
<>
{/* Subtle drag hint — a small square, not a bar. The whole card
is draggable; this just signals it (pointer-events-none so
the drag passes through to gridstack). */}
<span
aria-hidden
title="拖动卡片调整位置 · 拖回右侧部件库可移除"
className="pointer-events-none absolute left-1.5 top-1.5 z-20 inline-flex size-6 items-center justify-center rounded-md bg-background/70 text-muted-foreground opacity-50 backdrop-blur-sm"
>
<GripVertical className="size-3.5" /> 拖动
</div>
{configurableIds.has(b.id) && b.visible && (
<GripVertical className="size-3.5" />
</span>
{configurableIds.has(b.id) && (
<button
type="button"
onClick={() => onConfigOpen(b.id)}
title="设置"
aria-label="设置"
className="inline-flex size-6 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
className="pointer-events-auto absolute right-1.5 top-1.5 z-20 inline-flex size-6 items-center justify-center rounded-md bg-background/70 text-muted-foreground opacity-60 backdrop-blur-sm transition-all outline-none hover:opacity-100 hover:text-foreground focus-visible:opacity-100 focus-visible:ring-[3px] focus-visible:ring-ring/40 cursor-pointer"
>
<Settings2 className="size-3.5" />
</button>
)}
<button
type="button"
onClick={() => onToggleVisible(b.id)}
title={b.visible ? '隐藏' : '显示'}
aria-label={b.visible ? '隐藏' : '显示'}
className="inline-flex size-6 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
{b.visible ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}
</button>
</div>
)}
{hidden ? (
<div className="flex h-full w-full items-center justify-center rounded-xl border border-dashed bg-muted/20 px-2 text-center text-[11px] text-muted-foreground">
{labelFor(b.id)} · 已隐藏
</div>
) : (
<div className={cn('h-full w-full overflow-auto rounded-xl', editing && 'pointer-events-none select-none')}>
{renderWidget(b)}
</div>
</>
)}
<div className={cn('h-full w-full overflow-auto rounded-xl', editing && 'pointer-events-none select-none')}>
{renderWidget(b)}
</div>
</div>,
target,
);
@@ -3,7 +3,8 @@ import { motion, Reorder } from 'motion/react';
import { Link } from '@tanstack/react-router';
import {
Activity, ArrowRight, Bell, Cable, Check, Cpu, ExternalLink, Eye, EyeOff, GripVertical,
MemoryStick, MonitorCog, Pencil, PlugZap, RefreshCw, RotateCcw, Server, Settings2, Users,
LayoutGrid, MemoryStick, MonitorCog, Pencil, Plus, PlugZap, RefreshCw, RotateCcw, Server,
Settings2, Users,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -21,14 +22,14 @@ import { useTheme } from '@/contexts/ThemeContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query';
import {
CONFIGURABLE_WIDGETS, GRID_COLS, MOBILE_WIDGET_IDS, STATIC_WIDGET_IDS, mobileHeightOf,
CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, MOBILE_WIDGET_IDS, STATIC_WIDGET_IDS, mobileHeightOf,
parseAccountConfig, parseAlertsConfig, parseConnectionsConfig, parseHostConfig,
parseLinkConfig, parseNoteConfig, parseSessionsConfig, widgetLabel,
type AccountConfig, type AlertsConfig, type ConnectionsConfig, type HostConfig,
type LinkConfig, type NoteConfig, type SessionsConfig,
} from '@/lib/dashboard-layout';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid';
import { DashboardGrid, WIDGET_DRAG_TYPE, type GridCoord } from '@/components/pages/dashboard-grid';
import {
AccountConfigForm, AlertsConfigForm, ConnectionsConfigForm, HostConfigForm,
LinkConfigForm, LINK_ICON_COMPONENTS, NoteConfigForm, SessionsConfigForm,
@@ -62,12 +63,12 @@ export function OverviewPage() {
const isWide = useMediaQuery('(min-width: 768px)');
// Free-grid 2D editing is desktop-only; on a phone, editing surfaces a
// single-column drag-sort panel (overviewMobile) instead.
const gridEditing = isWide && editing;
const [configId, setConfigId] = useState<string | null>(null);
// The grid shows only visible widgets (Apple-widgets model); hidden ones live
// in the gallery and are dragged in/out to add/remove.
const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [overviewBlocks]);
// In edit mode show ALL blocks (hidden ones as re-enableable ghosts); else visible-only.
const gridBlocks = gridEditing ? overviewBlocks : visibleBlocks;
const hiddenBlocks = useMemo(() => overviewBlocks.filter((b) => !b.visible), [overviewBlocks]);
// Per-widget config lives on the desktop blocks; mobile widgets reuse it.
const configById = useMemo(
@@ -81,18 +82,28 @@ export function OverviewPage() {
[overviewMobile],
);
// Single writer for the grid: move/resize updates coords; a visible block no
// longer present in the snapshot was dragged out to the gallery → hide it.
const onGridChange = (coords: GridCoord[]) => {
const cmap = new Map(coords.map((c) => [c.id, c]));
setOverviewBlocks(
overviewBlocks.map((b) => {
if (!b.visible) return b; // hidden (in the gallery) — leave untouched
const c = cmap.get(b.id);
return c ? { ...b, x: c.x, y: c.y, w: c.w, h: c.h } : b;
if (c) return { ...b, x: c.x, y: c.y, w: c.w, h: c.h };
return { ...b, visible: false }; // was in the grid, now gone → removed
}),
);
};
const toggleBlock = (id: string) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b)));
// Add a widget dragged from the gallery at the dropped cell (catalogue size).
const addWidget = (id: string, x: number, y: number) => {
const spec = GRID_WIDGETS.find((w) => w.id === id);
setOverviewBlocks(overviewBlocks.map((b) => (
b.id === id ? { ...b, visible: true, x, y, w: spec?.def.w ?? 3, h: spec?.def.h ?? 2 } : b
)));
};
const toggleMobile = (id: string) =>
setOverviewMobile(mobileItems.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b)));
const reorderMobile = (ids: string[]) => {
@@ -126,7 +137,7 @@ export function OverviewPage() {
{editing && (
<p className="rounded-xl border border-primary/20 bg-primary/5 px-3.5 py-2.5 text-[11px] leading-relaxed text-muted-foreground">
{isWide
? '拖动卡片顶部的「拖动」手柄移动位置、拖右下角缩放;眼睛图标显隐、齿轮改设置。左侧导航也可在编辑态拖动排序。'
? '拖动卡片移动位置、拖右下角缩放,右上齿轮改设置;把卡片拖回右侧「部件库」即可移除,从部件库拖到画布即可添加。左侧导航也可在编辑态拖动排序。'
: '拖动手柄调整卡片顺序,眼睛图标显隐,齿轮改设置。手机为单列布局,与桌面网格各自独立。'}
</p>
)}
@@ -155,21 +166,30 @@ export function OverviewPage() {
)}
{isWide ? (
visibleBlocks.length === 0 && !gridEditing ? (
<EmptyLayout onReset={resetLayout} />
) : (
<DashboardGrid
blocks={gridBlocks}
editing={gridEditing}
cols={GRID_COLS}
onChange={onGridChange}
renderWidget={renderWidget}
labelFor={widgetLabel}
configurableIds={CONFIGURABLE_WIDGETS}
onToggleVisible={toggleBlock}
onConfigOpen={setConfigId}
/>
)
<div className="flex items-start gap-4">
<div className="min-w-0 flex-1">
{visibleBlocks.length === 0 ? (
editing ? (
<DropPlaceholder onAdd={addWidget} />
) : (
<EmptyLayout onReset={resetLayout} />
)
) : (
<DashboardGrid
blocks={visibleBlocks}
editing={editing}
cols={GRID_COLS}
onChange={onGridChange}
renderWidget={renderWidget}
configurableIds={CONFIGURABLE_WIDGETS}
onConfigOpen={setConfigId}
removableSelector=".widget-gallery"
onAdd={addWidget}
/>
)}
</div>
{editing && <WidgetGallery hidden={hiddenBlocks} />}
</div>
) : (
<MobileOverview
items={mobileItems}
@@ -288,14 +308,73 @@ function MobileOverview({
cols={1}
onChange={() => { /* no drag on mobile — order edited via the panel */ }}
renderWidget={renderWidget}
labelFor={widgetLabel}
configurableIds={CONFIGURABLE_WIDGETS}
onToggleVisible={() => { /* unused in view mode */ }}
onConfigOpen={onConfigOpen}
/>
);
}
// ─────────────── widget gallery (desktop edit mode) ───────────────
// The right-hand "store": hidden widgets shown as draggable tiles. Dragging a
// tile onto the canvas adds it (HTML5 DnD); dragging a canvas card back onto
// this panel removes it (gridstack `removable`, matched by the .widget-gallery
// class). Edit-mode only, desktop only.
function WidgetGallery({ hidden }: { hidden: UiLayoutItem[] }) {
return (
<div className="widget-gallery w-56 shrink-0 self-stretch rounded-xl border border-dashed bg-muted/20 p-3">
<div className="mb-1.5 flex items-center gap-1.5 px-1">
<LayoutGrid className="size-3.5 text-primary" />
<span className="text-xs font-semibold">部件库</span>
</div>
<p className="mb-3 px-1 text-[11px] leading-snug text-muted-foreground">
拖到左侧画布添加;把卡片拖回此处即可移除。
</p>
{hidden.length === 0 ? (
<div className="rounded-lg border border-dashed px-2 py-8 text-center text-[11px] text-muted-foreground">
全部部件已添加
</div>
) : (
<div className="flex flex-col gap-1.5">
{hidden.map((b) => (
<div
key={b.id}
draggable
onDragStart={(e) => {
e.dataTransfer.setData(WIDGET_DRAG_TYPE, b.id);
e.dataTransfer.effectAllowed = 'copy';
}}
className="flex cursor-grab items-center gap-2 rounded-lg border bg-card/70 px-2.5 py-2 text-sm transition-colors active:cursor-grabbing hover:border-primary/40 hover:bg-accent/30"
>
<GripVertical className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{widgetLabel(b.id)}</span>
<Plus className="size-3.5 shrink-0 text-muted-foreground/60" />
</div>
))}
</div>
)}
</div>
);
}
// Empty-canvas drop target shown in edit mode when no widget is on the grid —
// keeps an HTML5 drop zone so the first widget can still be dragged in.
function DropPlaceholder({ onAdd }: { onAdd: (id: string, x: number, y: number) => void }) {
return (
<div
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const id = e.dataTransfer.getData(WIDGET_DRAG_TYPE);
if (id) onAdd(id, 0, 0);
}}
className="flex min-h-60 flex-col items-center justify-center gap-3 rounded-xl border-2 border-dashed py-16 text-center text-muted-foreground"
>
<LayoutGrid className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">从右侧「部件库」拖动部件到这里</p>
</div>
);
}
// ─────────────── stat tiles (one widget each) ───────────────
function StatTile({