NE.Standard.UI.Graph

The node canvas

A node kind

[GraphNode(Category = "Maths", Title = "Operation", Color = "#8b5cf6")]
public sealed class OperationNode : IGraphNode
{
    [GraphInput(Title = "Left")]
    public double Left { get; set; }

    [GraphInput(Title = "Right")]
    public double Right { get; set; }

    [GraphInput(Choices = ["Add", "Subtract", "Multiply", "Divide"])]
    public string Operation { get; set; } = "Add";

    [GraphOutput]
    public double Result { get; set; }

    public void Execute(UINodeRunContext context)
        => Result = Operation switch
        {
            "Subtract" => Left - Right,
            "Multiply" => Left * Right,
            "Divide" => Left / Right,
            _ => Left + Right
        };
}

What the attributes decide

[GraphNode] — the kind as a whole:

Property Says
Key The name the document stores the kind under; unset, the class's name
Title The title the node and the picker show; unset, the class's name read as words
Description The line under the title in the picker
Category How the picker groups the kinds; a path nests a group, Maths/Rounding standing under Maths
Icon, Color The icon beside the title, and the node's colour (the viewer may change it)
MinWidth The floor of the node's width, in rem; the viewer drags a node wider by its corner
Resizable Whether the viewer may drag the node's corner to resize it — on unless set to false
ShowProgress Whether the node draws a progress bar while it runs — off by default; without it no status effect makes one appear
Hidden The picker leaves the kind out; a document that already uses it still loads, runs and draws it, and a copy or a paste can add it — a kind retired from the picker, never one kept from a viewer
Compact The node is drawn as a small box with its pins on its two ends and no head or fields — a reroute
AlwaysRuns The node runs every time, never handed on from its last run: it waits, reads or writes the disk, reads the clock

The icon is an icon value: a glyph name from whatever icon pack your application registered, or one of the framework's own ne- marks (UIGlyphs), which need no pack. The package names no glyph class of its own; its built-in menu entries wear UIGlyphs marks, and SetCommandIcon(UIGraphCommands.AddNode, …) replaces one with an icon value of your own.

[GraphInput] — a value with an input pin and the editor its type asks for:

Ask for Write
The pin's caption, and a tooltip on it Title (unset, the property's name read as words), Description
The hint inside an empty text or number editor Placeholder = "..." ("—" when unset); a wired input pin disables its inline editor (UINodePin.Enabled) while an edge feeds it
A pin with no editor PinOnly = true (literal values in UINode.Values are ignored)
An editor with no pin NoPin = true (already the default for choice, enum, ChoicesFrom and ChoicesKey inputs)
An input pin on a choice or enum editor HasPin = true (opt-in on choice, enum, ChoicesFrom and ChoicesKey inputs, which carry no pin unless HasPin = true, PinOnly = true, Display = true or Multiple = true is set)
A pin that takes several connections Multiple = true — the property is an array or a list, the pin's type is its element type, and the connected values arrive in the order of their edges
A value the node cannot run without Required = true — a run stops at the node with an error and skips everything below it
A pin shown only while another holds a value VisibleWhen = nameof(OtherInput), and VisibleValues = ["a", "b"] to name which values; a hidden pin is still saved and fed, and a parameter set out on it leaves the parameters column until it shows again
A combo box over a text Choices = ["a", "b"], ChoicesFrom = nameof(Members) naming a public static member, or ChoicesKey = "models" filled at runtime through NodesComponent.SetPinChoices / BindPinChoices
Several values out of a set An enum array, or Choices/ChoicesFrom/ChoicesKey on a string[] or List<string> — a list whose every row is a combo box
A picture, from the address the value holds, with a file the viewer sends the server Image = true (on a PinOnly input, the pin alone is a picture's); add Large = true for one large pressable surface instead of a thumbnail with its address
A pin that shows what a run put there rather than taking a value Display = true
How a display pin writes a number Format — a standard numeric format (N, F2, P, C) in the page's culture; not applied to an editable field
What a number editor accepts Min, Max, Step (a whole number steps by one on its own)
What the value is measured in Unit = "kg", written after the editor inside its box
What a text editor accepts MaxLength, MaxLines
How much room the editor takes Height (rem)
Where the pin stands Order — counted from one among its own side's pins; unset, the place the class declares it in
A value the node itself changes as it runs, kept for the next run State = true — never a pin; the node offers a button that puts it back to its default (see Running again and again)
Such a value kept out of sight State = true, Hidden = true — nothing drawn; the node's menu has Reset, which puts every state value of the node back to its default

A catalogue's text — a kind's title, category and description, a pin's caption, unit, choices and description — is the application's content, like a name the viewer gives a node: the node's head, its fields, the picker and its search, the parameters column, the log and the run line show it as written in every language, and it is never looked up nor reported as a missing word, whatever the application's KeyPrefixes. An application that wants its kinds in another language titles them in it. What the canvas says itself is words (GraphStrings): its menus and panels, the run and zoom controls, and a pin's type in its tooltip (ui.graph.type-* inside ui.graph.pin-type's {name} ({type})) — an enum or a class of the application's own is named by its name read as words (UINodePin.TypeTitle), which is the catalogue's and shows as written.

