Adapt Raw hierarchy density and menu placement to touch layouts

This commit is contained in:
Joseph Doherty
2026-11-13 23:09:26 -05:00
parent 78bad3a6c9
commit c5a288b080
20 changed files with 855 additions and 33 deletions
@@ -27,7 +27,8 @@
<a class="btn btn-sm btn-outline-secondary" href="/fleet">Back to fleet status</a>
</div>
<div class="d-flex align-items-center mb-3 gap-2 flex-wrap">
<div class="ot-toolbar d-flex align-items-end mb-3 gap-2 flex-wrap">
<div class="ot-toolbar-field">
<label class="small text-muted mb-0" for="diag-node">Node</label>
<select id="diag-node" class="form-select form-select-sm" style="width:auto"
value="@_selectedNode" @onchange="OnNodeSelected">
@@ -41,9 +42,12 @@
<option value="@_selectedNode">@_selectedNode (not an Up member)</option>
}
</select>
<input type="text" class="form-control form-control-sm" style="width:220px"
placeholder="or type host:port…" @bind="_typedNode" @bind:event="oninput"
@onkeydown="OnTypedKeyDown" />
</div>
<label class="ot-toolbar-field small text-muted">Host:port
<input type="text" class="form-control form-control-sm" style="width:220px;max-width:100%"
placeholder="or type host:port…" @bind="_typedNode" @bind:event="oninput"
@onkeydown="OnTypedKeyDown" />
</label>
<button class="btn btn-sm btn-outline-primary" @onclick="UseTypedNodeAsync"
disabled="@(string.IsNullOrWhiteSpace(_typedNode))">Go</button>
<button class="btn btn-sm btn-outline-primary" @onclick="RefreshAsync"
@@ -1,3 +1,6 @@
@using Microsoft.JSInterop
@inject IJSRuntime MenuLayoutJS
@implements IAsyncDisposable
@* Reusable right-click / context menu.
Consumers get two (independently optional) triggers over one item list:
@@ -6,7 +9,8 @@
Mouse/touch open the menu anchored at the pointer (fixed positioning). Keyboard
activation of the "⋯" button carries no pointer coordinates, so the menu instead
anchors just below the button (absolute positioning inside the trigger wrap).
anchors below the measured button, clamped to the viewport. The local geometry adapter keeps
the original menu node in the native top layer when supported.
Outside-click (or a right-click elsewhere) closes via a transparent full-viewport
backdrop — no JS alert/confirm. Keyboard: Arrow up/down move selection, Enter/Space
activate, Esc closes; focus returns to the "⋯" trigger on close. *@
@@ -28,7 +32,7 @@
{
<span class="ctx-ellipsis-wrap">
<button type="button" class="ctx-ellipsis" title="@TriggerLabel" aria-label="@TriggerLabel"
aria-haspopup="true" aria-expanded="@_open" @ref="_ellipsisRef" @onclick="OpenAt">
aria-haspopup="true" aria-expanded="@_open" @ref="_ellipsisRef" @onclick="OpenFromTrigger">
&#x22EF;@* ⋯ MIDLINE HORIZONTAL ELLIPSIS *@
</button>
@if (_open && _anchorToEllipsis)
@@ -59,6 +63,13 @@
/// <summary>Contextual accessible name and tooltip for the native menu trigger.</summary>
[Parameter] public string TriggerLabel { get; set; } = "More actions";
private readonly string _menuId = "ctx-menu-" + Guid.NewGuid().ToString("N");
private string MenuItemId(int index) => _menuId + "-item-" + index;
private readonly SemaphoreSlim _menuLayoutGate = new(1);
private IJSObjectReference? _menuLayoutModule;
private Task? _menuLayoutDisposal;
private bool _menuLayoutDisposed;
private long _menuGeneration;
private bool _open;
private double _x;
private double _y;
@@ -69,12 +80,16 @@
private bool _focusMenuPending;
private bool _focusEllipsisPending;
// Mouse right-click / touch-tap carry real pointer coordinates → anchor the menu there
// (fixed). Keyboard activation of the "⋯" button dispatches a click with clientX/Y == 0
// (no pointer) → anchor the menu below the button instead of at viewport origin (0,0).
private void OpenAt(MouseEventArgs e)
// WebKit keyboard clicks have detail=0 even with nonzero coordinates.
// A native contextmenu event also has detail=0, so its invoker stays explicit.
private void OpenFromTrigger(MouseEventArgs e) => OpenMenu(e, e.Detail == 0);
private void OpenAt(MouseEventArgs e) => OpenMenu(e, anchored: false);
private void OpenMenu(MouseEventArgs e, bool anchored)
{
_anchorToEllipsis = e.ClientX == 0 && e.ClientY == 0;
if (_menuLayoutDisposed) return;
++_menuGeneration;
_anchorToEllipsis = anchored;
_x = e.ClientX;
_y = e.ClientY;
_activeIndex = FirstEnabledIndex();
@@ -85,6 +100,7 @@
private void Close()
{
if (!_open) return;
++_menuGeneration;
var returnFocus = _anchorToEllipsis; // keyboard-opened via the ⋯ button — restore its focus
_open = false;
_activeIndex = -1;
@@ -150,10 +166,10 @@
}
// The menu body, shared between the pointer-anchored (fixed) and ellipsis-anchored
// (absolute) placements so the item loop lives in exactly one place.
// (clamped fixed) placements so the item loop lives in exactly one place.
private RenderFragment RenderMenu(string cssClass, string? style) => __builder =>
{
<div class="@cssClass" style="@style" role="menu" tabindex="0" @ref="_menuRef" @onkeydown="OnKeyDown">
<div class="@cssClass" style="@style" role="menu" aria-label="@TriggerLabel" aria-activedescendant="@(_activeIndex >= 0 && _activeIndex < Items.Count ? MenuItemId(_activeIndex) : null)" tabindex="0" @ref="_menuRef" @onkeydown="OnKeyDown">
@for (var i = 0; i < Items.Count; i++)
{
var item = Items[i];
@@ -164,7 +180,7 @@
else
{
var index = i;
<button type="button" role="menuitem"
<button id="@MenuItemId(index)" type="button" role="menuitem" tabindex="0" @onfocus="() => _activeIndex = index"
class="ctx-item @(index == _activeIndex ? "active" : "")"
disabled="@item.Disabled"
@onclick="() => Activate(item)">
@@ -184,14 +200,69 @@
if (_focusMenuPending)
{
_focusMenuPending = false;
try { await _menuRef.FocusAsync(); }
catch { /* the menu may have closed before the focus round-trip completed */ }
var generation = _menuGeneration;
var menu = _menuRef;
var trigger = _ellipsisRef;
var anchored = _anchorToEllipsis;
var x = _x;
var y = _y;
var positioned = false;
await _menuLayoutGate.WaitAsync();
try
{
if (_menuLayoutDisposed || !_open || generation != _menuGeneration) return;
_menuLayoutModule ??= await MenuLayoutJS.InvokeAsync<IJSObjectReference>("import", "./_content/ZB.MOM.WW.OtOpcUa.AdminUI/js/tree-layout.js");
if (!_menuLayoutDisposed && _open && generation == _menuGeneration)
positioned = await _menuLayoutModule.InvokeAsync<bool>("placeMenu", menu, trigger, anchored, x, y);
}
catch (JSDisconnectedException) { }
catch (JSException) { /* The fixed visible fallback remains keyboard reachable. */ }
catch (InvalidOperationException) { /* prerender */ }
finally { _menuLayoutGate.Release(); }
if (!positioned && !_menuLayoutDisposed && _open && generation == _menuGeneration)
{
try { await menu.FocusAsync(); }
catch (JSDisconnectedException) { }
catch (JSException) { }
catch (InvalidOperationException) { }
}
}
if (_focusEllipsisPending)
{
_focusEllipsisPending = false;
try { await _ellipsisRef.FocusAsync(); }
catch { /* the trigger may have unmounted */ }
if (!_menuLayoutDisposed && !_open)
{
try
{
if (_menuLayoutModule is not null)
await _menuLayoutModule.InvokeVoidAsync("restoreMenuTrigger", _ellipsisRef);
else await _ellipsisRef.FocusAsync();
}
catch (JSDisconnectedException) { }
catch (JSException) { }
catch (InvalidOperationException) { }
}
}
}
/// <summary>Releases the local geometry module without changing any menu action.</summary>
/// <returns>The shared teardown operation.</returns>
public ValueTask DisposeAsync() => new(_menuLayoutDisposal ??= DisposeMenuLayoutAsync());
private async Task DisposeMenuLayoutAsync()
{
_menuLayoutDisposed = true;
++_menuGeneration;
await _menuLayoutGate.WaitAsync();
try
{
if (_menuLayoutModule is not null)
{
try { await _menuLayoutModule.DisposeAsync(); }
catch (JSDisconnectedException) { }
catch (TaskCanceledException) { }
}
}
finally { _menuLayoutGate.Release(); }
}
}
@@ -1,13 +1,13 @@
/* Scoped styles for ContextMenu. Colours come from the shared ZB.MOM.WW.Theme
tokens (theme.css) so the menu tracks the app palette. The kit is light-only —
Theme 0.3.1 ships no dark-scheme block, and neither does site.css or this file —
Theme 1.0.1 ships no dark-scheme block, and neither does site.css or this file —
so there is no dark variant to track. */
.ctx-surface {
display: inline;
}
/* Positioned wrap so a keyboard-opened menu can anchor below the "⋯" button. */
/* Preserve the trigger geometry measured by the local fixed-menu adapter. */
.ctx-ellipsis-wrap {
position: relative;
display: inline-block;
@@ -58,12 +58,12 @@
outline: none;
}
/* Keyboard-opened placement: anchored just below the "⋯" trigger instead of the pointer. */
/* Visible fixed fallback before the adapter measures the keyboard trigger. */
.ctx-menu--anchored {
position: absolute;
top: 100%;
left: 0;
margin-top: 0.25rem;
position: fixed;
top: 0.5rem;
left: 0.5rem;
margin-top: 0;
}
.ctx-item {
@@ -107,3 +107,9 @@
margin: 0.25rem 0.3rem;
background: var(--bs-border-color);
}
.ctx-menu { white-space:normal; max-width:calc(100vw - 1rem); max-height:calc(100dvh - 1rem); overflow:auto; }
@media (pointer:coarse) {
.ctx-ellipsis { width:44px; height:44px; }
.ctx-item { min-height:44px; }
}
@@ -22,14 +22,20 @@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers
@inject IRawTreeService Svc
@inject IJSRuntime TreeLayoutJS
@using Microsoft.JSInterop
@implements IAsyncDisposable
@* One flat, virtualized row list (R04 P5): only the rows in view render, and each expanded level
shows RawTreeRows.DefaultPageSize children before a "Show more" row. Flatten runs per render; it is
O(visible rows) with no allocation per node beyond one row struct, so every mutation path below
(reload, toggle, load) is picked up without separate invalidation. *@
<Virtualize Items="@RawTreeRows.Flatten(Roots)" ItemSize="30" OverscanCount="20" Context="row">
@RenderRow(row)
</Virtualize>
<div class="raw-tree-rows" role="region" aria-label="Raw hierarchy" tabindex="0"
data-density="@(_rowHeight == 44 ? "touch" : "compact")" style="@($"--raw-row-height:{_rowHeight}px")">
<Virtualize Items="@RawTreeRows.Flatten(Roots)" ItemSize="@_rowHeight" OverscanCount="20" Context="row">
@RenderRow(row)
</Virtualize>
</div>
@* --- Real modals + dialogs (one instance each for the whole recursive tree) --- *@
<DriverConfigModal @bind-Visible="_driverCfgVisible" DriverInstanceId="@_driverCfgId" OnSaved="DriverCfgSaved" />
@@ -63,6 +69,73 @@
NodeName="@_msgNodeName" OnClose="CloseMessage" />
@code {
private readonly string _densityId = "raw-density-" + Guid.NewGuid().ToString("N");
private readonly SemaphoreSlim _densityGate = new(1);
private DotNetObjectReference<RawTree>? _densityReference;
private IJSObjectReference? _treeLayoutModule;
private bool _densityDisposed;
private Task? _densityDisposal;
private int _rowHeight = 30;
private long _densityRevision = -1;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
await _densityGate.WaitAsync();
try
{
if (_densityDisposed) return;
_treeLayoutModule = await TreeLayoutJS.InvokeAsync<IJSObjectReference>("import", "./_content/ZB.MOM.WW.OtOpcUa.AdminUI/js/tree-layout.js");
if (_densityDisposed) return;
_densityReference = DotNetObjectReference.Create(this);
var coarse = await _treeLayoutModule.InvokeAsync<bool>("observeDensity", _densityId, _densityReference);
if (!_densityDisposed && _densityRevision < 0) await SetPointerDensity(0, coarse);
}
catch (JSDisconnectedException) { }
catch (JSException) { /* Keep the compact, internally consistent fallback. */ }
catch (InvalidOperationException) { /* prerender */ }
finally { _densityGate.Release(); }
}
/// <summary>Applies the current native pointer density to both rows and their virtualization estimate.</summary>
/// <param name="revision">Monotonic identity of the media-query observation.</param>
/// <param name="coarse">Whether the current pointer needs larger targets.</param>
/// <returns>The serialized render update.</returns>
[JSInvokable]
public Task SetPointerDensity(long revision, bool coarse) => InvokeAsync(() =>
{
if (_densityDisposed || revision <= _densityRevision) return;
_densityRevision = revision;
var height = coarse ? 44 : 30;
if (height == _rowHeight) return;
_rowHeight = height;
StateHasChanged();
});
/// <summary>Releases only the local density observer and its callback handle.</summary>
/// <returns>The shared teardown operation.</returns>
public ValueTask DisposeAsync() => new(_densityDisposal ??= DisposeDensityAsync());
private async Task DisposeDensityAsync()
{
_densityDisposed = true;
await _densityGate.WaitAsync();
try
{
if (_treeLayoutModule is not null)
{
try
{
await _treeLayoutModule.InvokeVoidAsync("stopDensity", _densityId);
await _treeLayoutModule.DisposeAsync();
}
catch (JSDisconnectedException) { }
catch (TaskCanceledException) { }
}
}
finally { _densityReference?.Dispose(); _densityGate.Release(); }
}
private readonly string _labelScope = "raw-control-" + Guid.NewGuid().ToString("N") + "-";
/// <summary>The top-level Raw nodes to render (the enterprise roots from <c>LoadRootsAsync</c>).</summary>
[Parameter, EditorRequired] public IReadOnlyList<RawNode> Roots { get; set; } = default!;
@@ -179,17 +252,17 @@
@RenderNode(row.Node, row.Depth)
break;
case RawTreeRowKind.Loading:
<div @key="row.Key" class="small text-muted py-1" style="@($"padding-left:{row.Depth * 18}px")">
<div @key="row.Key" class="raw-tree-row small text-muted" style="@($"padding-left:{row.Depth * 18}px")">
<span class="spinner-border spinner-border-sm me-1"></span>Loading&hellip;
</div>
break;
case RawTreeRowKind.Error:
<div @key="row.Key" class="small text-danger py-1" style="@($"padding-left:{row.Depth * 18}px")">
<div @key="row.Key" class="raw-tree-row small text-danger" style="@($"padding-left:{row.Depth * 18}px")">
@row.Node.Error
</div>
break;
default:
<div @key="row.Key" class="small py-1" style="@($"padding-left:{row.Depth * 18}px")">
<div @key="row.Key" class="raw-tree-row small" style="@($"padding-left:{row.Depth * 18}px")">
<button type="button" class="btn btn-sm btn-link p-0" aria-label="@($"Show {Math.Min(row.Remaining, RawTreeRows.DefaultPageSize)} more ({row.Remaining} not shown) under {row.Node.DisplayName}")" @onclick="@(() => ShowMore(row.Node))">
Show @Math.Min(row.Remaining, RawTreeRows.DefaultPageSize) more
(@row.Remaining not shown)
@@ -208,7 +281,7 @@
var muted = node.Enabled == false && node.Kind is RawNodeKind.Driver or RawNodeKind.Device;
var items = _menus.GetOrBuild(node, PickerMode, MenuFor);
<div @key="node.Key" class="d-flex align-items-center gap-1 py-1" style="@indent">
<div @key="node.Key" class="raw-tree-row d-flex align-items-center gap-1" style="@indent">
@if (hasExpander)
{
<button type="button" class="btn btn-sm btn-link p-0 tree-twist"
@@ -238,12 +311,14 @@
// The icon + label + badge shown for a node — the ContextMenu right-click surface.
private RenderFragment RenderRowBody(RawNode node, bool muted) => __builder =>
{
<span class="d-inline-flex align-items-center gap-1">
<span class="raw-node-body d-inline-flex align-items-center gap-1">
@if (PickerMode && node.Kind == RawNodeKind.Tag)
{
<label class="raw-select-target">
<input type="checkbox" class="form-check-input me-1" aria-labelledby="@(_labelScope + Convert.ToHexString(System.Text.Encoding.UTF8.GetBytes(node.Key)))"
title="@($"{node.Kind} {node.Key}")" checked="@IsTagSelected(node)"
@onchange="@(e => ToggleTagSelection(node, e.Value is true))" />
</label>
}
<span aria-hidden="true">@KindIcon(node.Kind)</span>
<span id="@(_labelScope + Convert.ToHexString(System.Text.Encoding.UTF8.GetBytes(node.Key)))" class="mono small @(muted ? "text-muted" : "")">@node.DisplayName</span>
@@ -59,3 +59,25 @@
.rise {
animation-fill-mode: backwards;
}
/* Raw hierarchy owns a bounded scroll viewport so indentation and complete node
names stay local. Every virtual item uses the same measured density estimate. */
.raw-tree-rows { max-width:100%; max-height:60vh; max-height:60dvh; overflow:auto; }
.raw-tree-row { height:var(--raw-row-height,30px); min-height:var(--raw-row-height,30px); width:max-content; min-width:100%; box-sizing:border-box; white-space:nowrap; padding-top:0; padding-bottom:0; }
.raw-node-body { height:var(--raw-row-height,30px); white-space:nowrap; }
.raw-tree-rows .tree-twist { display:inline-flex; align-items:center; justify-content:center; height:var(--raw-row-height,30px); }
.raw-tree-rows[data-density="compact"] .ctx-ellipsis { width:28px; height:28px; }
.raw-select-target { display:inline-flex; align-items:center; justify-content:center; width:24px; height:var(--raw-row-height,30px); margin:0; cursor:pointer; }
.raw-select-target .form-check-input { margin:0!important; }
.raw-tree-rows[data-density="touch"] .tree-twist { width:44px; flex-basis:44px; }
.raw-tree-rows[data-density="touch"] .ctx-ellipsis,
.raw-tree-rows[data-density="touch"] .raw-select-target { width:44px; height:44px; }
.raw-tree-row > .btn { min-height:var(--raw-row-height,30px); }
@media (pointer:coarse) {
.ot-toolbar .btn, .ot-toolbar .form-control, .ot-toolbar .form-select { min-height:44px; }
}
.ot-toolbar { min-width:0; max-width:100%; }
.ot-toolbar .form-control, .ot-toolbar .form-select { max-width:100%; min-width:0; }
.ot-toolbar-field { flex:1 1 12rem; min-width:0; max-width:100%; margin:0; }
.ot-toolbar-field > label { display:block; }
@@ -0,0 +1,92 @@
// App-local geometry only. No node data, service calls or mutation actions.
const densityObservers = new Map();
const keyGuards = new WeakSet();
export function observeDensity(id, callback) {
stopDensity(id);
const media = matchMedia('(pointer: coarse)');
const state = { media, revision: 0, changed: null };
state.changed = () => callback.invokeMethodAsync('SetPointerDensity', ++state.revision, media.matches)
.catch(() => stopDensity(id));
media.addEventListener('change', state.changed);
densityObservers.set(id, state);
return media.matches;
}
export function stopDensity(id) {
const state = densityObservers.get(id);
if (!state) return;
state.media.removeEventListener('change', state.changed);
densityObservers.delete(id);
}
const positionedMenus = new Map();
function releaseMenu(menu) {
const state = positionedMenus.get(menu);
if (!state) return;
removeEventListener('resize', state.reposition);
state.observer.disconnect();
positionedMenus.delete(menu);
}
new MutationObserver(() => {
for (const menu of positionedMenus.keys()) if (!menu.isConnected) releaseMenu(menu);
}).observe(document.documentElement, { childList: true, subtree: true });
function repositionMenu(state) {
const { menu, trigger, anchored } = state;
if (!menu.isConnected) { releaseMenu(menu); return; }
menu.style.left = '0px';
menu.style.top = '0px';
const box = menu.getBoundingClientRect();
let { x, y } = state;
if (anchored && trigger?.isConnected) {
const anchor = trigger.getBoundingClientRect();
x = anchor.left;
y = anchor.bottom + 4;
}
const left = Math.max(8, Math.min(x, innerWidth - box.width - 8));
const top = Math.max(8, Math.min(y, innerHeight - box.height - 8));
menu.style.left = `${left - box.left}px`;
menu.style.top = `${top - box.top}px`;
}
export function placeMenu(menu, trigger, anchored, x, y) {
if (!menu?.isConnected) return false;
if (!keyGuards.has(menu)) {
menu.addEventListener('keydown', event => {
const item = event.target instanceof Element && event.target.closest('[role="menuitem"]');
if (item && ['Enter', ' '].includes(event.key)) {
// The focused button's native click owns activation. Do not also
// route Enter through the menu's active-descendant handler.
event.stopPropagation();
return;
}
if (item && ['ArrowUp', 'ArrowDown'].includes(event.key)) menu.focus({ preventScroll: true });
if (['ArrowUp', 'ArrowDown', 'Enter', ' ', 'Escape'].includes(event.key)) event.preventDefault();
});
keyGuards.add(menu);
}
// Keep the original Blazor-owned node outside overflow/entrance-transform
// clipping. Existing backdrop and action callbacks still own dismissal.
if (typeof menu.showPopover === 'function') {
menu.setAttribute('popover', 'manual');
if (!menu.matches(':popover-open')) menu.showPopover();
}
menu.style.position = 'fixed';
menu.style.margin = '0';
let state = positionedMenus.get(menu);
if (!state) {
state = { menu, trigger, anchored, x, y, observer: null, reposition: null };
state.reposition = () => repositionMenu(state);
state.observer = new ResizeObserver(state.reposition);
state.observer.observe(menu);
if (trigger?.isConnected) state.observer.observe(trigger);
addEventListener('resize', state.reposition);
positionedMenus.set(menu, state);
} else Object.assign(state, { trigger, anchored, x, y });
repositionMenu(state);
menu.focus({ preventScroll: true }); // Own initial focus once, before the interop reply.
return true;
}
export function restoreMenuTrigger(trigger) {
if (!trigger?.isConnected || document.querySelector('.ctx-menu')) return;
const active = document.activeElement;
if (active === trigger) return;
if (active && active !== document.body && active !== document.documentElement) return;
trigger.focus({ preventScroll: true });
}