Files
avcf/docs/API.md
adrien b8e8ef9113 overhaul: modular architecture, tests, doc generation, warning system, and UX improvements
- Modular block files: split into blocks-algo, blocks-data, blocks-proc
- New modules: sections.js (labelled canvas areas), proc-browser.js (procedure tree modal), lib-loader.js (lazy library loading), templates.js (project templates), errno-data.js (errno table)
- Test infrastructure: browser test suite (28 tests) and Node pure-function tests (75 tests)
- Warning system: unified .block-warn for disconnected inputs, unconnected error hooks, and zero-exit-in-error-path
- Error path highlighting: red flow paths and block borders for error-only subgraphs
- Input hooks: hidden by default, shown during linking; outputs always at bottom
- Block editor modal: pencil icon, colour picker for accent, compact field labels
- Doc generation: standalone node script extracts JSDoc -> docs/API.md (124 declarations)
- Persistence: save/restore sections, errno selection, block colours
- Fixes: _segmentsIntersect bug, WCEnd crash from closest(this), drawpath guard on detached elements
2026-06-22 18:31:23 +02:00

31 KiB
Raw Permalink Blame History

API Reference

Generated from JSDoc annotations in 16 source files.


dom.js

const svgNamespace

Line 19

SVG namespace URI, required when creating SVG elements via JS.

const STORAGE_KEY

Line 22

localStorage key for workspace persistence (save/load/new).


helpers.js

function splitValueAndUnit

Line 29

Parses a string like "5 km" into a numeric value and an optional unit suffix. Falls back to parsing the entire string as a bare number when no suffix is present.

Parameters:

Name Type Description
str string - e.g. "5 km", "42", ""
defaultNum number - fallback when parseFloat yields NaN

Returns: { numVal: number, unitSuffix: string|null — }

function rebuildSelect

Line 50

Replaces all options in a , preserving the current selection if it still exists.

Parameters:

Name Type Description
sel HTMLSelectElement - the select element to rebuild
placeholder string - text for the first (empty-value) option
values string[] - option value/label pairs to add
current string - currently selected value to attempt to preserve

function refreshQuantityOptions

Line 69

Refreshes every quantity-name dropdown (.var-type, .unit-type) by scanning all wc-quantity blocks in the data area.

function refreshUnitOptions

Line 92

Refreshes the unit-suffix dropdown on every datum block to show only units that match the datum's currently selected quantity.

function getDefaultUnitSuffix

Line 124

Looks up the default unit suffix for a given quantity name.

Parameters:

Name Type Description
quantityName string

Returns: string — default unit suffix, or "" if not found

function refreshDefaultUnitOptions

Line 141

Refreshes the default-unit dropdown on every quantity block with suffixes of matching unit blocks.

function refreshVarRefOptions

Line 171

Refreshes the variable-select dropdown on every wc-varref block in the algorithm pane. Scans all boolean, scalar, string, and array blocks.

function switchLibTab

Line 204

Activates the clicked library sub-tab and shows its corresponding pane.

Parameters:

Name Type Description
name string - library name (matches data-lib-name attribute)

const _dataSourceCache

Line 214

Type: WeakMap<HTMLElement,HTMLElement> Cache mapping data hooks to their source blocks.

function findDataSource

Line 222

Finds the block connected to a given data hook via any .flow-data path. Results are cached in _dataSourceCache.

Parameters:

Name Type Description
hook HTMLElement - the data hook button element

Returns: HTMLElement|null — the source block, or null if nothing is connected

function copyCode

Line 234

Copies the generated C code text to the clipboard.

function escapeString

Line 245

Escapes special characters for embedding in a C string literal. Handles backslash, double-quote, newline, carriage return, and tab.

Parameters:

Name Type Description
str string - raw string

Returns: string — escaped string safe for C "..." literals

const C_KEYWORDS

Line 253

Type: Set<string> C reserved keywords — toCName appends "_" to avoid clashes.

function toCName

Line 268

Converts a natural-language name into a valid C identifier. Lowercases, replaces non-alphanumeric chars with underscores, collapses runs of underscores, strips leading/trailing underscores, and prepends an underscore if the result starts with a digit.

Parameters:

Name Type Description
str string - natural name like "My Variable 2"

Returns: string — valid C identifier like "my_variable_2"

function deriveNaturalName

Line 284

Derives a human-readable natural name from a C function/tech name. Converts camelCase and snake_case to words, strips common prefixes.

Parameters:

Name Type Description
techName string - e.g. "SDL_CreateWindow", "glfwInit", "puts"

Returns: string — e.g. "Create Window", "Init GLFW", "Puts"

function commentPrefix

Line 316

Builds a C comment prefix from a variable's natural name and an optional comment.

Parameters:

Name Type Description
naturalName string - the human-readable variable name
comment string - the optional comment text

Returns: string — e.g. "// My Flag: indicates status\n" or "" when no comment

function resolveSourceName

Line 330

Resolves the ultimate C variable name from a block by checking for .var-name, .expr-name, and following .varref-select chains. Returns the empty string when nothing is found.

Parameters:

Name Type Description
block HTMLElement - any block that may hold a variable reference
[visited] Set - cycle detection set (internal use)

Returns: string — the C name, or ""

function refreshBlockWarnings

Line 349

Check every algorithm block and flag those without an incoming logic connection.

function refreshAll

Line 356

Runs all refresh passes in dependency order.


error.js

function showError

Line 12

Shows the error modal with the given message. The overlay is absolutely positioned and blocks all interaction until dismissed.

Parameters:

Name Type Description
msg string - message to display inside the error box

function closeError

Line 25

Hides the error modal. Triggered by clicking the × button, the overlay backdrop, or called programmatically.

Parameters:

Name Type Description
[ev] MouseEvent - event to check target matching

errno-data.js

const ERRNO_LIST

Line 6

Type: Array<{code:number, name:string, desc:string >}


draw.js

const EXT

Line 12

Type: number Pixels the path extends from a hook in its exit direction.

function routeBetween

Line 31

Routes a 45°-constrained polyline between two points. Returns the SVG path data (everything after the initial "M") as a string suitable for appending to an existing moveto.

Parameters:

Name Type Description
x1 number - start x
y1 number - start y
x2 number - end x
y2 number - end y

Returns: string — SVG path data segment (e.g. "L 100 50 L 150 50")

function resolveHook

Line 72

Resolves a hook DOM element, preferring the explicitly stored reference and falling back to the block's first .hook child.

Parameters:

Name Type Description
path SVGPathElement
which string - "from" or "to"

Returns: HTMLElement — the hook button

function getHookExit

Line 88

Computes the extended control point for a hook: the hook centre pushed EXT pixels in the hook's declared exit direction.

Parameters:

Name Type Description
hook HTMLElement - the hook button element
svgRect DOMRect - bounding rect of the SVG viewport

Returns: { x: number, y: number — }

function drawpath

Line 109

Draws (or redraws) an SVG connection path between two linked block hooks. Each segment starts by extending EXT pixels in the source hook's exit direction and ends by approaching from the target hook's exit direction. The middle portion uses 45°-constrained routing.

Parameters:

Name Type Description
path SVGPathElement - path element with fromHook / toHook references

function _linkFlow

Line 143

Programmatically connects two hooks with a logic flow link.

Parameters:

Name Type Description
fromBlock HTMLElement - source block element
fromHookSel string - CSS selector for the source hook (e.g. ".hook", "#hook-fore")
toBlock HTMLElement - target block element
toHookSel string - CSS selector for the target hook

Line 168

Begins showing a dashed shadow path from the given hook to the cursor.

Parameters:

Name Type Description
hook HTMLElement - the source hook button

function onShadowMove

Line 179

Updates the shadow path endpoint to follow the mouse.

Line 201

Removes the shadow path and stops tracking the mouse.

function resetLinkage

Line 211

Cancels any pending link operation and removes the shadow.

Line 223

Removes an SVG connection path and cleans up both blocks' flow arrays.

Parameters:

Name Type Description
path SVGPathElement - the flow path element to delete

sections.js

const _sec

Line 23

Internal state for the sections subsystem. @type {{ list: Array<{id:string, points:Array<{x:number,y:number}>, title:string}>, nextId: number, creating: boolean, curPoints: Array<{x:number,y:number}>, editingId: string|null, editOverlay: HTMLElement|null, previewPoly: SVGPolygonElement|null, previewLine: SVGLineElement|null, ghostCircles: SVGCircleElement[] }}

function _gridSize

Line 38

Returns: number — The CSS --grid-size value, defaulting to 25.

function _snap

Line 49

Snaps a coordinate value to the nearest grid multiple.

Parameters:

Name Type Description
v number

Returns: number —

function _snapAngle

Line 57

Constrains a new point to 0°, 45°, or 90° relative to the previous point. @param {{x:number,y:number}} prev @param {{x:number,y:number}} raw