[GraphOutput] — an output pin of the property's type, with Title, Description and Order as an input has them; TypeOf = nameof(SomeInput) makes its type follow whatever is connected to that input, and Image = true makes a text output a picture's.

Pins are typed. A connection is allowed between matching types and always to or from object, the universal type; a picture and a text join, since a picture is an address. An input takes one edge unless it says Multiple = true; an output feeds any number. An array pin (T[], List<T>) accepts an array of the same element type or the universal array. Your own class is a pin type named by the class and connects to its own kind or to object.

A node's corners are the theme's card radius unless the canvas says otherwise: SetNodeCornerRadius(UICornerRadius.Uniform(0)) squares them, any other UICornerRadius rounds each corner as a bordered component's BorderRadius does, and BindNodeCornerRadius lets a setting change them while the sheet is open. The node's head and the ring of a chosen node follow each corner, and so does a group's frame and its chosen halo.

Running the network

UINodeCatalog catalog = UINodeCatalog.FromTypes(typeof(OperationNode), typeof(NumberNode), typeof(ResultNode));
UINodeRunner runner = new(catalog) { OnStatus = (id, state, progress, message) => … };

UINodeRunResult result = await runner.RunAsync(sheet);

The runner materializes the document into instances of your classes (catalog.Materialize(sheet, pinChoices), using runner.PinChoices or runs.PinChoices when choices come from ChoicesKey), walks them in the order their connections put them — a cycle is refused rather than followed — fills each node's inputs from the outputs feeding them, calls Execute, and answers every node's outputs. A kind that waits on something implements IGraphNodeAsync instead; one that does no work and has no pin — a note — is passed over. A node that throws fails, and its branch stops there while the rest of the sheet runs — wherever its code threw: in Execute, in a setter an input was fed through, in an output's getter, in HasMore or in a display pin's getter. The document may be the browser's, so a node with no id or no kind, one whose id an earlier node took, and an edge naming no pin are left out, as catalog.Materialize leaves out a node of a kind the catalogue does not know; when UINodeRunner.RunAsync runs a sheet containing an enabled node whose kind is missing from the current catalogue (for example, from an unloaded plugin on a BindCatalog canvas), reaching that node fails it cleanly with UIGraphWords.RunMissingKind and marks its downstream branch Skipped, while on the canvas its saved values and connected wires stay preserved until its kind returns.

A node turned off. A node's menu has Disabled, a check, for the node and every other chosen one: the node stands dimmed, and a run passes it over — UINode.Enabled is false, saved with the sheet, and UINodeCatalog.Materialize leaves the node out with every edge it has, so whatever walks the network does the same. What it fed gets nothing from it: an input it reached takes the value typed on it, or its kind's default, as though unwired — a required one stops its node as an unwired one would — and a pin that takes several keeps its other connections. The state and the displays the last run left on the node go when it is turned off. A group's menu has Disabled too, for the nodes standing wholly inside its frame as it opens, pinned ones among them: it turns them all off, or all on again when every one is off — checked then — as one step of the undo; it is unavailable on a frame with no node in it. It is an act on those nodes, not a state of the group: a node moved in later is not turned off, and the run knows nothing of groups. Reset values beside the node's own puts every input of the node back to its kind's default, as each pin's own Reset puts one — a kept state among them — and leaves its wires as they are; it is unavailable while nothing differs.

OnStatus is what a controller turns into SetNodeStatusEffects, and OnDisplay — what each display pin came to hold — into SetNodeDisplayEffects. Both reach a node without touching the document: a state colouring its frame, a progress bar only on a kind that says [GraphNode(ShowProgress = true)] (a message goes to the run line, not onto the node, where a line would shove its pins about), and a panel drawn from whatever shape the value turns out to have — a number, a text, a picture, a list of lines, a table of records, or an object's fields; a list or a record inside a cell or a field is written on one line, its entries joined as the page's language joins a list (Intl.ListFormat) and a record's field in the word ui.graph.display-field ({key}: {value}). What a display is sent is a readable share: a text past 10 000 characters or a list past 200 entries is cut short with what was left out said at its end in the page's words (ui.graph.more), and a record past 256 KB of JSON, or one that cannot travel as JSON, is sent as its text — a number JSON cannot spell too, NaN or an infinity, alone or inside a record; a state value on its way back to the canvas is sent the same way, and read as the number again on the next run.

