NE.Standard

Interactions and Effects

Two mechanisms make a component react to something besides its own bound values: an interaction, entirely client-side, and a client effect, which a command (or an interaction) hands the client to run.

Interactions

An interaction watches one component's event and writes a property on another — or on itself — with no round trip. Every visual component exposes them through VisualComponentBase<TComponent>.

The reference or id always names the source, never the target. The component the call is made on is the one whose property changes; the source argument — either the watched component instance itself (IVisualComponent / IBindableComponent, via UIComponentReference) or its string component id — is the component whose event or value is watched:

new StackPanelComponent()
    .SetVisibility(UIVisibility.Hidden)
    .InteractOnHoverStart(card, IVisualComponent.VisibilityProperty, UIVisibility.Visible)
    .InteractOnHoverEnd(card, IVisualComponent.VisibilityProperty, UIVisibility.Hidden)

Written the other way round it compiles and does nothing — the source would be a component that is hidden and can never raise the event. The single-argument overloads default the source to the component itself, which is why InteractBeforeClick(LoadingProperty, true) reads naturally.

Interact — comparing a value

public TComponent Interact(UIProperty property, UIComparisonOperator @operator = UIComparisonOperator.Equal,
    object? value = null, object? whenTrue = null, object? whenFalse = null)

public TComponent Interact(UIProperty source, UIProperty target, UIComparisonOperator @operator = UIComparisonOperator.Equal,
    object? value = null, object? whenTrue = null, object? whenFalse = null)

public TComponent Interact(string sourceComponentId, UIProperty source, UIProperty target,
    UIComparisonOperator @operator = UIComparisonOperator.Equal, object? value = null, object? whenTrue = null, object? whenFalse = null)

Watches source continuously and writes target to whenTrue or whenFalse depending on whether source @operator value holds. UIComparisonOperator has twelve members: Required, Equal, NotEqual, Greater, GreaterOrEqual, Less, LessOrEqual, Like, In, Regex, LikeIgnoreCase, RegexEach (every item of a list value matches — a multi-select's each key).

The source is heard both ways it can change: a value the server pushes, and the reader's own edit of the field that holds it — a switch turned on, a box ticked, a word typed — as it happens, before anything is sent. A value the server refuses and pushes back puts the target back with it.

InteractCopyValue — following another component's value live

public TComponent InteractCopyValue(string sourceComponentId, UIProperty target)
public TComponent InteractCopyValue(string sourceComponentId, UIProperty source, UIProperty target)

Copies the source's value — its Value, or the property named — into target as it is, with no comparison. It runs where Interact runs, and also while the reader drags a slider or types in a field: every input, at most once a frame, before anything is sent. So a slider previews what it sets with no round trip per step:

new ContainerComponent()
    .BindBackgroundImageDim(nameof(ChatController.WallpaperDim))
    .InteractCopyValue(DimSliderId, ISurfaceComponent.BackgroundImageDimProperty)

The preview is never sent: the slider's own binding sends the value it is let go on, and a target bound to the same state gets the server's value after that, as before — the same one, unless the server changed or refused it. Since nothing is converted on the page, the view refuses at compile time a target that cannot take the source's type: a number takes a number (a whole-number property refuses a fraction), a text property the reader's words, anything else its own type. Any other interaction still runs once, on the committed value.

InteractOn* — reacting to an event

public TComponent InteractBefore(string eventName, UIProperty target, object? value)
public TComponent InteractAfter(string eventName, UIProperty target, object? value)
public TComponent InteractBefore(string eventName, ClientEffect effect)
public TComponent InteractAfter(string eventName, ClientEffect effect)
public TComponent InteractBeforeClick(UIProperty target, object? value)
public TComponent InteractAfterClick(UIProperty target, object? value)
public TComponent InteractBeforeClick(ClientEffect effect)
public TComponent InteractAfterClick(ClientEffect effect)
public TComponent InteractOnHoverStart(UIProperty target, object? value)
public TComponent InteractOnHoverEnd(UIProperty target, object? value)
public TComponent InteractOn(string sourceEvent, UIProperty target, object? whenTriggered)

Any other event name goes through the last, general-purpose overload — InteractOn("focus", ...).

Each has overloads taking a source component instance (or sourceComponentId string) for watching another component, as do Interact, InteractCopyValue and ShowLoadingDuring. InteractBefore fires just before the command a component runs on that event dispatches — after a submit's validation, after a change's value reached the server; InteractAfter fires after the command's result — changes and effects — has been applied, or the connection dropped under it. Neither fires for a command refused before it leaves — a press repeated while its command runs, a form failing its rules. One asked of an event its source runs no command on does not compile: an event is named exactly as registered (EventNames.Click), and an item's event is asked on its template, not its host. The click pair is their shorthand. The other way round fails too: a plain InteractOn of an event its source runs a command on does not compile, since the page sends the command and never runs the interaction — an effect beside a command is written around it, a Send that puts the caret back in its composer as .OnClick(nameof(Send)).InteractAfterClick(new FocusEffect(composerId)). The after-pair runs on any answer, a failure and a dropped connection included: a Save that closes its dialog returns new CloseDialogEffect(key) from the command, so a failed Save keeps the dialog and what was typed in it. A rule reading a property its source does not have (ShownWhen over a toggle button, whose state is Pressed) does not compile either. Together they are the "busy while this round trip runs" idiom, and ShowLoadingDuring(eventName) is exactly this pair wired to Loading — for any event, and ShowLoadingDuring(sourceComponentId, eventName) for another component's (a form's panel while its button saves):

