Files
app/frontend/src/components/Flow/queries.ts
T
Melvin StroblandClaude Opus 5 9cede8dbb5 Add undo on the canvas, and sharpen the flow chrome
Deleting a node cost its source with no way back. Every mutation already
funnels through one commit, so undo/redo is a bounded stack of node
snapshots replayed through the same debounced save. Deleting a node only
drops it from flow.json — the source file survives — so restoring the id
restores the code. Renaming a message now offers to follow the rename
across every node still bound to the old name, as one undoable step.

Autosave never fired: flush depended on the whole mutation object, which
react-query rebuilds every render, so the effect re-ran and its cleanup
cancelled the pending timer. Unmounting now flushes rather than drops.

The canvas looked blurry zoomed out because Background scales the dot
radius by zoom, leaving quarter-pixel dots on a drifting tile; radius
and spacing now divide the zoom back out, spacing in octaves so the grid
halves. Edge value labels are opaque, the edge popover fits its summary
on one row with a trash icon and scrolls names that overflow, and flow
settings moved to the flowbar. The flowbar was sized against the
viewport rather than the canvas, so its buttons left the screen once
enough flows were open.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KkmeRiyeYmVZqJVwuyHq9o
2026-08-15 21:19:53 +02:00

108 lines
3.4 KiB
TypeScript

import {
type UseMutationResult,
useMutation,
useQueryClient,
} from "@tanstack/react-query"
import { useCallback, useEffect, useRef } from "react"
import { type FlowDef_Input, FlowsService } from "@/client"
export const flowKeys = {
all: ["flows"] as const,
detail: (name: string) => ["flows", name] as const,
source: (name: string, nodeId: string) =>
["flows", name, "source", nodeId] as const,
nodeTypes: ["flows", "node-types"] as const,
}
export const flowsQueryOptions = () => ({
queryKey: flowKeys.all,
queryFn: () => FlowsService.readFlows(),
})
export const flowQueryOptions = (name: string) => ({
queryKey: flowKeys.detail(name),
queryFn: () => FlowsService.readFlow({ name }),
})
export const nodeTypesQueryOptions = () => ({
queryKey: flowKeys.nodeTypes,
queryFn: () => FlowsService.readNodeTypes(),
staleTime: Number.POSITIVE_INFINITY,
})
export const nodeSourceQueryOptions = (name: string, nodeId: string) => ({
queryKey: flowKeys.source(name, nodeId),
queryFn: () => FlowsService.readNodeSource({ name, nodeId }),
})
const AUTOSAVE_DELAY = 800
/**
* Saves the flow a moment after the last edit, and immediately when the editor
* needs the server to be current (closing a panel, switching flow, running).
*
* Identical documents are skipped server-side, so a quiet canvas writes nothing.
*/
export function useAutosave(name: string): {
save: (definition: FlowDef_Input) => void
flush: () => void
mutation: UseMutationResult<unknown, unknown, FlowDef_Input, unknown>
} {
const queryClient = useQueryClient()
const pending = useRef<FlowDef_Input | null>(null)
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
const mutation = useMutation({
mutationFn: (definition: FlowDef_Input) =>
FlowsService.saveFlow({ name, requestBody: definition }),
onSuccess: (detail) => {
// Write the server's answer straight into the cache: invalidating would
// pull the document back out from under edits still in flight.
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
})
// react-query hands back a new mutation object on every render, so flushing
// has to hang off `mutate`, which is stable. Depending on the whole mutation
// re-ran the effect below on every render, and its cleanup cancelled the
// pending save before it ever fired.
const { mutate } = mutation
const flush = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current)
timer.current = null
}
const definition = pending.current
pending.current = null
if (definition) {
mutate(definition)
}
}, [mutate])
const save = useCallback(
(definition: FlowDef_Input) => {
pending.current = definition
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(flush, AUTOSAVE_DELAY)
},
[flush],
)
// Leaving the tab is the last chance to persist what is still queued.
useEffect(() => {
const onHidden = () => {
if (document.visibilityState === "hidden") flush()
}
document.addEventListener("visibilitychange", onHidden)
return () => {
document.removeEventListener("visibilitychange", onHidden)
// Unmounting is a flow switch, not a reason to drop a queued edit.
flush()
}
}, [flush])
return { save, flush, mutation }
}