A display draws a picture by type, never by what a text looks like. A text is drawn as a picture when the display pin is a picture's itself ([GraphInput(Display = true, Image = true)]) or the output feeding it is one — [GraphOutput(Image = true)], followed through anything that hands its input on (TypeOf: a Delay, a reroute); any other text is text, however much it looks like an address. A picture inside a record or a list has no pin to say so, so it says so itself: it is a UINodeImage (its address, and a Width and Height to draw it at if it has them), which travels marked as a picture.

[GraphOutput]
public UINodeImage Preview => new(Address, Width: 160, Height: 120);   // drawn at 160 by 120 in a display

[GraphOutput]
public UINodeImage[] Frames { get; set; } = [];                          // a list of pictures

Even a picture a type names is drawn only from an address the framework draws a picture from — this site, the web, an inline picture, judged as the browser reads the address (urls.isImageSource on the plugin surface) — or a local blob:; //host/… and /\host/… start with a slash but are another site's, and stay text. Pass the application's services to the runner (new UINodeRunner(catalog, services)) and a node reaches them through context.Services: a node kind is built from a parameterless constructor, so that is the way in.

Both hooks are awaited, so a run is watched as it runs rather than all at once when it answers — push each effect as it arrives instead of collecting them for the command's result:

// In a controller command; CanvasId is the NodesComponent's id.
UINodeRunner runner = new(catalog, Context.Services)
{
    OnStatus = (id, state, progress, message)
        => new(Context.SendEffectsAsync([new SetNodeStatusEffect(CanvasId, id, state) { Progress = progress, Message = message }], cancellationToken))
};

A node says how far along it is with context.ReportAsync("Reading", 0.4), or in a word of its own, context.ReportAsync(UIPhrase.Of("my.reading", ("file", name)), 0.4); only a kind that waits (IGraphNodeAsync) can, since a kind that runs straight through has nothing to say in the middle of itself. The message shows on the run line while the node runs; the fraction draws a bar only when the kind says [GraphNode(ShowProgress = true)].

What a run says travels as a UIPhrase. The runner's own messages are the package's words, written in the page's language — an input left empty (UIGraphWords.RunRequired, the input's title filling it as written), a node cut short by Stop (RunStopped), a node on a cycle (RunCycle), a value past its pin's MaxLength, Min or Max (RunOutOfBounds, unless an edge fills the input) or outside an enum/choice/ChoicesKey pin's allowed set (literal or wired, also RunOutOfBounds), a text output past the runner's MaxTextLength (RunTooLong, a million characters), a sheet past its MaxNodes (RunTooManyNodes, 2 000, refused whole and said on the run line), a folder's file (FileProgress); a run of all ends as Stop ends it past UINodeRuns.MaxRunTime (ten minutes), UINodeRunOutcome.TimedOut telling that end from a Stop. What a node says itself — ReportAsync, Log, the message of a UINodeFailureException it throws ("Division by zero.") — is its content, shown as written, as the catalogue's text is. Any other exception is named by its type alone and goes whole to the server's log, its message shown only with the runner's IncludeExceptionDetail; every built-in kind fails through UINodeFailureException. A kind that wants its line in the page's language reports or logs a phrase of its own keys, context.Log(UIPhrase.Of("my.key", ("count", n))). A catalogue's text passed into such a phrase — a pin's title, a node's name — goes as a plain argument, written as it is, never as UIPhrase.Text, which the page would look up.

Running again and again

A node can keep something between runs: a property marked [GraphInput(State = true)] is filled from the document like any value, and what the node leaves it at is reported (OnState) and written back — the next run starts from it. A node that hands out one item a run implements IGraphNodeSequence and says whether it has more; RunAllAsync runs the sheet until one such node has none left:

[GraphNode(Title = "Next id")]
public sealed class NextIdNode : IGraphNode, IGraphNodeSequence
{
    [GraphInput(State = true)]
    public int Issued { get; set; }

    [GraphOutput]
    public string Id { get; set; } = "";

    public bool HasMore => Issued < 100;

    public void Execute(UINodeRunContext context)
        => Id = $"item-{++Issued}";
}