public TComponent ShowLoadingDuring(string eventName)
    => InteractBefore(eventName, IVisualComponent.LoadingProperty, true)
        .InteractAfter(eventName, IVisualComponent.LoadingProperty, false);

ButtonComponent.OnClickShowingLoading(command) is OnClick(command).ShowLoadingDuring(EventNames.Click), with the overloads OnClick has (arguments, OnClickShowingLoadingLiteral, OnClickShowingLoadingWithItemKey); a form's button is OnSubmitShowingLoading(formId, command), with arguments and OnSubmitShowingLoadingLiteral — busy for the command's round trip, and not at all when the form fails its rules. An item's or a row's event is its template's, so ShowLoadingDuring goes on the template and shows on that row.

This is one of two independent ways to say a control is busy — entirely client-side, nothing bound, nothing for a controller to clear. The other is binding Loading to a controller flag the command itself sets; that one starts and stops on the server's own timing, for when being busy outlives the single command. Using InteractBefore without a matching InteractAfter (or a binding that clears it) leaves a spinner that never stops.

An interaction may run a client effect instead of writing a property:

public TComponent InteractOn(string sourceEvent, ClientEffect effect)
public TComponent InteractOn(string sourceComponentId, string sourceEvent, ClientEffect effect)
public TComponent Interact(UIProperty source, ClientEffect effect, UIComparisonOperator @operator = UIComparisonOperator.Required, object? value = null)
public TComponent Interact(string sourceComponentId, UIProperty source, ClientEffect effect, UIComparisonOperator @operator = UIComparisonOperator.Required, object? value = null)