Returns: {x:number,y:number — }

function _xy

Line 73

Converts a mouse event to grid-snapped coordinates relative to #draw-area.

Parameters:

Name Type Description
ev MouseEvent

Returns: {x:number, y:number — }

function _svgPt

Line 86

Converts absolute page coordinates to SVG-relative coordinates.

Parameters:

Name Type Description
x number
y number

Returns: {x:number, y:number — }

function _shoelace

Line 99

Computes the signed area of a polygon via the shoelace formula. Used to reject tiny/collinear sections. @param {Array<{x:number,y:number}>} pts

Returns: number —

function _ptInPoly

Line 116

Ray-casting point-in-polygon test. @param {Array<{x:number,y:number}>} pts Polygon vertices in order

Parameters:

Name Type Description
px number
py number

Returns: boolean —

function _segmentsIntersect

Line 134

Checks whether two line segments AB and CD intersect (including endpoints). @param {{x:number,y:number}} a @param {{x:number,y:number}} b @param {{x:number,y:number}} c @param {{x:number,y:number}} d

Returns: boolean —

function _rectPolyOverlap

Line 152

Checks whether a rectangle overlaps a polygon (any edge crossing or one fully containing the other). @param {Array<{x:number,y:number}>} pts Polygon vertices

Parameters:

Name Type Description
rx number Rectangle left
ry number Rectangle top
rw number Rectangle width
rh number Rectangle height

Returns: boolean —

function _pointsAttr

Line 180

Converts a points array to an SVG points attribute string ("x,y x2,y2 …"). @param {Array<{x:number,y:number}>} pts

Returns: string —

function _topLeftOf

Line 189

Returns the top-left-most point in a polygon (used for label positioning). @param {Array<{x:number,y:number}>} pts

Returns: {x:number,y:number — }

function _ensureSectionGroup

Line 199

Returns: SVGGElement|null — The <g class="sections-group">, creating it if needed.

function renderSection

Line 215

Renders one section as SVG polygon + text label. @param {{id:string, points:Array<{x:number,y:number}>, title:string}} s

function _removeSectionEls

Line 242

Removes all SVG elements for a given section ID. @param {string} id

function renderAllSections

Line 249

Re-renders every section from scratch.

function _showOverlay

Line 258

Shows the dimming overlay that blocks interaction with blocks/links during section editing.

function _hideOverlay

Line 270

Hides the dimming overlay.

function _clearPreview

Line 282

Removes all preview visuals (polygon, line, ghost circles).

function _updatePreview

Line 296

Updates the visual preview during polygon point placement. @param {Array<{x:number,y:number}>} pts Points placed so far @param {{x:number,y:number}|null} mouse Current snapped mouse position

function _onCreateClick

Line 335

Parameters:

Name Type Description
ev MouseEvent Handles a click during polygon creation (adds point or closes polygon).

function _onCreateMove

Line 357

Parameters:

Name Type Description
ev MouseEvent Updates the preview line during mouse movement in create mode.

function _onCreateDblClick

Line 365

Parameters:

Name Type Description
ev MouseEvent Finishes polygon creation on double-click.

function _finishSection

Line 375

Finalises a section from the placed points, adds it to the list, renders it, and exits create mode. @param {Array<{x:number,y:number}>} pts

function _cancelCreate

Line 386

Cancels section creation without saving.

function _exitCreateMode

Line 391

Cleans up all create-mode event listeners and preview elements.

function _onCreateKey

Line 406

Parameters:

Name Type Description
ev KeyboardEvent Handles Escape (cancel) / Enter (finish) during creation.

function enterCreateMode

Line 413

Enters polygon creation mode: sets up event listeners and the dimming overlay.

function _editTitle

Line 432

Shows an inline text input (via SVG foreignObject) to edit a section's title.

Parameters:

Name Type Description
id string Section ID

function _commitTitle

Line 471

Commits an edited section title and removes the editing foreignObject.

Parameters:

Name Type Description
id string
title string
fo SVGForeignObjectElement

function _cancelEdit

Line 485

Cancels section title editing without saving.

Parameters:

Name Type Description
id string

function _hideOverlayIfIdle

Line 495

Hides the overlay if neither creation nor editing is active.

function blockOnSectionBorder

Line 507

Checks whether a block's bounding rectangle overlaps any section polygon. Called during drag to prevent blocks from sitting on section borders.

Parameters:

Name Type Description
block HTMLElement A WCBlock element

Returns: boolean —

function saveSections

Line 520

Returns: Array<{id:string, title:string, points:Array<{x:number,y:number — >}>}

function restoreSections

Line 530

Deserialises and restores sections from saved data. @param {Array<{id?:string, title?:string, points?:Array<{x:number,y:number}>}>} data

function _onSectionClick

Line 546

Handles a click on a section polygon: selects it, shows draggable vertex handles.

Parameters:

Name Type Description
ev MouseEvent

function _deselectSection

Line 613

Deselects a section when clicking outside all section elements.

Parameters:

Name Type Description
ev MouseEvent

function deleteSelectedSection

Line 624

Deletes the currently selected/editing section.

function initSections

Line 638

Wires up section-related event listeners (SVG click, document click, delete key).


wcblock.js

class WCBlock

Line 18

Base class for all draggable, linkable flowchart and measurement blocks.


blocks-algo.js

class WCStart

Line 19

Program entry point. Cannot be deleted.

class WCEnd

Line 27

Program exit block with errno autocomplete. At least one must return 0.

class WCOutput

Line 36

Output description block. Provides inline documentation without generating code.

class WCDecision

Line 55

Conditional branch block; splits flow into yes/no branches and emits if/else C code.

class WCAssign

Line 137

Variable assignment block; writes to scalar/array/vector/string targets with data hooks.

class WCVarRef

Line 247

Read-only variable reference with data output hook; syncs type from selected variable.

class WCExpression

Line 281

Math expression block with LaTeX rendering via MathJax and dynamic variable data hooks.


blocks-data.js

class WCQuantity

Line 20

Measurement quantity definition: name, 7 SI base dimensions, min/max range, default unit.

class WCUnit

Line 67

Unit of measurement: name, associated quantity, suffix, SI factor, recursive SI resolution.

class WCBoolean

Line 140

Boolean variable: name, true/false value, optional comment. Generates C int.

class WCScalar

Line 173

Typed scalar variable with quantity, unit, SI conversion, and auto-sync between value and unit.

class WCVector

Line 291

N-dimensional vector variable with quantity, unit, SI conversion; generates C array.

class WCString

Line 428

String variable: name, value. Generates C string struct with malloc/memcpy.

class WCArray

Line 463

Typed C array variable with dynamic element list and optional vector dimension.


blocks-proc.js

const LIB_ICONS

Line 17

Type: Object<string,string> Maps library IDs to icon image paths for procedure call blocks.

class WCProcedure

Line 27

Procedure definition block with inputs/outputs/description/return-style. Lives in the Procedures tab.

const _FMT_SPEC_RE

Line 150

Type: RegExp Matches C printf-format specifiers, capturing the type character.

function _specDataType

Line 157

Maps a printf format specifier character to a C data type.

Parameters:

Name Type Description
spec string Single format character (e.g. "d", "f", "s")

Returns: string — "int", "double", or "string"

class WCProcCall

Line 166

Procedure call block with dynamic argument fields, format-string support, and error-handling hooks. Lives in the Algorithm tab.


wcprogram.js

class WCProgram

Line 24

Root container custom element; owns the flowchart workspace, block creation, and code generation.

const INCLUDE_MAP

Line 252

Maps library names to their C #include paths. Libraries not listed here use the default <{name}.h> convention.

const BLOCK_REGISTRY

Line 263

Type: Object<string,{cls:typeof WCBlock, template:string, prefix:string, getParent:(()=>HTMLElement)|null >}

const BLOCK_ACTIONS

Line 265

Type: Object<string,string> Maps toolbar action names to block tag names.

function registerBlock

Line 275

Registers a custom element class and adds it to the block registry and action map.

Parameters:

Name Type Description
tag string Custom element tag (e.g. "wc-decision")
cls typeof WCBlock Class constructor
prefix string ID prefix for auto-generated block IDs
creatable `string null`
getParent `(()=>HTMLElement) null`

const _connObserver

Line 299

Type: MutationObserver Watches SVG connections for changes and refreshes assign-block value visibility.


persist.js

function saveBlockData

Line 18

Reads the position and type-specific data from a single block element. Delegates to the block's saveData() method for type-specific fields.

Parameters:

Name Type Description
block HTMLElement - a WCBlock or WCProgram child element

Returns: { x: number, y: number, ... — }

function saveWorkspace

Line 33

