Yuchen Yuan commited on
Commit
d9a330d
·
1 Parent(s): 61bf7f9

NodePalette: checkbox multi-select + batch add to canvas

Browse files

Three ways to add blocks now:
1. Drag a tile onto the canvas (unchanged).
2. Click the checkbox (top-left corner of tile) to select, then hit
the "Add N to canvas" button that appears in the header. All
checked blocks are created on the canvas in family order and
auto-connected in one shot.
3. Hover a tile and click the + icon (top-right) to add just that
one block instantly.

Implementation:
- NodePalette tracks a `checked: Set<NodeKind>` state. Checked tiles
get an accent border + filled checkbox.
- On "Add to canvas", NodePalette pushes the ordered list of kinds
to `useApp.addBlocksToCanvas(kinds)` (new Zustand store field).
- FlowCanvas watches `pendingBlockKinds` via useEffect: creates
nodes positioned to the right of existing ones, merges them into
the canvas, auto-connects the whole graph, shows a toast with
any warnings, and fitViews to show all nodes.
- Zustand bridge avoids restructuring the component tree (NodePalette
and FlowCanvas are siblings, not parent-child).

frontend/src/components/FlowCanvas.tsx CHANGED
@@ -130,6 +130,8 @@ export function FlowCanvas() {
130
  const running = useApp((s) => s.running);
131
  const setRunning = useApp((s) => s.setRunning);
132
  const useLiveIbm = useApp((s) => s.useLiveIbm);
 
 
133
  const [notice, setNotice] = useState<Notice>(null);
134
  // Non-danger toasts auto-fade; success is quick, warnings linger a bit
135
  // longer so the user has time to read every bullet. Runner errors stay
@@ -145,6 +147,58 @@ export function FlowCanvas() {
145
  const wrapperRef = useRef<HTMLDivElement>(null);
146
  const { screenToFlowPosition, fitView } = useReactFlow();
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  // Auto-load a sample circuit on boot so the canvas has something to chew
149
  // on. Prefer the share-link's `sk` key if present; fall back to bell_state.
150
  useEffect(() => {
 
130
  const running = useApp((s) => s.running);
131
  const setRunning = useApp((s) => s.setRunning);
132
  const useLiveIbm = useApp((s) => s.useLiveIbm);
133
+ const pendingBlockKinds = useApp((s) => s.pendingBlockKinds);
134
+ const clearPendingBlocks = useApp((s) => s.clearPendingBlocks);
135
  const [notice, setNotice] = useState<Notice>(null);
136
  // Non-danger toasts auto-fade; success is quick, warnings linger a bit
137
  // longer so the user has time to read every bullet. Runner errors stay
 
147
  const wrapperRef = useRef<HTMLDivElement>(null);
148
  const { screenToFlowPosition, fitView } = useReactFlow();
149
 
150
+ // Watch the Zustand pendingBlockKinds queue: NodePalette pushes block
151
+ // kinds here when the user checks tiles and clicks "Add to canvas" (or
152
+ // clicks the single-add + icon). We create nodes, append them to the
153
+ // canvas, and auto-connect the whole graph.
154
+ useEffect(() => {
155
+ if (pendingBlockKinds.length === 0) return;
156
+ const kinds = pendingBlockKinds;
157
+ clearPendingBlocks();
158
+
159
+ // Position new nodes to the right of existing ones.
160
+ const SPACING_X = 260;
161
+ const Y = 120;
162
+ const maxX = nodes.reduce(
163
+ (mx, n) => Math.max(mx, (n.position?.x ?? 0) + 200),
164
+ 0,
165
+ );
166
+ const startX = nodes.length === 0 ? 80 : maxX + 60;
167
+
168
+ const newNodes: RFNode[] = kinds.map((kind, i) => ({
169
+ id: `n${Date.now().toString(36)}${i}`,
170
+ type: "qnode",
171
+ position: { x: startX + i * SPACING_X, y: Y },
172
+ data: {
173
+ kind,
174
+ params: { ...(NODE_BY_KIND[kind].defaultData ?? {}) },
175
+ },
176
+ }));
177
+
178
+ setNodes((ns) => {
179
+ const merged = [...ns, ...newNodes];
180
+ const result = autoConnect(merged, []);
181
+ if (result.connected) {
182
+ setEdges(result.edges);
183
+ setNotice(
184
+ result.warnings.length > 0
185
+ ? {
186
+ text: `Added ${kinds.length} block${kinds.length > 1 ? "s" : ""} and auto-connected.`,
187
+ tone: "warn",
188
+ detail: result.warnings.join("\n"),
189
+ }
190
+ : {
191
+ text: `Added ${kinds.length} block${kinds.length > 1 ? "s" : ""} and auto-connected.`,
192
+ tone: "ok",
193
+ },
194
+ );
195
+ }
196
+ return merged;
197
+ });
198
+
199
+ requestAnimationFrame(() => fitView({ padding: 0.2, duration: 300 }));
200
+ }, [pendingBlockKinds]); // eslint-disable-line react-hooks/exhaustive-deps
201
+
202
  // Auto-load a sample circuit on boot so the canvas has something to chew
203
  // on. Prefer the share-link's `sk` key if present; fall back to bell_state.
204
  useEffect(() => {
frontend/src/components/NodePalette.tsx CHANGED
@@ -1,6 +1,7 @@
1
  import { useState, useMemo } from "react";
2
- import { ChevronDown, FileText, Search, X } from "lucide-react";
3
- import { NODE_CATALOG, type NodeSpec } from "../lib/nodeCatalog";
 
4
 
5
  /**
6
  * Categorised block catalog above the canvas.
@@ -10,53 +11,40 @@ import { NODE_CATALOG, type NodeSpec } from "../lib/nodeCatalog";
10
  * section with a header chip. A search box filters across all families
11
  * in real time.
12
  *
13
- * Two interaction modes, both always available:
14
- * - **Drag** a tile onto the canvas (existing behaviour).
15
- * - **Click** a tile to add it at the canvas centre (TODO: wire up
16
- * in FlowCanvas via an onAddBlock callback when ready).
 
 
 
17
  *
18
  * The whole palette collapses to a thin bar ("N blocks available") via
19
  * a toggle so the canvas can reclaim vertical space.
20
  */
21
 
22
- /** Family metadata: display label + ordering. */
23
  const FAMILY_META: {
24
  key: NodeSpec["family"];
25
  label: string;
26
  description: string;
27
  }[] = [
28
- {
29
- key: "source",
30
- label: "Source",
31
- description: "Where the pipeline starts",
32
- },
33
- {
34
- key: "backend",
35
- label: "Backend",
36
- description: "Provides a noise model",
37
- },
38
  {
39
  key: "algorithm",
40
  label: "Algorithm",
41
  description: "Research algorithms that transform or analyse the circuit",
42
  },
43
- {
44
- key: "metric",
45
- label: "Metric",
46
- description: "Computes a quantitative score",
47
- },
48
- {
49
- key: "sink",
50
- label: "Sink",
51
- description: "Aggregates final output",
52
- },
53
  ];
54
 
55
  export function NodePalette() {
56
  const [search, setSearch] = useState("");
57
  const [expanded, setExpanded] = useState(true);
58
- // Track which families are collapsed; default all expanded.
59
  const [collapsedFams, setCollapsedFams] = useState<Set<string>>(new Set());
 
 
60
 
61
  const toggleFamily = (fam: string) =>
62
  setCollapsedFams((s) => {
@@ -65,7 +53,27 @@ export function NodePalette() {
65
  return next;
66
  });
67
 
68
- // Filter blocks by search query (matches label, tagline, family, kind).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  const filtered = useMemo(() => {
70
  if (!search.trim()) return NODE_CATALOG;
71
  const q = search.toLowerCase();
@@ -99,7 +107,7 @@ export function NodePalette() {
99
 
100
  return (
101
  <div className="shrink-0 border-b border-edge bg-surface/40">
102
- {/* Header row: search + collapse toggle */}
103
  <div className="px-3 pt-2 pb-1 flex items-center gap-2">
104
  <div className="relative flex-1 max-w-[220px]">
105
  <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-mute pointer-events-none" />
@@ -120,7 +128,7 @@ export function NodePalette() {
120
  </button>
121
  )}
122
  </div>
123
- {/* Family quick-jump chips */}
124
  <div className="hidden md:flex items-center gap-1">
125
  {FAMILY_META.map((fm) => {
126
  const count = filtered.filter((n) => n.family === fm.key).length;
@@ -143,6 +151,17 @@ export function NodePalette() {
143
  );
144
  })}
145
  </div>
 
 
 
 
 
 
 
 
 
 
 
146
  <div className="flex-1" />
147
  <button
148
  type="button"
@@ -162,7 +181,6 @@ export function NodePalette() {
162
  const isCollapsed = collapsedFams.has(fm.key);
163
  return (
164
  <div key={fm.key} className="shrink-0 flex items-start gap-1">
165
- {/* Family label (vertical on desktop, horizontal on mobile) */}
166
  <button
167
  type="button"
168
  onClick={() => toggleFamily(fm.key)}
@@ -181,11 +199,16 @@ export function NodePalette() {
181
  }`}
182
  />
183
  </button>
184
- {/* Tiles */}
185
  {!isCollapsed && (
186
  <div className="flex items-center gap-1 flex-wrap">
187
  {items.map((n) => (
188
- <PaletteTile key={n.kind} spec={n} />
 
 
 
 
 
 
189
  ))}
190
  </div>
191
  )}
@@ -194,7 +217,6 @@ export function NodePalette() {
194
  {items.length} hidden
195
  </div>
196
  )}
197
- {/* Divider between families */}
198
  <div className="hidden md:block w-px self-stretch bg-edge/40 mx-0.5" />
199
  </div>
200
  );
@@ -209,7 +231,17 @@ export function NodePalette() {
209
  );
210
  }
211
 
212
- function PaletteTile({ spec }: { spec: NodeSpec }) {
 
 
 
 
 
 
 
 
 
 
213
  const Icon = spec.icon;
214
  function onDragStart(e: React.DragEvent) {
215
  e.dataTransfer.setData("application/reactflow", spec.kind);
@@ -219,9 +251,48 @@ function PaletteTile({ spec }: { spec: NodeSpec }) {
219
  <div
220
  draggable
221
  onDragStart={onDragStart}
222
- className="group relative shrink-0 cursor-grab active:cursor-grabbing flex flex-col items-center justify-center gap-0.5 w-[108px] h-[76px] rounded-md border border-edge/60 hover:border-edge hover:bg-surfaceAlt transition-colors text-center px-1.5 py-1.5"
 
 
 
 
223
  title={spec.description}
224
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  {spec.paper && (
226
  <a
227
  href={spec.paper.url}
 
1
  import { useState, useMemo } from "react";
2
+ import { Check, ChevronDown, FileText, Plus, Search, X } from "lucide-react";
3
+ import { NODE_CATALOG, type NodeKind, type NodeSpec } from "../lib/nodeCatalog";
4
+ import { useApp } from "../lib/store";
5
 
6
  /**
7
  * Categorised block catalog above the canvas.
 
11
  * section with a header chip. A search box filters across all families
12
  * in real time.
13
  *
14
+ * Three interaction modes:
15
+ * - **Drag** a tile onto the canvas (classic).
16
+ * - **Click** the checkbox on a tile to select it, then hit "Add N
17
+ * to canvas" to batch-add all selected blocks at once (the
18
+ * FlowCanvas picks them up via the Zustand `pendingBlockKinds`
19
+ * bridge and auto-connects them).
20
+ * - **Single click** the + icon on a tile to add just that one block.
21
  *
22
  * The whole palette collapses to a thin bar ("N blocks available") via
23
  * a toggle so the canvas can reclaim vertical space.
24
  */
25
 
 
26
  const FAMILY_META: {
27
  key: NodeSpec["family"];
28
  label: string;
29
  description: string;
30
  }[] = [
31
+ { key: "source", label: "Source", description: "Where the pipeline starts" },
32
+ { key: "backend", label: "Backend", description: "Provides a noise model" },
 
 
 
 
 
 
 
 
33
  {
34
  key: "algorithm",
35
  label: "Algorithm",
36
  description: "Research algorithms that transform or analyse the circuit",
37
  },
38
+ { key: "metric", label: "Metric", description: "Computes a quantitative score" },
39
+ { key: "sink", label: "Sink", description: "Aggregates final output" },
 
 
 
 
 
 
 
 
40
  ];
41
 
42
  export function NodePalette() {
43
  const [search, setSearch] = useState("");
44
  const [expanded, setExpanded] = useState(true);
 
45
  const [collapsedFams, setCollapsedFams] = useState<Set<string>>(new Set());
46
+ const [checked, setChecked] = useState<Set<NodeKind>>(new Set());
47
+ const addBlocksToCanvas = useApp((s) => s.addBlocksToCanvas);
48
 
49
  const toggleFamily = (fam: string) =>
50
  setCollapsedFams((s) => {
 
53
  return next;
54
  });
55
 
56
+ const toggleCheck = (kind: NodeKind) =>
57
+ setChecked((s) => {
58
+ const next = new Set(s);
59
+ next.has(kind) ? next.delete(kind) : next.add(kind);
60
+ return next;
61
+ });
62
+
63
+ const addSingle = (kind: NodeKind) => {
64
+ addBlocksToCanvas([kind]);
65
+ };
66
+
67
+ const addSelected = () => {
68
+ if (checked.size === 0) return;
69
+ // Preserve catalog family order so auto-connect produces a sensible chain.
70
+ const ordered = NODE_CATALOG.filter((n) => checked.has(n.kind)).map(
71
+ (n) => n.kind,
72
+ );
73
+ addBlocksToCanvas(ordered);
74
+ setChecked(new Set());
75
+ };
76
+
77
  const filtered = useMemo(() => {
78
  if (!search.trim()) return NODE_CATALOG;
79
  const q = search.toLowerCase();
 
107
 
108
  return (
109
  <div className="shrink-0 border-b border-edge bg-surface/40">
110
+ {/* Header row */}
111
  <div className="px-3 pt-2 pb-1 flex items-center gap-2">
112
  <div className="relative flex-1 max-w-[220px]">
113
  <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-mute pointer-events-none" />
 
128
  </button>
129
  )}
130
  </div>
131
+ {/* Family chips */}
132
  <div className="hidden md:flex items-center gap-1">
133
  {FAMILY_META.map((fm) => {
134
  const count = filtered.filter((n) => n.family === fm.key).length;
 
151
  );
152
  })}
153
  </div>
154
+ {/* Add-selected button (appears when any block is checked) */}
155
+ {checked.size > 0 && (
156
+ <button
157
+ type="button"
158
+ onClick={addSelected}
159
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium bg-accent text-canvas hover:bg-accent/90 transition-colors whitespace-nowrap"
160
+ >
161
+ <Plus className="w-3 h-3" />
162
+ Add {checked.size} to canvas
163
+ </button>
164
+ )}
165
  <div className="flex-1" />
166
  <button
167
  type="button"
 
181
  const isCollapsed = collapsedFams.has(fm.key);
182
  return (
183
  <div key={fm.key} className="shrink-0 flex items-start gap-1">
 
184
  <button
185
  type="button"
186
  onClick={() => toggleFamily(fm.key)}
 
199
  }`}
200
  />
201
  </button>
 
202
  {!isCollapsed && (
203
  <div className="flex items-center gap-1 flex-wrap">
204
  {items.map((n) => (
205
+ <PaletteTile
206
+ key={n.kind}
207
+ spec={n}
208
+ isChecked={checked.has(n.kind)}
209
+ onToggleCheck={() => toggleCheck(n.kind)}
210
+ onAddSingle={() => addSingle(n.kind)}
211
+ />
212
  ))}
213
  </div>
214
  )}
 
217
  {items.length} hidden
218
  </div>
219
  )}
 
220
  <div className="hidden md:block w-px self-stretch bg-edge/40 mx-0.5" />
221
  </div>
222
  );
 
231
  );
232
  }
233
 
234
+ function PaletteTile({
235
+ spec,
236
+ isChecked,
237
+ onToggleCheck,
238
+ onAddSingle,
239
+ }: {
240
+ spec: NodeSpec;
241
+ isChecked: boolean;
242
+ onToggleCheck: () => void;
243
+ onAddSingle: () => void;
244
+ }) {
245
  const Icon = spec.icon;
246
  function onDragStart(e: React.DragEvent) {
247
  e.dataTransfer.setData("application/reactflow", spec.kind);
 
251
  <div
252
  draggable
253
  onDragStart={onDragStart}
254
+ className={`group relative shrink-0 cursor-grab active:cursor-grabbing flex flex-col items-center justify-center gap-0.5 w-[108px] h-[76px] rounded-md border transition-colors text-center px-1.5 py-1.5 ${
255
+ isChecked
256
+ ? "border-accent bg-accent/10"
257
+ : "border-edge/60 hover:border-edge hover:bg-surfaceAlt"
258
+ }`}
259
  title={spec.description}
260
  >
261
+ {/* Checkbox (top-left) */}
262
+ <button
263
+ type="button"
264
+ onClick={(e) => {
265
+ e.stopPropagation();
266
+ onToggleCheck();
267
+ }}
268
+ draggable={false}
269
+ onDragStart={(e) => e.stopPropagation()}
270
+ className={`absolute top-1 left-1 w-4 h-4 rounded flex items-center justify-center transition-colors z-10 ${
271
+ isChecked
272
+ ? "bg-accent border border-accent text-canvas"
273
+ : "border border-edge bg-surface text-transparent hover:border-mute hover:text-mute"
274
+ }`}
275
+ aria-label={isChecked ? `Deselect ${spec.label}` : `Select ${spec.label}`}
276
+ >
277
+ <Check className="w-2.5 h-2.5" strokeWidth={3} />
278
+ </button>
279
+ {/* Quick-add button (top-right, shows on hover when not checked) */}
280
+ {!isChecked && !spec.paper && (
281
+ <button
282
+ type="button"
283
+ onClick={(e) => {
284
+ e.stopPropagation();
285
+ onAddSingle();
286
+ }}
287
+ draggable={false}
288
+ onDragStart={(e) => e.stopPropagation()}
289
+ className="absolute top-1 right-1 w-4 h-4 rounded-full border border-edge bg-surface text-mute hover:border-accent hover:text-accent flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"
290
+ title={`Add ${spec.label} to canvas`}
291
+ aria-label={`Add ${spec.label} to canvas`}
292
+ >
293
+ <Plus className="w-2.5 h-2.5" strokeWidth={2.5} />
294
+ </button>
295
+ )}
296
  {spec.paper && (
297
  <a
298
  href={spec.paper.url}
frontend/src/lib/store.ts CHANGED
@@ -3,6 +3,7 @@
3
 
4
  import { create } from "zustand";
5
  import type { CircuitInfo, RunResponse, HealthResponse } from "./api";
 
6
 
7
  const LS_USE_LIVE_IBM = "jqub.useLiveIbm";
8
 
@@ -50,6 +51,15 @@ interface AppState {
50
  */
51
  useLiveIbm: boolean;
52
  setUseLiveIbm: (v: boolean) => void;
 
 
 
 
 
 
 
 
 
53
  }
54
 
55
  export const useApp = create<AppState>((set) => ({
@@ -72,4 +82,7 @@ export const useApp = create<AppState>((set) => ({
72
  }
73
  set({ useLiveIbm: v });
74
  },
 
 
 
75
  }));
 
3
 
4
  import { create } from "zustand";
5
  import type { CircuitInfo, RunResponse, HealthResponse } from "./api";
6
+ import type { NodeKind } from "./nodeCatalog";
7
 
8
  const LS_USE_LIVE_IBM = "jqub.useLiveIbm";
9
 
 
51
  */
52
  useLiveIbm: boolean;
53
  setUseLiveIbm: (v: boolean) => void;
54
+
55
+ /**
56
+ * Cross-component bridge: NodePalette pushes block kinds here when the
57
+ * user checks blocks and clicks "Add to canvas". FlowCanvas watches
58
+ * this via useEffect, creates the nodes, auto-connects, and clears.
59
+ */
60
+ pendingBlockKinds: NodeKind[];
61
+ addBlocksToCanvas: (kinds: NodeKind[]) => void;
62
+ clearPendingBlocks: () => void;
63
  }
64
 
65
  export const useApp = create<AppState>((set) => ({
 
82
  }
83
  set({ useLiveIbm: v });
84
  },
85
+ pendingBlockKinds: [],
86
+ addBlocksToCanvas: (kinds) => set({ pendingBlockKinds: kinds }),
87
+ clearPendingBlocks: () => set({ pendingBlockKinds: [] }),
88
  }));