Only an effect whose CanRunInInteraction is true may be used this way — true only for an effect that completes entirely on the client, with no round trip behind it (see the table below). Any other effect fails the view's compile, so a NavigateEffect always goes through a command that returns it (a fixed address is a link, and NavigateBackEffect runs in an interaction); opening a dialog the view declares, a toast with no action ("Copied.") and a form's discard do not need one. An effect aimed at a component it cannot act on — a picker at anything but a file or image input, a row at anything but a list, table or tree, a rename at anything but a tree, a tabs view, a text or a text header region, text at anything but a field the reader types into (ICaretFieldComponent: a text input, a text area, a number input, a search's field, the code editor) — fails the compile, and the same from a command is dropped from its answer; a component derived from one of those (a data grid from a table) takes what its base takes, and a package's component drawing a caret field of its own implements ICaretFieldComponent. A language switch must name a language the application translates into.

An effect raised by an interaction inside a row finds its target in that row, or in an enclosing one, or outside the list altogether — the nearest that holds a component of that id — so a tile in an emoji panel's list inserts into the composer beside it, and a row's button focuses a field of its own row.

One entry's effect

A menu's entries share one command; an entry the page can answer alone takes an effect of its own, keyed by the entry, in place of that command:

new MenuComponent()
    .BindItems(nameof(Message.Actions), UIBindingScope.Relative)
    .OnItemClick(nameof(ChatController.MessageAction), UIAction.ArgCurrentItemKey("action"), UIAction.ArgParent("id", nameof(Message.Id)))
    .OnItemClick("copy", CopyToClipboardEffect.ValueOf(MessageTextId))
    .OnItemClick("copy", new ShowNotificationEffect("Copied."))

The copy entry's press runs both effects and sends nothing; every other entry sends MessageAction. The key is data, so bound entries take it as declared ones do, and it holds wherever the entry is pressed: a click, the keyboard, its shortcut, a long press's strip, the action bar. A menu standing in a row finds the effect's target in that row. OnItemClick(key, effect) is on every host with entries — a menu, a split button, a command bar, a button group, breadcrumbs, an items view — and a table's OnItemClick — a list's, a table's or a tree's — and a key-value action's OnActionClick take the same pair. Underneath it is InteractOnRow(eventName, rowKey, effect) on the entries' template, refused at compile on a component that stands in no row. In a nested menu (MenuItem.Items), rowKey matches either the leaf entry's own Id or any ancestor submenu group's Id, so .OnItemClick("phrases", InsertTextEffect.CurrentItemValue(ComposerId)) handles every bound child inside the "phrases" submenu without a round trip.

Client effects

A ClientEffect is something a command (or a qualifying interaction) hands the client to run after the result — changes first, then effects, so an effect that focuses or scrolls sees what the command just changed. Every targeted effect below (FocusEffect, ScrollToEffect, ScrollEffect, ScrollToItemEffect, RenameItemEffect, CopyToClipboardEffect.ValueOf, InsertTextEffect, OpenPickerEffect, ExpandFieldEffect) accepts a target component instance (UIComponentReference) directly beside a string targetComponentId. ClientEffectKinds lists the built-in kinds; a package can add its own by returning a new Kind string.

Effect Constructor Does In an interaction
NavigateEffect NavigateEffect(UINavigationRequest request), or (string address) Navigates the client to another route — while the page holds unsaved work, asking its controller first (see controllers). A route without a leading / gains it, as the route registry reads the one it was registered under. No
NavigateBackEffect NavigateBackEffect(string fallback = "/") The browser's Back where a page of this site stands behind, else fallback, an address of this site followed as a NavigateEffect's (see Going back, below). Yes
ReplaceAddressEffect ReplaceAddressEffect(IReadOnlyDictionary<string, object?>? parameters) Writes the page's state into its address in place: the route stays, the query becomes parameters, the current history entry is replaced. No page load, no new runtime, no leave guard (see routing). No
PushAddressEffect PushAddressEffect(IReadOnlyDictionary<string, object?>? parameters) The same as a new history entry, which Back undoes: the controller hears the entry it returns to in OnNavigatedAsync, on the same runtime. No
ConfirmLeaveEffect ConfirmLeaveEffect(string target) Asks in the framework's own dialog whether to leave a page holding unsaved work: Leave goes to target, Stay keeps the page. What OnLeaveRequestedAsync answers unless overridden. No
FocusEffect FocusEffect(string targetComponentId, params object?[]? dynamicParameters) Focuses a component. Yes
ScrollToEffect ScrollToEffect(string targetComponentId, ScrollToBehavior behavior, ScrollToBlock block, params object?[]? dynamicParameters) Scrolls a component into view. Yes
ScrollEffect ScrollEffect(string targetComponentId, ScrollPosition position, params object?[]? dynamicParameters) Scrolls a container (start/end/offset/page), as opposed to bringing a component into view. Yes
ScrollToItemEffect ScrollToItemEffect(string targetComponentId, string key, params object?[]? dynamicParameters), with Block and Behavior Brings the row of a list whose item has key into view — at the top unless Block says otherwise, the group header over it with it — and keeps it there while the window around it is read, until the reader scrolls. A command that reads a windowed source's window at the row (LoadWindowAsync) answers with it: a day jumped to, a search hit. Yes
DiscardFormEffect DiscardFormEffect(string formId) Drops a form's unsent edits: every OnSubmit field of the form shows the value the server holds again, and what its rules said of the form's fields goes with them (see binding, a form). The page holds that value, so a Cancel or a Discard runs it alone. Yes
OpenDialogEffect OpenDialogEffect(string dialogKey) Opens a dialog declared by the view; a key it does not declare fails the compile from an interaction, and is dropped from a command. Yes
CloseDialogEffect CloseDialogEffect(string dialogKey), with RaisesClose Closes a dialog; with RaisesClose it is the viewer's own close — an × in the dialog — and raises the dialog's OnClose as Escape does. With RaisesClose
ShowNotificationEffect ShowNotificationEffect(string message, UIColorStyle tone = UIColorStyle.Info), or (UIPhrase message, …) Shows a toast, its words translated on the page and again at a language switch. Without an Action
ShowSystemNotificationEffect ShowSystemNotificationEffect(string title, string? body = null), or (UIPhrase title, UIPhrase? body = null) Shows the operating system's notification, which reaches a reader not looking at the page, or its fallback where it does not show (see dialogs and notifications). No
RequestNotificationPermissionEffect RequestNotificationPermissionEffect() Asks the browser's permission prompt for system notifications and reports the answer to the runtime; a browser shows it only inside the reader's press, so raise it from an interaction. Yes
AnnounceEffect AnnounceEffect(string message, AnnouncePoliteness politeness = AnnouncePoliteness.Polite), or (UIPhrase message, …) Says the words to a screen reader and shows nothing — "12 results", "Saved", "Message sent" — politely, or at once with Assertive; translated as a toast's. Yes
DownloadFileEffect DownloadFileEffect(string requestPath, string fileName) Fetches a file staged through Context.Downloads; the path is single-use. No
SetThemeEffect SetThemeEffect(UIThemeMode? mode = null) Puts the client into a theme and persists it as the session's. Yes
SetThemeColorsEffect SetThemeColorsEffect(UIThemeColors? colors = null) Puts the reader's own primary and accent over the application's palette and keeps them on the session; none goes back to the application's (see theming). Yes
SetLanguageEffect SetLanguageEffect(string language) Switches the page to a language in place — its words written again, no navigation, and numbers, dates and timestamps without a custom Culture updated to the new culture pack; raised on the page, it stores the language in the session first. Yes
RenameItemEffect RenameItemEffect(string targetComponentId, params object?[]? dynamicParameters) / (string targetComponentId, string key, params object?[]? dynamicParameters) Opens the inline rename field on a standalone text or text header region (ExpanderHeaderRegion, CardHeaderRegion, TabCaptionRegion), or on one item of a tree or a tabs view, the way F2, a double-click or the tab menu's Rename does (even when Renamable is off; an item's CanRename = false still refuses it). Requires a writable BindRenamedTitle on the target or item template; aimed at any other component, the view does not compile. Yes
CopyToClipboardEffect CopyToClipboardEffect.Literal(string text) / .ValueOf(string targetComponentId, ...) Copies text, or what a component holds — a field's value, else the words it shows (a message's text in its row; a text's description line alone where it shows one, its title being a label) — to the clipboard. Yes
DevelopmentReportEffect DevelopmentReportEffect(string message) Writes an author's mistake to the page's console. The runtime sends it in Development in place of a command's effect it dropped. —
InsertTextEffect InsertTextEffect.Literal(string targetComponentId, string text, ...) / .CurrentItemKey(string targetComponentId, ...) / .CurrentItemValue(string targetComponentId, ...) Puts text at the caret of a field the reader types into (ICaretFieldComponent), in place of its selection, as typing would: the given text, the key of the row whose press raised it, or the clicked item's Value (IMenuItemModel.Value, falling back to its visible text) — the last two only in an interaction, since a command's result has no row (a command's is dropped). Yes
OpenPickerEffect OpenPickerEffect(string targetComponentId, params object?[]? dynamicParameters) Opens a file or image input's file chooser from another control — a composer's clip. A browser opens a chooser only inside the reader's own press, so raise it from an interaction; returned from a command it runs after the round trip, and the browser may refuse it. Yes
ExpandFieldEffect ExpandFieldEffect(string targetComponentId, params object?[]? dynamicParameters) Opens an expandable text area's or code editor's (SetExpandable) full-height modal editor from another control or a command, even when ShowButton is false or the field sits inside a collapsed expander. Aimed at a component that is no IExpandableInputComponent, the view does not compile. Yes
ShowImageEffect ShowImageEffect(string source, UIPhrase? caption = null), (IEnumerable<string> sources, int startIndex = 0), (IEnumerable<UILightboxImage> images, int startIndex = 0); ShowImageEffect.Of(string componentId, ...) / .AmongRows(string componentId) Shows a picture full size over the page, or a set of them from one — see below. An address no picture may be fetched from (javascript:, another site's //host) is refused as the effect is made. Yes

Showing a picture full size

ShowImageEffect is a lightbox the page draws by itself: the picture fitted to the window — shrunk to fit, never blown up past its own size — over a darkened backdrop. The picture is the only panel, so the bands beside a picture of another shape than the window are the backdrop: a press there closes it, as Escape and the × in the corner do. The focus stays in it while it is open and goes back to what opened it.

A set walks by the arrows at the picture's foot — shown while the pointer is over the picture or the keyboard's focus is on one, always on a touch screen — by ← and →, and by a swipe across, round past either end, with a counter between the arrows that keeps its width as it counts; a single picture shows none. The pictures slide as a strip: under a finger the picture follows it and its neighbour comes in from the side it is dragged away from, and a step slides the way it goes, round the end too; where the reader asks for less motion a step lands at once. Each picture may carry the words shown under it, and the words a screen reader says for it:

new ShowImageEffect(["/images/harbour.jpg", "/images/shore.jpg"], startIndex: 1);

new ShowImageEffect(
[
    new UILightboxImage("/images/harbour.jpg", "The harbour at dusk"),
    new UILightboxImage("/images/shore.jpg") { AltText = "A meteor over the shore" }
]);

Given a component instead, it reads the picture off the page as it runs — an image, or the first picture inside a surface: ShowImageEffect.Of(id). ShowImageEffect.AmongRows(id) shows the picture of the row the press came from among the ones the same component shows in its list's other drawn rows — a chat message's photos, walked without those of other messages. The shortest way is a surface round the picture, which also makes it a Tab stop that Enter and Space press:

new SurfaceComponent()
    .SetContent(new ImageComponent().BindSource(nameof(Photo.Source), UIBindingScope.Relative))
    .OnClickShowImage(amongRows: true)

From an interaction it runs with no round trip; returned from a command it shows after the answer, the pictures given.

Returning effects from a command

UICommandResult.Ok(effects) and UICommandResult.Fail(error, effects) both take an optional IReadOnlyList<ClientEffect>?. An effect the page could not carry out — naming a component or a dialog the view lacks, aimed at a component of the wrong kind, switching to a language the application does not translate into — is dropped and logged as an error, and in Development the page's console says so; the command's result stands, and a toast whose action could not be offered still shows its words:

private readonly List<int> _releases = [479, 480, 481];

[UICommand]
public UICommandResult AskBeforeDelete()
{
    if (_releases.Count == 0)
        return UICommandResult.Ok([new ShowNotificationEffect("Nothing left to delete.", UIColorStyle.Info)]);

    return UICommandResult.Ok([new OpenDialogEffect(ConfirmKey)]);
}

[UICommand]
public UICommandResult DeleteRelease()
{
    _releases.RemoveAt(_releases.Count - 1);

    return UICommandResult.Ok([new CloseDialogEffect(ConfirmKey), new ShowNotificationEffect("The release is gone.", UIColorStyle.Success)]);
}

ConfirmKey here is the Key of a UIDialog the view declared in CreateDialogs() — the whole confirmation, view and controller, is in dialogs and notifications.

How a failed command is reported

The client never inspects success/error directly — both delivery channels only ever apply changes and effects. A failed UICommandResult with no effects of its own therefore gets a ShowNotificationEffect attached automatically, and returning your own effects from a failure is how a command takes over the reporting. What that toast says, and where a failing page goes instead, is set by UIErrorHandlingOptions — see dialogs and notifications.

NavigateEffect takes a UINavigationRequest:

public sealed class UINavigationRequest
{
    public required string Route { get; init; }
    public IReadOnlyDictionary<string, object?>? Parameters { get; init; }
}
return UICommandResult.Ok([new NavigateEffect(new UINavigationRequest { Route = "/dashboard" })]);

Parameters become the route's navigation parameters — the same shape a query string produces on a direct request, read in OnNavigatedAsync(UINavigationRequest, …), which runs on a kept runtime too, where OnInitializeAsync does not run again (see controllers). They are appended to any query the route already carries, ahead of its fragment; an array is one pair per item, and an object goes as its JSON. new NavigateEffect("/notes?id=7") takes an address of the site as written, its query and fragment included — the target a leave was asked about (OnLeaveRequestedAsync). While the page holds unsaved work, a NavigateEffect from any command asks the controller as a link does, unless the same answer cleared the flag.

Going back

A page reached from another — a note opened from the list, a server from the fleet — leads its header with Back (UIPage.Header(leading, …), extensions). NavigateBackEffect is the browser's own Back, so it lands where Back would and is followed as Back is: an entry of this route's runtime is told to the controller (OnNavigatedAsync), one of another runtime of a route.Identity route is gone to in place, any other loads its page, and a page holding unsaved work asks first — its controller for a step within the route, the browser's own question for a page load. Back names no address a link could carry, so unlike a navigation it runs in an interaction, in the press itself:

UIIconButtons.Back().InteractOn(EventNames.Click, new NavigateBackEffect("/notes"))

Where nothing of this site stands behind the page — it was opened from a bookmark, a link from elsewhere, a new tab — the effect goes to its fallback instead ("/" unless given), as a NavigateEffect goes: the controller asked first while the page holds unsaved work. The page knows what stands behind it from the browser's Navigation API; a browser without it counts an entry the page wrote itself (PushAddressEffect) or a page of this site it was loaded from. Where back means a place of the application's rather than the last page — the tree a note was opened from, on a phone — give the button a command that answers with a NavigateEffect.

Scrolling components together

Scrolling is not an interaction: it is a position the page keeps for itself, many times a second, with nothing for the server to know. Components that should scroll together share a group name instead:

new CodeInputComponent()
    .SetLanguage(UICodeLanguages.Markdown)
    .SetScrollGroup("readme")

new ScrollContainerComponent()
    .SetScrollGroup("readme")
    .AddChild(new MarkdownDisplayComponent().BindText(nameof(Controller.Readme)))

Every component on the page with the same ScrollGroup follows the one the reader scrolls, whichever it is. A component that shows lines of a source and one that renders it — the code field and the Markdown display — are kept line against line, so a heading in the editor stands level with the same heading in the rendering; any other pair follows by the share of the way scrolled. What a component scrolls is its own: the code field's text, a table's rows, a scroll container itself.

Where to go next

  • Controllers for how a command is declared and what its return type may be.
  • Dialogs and notifications for the dialogs OpenDialogEffect/CloseDialogEffect target, toasts, and the error handling options.
  • Binding for the properties an interaction writes.