Serialises the entire workspace to localStorage under STORAGE_KEY. Captures all blocks from algorithm, measurements, and data panes, plus every SVG connection path.

function restoreBlock

Line 97

Deep-clones a block by tag name and restores position + data onto it. Delegates to the element's restoreData() method for type-specific fields. @param {{ id: string, tag: string, data: object }} info - saved block descriptor

Returns: HTMLElement|null — the restored element, or null for unknown tags

function restoreGroup

Line 120

Restores a group of block descriptors into a container in a single pass. Creates each block, appends it, then calls restoreData on all of them. @param {{ id: string, tag: string, data: object }[]} infos - saved block descriptors

Parameters:

Name Type Description
container HTMLElement - parent element to append blocks into

function loadWorkspace

Line 134

Deserialises the workspace from localStorage and reconstructs all blocks, connections, and internal state. Existing user blocks are removed first.

function newWorkspace

Line 270

Clears the saved workspace (removes localStorage entry) and reloads the page, returning the app to its pristine default state.


lib-loader.js

const LOADED_LIBS

Line 13

Type: Set<string> Tracks which libraries have been loaded (prevents re-loading).

function _addProcParams

Line 24

Creates param rows on a procedure block and sets their name/type values. Follows the same pattern as WCProcedure.restoreData().

Parameters:

Name Type Description
proc HTMLElement A wc-procedure element
inputs Array<[string,string]> Array of [name, type] pairs
outputs Array<[string,string]> Array of [name, type] pairs

function getLibraryIndex

Line 115

Returns the loaded library index (synchronous after loadLibraryIndex).

Returns: Array<{id:string, name:string, group?:string — >}

function isLibraryLoaded

Line 125

Checks if a library has been loaded yet.

Parameters:

Name Type Description
libId string

Returns: boolean —

function markLibLoaded

Line 134

Marks a library as loaded (for user-created libs that don't have JSON files).

Parameters:

Name Type Description
libId string

proc-browser.js

function _buildTreeData

Line 16

Builds the tree data structure from all wc-procedure blocks and the library index.

Returns: Array<{label:string, items:Array<{qname:string, naturalName:string, techName:string, readonly:boolean — >, userDefined:boolean}>}

function _createGroupElement

Line 83

Creates a collapsible group DOM element in the procedure browser tree. @param {{label:string, items:Array, userDefined:boolean}} group

Parameters:

Name Type Description
[selectedQname] string QName to pre-select

Returns: HTMLElement —

function _applySearchFilter

Line 163

Filters the procedure tree by a search query, showing/hiding groups and items.

Parameters:

Name Type Description
query string
overlay HTMLElement The procedure browser overlay element

function _escapeHtml

Line 230

Escapes HTML special characters for safe innerHTML insertion.

Parameters:

Name Type Description
str string

Returns: string —

function _confirmSelection

Line 240

Confirms a procedure selection, closes the browser, and invokes the callback.

Parameters:

Name Type Description
qname string Qualified procedure name

function _cancelBrowser

Line 250

Cancels procedure selection, closes the browser, invokes callback with null.

function showProcedureBrowser

Line 264

Opens the procedure browser modal, builds the tree, and wires up search/cancel/select.

Parameters:

Name Type Description
selectedQname string
callback `(qname:string null)=>void`

templates.js

function _clearWorkspace

Line 16

Removes all user-created blocks, connections, library tabs and panes, resetting flow arrays and LOADED_LIBS. Used by templates (new project) and persist.js (load workspace, with keepStorage:true to preserve localStorage). @param {{ keepStorage?: boolean }} [opts]


app.js

function createDefaultMeasurements

Line 19

Pre-populates the Measurements tab with SI base and coherent derived types/units. 22 types and 22 units arranged in a 4-column grid. No prefixed units are created except kilogram (the SI base unit for mass).

function addLibTab

Line 118

Creates a library tab and its associated pane in the Procedures tab.

Parameters:

Name Type Description
libName string - library identifier
[makeActive] boolean - whether to mark the tab/pane as active

Returns: HTMLElement — the #procedures-area element inside the new pane

function switchTab

Line 170

Activates the clicked tab and shows its corresponding pane.

Parameters:

Name Type Description
name string - tab identifier (matches data-tab attribute and pane id suffix)

function setupUI

Line 183

Wires all static button click handlers (replaces inline onclick attributes).

function main

Line 426

Bootstraps the application: builds the flowchart canvas with start/end blocks, creates default SI measurements, optionally loads a saved workspace, then wires up all UI event listeners.