A failure takes its branch and its run, and the next run goes on with the next item — one bad file does not stop a folder — unless the sequence node itself failed. The state a run changed is reported once the run is through, so a run stopped part way changes none of it: a folder's place moves on only for a file whose whole run happened, and the node cut short stands idle again. A collection kept as state may be changed in place — a list the node adds to counts as changed when its items did — and each run's node works on its own copy, so the document a run started from is not changed under it.

Handing on what has not changed

A runner given a cache (UINodeRunner.Cache, a UINodeRunCache) hands on what a node last came to when its inputs are the ones it last ran on, rather than running it again, and draws it Cached: a chain of pictures re-run with one number changed at its end reworks that end alone. The cache keeps a node's last run and no more, so it is never larger than the sheet. A node with state always runs, and so does a kind that does more than turn its inputs into its outputs — waits, reads or writes the disk, reads the clock — which says so with [GraphNode(AlwaysRuns = true)]. A node that fails forgets its own last run and those of every node above it, so the next run makes them afresh rather than handing the same thing on. UINodeRuns keeps one for its canvas; clear it (Cache.Clear()) when the sheet is replaced. Two counters make a loop inside a loop: the inner one's Wrapped into the outer one's Advance, the inner starting over, and the outer moves once a round of the inner — or one Range XY does it alone.

The canvas runs itself with its run panel and UINodeRuns, which does all of the above for a controller: Run and Run all save the sheet under a run's reason, the save command hands the save on, and every status, display, log line, progress and state reaches the canvas as it happens, the state kept on the controller's sheet too. The run line along the top (ShowRunProgress, on unless told otherwise) shows from the first run on and keeps the last run's end; before it, its room stays clear, so the corner menu and the run panel stand where they will stay. The reason is the browser's to send, so UINodeRuns.ShowRunPanel says what the view says: while it is off, a save under a run's reason runs nothing.

// The view
new NodesComponent(CanvasId)
    .SetShowRunPanel(true)
    .OnSave(nameof(Controller.SaveAsync), UIGraphArguments.Reason("reason"))
    .OnStop(nameof(Controller.Stop));

// The controller
private readonly UINodeRuns _runs;

public Controller()
{
    _runs = new UINodeRuns(CanvasId, Catalog, () => Sheet, sheet => Sheet = sheet) { ShowRunPanel = true };
}

[UICommand(ConcurrencyMode = UICommandConcurrencyMode.Background, MaxConcurrent = 4)]
public async Task<UICommandResult> SaveAsync(string reason, CancellationToken cancellationToken)
{
    UINodeRunOutcome? outcome = await _runs.SavedAsync(Context.SendEffectsAsync, Context.Runtime.InvokeAsync, Context.Services, reason, cancellationToken);   // null for a save and no run
    return UICommandResult.Ok();
}

[UICommand]
public void Stop() => _runs.Stop();

The panel's Stop runs OnStop(command); OnStop(command, arguments) and OnStopLiteral(command, …) pass arguments of their own. When Catalog changes at runtime (BindCatalog), pass () => Catalog to new UINodeRuns(CanvasId, () => Catalog, () => Sheet, ...) or assign _runs.Catalog = nextCatalog so subsequent runs read the active catalogue.

The save command is a background one: an ordinary command holds its tab until it answers, and the panel's Stop could not reach the server while a run of all goes on. It allows more than one run of itself at once (MaxConcurrent, one by default): an edit the viewer saves while a run of all goes on is a second run of the same command, which one would refuse. One run of the sheet goes at a time — a second asked for meanwhile is a save and no more — and the package needs nothing of the controller but the three things it hands in: where effects go, the runtime's own turn it writes the sheet in, and the services the nodes reach. The command runs beside its tab, so the state a run leaves is read onto the sheet and written back inside Context.Runtime.InvokeAsync, where a save the viewer makes at that moment cannot land between the two. A controller running the sheet itself hands OnState a committed SetNodeValueEffect (Committed = true, no step to undo) and writes the state back with UINodeDocument.WithValue, as UINodeRuns does.

The sheet's parameters

A canvas's parameters stand beside it, in a NodesParametersComponent aimed at it: a column of its own the page puts where it likes — beside the canvas in a container, or a pane of a PaneContainerComponent the viewer carries to either side (added with keepsSize, it keeps its width there). Only a canvas such a component is aimed at offers them. A right press anywhere on an input's row — its pin, its caption, its field — opens the pin's menu, and Add to parameters sets the input out in the column too: under its node's name, in the same field its node draws, bound to the same value, so an edit in either shows in the other. A press on the name brings the node into view; the cross, or Remove from parameters in the pin's menu, takes the input back out. The set is part of the document (UINodeDocument.Parameters), saved and undone with the sheet, and an application may set some out before the viewer sees it:

new NodesComponent(CanvasId);
new NodesParametersComponent()
    .SetCanvas(CanvasId);

Sheet = StartingSheet().WithParameters(new UINodeParameter("rate", nameof(RateNode.Percent)));

Only an input with a field of its own that no wire feeds can be one — text, number, boolean, date and time, choice; a picture, a list, a display, a pin-only input and a hidden state cannot, and the pin's menu does not offer them. Wiring an input takes it out of the parameters in the same step, so an undo brings both back, and one whose node leaves the sheet leaves the column. An input its node hides for now (VisibleWhen) leaves the column while it is hidden and comes back when it shows; the parameter stays in the document meanwhile. WithParameters refuses a wired input or a node the sheet lacks. A document comes back off the wire as the browser sent it, so a server reads a sheet's parameters through the catalogue — UINodeCatalog.ParametersOf(document) passes over any that may not stand (a hidden one among them), and CanBeParameter(document, parameter) answers for one.

The pin's menu stands over the node's wherever a pin's row is pressed; a line with a pin-only input and an output gives each half its own. A folded node has no rows, so each pin on its head opens its own pin's menu, as a reroute's two ends do. Beside the parameter entries, which only a canvas a parameters column is aimed at offers, it carries Reset: an input lets its wires go and takes its kind's default value back, an output lets its wires go — one step to undo. Reset is unavailable while the pin has nothing to reset, and on a read-only canvas every entry is.

A picture a node uploads

A picture pin's control sends the chosen file through the framework's own upload and raises graph-image-upload, naming the node, the pin, the selection and the file's name:

// In the view
new NodesComponent(Controller.CanvasId)
    .OnImageUpload(nameof(Controller.ImageUploadedAsync));

// In the controller
[UICommand]
public async Task<UICommandResult> ImageUploadedAsync(string node, string pin, string selection, string fileName, CancellationToken cancellationToken)
{
    UIUploadSelection chosen = await Context.Uploads.GetSelectionAsync(Context.Handle, selection, cancellationToken);
    var address = …;   // keep the file wherever this application keeps its pictures

    return UICommandResult.Ok([new SetNodeValueEffect(CanvasId, node, pin, address)]);
}

Where the picture is kept, and whether it is kept at all, is the application's own business; the pin shows nothing until the command answers. SetNodeValueEffect writes that one pin rather than pushing the whole document back, so the viewer's unsaved work survives it — and the canvas is left dirty, so save before running the sheet.

Whose document it is

The sheet on the canvas is the viewer's until they save it. Bind the value OnSubmit with a FormId, the framework's own way of holding an edit until it is sent:

// On the controller, beside CanvasId
public const string CanvasForm = "sheet-form";

// In the view
new NodesComponent(Controller.CanvasId)
    .SetFormId(Controller.CanvasForm)
    .BindValue(nameof(Controller.Sheet), mode: UIBindingMode.OnSubmit)
    .OnSave(nameof(Controller.SaveAsync), UIGraphArguments.Reason("reason"))

From the first edit the canvas holds its document: a value the server pushes meanwhile is not put on, so a flush that happens to carry the sheet cannot take the viewer's work with it. A save submits the form and the canvas stands unsaved until the command it raised has answered — a command that fails leaves it unsaved, as it should — and undoing back to the saved sheet lets the document go again. An application that means to put a sheet on sets the value and says so:

Sheet = StartingSheet();

return UICommandResult.Ok([new DiscardFormEffect(CanvasForm)]);

DiscardFormEffect lets the viewer's unsaved work go, and the canvas takes the server's sheet with a fresh undo history. A sheet of any size travels: the framework sends a value over 8 KB beside the connection, both ways.

A page whose document is the application's at once rather than the viewer's until Ctrl+S turns on AutoSave: every edit is saved as it is made, the save event carrying UIGraphArguments.AutoSaveReason, and a save still in flight queues the next behind it. The planner's builds do this, so a target named in the plan's panel is the build's goal before another tab is opened:

new ProductionGraphComponent("plan")
    .BindItems(nameof(Controller.Catalogue))
    .SetMode(UIProductionMode.Plan)
    .SetAutoSave(true)
    .SetFormId(Controller.PlanForm)
    .BindValue(nameof(Controller.Plan), mode: UIBindingMode.OnSubmit)
    .OnSave(nameof(Controller.SaveGoals));