Front Matter
Title: Visual Canvas ([2.2])
Author: Joylynne Grace C. Esportuno — original author (March 2026)
Updated by: Patrick Babala — author of PRs #667, #680, #700, #708, #712, #760, #788, #800
Reviewers: James Billate and Uriel Tribiana — original review. Update review: Clyde Ador (@clydetims), Christian Denzon (@cdnzn) (reviewed PRs #680 / #700 / #708 / #712 / #760 / #788 / #800; @ybcole also reviewed #708).
Created: March 3, 2026
Updated: 2026-09-30
Status: Published (feature live)
References:
Issue: [2.2] Visual Canvas — #31
Sub-issues: #160 [2.2.1] Toggleable Button for Outline and Visual View; #161 [2.2.2] Node bar; #162 [2.2.3] Nodes Implementation; #249 [2.2.4] Linear Mode - Visual Canvas; #270 [2.2.5] Node deletion via eraser and "All" implementation; #280 [2.2.6] Quest Mode Conversion Linear to Exploration and vice-versa Logic; #451 [2.2.7] Full Screen Node
Milestone: [2] Design (Dual Editor)
Update PRs covered by this revision: #667 quest/card background audio; #680 motivation pop-ups + canvas bug fixes; #700 node fullscreen in linear mode; #708 activity/code-block fixes + linear layout engine; #712 preview reset, question handles, code language + 50k limit; #760 archived-node publish validation + persistence; #788 responsive dialogs + touch targets; #800 canvas CodeBlock input fix
Related features (separate guides): Form Editor ([2.1]); Creator Quest Card Background Audio (#667) — the background-audio and motivation sections on canvas nodes are covered in depth in their own guide; this guide documents the canvas integration only.
Corrected in 2.0: the original guide's References pointed at https://github.com/wyzlab/WyzQuests/issues/81, which is actually [6.3] Suspend User — an unrelated, since-closed issue. The correct parent issue is [2.2] Visual Canvas — #31, and its seven sub-issues are now listed above.
INTRODUCTION & GOALS
Problem Summary
As branching scenarios grow in complexity, it becomes easy to lose track of decision paths and logic flow. The Visual Canvas addresses this by giving creators a clear, top-level view of their entire scenario — allowing them to build workflows intuitively by dragging and dropping nodes and connecting them via handles to define relationships.
Goals & Non-Goals
Goals
Provide creators with a bird's-eye view of the entire branching scenario at once, so no path is hidden or lost.
Allow creators to construct workflows by dragging and dropping nodes rather than filling out forms.
Connect nodes via handles to make logic flow immediately obvious.
(Added in 2.0) Let creators attach per-node background audio and a motivation pop-up directly on the canvas (
CanvasAudioSection/CanvasMotivationSection), reusing the Form Editor's model (PRs #667, #680).(Added in 2.0) Provide fullscreen node editing in both Exploration and Linear modes (PR #700 completed Linear; #451 was the original Exploration implementation).
Non-Goals
Real-time multiplayer editing (collaboration with other creators) is out of scope.
Mobile authoring is explicitly unsupported — the canvas itself remains desktop-only. Responsiveness added in PR #788 targets the learner player, dialogs, and touch targets, not the canvas workspace.
Glossary
Node — A single unit of content or logic.
Handle — The connection points on a node used to link it to other nodes.
Edge — The line drawn between two handles, representing a path or relationship.
Canvas — The workspace where all nodes and edges are displayed and managed.
Node bar — A toolbar consisting of all available nodes and actions.
Exploration Mode — This mode allows creators to create branching scenarios, wherein succeeding scenarios are determined based on the learner's choices.
Linear Mode — This mode is for creating a linear quest progression.
Archived Node — (Added in 2.0) A node removed from the active canvas but retained in
canvas_metadatawithdata.isArchived = true; managed via the Archived Nodes modal.NodeToolbar — (Added in 2.0) The per-node icon row (Music = background audio, Sparkles = motivation) that opens the inline settings panels.
Fullscreen (focus) mode — (Added in 2.0) A modal that hosts a single node for distraction-free editing (
useNodeFullscreen+NodeFullscreenModal).
HIGH-LEVEL ARCHITECTURE
System Diagram
Technologies used
Next.js (App Router), TypeScript, Shadcn, TailwindCSS
Supabase (Postgres, Storage, Auth), RESTful APIs
React Flow (
@xyflow/react) for the canvas; dnd-kit for scenario-child reorderingZod for payload/schema validation
Monaco Editor (
@monaco-editor/react) for Code nodesSonner for toast notifications
Corrected in 2.0: the original guide listed "Supabase" generically. Authoring is authenticated with Supabase Auth, not Clerk; route handlers call getCreatorAuthContext() (lib/auth/agencyOwnership.ts:674) and verifyAgencyResourceOwnership(). (Legacy clerk_id DB column names remain, but no @clerk import exists in any visual-canvas path.)
DETAILED DESIGN & IMPLEMENTATION
Data Model/Schema
The Visual Canvas state is persisted to the quests table. The entire flow structure is serialized and stored in the canvas_metadata column as JSON, preserving node positions, edges, folders, and custom data attributes.
canvas_metadataisJSONB NOT NULL DEFAULT '{"nodes": [], "edges": []}'::jsonb(supabase/migrations/001_add_canvas_metadata.sql:27-29) with a structure check thatnodes/edgesexist and are arrays (:41-48) and a GIN index (:54-55). The DB check does not validatefolders,quest_mode,node_folder_ids, orfolder_positions.At runtime the document also carries
quest_mode,folders,node_folder_ids, andfolder_positions(shared/schemas/questSchema.ts:78-85).quests.quest_modeis the Postgres enumquest_mode_type(linear|exploration;20260310_convert_quest_mode_text_to_enum.sql:9),NOT NULL DEFAULT 'exploration'.quests.publishing_statusis a CHECK constraint, not an enum type:published,draft,archived,submitted,in_review,changes_requested,approved(20260219104324_extend_publishing_status_for_reviewer_queue.sql:5-6).
Example (canvas_metadata):
{ "quest_mode": "exploration", "edges": [ { "id": "xy-edge__[source-id]-source-right-[target-id]-target-left", "source": "[source-id]", "target": "[target-id]", "sourceHandle": "[source-id]-source-right", "targetHandle": "[target-id]-target-left" } ], "nodes": [ { "id": "[node-id]", "type": "Scenario", "x": 80, "y": 288.75, "data": { "type": "Scenario", "label": "Computer Science Fundamentals", "isStart": true, "isEnd": false, "isArchived": false, "audio_url": "https://…/background.mp3", "children": [ { "id": "[child-id]", "type": "Text", "label": "Instructions", "data": { "type": "Text", "label": "Instructions", "textContent": "Computer Science is…" } } ] } } ], "folders": [], "node_folder_ids": {}, "folder_positions": {}}
Node data schemas — lib/schemas/nodes.schema.ts defines one Zod schema per node type: textNodeDataSchema (:4), imageNodeDataSchema (:17), questionNodeDataSchema (:46), discussionNodeDataSchema (:62), videoNodeDataSchema (:79), codeNodeDataSchema (:92), fileNodeDataSchema (:116), linkNodeDataSchema (:130), audioNodeDataSchema (:143), reflectionNodeDataSchema (:156), quizNodeDataSchema (:226), scenarionodeDataSchema (:286).
Corrected in 2.0 (verified against code):
codeContentis capped at 50,000 characters (nodes.schema.ts:96); this is the schema half of the PR #712 limit, enforced server-side inupdate-quest-canvas.audio_url(optional string) exists on 10 node types (Text, Image, Question, Discussion, Code, File, Link, Reflection, Quiz, Scenario) but is intentionally absent on Video and Audio nodes (:79-90,:143-154) — they are dedicated media nodes.motivationis not declared on any node schema. It rides onnode.datavia the schemas'.catchall(z.unknown())and is injected/read bylib/canvas-sync(formToCanvas.ts:323;canvasToForm.ts:212,223). It is a content-card field (types/quest-content-cards.d.ts:58).Archived nodes are not a separate collection. They live inline in
nodes[]withdata.isArchived = true(useCanvasFunctions.ts:510-517,:742), socanvasMetadataSchemavalidates them as ordinary nodes.
API Specification
GET /api/creator/update-quest-canvas?quest_id=…Load canvas state for creator. Returns canvas_metadata (+ quest_mode, title).If stored metadata fails canvasMetadataSchema validation, returns an emptydefault payload with message "reset to default due to invalid data". GET /api/reviewer/get-canvas?quest_id={questId}Loads canvas metadata for readonly reviewer mode (agency-scoped). PUT /api/creator/update-quest-canvasTriggered whenever a user adds, removes, or repositions elements on the canvas.Rejects Code-node content over 50,000 characters; reverts a published quest todraft when hasMeaningfulCanvasChange detects a real canvas mutation. POST /api/ai/compute-canvas-layoutUsed during exploration-mode AI imports and smart merges to compute betternode positions (delegates to Gemini; falls back to placeholder positions). POST /api/creator/convert-canvas-to-cardsConverts canvas nodes into Form Editor content cards after an AI import.Only runs when the quest has no cards yet.
Corrected in 2.0: the original guide's API block was accurate at a high level. Details verified and extended below.
Canvas APIs
GET
/api/creator/update-quest-canvas— agency-scoped load; returns{ ...canvas, quest_mode, title }viaApiResponseHelper.success(app/api/creator/update-quest-canvas/route.ts:85-88). Invalid metadata is returned as an empty default (:70-83).PUT
/api/creator/update-quest-canvas— the client payload is the source of truth for folders/node assignments; for linear quests it upserts cards (:185-190). A manual loop rejects anyCodenode withcodeContent.length > 50000(:122-133).hasMeaningfulCanvasChange(existing, incoming)marks a published questdraft(:248-261).GET
/api/reviewer/get-canvas— reviewer GET; read-only is enforced client-side by selecting this endpoint whenquestView === "readonly"and by refusing saves insaveCanvasNow(useCanvasFunctions.ts:435-438,:803).POST
/api/ai/compute-canvas-layout— requires an authenticated user andassertNotSuspended; validates{ canvas, questMode }and returnscomputeCanvasLayout(canvas, questMode, userId)(app/api/ai/compute-canvas-layout/route.ts:35-74).POST
/api/creator/convert-canvas-to-cards— verifies ownership, skips if cards already exist, filtersScenario | Question | quest-card | activity(excluding start nodes), and inserts cards (convert-canvas-to-cards/route.ts:23-224).POST
/api/creator/quest-content-nodes/get-upload-url/ DELETE…/delete-media— signed-URL media upload for canvas nodes; path-segment hardened deletion.
Not found (do not reference): there is no app/api/creator/quest-content-cards/upload-media/route.ts. The motivation media route is quest-content-cards/upload-motivation-media/route.ts. (The multipart upload-media route was removed in PR #790 — see the Form Editor guide.)
Supporting APIs — quest-content-cards/{list,create,update,delete,reorder} (linear-mode card mirror), validate-quest-content, update-quest (PATCH, publish/draft), and learner/get-quest.
Logic & Workflow
Main Workflow
The creator goes to the Visual Canvas.
The creator drags a node from the Node bar and drops it onto the Canvas.
The creator fills all necessary data within the Node (input fields, labels, file uploads, etc.).
The creator creates an edge by dragging from the handle of a node and connecting it to another node's handle.
The creator adds a Scenario Node onto the Canvas.
The creator drops a node within the Scenario Node, making it a child node (the child node must not be a Scenario Node).
The creator deletes unwanted edges or nodes (active or archived).
(Added in 2.0) The creator opens a node fullscreen for focused editing, and/or attaches background audio / a motivation pop-up via the node toolbar.
The creator publishes the Quest.
The Quest will be published if it passes all validation checks (complete edges and node details).
Logic
Visual Canvas Hooks
useNodeActions()— provides core node operations (delete, add/update choices, update node data, labels, start/end toggles, archive/unarchive). It fires toast feedback vialib/node-toasts.ts(hooks/visual-canvas/useNodeActions.ts:10,106,166).useCanvasFunctions()— provides the canvas utility functions and ownsnodes/edges/archivedNodesstate and autosave.(Added in 2.0)
useNodeFullscreen()— returnsfullscreenNode,isModalOpen,openFullscreen,closeFullscreen,toggleFullscreen(hooks/visual-canvas/useNodeFullscreen.ts:47-53).
Constants and Helpers
getInitialData(type, quest_mode)— returns the correct default data shape for a newly created node based on its type (useCanvasFunctions.ts:93). Every node type has required fields (e.g.TextneedstextContent,Quizneedsquestions[]), so nodes are never created with missing data.NODE_GAP_VALUE— the legacy horizontal spacing constant (500) still used byadd_nodeand bydrag_reorder's index math (useCanvasFunctions.ts:130,1353,996).(Added in 2.0, PR #708)
TARGET_GAP = 60withgetNodeWidth(type)(code 540px, scenario 420px, else 320px) andgetXForIndex(nodes, i)— a cumulative accumulator that lays nodes out edge-to-edge with a uniform gap (useCanvasFunctions.ts:128-145). Used bylinear_refreshand the import/mode paths. Naming correction: PR #708 referred to this helper asgetIndexForX; the shipped function isgetXForIndex.(Added in 2.0, PR #708)
getBaseZIndex(nodeType)— Scenario = 1 (container bottom), Code = 11 (top), Question/Quiz = 10, default = 5; dragged nodes are temporarily bumped to 100 (useCanvasFunctions.ts:147-153).resolveImportCollisions(nds)— a post-render utility that runs after an AI canvas import. The layout service estimates node heights before React Flow measures them; once React Flow populatesn.measured?.height, this pushes overlapping game-over nodes downward until they clear all other cards. Runs up to 30 passes, sorted by Y position, and only moves game-over nodes (useCanvasFunctions.ts:175).reconstruct_edges(currentNodes)— builds a sequential chain of edges connecting each node to the next by index usingsource-right→target-lefthandle pairs (useCanvasFunctions.ts:1674-1697). Called whenever the linear node order changes. Returns edges withtype: "default"andanimated: true.start_end_indicators(nodes)— pure utility marking the first top-level nodeisStart(unless a user-set start exists), ensuring start ≠ end and skipping children (useCanvasFunctions.ts:1699-1727).(Added in 2.0)
hasMeaningfulCanvasChange(previousCanvas, nextCanvas)— JSON-comparesquest_mode,nodes(positions stripped, sorted by id) andedges(sorted); any difference means the published quest must be taken offline (lib/quest/hasMeaningfulCanvasChange.ts:19-31).(Added in 2.0)
lib/node-toasts.ts— client-onlyshowNodeDeletedToast,showNodeArchivedToast,showNodeRestoredToast(:18,28,38).(Added in 2.0, PR #708)
lib/utils/template-helpers.tsx— sharedTEMPLATE_ICONS,insertTemplate(...),getTemplateIcon(...)extracted from the duplicated Code editor template logic.
State
nodes/setNodes— ReactFlow node array — the live canvas state.edges/setEdges— ReactFlow edge array.nodesRef/edgesRef— refs that mirror node/edge state, used in callbacks where stale closure values would be a problem (e.g. smart merge).archivedNodesRef/archivedNodes— archived nodes are removed from the canvas but kept in state and saved to DB, both as a ref (synchronous access) and as React state (UI). Autosave now depends onarchivedNodes(useCanvasFunctions.ts:1148).currentLength— a ref tracking the previous node count, used bylinear_refreshto detect additions and deletions.draggedNodeId— tracks which node is currently being dragged; suppresseslinear_refreshcollision avoidance and gatesfilteredEdges.mergeDialog— controls the import merge dialog (open state, node counts, pending import data).importedCount— number of AI-imported nodes, shown in the success banner.hasLoaded— becomestrueonce the canvas has finished loading from DB (or confirmed empty); gates auto-save and mode effects.isSaving— drives the "Saving…" indicator.hasInitializedRef— prevents the canvas load effect from running more than once per mount.pendingCollisionResolutionRef— settrueafter an exploration import; tells the collision-resolution effect to fire once React Flow has measured all nodes.previousQuestMode— tracks the previous quest mode so the mode-conversion effect knows when a real switch happened.(Added in 2.0, PR #708)
reorderEpoch— plumbed throughReorderProviderintoCodeNode's Monaco remount key. Caveat: there is no setter (useCanvasFunctions.ts:255declaresconst [reorderEpoch] = useState(0)), so it is always0and effectively inert. The epoch-key remount is retained inCodeNode.tsx:79.
Effects
Canvas Load Effect (
useEffecton[questId, setNodes, setEdges, hasLoaded]) — runs once on mount. CheckssessionStoragefor an AI-generated curriculum first; if found, parses and imports it. For exploration mode it calls the layout API to compute collision-free positions before rendering; for linear mode it snaps nodes to the grid directly. Otherwise it loads existing canvas from the DB viaGET /api/creator/update-quest-canvas(or the reviewer API in read-only mode). Separates archived and active nodes on load, deduplicates by ID, and sets both into state.Collision Resolution Effect (
useEffecton[nodes]) — active only whenpendingCollisionResolutionRefis set (after an exploration import). Waits until every non-game-over node has a non-zeromeasured.height, then runsresolveImportCollisionsexactly once and clears the ref.Auto-save Effect (
useEffecton[nodes, edges, questId, hasLoaded, archivedNodes]) — debounces canvas saves with a 2-second timer (useCanvasFunctions.ts:1136). On every node/edge/archived change, cancels any pending save and schedules a new one. Sends the full state (nodes + edges + archived nodes) toPUT /api/creator/update-quest-canvas. Skipped entirely in read-only mode. Corrected in 2.0 (PR #760): the original guide omittedarchivedNodesfrom the dependency list. Without it, archived-only mutations (delete an archived node) never triggered a save and reappeared after refresh. Archive/unarchive/delete of archived nodes now also persist immediately viasaveCanvasNow({ force: true })and roll back on failure.linear_refreshEffect (useEffecton[nodes, hasLoaded]) — runs on every node change in linear mode (useCanvasFunctions.ts:1161). Two jobs: (1) snap any off-grid node back to itsgetXForIndexx-position and updateisStart/isEndflags; (2) reconstruct edges when node count or positions change. UsescurrentLength.currentto detect additions/deletions; only callssetNodes/setEdgeswhen something actually needs to change. Actual measured widths (n.measured?.width) are read here, not in the spacing helper.Mode Conversion Effect (
useEffecton[previousQuestMode.current, questMode, hasLoaded]) — fires when the mode switches. Repositions nodes to the linear grid when switching to linear, or updatesquest_modein node data when switching to exploration; reconstructs linear edges.
Canvas Functions
add_node(e)— theonDrophandler (useCanvasFunctions.ts:1351). Determines what was dropped and where: a Node bar item onto a Scenario → adds it as a child; a Node bar item onto empty canvas → creates a standalone node, placed at the end and auto-connected in linear mode; a Canvas node onto a Scenario → converts it to a child and removes it from the canvas; a Scenario child dragged out → converts it back to a standalone node, sorting by drop x-position in linear mode.drag_over_node(e)— theonDragOverhandler; setsdropEffect: "move".drag_start_node(event, draggedNode)— setsdraggedNodeId; suppresseslinear_refreshand switches<ReactFlow>tofilteredEdgesfor the ghost preview.drag_x_node(event, draggedNode)— theonNodeDraghandler in linear mode. Corrected in 2.0 (PR #708): it is now pure-visual — it only updates the dragged node's position and the in-memory order; it does not splice arrays, callsetEdges, or save during the gesture.drag_reorder_commit(event, draggedNode)— theonNodeDragStophandler; clearsdraggedNodeId, then converts to a child (dropped on a Scenario) or commits the reorder and reconstructs edges.drag_reorder(currentNodes, draggedNode)— pure utility computing the new index from the dragged node's current x-position and returning a reordered copy.filteredEdges— a derived value (not a function) computed each render; callsreconstruct_edgeson nodes excluding the dragged node (useCanvasFunctions.ts:2421). Used as theedgesprop only during an active linear drag.connect_node(params)— theonConnecthandler for exploration mode; guards duplicatesourceHandlethen adds an edge (useCanvasFunctions.ts:1730-1749).flag_node(changes)— theonNodesChangehandler with three branches: Removal (drops the nodes, clearsisEndif the end node was deleted, recalculatesisStart/isEnd); Exploration mode (intercepts position changes and applies collision avoidance beforeapplyNodeChanges, up to 10 passes); Linear / other (passes changes through unchanged) (useCanvasFunctions.ts:1752-1859).start_end_indicators(nodes)— see Helpers.delete_all_nodes()— clears the entire canvas (useCanvasFunctions.ts:1861). It sets nodes/edges to empty and shows a toast; persistence is left to the debounced autosave.
AI & Import Functions
ai_import(selected)— adds AI-generated scenarios as Scenario nodes (each with a pre-populated Question child) in a horizontal batch, connected sequentially with dashed step edges (useCanvasFunctions.ts:2170).ai_scenarios_to_nodes(scenarios, existingNodeCount, batchIndex, batchId)— converts raw AI scenario data into ReactFlow nodes/edges; each scenario becomes a Scenario node with a Question child (useCanvasFunctions.ts:2197).import_to_flownode(canvasData)— converts aCanvasMetadataobject into ReactFlow nodes/edges. In linear mode it snaps to the grid and enforces a sequential chain; in exploration mode it preserves branching topology and assigns handles by relative node positions (useCanvasFunctions.ts:2053).create_content_cards_from_canvas(qId, importedNodes)— after an AI import, callsPOST /api/creator/convert-canvas-to-cardsto create publishable cards so the quest can be published (useCanvasFunctions.ts:2009).
Merge Functions
replace()— replaces the entire existing canvas with the pending import nodes and edges (useCanvasFunctions.ts:1871).cancel()— dismisses the dialog and keeps the existing canvas unchanged (useCanvasFunctions.ts:1886).smart(resolutions)— content-aware merge using user-confirmed resolutions; re-snaps linear results to the grid, or calls the layout API for exploration; only creates new cards for genuinely new nodes (useCanvasFunctions.ts:1897).
Node Lifecycle Functions (archive / delete / unarchive)
These are inline functions on the canvas return object.
delete_node(id, isChild?)— removes a node from the canvas (useCanvasFunctions.ts:2561). For child nodes it cleans up edges from their choice handles; for top-level nodes it reassignsisStartif the start node was deleted.archive_node(id, isChild?)— moves a node out of the active canvas intoarchivedNodesRef/archivedNodes, markingisArchived: true, and removes its edges (useCanvasFunctions.ts:2663).unarchive_node(id, isChild?)— restores an archived node, clearsisArchived, and removes it from the archived collections (useCanvasFunctions.ts:2832).Corrected in 2.0 (PR #760):
archive_nodeandunarchive_node(child + non-child) now compute the next node array, write it to bothnodesRef.currentandsetNodes(...)synchronously, force-save (saveCanvasNow({ force: true })), and roll back plus showtoast.erroron failure. Archived scenario children keepposition: { x: 0, y: 0 }so payload building does not throw.delete_node's archived-node branch force-saves and rolls back; active-node deletion relies on the debounced autosave. Deletion/archiving/restoring now fire Sonner toasts vialib/node-toasts.ts.
Fullscreen (focus) mode — added 2.0 (PR #700)
useNodeFullscreen()+NodeFullscreenModal+NodeFullscreenContentare wired into bothlinear/page.tsx:26-28,72-78,254,452-469andexploration/page.tsx:28-30,64-70,153,339-356.Each openable node renders a
Maximize2button that callsopenFullscreen(id, data.type, nodeNumber)(e.g.nodes/TextNode.tsx:172-180,nodes/CodeNode.tsx:356-365,nodes/QuestionNode.tsx:291-300,nodes/ScenarioNode.tsx:203-212).On the canvas, only
onOpenFullscreenis threaded into nodes;isFullscreen={true}is set insideNodeFullscreenContent.tsx:87, not by the linear page. (The exploration implementation of this feature was sub-issue #451; #700 extended it to linear.)visual-canvas/page.tsxis only a router +ReactFlowProvider/DnDProvider— each mode renders its own<ReactFlow>(linear/page.tsx:417,exploration/page.tsx:296); there is no single shared canvas owner.
Node toolbar, background audio & motivation — added 2.0 (PRs #667, #680)
NodeToolbarrenders a Music icon (background audio) and a Sparkles icon (motivation) and expands toCanvasAudioSection/CanvasMotivationSectioninline (components/quest-editor/visual-canvas/NodeToolbar.tsx:45-98).CanvasAudioSectionsupports three source tabs — Local / URL / Assets (not "Upload Local / Via Link / From Assets"), a 10 MB client limit, acacheBustUrl-memoized preview, andconfirmPublishedEdit()gating on every mutation (CanvasAudioSection.tsx:64,75-78,143,152,158,172-175,180-203).CanvasMotivationSectionmirrors that pattern for Text / Image / Video / GIF / Audio motivations with an editable pop-up title (CanvasMotivationSection.tsx:47-54,279-396).Both are mounted through
NodeToolbar, which is rendered by all 12 node card components; 8 node files still carry unused directCanvasAudioSectionimports from the original design — the live render path isNodeToolbaronly.Scenario children get their own toolbar because each child card component (Text/Question/Code/…) renders
NodeToolbarwithisChild={true}andonUpdate; the sections are not literally insideScenarioNode.tsx.
Code node constraints — added 2.0 (PRs #708, #712, #800)
Text input: the Monaco container uses
nodrag nopan nokey nowheelso React Flow no longer swallows space/backspace or zooms the canvas while typing (nodes/CodeNode.tsx:75, PR #800).Length limit: red banner + character counter over 50,000, yellow warning at 45,000–50,000, auto-save paused when exceeded (
CodeNode.tsx:149,440,443,522-532). Server-side this is the 50,000-char guard inupdate-quest-canvas/route.ts:122-133.Stability:
MemoizedMonacoEditorwith an epoch-key remount,keepCurrentModel,overrideServices={{}}, and aflex flex-collayout replacing the oldgrid-cols-2toggle (CodeNode.tsx:57,74,79,97-98,502).
Exploration-only question handles — added 2.0 (PR #712)
Per-choice source handles on QuestionNode are gated by data.quest_mode !== 'linear' in both expanded and collapsed views (nodes/QuestionNode.tsx:519,620), so linear-mode questions do not expose choice handles.
INFRASTRUCTURE & OPERATIONS
Dependencies
Dependency | Notes |
|---|---|
React Flow node/edge state | Canvas renders entirely from |
| Validates DB canvas payload on load; invalid data falls back to an empty canvas ( |
dnd-kit | A modern drag-and-drop toolkit for reordering child nodes within a Scenario node |
Monaco Editor | Code editor used by Code nodes |
Sonner | Toast feedback for node delete/archive/restore |
Supabase (Postgres, Storage, Auth) | Canvas metadata, media objects ( |
Monitoring & Alerting
The Visual Canvas validation helper lives at lib/validation/quest-validation.ts. It defines validateQuestContent, which takes a CanvasMetadata object and returns an array of ValidationErrors found in the quest's nodes.
Validation Errors Structure:
export interface ValidationError { nodeId: string; nodeLabel: string; edgeLabel?: string; nodeType: string; edgeId?: string; error: string;}
Recursive Node Validation: validateNode validates individual nodes (text, image, video, code, file, link, audio, reflection, question, quiz, scenario). It first checks that required data exists, pushing an error when a field is missing, and recursively validates scenario children.
Quest Metadata Parsing: validateQuestContent checks that canvasMetadata exists, then iterates the nodes, tracking per-type counts to report precise errors.
Corrected / added in 2.0 (PR #760): publish validation now validates only active nodes. Archived nodes are filtered out of the top-level loop (quest-validation.ts:369-370), archived children are filtered from scenarios (:311-312), connectivity is evaluated over active nodes only (:401-417), and a quest with zero active nodes fails with Quest has no content nodes (:373-381). Archived nodes' edges are removed on archive, so they are never flagged as unconnected.
Publish/unpublish safeguard: hasMeaningfulCanvasChange compares the full node/edge set (archived nodes included) and moves a published quest back to draft on any canvas mutation, so learners never see an inconsistent version (app/api/creator/update-quest-canvas/route.ts:248-261; lib/quest/hasMeaningfulCanvasChange.ts:7-12). This is intentional, including deleting an archived node.
Server log strings for triage:
Source | Log |
|---|---|
|
|
|
|
|
|
Deployment Plan
Merge Visual Canvas changes into the development branch after a successful code review.
Deploy to the dev server.
Verify creator mode can load, edit, auto-save, and reload canvas data.
Verify
readonlyreviewer mode loads from the reviewer endpoint and does not auto-save.Test AI Import, smart merge, replace, and cancel flows.
Test archived node restore/delete behavior, including persistence across a hard refresh.
(Added in 2.0) Verify node fullscreen in both Linear and Exploration modes.
(Added in 2.0) Verify background audio and motivation sections on nodes (upload/link/assets; published-edit confirmation).
(Added in 2.0) Verify the 50,000-character Code-node limit (client banner + server rejection).
(Added in 2.0) Verify responsive dialogs (Archived Nodes, Import & Merge) and ≥44 px touch targets.
Promote to staging after dev review.
TESTING & QUALITY ASSURANCE
Test Strategy
Automated coverage (verified in 2.0)
Area | Test file | Notes |
|---|---|---|
Canvas schemas |
|
|
Curriculum import |
|
|
Add/connect nodes, drag into Scenario, Form↔Canvas sync |
| QA-026.1/2, QA-027; waits on |
Archive / restore persistence |
| QA-030/031; waits for the forced PUT |
Delete archived node |
| Deletes from the Archived Nodes dialog |
Duplicate nodes guard |
| Asserts two nodes, one edge, no duplicates |
Scenario logic / standalone question / AI seed & publish |
| Exercise branching/import/publish flows |
Corrected in 2.0: the original guide claimed unit tests for reconstruct_edges, start_end_indicators, and import conversion, plus integration tests for load/save and read-only mode. Only canvas schema and curriculum import unit tests exist; there are no unit/integration tests for reconstruct_edges, start_end_indicators, hasMeaningfulCanvasChange, validateQuestContent, archived-node handling, or the load/save route. Coverage there is E2E only.
Manual coverage
Canvas editing: add/drag/connect/delete nodes and edges; folder collapse and reordering; Scenario child drag-in/out.
Node toolbar: background audio (Local / URL / Assets, 10 MB limit, published-edit confirm) and motivation (all five media types, editable title).
Fullscreen: open/close in Linear and Exploration; per-node maximize button.
Archived nodes: archive, restore, delete permanently; persistence across refresh.
AI Import / merge: replace, smart merge, cancel; collision resolution after import.
Code nodes: typing behavior over Monaco, 45k warning, 50k limit banner, auto-save pause.
Read-only reviewer: loads via reviewer endpoint, no autosave.
Publishing: archived nodes excluded from validation; meaningful change unpublishes a published quest.
Known Limitations
The canvas is desktop-only; real-time collaboration is not supported.
(Documented 2.0)
motivationis not part of any node Zod schema; it survives only via.catchalland the canvas-sync layer. This is fragile if.catchallis ever removed.(Documented 2.0)
audio_urlis intentionally absent from Video and Audio node schemas.(Documented 2.0)
reorderEpochhas no setter, so theCodeNodeepoch-key remount is currently inert.(Documented 2.0) 8 node components still import
CanvasAudioSectiondirectly without using it (dead imports from the original inline design).(Documented 2.0)
QuestPlayercallsuseGlobalBackgroundAudio(...)but discards its return value (components/learner/QuestPlayer.tsx:249-252), so quest-level background audio has no UI control; only per-card audio drives theAudioIndicator.(Documented 2.0) No automated tests cover
reconstruct_edges,start_end_indicators,hasMeaningfulCanvasChange, archived-node logic, or the canvas load/save route.
MAINTENANCE & SUPPORT
Troubleshooting
Canvas stays loading: confirm
questIdexists; confirm the correct API returns validcanvas_metadata(creator vs reviewer endpoint); checkcanvasMetadataSchemavalidation (invalid data loads an empty canvas by design).Canvas saves unexpectedly (Reviewer): confirm
questView === "readonly"is passed in reviewer mode; check the autosave effect inuseCanvasFunctionsand thesaveCanvasNowguard (:803).Linear edges are incorrect: check
reconstruct_edgesinuseCanvasFunctions; confirm nodes are ordered correctly before publishing.Archived node reappears after refresh: confirm the autosave effect depends on
archivedNodes; confirm the forced save inarchive_node/delete_node(archived branch) succeeded — a failed save rolls back and shows an error toast.Cannot publish — "Scenario has no content" / unconnected node: confirm the flagged node is not archived (archived nodes are excluded from validation); confirm the quest has at least one active node.
Code node rejects a save (character limit): the server returns HTTP 400 (via
ApiResponseHelper.validationError), not 422, with the node label and character count. ReducecodeContentto ≤ 50,000 characters.Fullscreen button does nothing: confirm the node renders
Maximize2and receivesonOpenFullscreen; the modal is rendered at the page level in bothlinear/page.tsxandexploration/page.tsx.Background audio / motivation does not appear on a node: confirm the node type supports it and
NodeToolbaris rendered by the card component; confirmnode.data.audio_url/node.data.motivationis populated and the quest is not read-only.Published quest unexpectedly moved to draft: expected — any canvas mutation (including deleting an archived node) triggers
hasMeaningfulCanvasChangeand unpublishes the quest.
Changelog
v1.0 (Feb 2026) — Initial implementation.
v2.0 (2026-09-30) — documented by Patrick Babala. See the Document version entry below.
Document version
2.0 – Updated by Patrick Babala, 2026-09-30. Overhauled for the current codebase:
Background audio on canvas nodes (PR #667):
CanvasAudioSectionwith Local / URL / Assets sources.Motivation pop-ups on canvas nodes (PR #680):
NodeToolbar+CanvasMotivationSection, plus canvas bug fixes.Node fullscreen in Linear mode (PR #700); original Exploration fullscreen is sub-issue #451.
Linear layout engine rewrite + Code-node stability (PR #708):
TARGET_GAP/getXForIndex/getBaseZIndex, pure-visual drag,MemoizedMonacoEditor, shared template helpers.Preview reset, exploration-only question handles, language detection, and the 50k Code limit (PR #712).
Archived-node publish validation + persistence + toasts (PR #760):
quest-validationexcludes archived nodes; forced save with rollback;lib/node-toasts.ts.Responsive dialogs and ≥44 px touch targets (PR #788).
Canvas CodeBlock input fix (PR #800):
nodrag nopan nokey nowheel.Corrections: primary issue link fixed (#31, not #81); sub-issues #160–#162, #249, #270, #280, #451 added; Supabase Auth; helper name
getXForIndex(notgetIndexForX); 50k rejection is HTTP 400 (not 422); test-coverage claims corrected; layered architecture diagram redrawn from code.
1.1 – Published, Add sub-category of Design to [2.2] Visual Canvas document, 06/30/2026
1.0 – Published, Feature pushed to dev server, 03/12/2026