[2.2] Visual Canvas

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_metadata with data.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 reordering

  • Zod for payload/schema validation

  • Monaco Editor (@monaco-editor/react) for Code nodes

  • Sonner 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_metadata is JSONB NOT NULL DEFAULT '{"nodes": [], "edges": []}'::jsonb (supabase/migrations/001_add_canvas_metadata.sql:27-29) with a structure check that nodes/edges exist and are arrays (:41-48) and a GIN index (:54-55). The DB check does not validate folders, quest_mode, node_folder_ids, or folder_positions.

  • At runtime the document also carries quest_mode, folders, node_folder_ids, and folder_positions (shared/schemas/questSchema.ts:78-85).

  • quests.quest_mode is the Postgres enum quest_mode_type (linear | exploration; 20260310_convert_quest_mode_text_to_enum.sql:9), NOT NULL DEFAULT 'exploration'.

  • quests.publishing_status is 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):

  • codeContent is capped at 50,000 characters (nodes.schema.ts:96); this is the schema half of the PR #712 limit, enforced server-side in update-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.

  • motivation is not declared on any node schema. It rides on node.data via the schemas' .catchall(z.unknown()) and is injected/read by lib/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[] with data.isArchived = true (useCanvasFunctions.ts:510-517, :742), so canvasMetadataSchema validates 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 empty
default 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-canvas
Triggered whenever a user adds, removes, or repositions elements on the canvas.
Rejects Code-node content over 50,000 characters; reverts a published quest to
draft when hasMeaningfulCanvasChange detects a real canvas mutation.
 
POST /api/ai/compute-canvas-layout
Used during exploration-mode AI imports and smart merges to compute better
node positions (delegates to Gemini; falls back to placeholder positions).
 
POST /api/creator/convert-canvas-to-cards
Converts 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 } via ApiResponseHelper.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 any Code node with codeContent.length > 50000 (:122-133). hasMeaningfulCanvasChange(existing, incoming) marks a published quest draft (:248-261).

  • GET /api/reviewer/get-canvas — reviewer GET; read-only is enforced client-side by selecting this endpoint when questView === "readonly" and by refusing saves in saveCanvasNow (useCanvasFunctions.ts:435-438, :803).

  • POST /api/ai/compute-canvas-layout — requires an authenticated user and assertNotSuspended; validates { canvas, questMode } and returns computeCanvasLayout(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, filters Scenario | 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

  1. The creator goes to the Visual Canvas.

  2. The creator drags a node from the Node bar and drops it onto the Canvas.

  3. The creator fills all necessary data within the Node (input fields, labels, file uploads, etc.).

  4. The creator creates an edge by dragging from the handle of a node and connecting it to another node's handle.

  5. The creator adds a Scenario Node onto the Canvas.

  6. The creator drops a node within the Scenario Node, making it a child node (the child node must not be a Scenario Node).

  7. The creator deletes unwanted edges or nodes (active or archived).

  8. (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.

  9. The creator publishes the Quest.

  10. The Quest will be published if it passes all validation checks (complete edges and node details).

Logic

Visual Canvas Hooks

  1. useNodeActions() — provides core node operations (delete, add/update choices, update node data, labels, start/end toggles, archive/unarchive). It fires toast feedback via lib/node-toasts.ts (hooks/visual-canvas/useNodeActions.ts:10,106,166).

  2. useCanvasFunctions() — provides the canvas utility functions and owns nodes/edges/archivedNodes state and autosave.

  3. (Added in 2.0) useNodeFullscreen() — returns fullscreenNode, 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. Text needs textContent, Quiz needs questions[]), so nodes are never created with missing data.

  • NODE_GAP_VALUE — the legacy horizontal spacing constant (500) still used by add_node and by drag_reorder's index math (useCanvasFunctions.ts:130,1353,996).

  • (Added in 2.0, PR #708) TARGET_GAP = 60 with getNodeWidth(type) (code 540px, scenario 420px, else 320px) and getXForIndex(nodes, i) — a cumulative accumulator that lays nodes out edge-to-edge with a uniform gap (useCanvasFunctions.ts:128-145). Used by linear_refresh and the import/mode paths. Naming correction: PR #708 referred to this helper as getIndexForX; the shipped function is getXForIndex.

  • (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 populates n.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 using source-right → target-left handle pairs (useCanvasFunctions.ts:1674-1697). Called whenever the linear node order changes. Returns edges with type: "default" and animated: true.

  • start_end_indicators(nodes) — pure utility marking the first top-level node isStart (unless a user-set start exists), ensuring start ≠ end and skipping children (useCanvasFunctions.ts:1699-1727).

  • (Added in 2.0) hasMeaningfulCanvasChange(previousCanvas, nextCanvas) — JSON-compares quest_mode, nodes (positions stripped, sorted by id) and edges (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-only showNodeDeletedToast, showNodeArchivedToast, showNodeRestoredToast (:18,28,38).

  • (Added in 2.0, PR #708) lib/utils/template-helpers.tsx — shared TEMPLATE_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 on archivedNodes (useCanvasFunctions.ts:1148).

  • currentLength — a ref tracking the previous node count, used by linear_refresh to detect additions and deletions.

  • draggedNodeId — tracks which node is currently being dragged; suppresses linear_refresh collision avoidance and gates filteredEdges.

  • 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 — becomes true once 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 — set true after 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 through ReorderProvider into CodeNode's Monaco remount key. Caveat: there is no setter (useCanvasFunctions.ts:255 declares const [reorderEpoch] = useState(0)), so it is always 0 and effectively inert. The epoch-key remount is retained in CodeNode.tsx:79.

Effects

  • Canvas Load Effect (useEffect on [questId, setNodes, setEdges, hasLoaded]) — runs once on mount. Checks sessionStorage for 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 via GET /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 (useEffect on [nodes]) — active only when pendingCollisionResolutionRef is set (after an exploration import). Waits until every non-game-over node has a non-zero measured.height, then runs resolveImportCollisions exactly once and clears the ref.

  • Auto-save Effect (useEffect on [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) to PUT /api/creator/update-quest-canvas. Skipped entirely in read-only mode. Corrected in 2.0 (PR #760): the original guide omitted archivedNodes from 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 via saveCanvasNow({ force: true }) and roll back on failure.

  • linear_refresh Effect (useEffect on [nodes, hasLoaded]) — runs on every node change in linear mode (useCanvasFunctions.ts:1161). Two jobs: (1) snap any off-grid node back to its getXForIndex x-position and update isStart/isEnd flags; (2) reconstruct edges when node count or positions change. Uses currentLength.current to detect additions/deletions; only calls setNodes/setEdges when something actually needs to change. Actual measured widths (n.measured?.width) are read here, not in the spacing helper.

  • Mode Conversion Effect (useEffect on [previousQuestMode.current, questMode, hasLoaded]) — fires when the mode switches. Repositions nodes to the linear grid when switching to linear, or updates quest_mode in node data when switching to exploration; reconstructs linear edges.

Canvas Functions

  • add_node(e) — the onDrop handler (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) — the onDragOver handler; sets dropEffect: "move".

  • drag_start_node(event, draggedNode) — sets draggedNodeId; suppresses linear_refresh and switches <ReactFlow> to filteredEdges for the ghost preview.

  • drag_x_node(event, draggedNode) — the onNodeDrag handler 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, call setEdges, or save during the gesture.

  • drag_reorder_commit(event, draggedNode) — the onNodeDragStop handler; clears draggedNodeId, 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; calls reconstruct_edges on nodes excluding the dragged node (useCanvasFunctions.ts:2421). Used as the edges prop only during an active linear drag.

  • connect_node(params) — the onConnect handler for exploration mode; guards duplicate sourceHandle then adds an edge (useCanvasFunctions.ts:1730-1749).

  • flag_node(changes) — the onNodesChange handler with three branches: Removal (drops the nodes, clears isEnd if the end node was deleted, recalculates isStart/isEnd); Exploration mode (intercepts position changes and applies collision avoidance before applyNodeChanges, 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 a CanvasMetadata object 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, calls POST /api/creator/convert-canvas-to-cards to 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 reassigns isStart if the start node was deleted.

  • archive_node(id, isChild?) — moves a node out of the active canvas into archivedNodesRef/archivedNodes, marking isArchived: true, and removes its edges (useCanvasFunctions.ts:2663).

  • unarchive_node(id, isChild?) — restores an archived node, clears isArchived, and removes it from the archived collections (useCanvasFunctions.ts:2832).

  • Corrected in 2.0 (PR #760): archive_node and unarchive_node (child + non-child) now compute the next node array, write it to both nodesRef.current and setNodes(...) synchronously, force-save (saveCanvasNow({ force: true })), and roll back plus show toast.error on failure. Archived scenario children keep position: { 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 via lib/node-toasts.ts.

Fullscreen (focus) mode — added 2.0 (PR #700)

  • useNodeFullscreen() + NodeFullscreenModal + NodeFullscreenContent are wired into both linear/page.tsx:26-28,72-78,254,452-469 and exploration/page.tsx:28-30,64-70,153,339-356.

  • Each openable node renders a Maximize2 button that calls openFullscreen(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 onOpenFullscreen is threaded into nodes; isFullscreen={true} is set inside NodeFullscreenContent.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.tsx is 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)

  • NodeToolbar renders a Music icon (background audio) and a Sparkles icon (motivation) and expands to CanvasAudioSection / CanvasMotivationSection inline (components/quest-editor/visual-canvas/NodeToolbar.tsx:45-98).

  • CanvasAudioSection supports three source tabs — Local / URL / Assets (not "Upload Local / Via Link / From Assets"), a 10 MB client limit, a cacheBustUrl-memoized preview, and confirmPublishedEdit() gating on every mutation (CanvasAudioSection.tsx:64,75-78,143,152,158,172-175,180-203).

  • CanvasMotivationSection mirrors 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 direct CanvasAudioSection imports from the original design — the live render path is NodeToolbar only.

  • Scenario children get their own toolbar because each child card component (Text/Question/Code/…) renders NodeToolbar with isChild={true} and onUpdate; the sections are not literally inside ScenarioNode.tsx.

Code node constraints — added 2.0 (PRs #708, #712, #800)

  • Text input: the Monaco container uses nodrag nopan nokey nowheel so 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 in update-quest-canvas/route.ts:122-133.

  • Stability: MemoizedMonacoEditor with an epoch-key remount, keepCurrentModel, overrideServices={{}}, and a flex flex-col layout replacing the old grid-cols-2 toggle (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 nodes/edges state — no separate store

canvasMetadataSchema (Zod)

Validates DB canvas payload on load; invalid data falls back to an empty canvas (shared/schemas/questSchema.ts:78-85)

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 (public-assets), and creator authentication

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

app/api/creator/update-quest-canvas/route.ts

Invalid canvas_metadata in database:, Database error:

app/api/creator/update-quest-canvas/route.ts

[Canvas→Form Sync] Failed: (non-fatal)

hooks/visual-canvas/useCanvasFunctions.ts

Canvas save failed: / save-error toasts

Deployment Plan

  1. Merge Visual Canvas changes into the development branch after a successful code review.

  2. Deploy to the dev server.

  3. Verify creator mode can load, edit, auto-save, and reload canvas data.

  4. Verify readonly reviewer mode loads from the reviewer endpoint and does not auto-save.

  5. Test AI Import, smart merge, replace, and cancel flows.

  6. Test archived node restore/delete behavior, including persistence across a hard refresh.

  7. (Added in 2.0) Verify node fullscreen in both Linear and Exploration modes.

  8. (Added in 2.0) Verify background audio and motivation sections on nodes (upload/link/assets; published-edit confirmation).

  9. (Added in 2.0) Verify the 50,000-character Code-node limit (client banner + server rejection).

  10. (Added in 2.0) Verify responsive dialogs (Archived Nodes, Import & Merge) and ≥44 px touch targets.

  11. Promote to staging after dev review.


TESTING & QUALITY ASSURANCE

Test Strategy

Automated coverage (verified in 2.0)

Area

Test file

Notes

Canvas schemas

tests/creator/utils/canvas-schemas.test.ts

canvasEdgeSchema, canvasNodeSchema, canvasMetadataSchema; empty-input defaults

Curriculum import

tests/creator/utils/canvas-import.test.ts

convertCurriculumToCanvas, validateCurriculumForImport (sequential chain)

Add/connect nodes, drag into Scenario, Form↔Canvas sync

tests/e2e/creator/visual-canvas.spec.ts

QA-026.1/2, QA-027; waits on PUT /api/creator/update-quest-canvas

Archive / restore persistence

tests/e2e/creator/node-archive-restore.spec.ts

QA-030/031; waits for the forced PUT

Delete archived node

tests/e2e/creator/delete-node.spec.ts

Deletes from the Archived Nodes dialog

Duplicate nodes guard

tests/e2e/creator/duplicate-nodes.spec.ts

Asserts two nodes, one edge, no duplicates

Scenario logic / standalone question / AI seed & publish

tests/e2e/creator/scenario-logic.spec.ts, standalone-question-node.spec.ts, ai-scenario-seed.spec.ts, publish-ai-scenario.spec.ts

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) motivation is not part of any node Zod schema; it survives only via .catchall and the canvas-sync layer. This is fragile if .catchall is ever removed.

  • (Documented 2.0) audio_url is intentionally absent from Video and Audio node schemas.

  • (Documented 2.0) reorderEpoch has no setter, so the CodeNode epoch-key remount is currently inert.

  • (Documented 2.0) 8 node components still import CanvasAudioSection directly without using it (dead imports from the original inline design).

  • (Documented 2.0) QuestPlayer calls useGlobalBackgroundAudio(...) 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 the AudioIndicator.

  • (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 questId exists; confirm the correct API returns valid canvas_metadata (creator vs reviewer endpoint); check canvasMetadataSchema validation (invalid data loads an empty canvas by design).

  • Canvas saves unexpectedly (Reviewer): confirm questView === "readonly" is passed in reviewer mode; check the autosave effect in useCanvasFunctions and the saveCanvasNow guard (:803).

  • Linear edges are incorrect: check reconstruct_edges in useCanvasFunctions; confirm nodes are ordered correctly before publishing.

  • Archived node reappears after refresh: confirm the autosave effect depends on archivedNodes; confirm the forced save in archive_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. Reduce codeContent to ≤ 50,000 characters.

  • Fullscreen button does nothing: confirm the node renders Maximize2 and receives onOpenFullscreen; the modal is rendered at the page level in both linear/page.tsx and exploration/page.tsx.

  • Background audio / motivation does not appear on a node: confirm the node type supports it and NodeToolbar is rendered by the card component; confirm node.data.audio_url / node.data.motivation is populated and the quest is not read-only.

  • Published quest unexpectedly moved to draft: expected — any canvas mutation (including deleting an archived node) triggers hasMeaningfulCanvasChange and 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): CanvasAudioSection with 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-validation excludes 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 (not getIndexForX); 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


Was this article helpful?