Skip to content

UI Components

Michael Riddle edited this page Aug 20, 2026 · 11 revisions

UI components

Developer-facing reference for the shared Razor components under src/KHost.Mobile.UI/Components/ and the JS interop modules under src/KHost.Mobile/wwwroot/js/. KHost.Mobile.UI is a plain net10.0 Razor class library with no MAUI workload — a component there physically cannot reference a MAUI type, so any platform capability (haptics, location, link launching, …) arrives only as an Abstractions interface, implemented by a Maui* adapter one layer down in the KHost.Mobile head. AlbumArtService lives in the same library, alongside the components. For the conventions these follow, see Conventions; for the app shell's data flow, see Architecture.

Component inventory

The sheets sit together in Components/Sheets/, pages in Components/Pages/, layout in Components/Layout/, icons in Components/Icons/; everything else is a shared control at the Components/ root.

Component Job Key [Parameter]s Used by
Sheet.razor Bottom-sheet shell: backdrop, ✕, pull-down-to-dismiss, scroll lock Open, Class, BackdropClass, ShowClose, ClosePx, OnClose, OnSwipeDismiss Every sheet below
SongDetailSheet.razor Read/edit one song's full detail card Item, AllowEdit, InTonight, KaraFunAvailable, OnSave, OnLogPerformance, OnToggleTonight MySongs.razor, Tonight.razor
RatingPromptSheet.razor "How did it go?" performance logging prompt, incl. the editable When date/time Item, RatePerformances, OnCommit, OnCancel MySongs.razor ("Log performance"), Tonight.razor (check-off)
PerformanceHistorySheet.razor Full performance history for one song, with swipe-to-remove / hold-to-edit-date rows Item, BayesScore, OnRatingChanged, OnNoteChanged, OnDateChanged, OnRemove, OnRestore SongDetailSheet's "Last" link host
SingerEditSheet.razor Add/edit a singer (name, color, glyph, activate, delete) Editing, IsNew, CanDelete, IsActive, OnSave, OnDelete, OnSetActive Singers.razor
VenueEditSheet.razor Add/edit a venue (name, glyph, KaraFun ID + QR scan, location, favorite/switcher flags) Editing, IsNew, OnSave Venues.razor
QrCodeSheet.razor Displays a QR code big enough to be scanned off the screen Open, Title, Subtitle, Svg, Caption, AriaLabel, OnClose Venues.razor (venue's KaraFun catalog)
SurpriseSheet.razor 🎲 draw-rule toggles (skip today, favour well-sung, never-sung-only, favorites-only, respect filters) Open, OnRoll, OnClose MySongs.razor (long-press on SurpriseFab)
RollResultSheet.razor Shows the 🎲 pick as a .song-card, with Add to Tonight / Open / Reroll / Options Item, InTonight, ShowTonight, BayesScore, OnAddToTonight, OnReroll, OnOptions MySongs.razor
IconPicker.razor Collapsible color + glyph picker Glyph/GlyphChanged, Color/ColorChanged, AvailableGlyphs, AvailableColors, LetterFallback SingerEditSheet (color+glyph), VenueEditSheet (glyph-only)
TagInput.razor Chip input for a song's free-form tags, with reuse suggestions Tags/TagsChanged, Suggestions, Placeholder SongDetailSheet edit form
StarRating.razor 0–5 star control, filled/read-only/tone variants Value/ValueChanged, ReadOnly, Sung, Tone ("hot"/"cool"/null) Song cards, SongDetailSheet, RollResultSheet, history rows
SplitButton.razor + SplitButtonItem.razor + SplitButtonOptions.cs Primary action + chevron menu of related actions PrimaryLabel/PrimaryContent, OnPrimary, Direction, Align, Variant, Disabled SongDetailSheet's KaraFun action
SurpriseFab.razor The 🎲 FAB: tap rolls, press-and-hold opens options NoNav, Hidden, OnRoll, OnOptions MySongs.razor
TutorialOverlay.razor First-run coach-mark tour (spotlight + tip card, chaptered) none (reads IAppSettings/IAppSession/stores directly) MainLayout.razor
QrCodeIcon.razor Decorative QR glyph (not scannable) Class VenueEditSheet's scan button
Icons/ChevronLeftIcon.razor Back-chevron vector (avoids a text-glyph baseline bug — see comment in source) Size Back/previous affordances
Icons/SpotifyIcon.razor, Icons/YouTubeMusicIcon.razor Brand marks Size, Fill (Spotify only) SongDetailSheet, import source pickers
Layout/MainLayout.razor App shell: header, ⋮ menu, safe-area insets, back-button routing, singer bootstrap gate — Root layout
Layout/NavMenu.razor Bottom tab bar (Tonight / My Songs), gated on TonightEnabled — MainLayout
Layout/SingerChip.razor Header avatar + "Who's singing?" switcher; owns the app-wide tint — MainLayout
Layout/VenueChip.razor Header venue chip + switcher; owns auto-detect tracking — MainLayout
Layout/UpdateBanner.razor Once-per-launch "a newer version is available" banner — MainLayout (inside <main>)

Sheet.razor — the bottom-sheet base

Every bottom sheet in the app wraps Sheet.razor rather than hand-rolling its own backdrop/close/drag plumbing. It owns:

  • Backdrop — a full-screen .sheet-backdrop that closes on tap.
  • ✕ — rendered unless ShowClose="false" (a sheet with its own dismiss controls).
  • Pull-down-to-dismiss — bound in OnAfterRenderAsync via khSheet.register, backed by wwwroot/js/sheet.js. Dragging past ClosePx (default 90px, raise it for a sheet with an inner scrolling list so a scroll-flick can't close it — PerformanceHistorySheet/SurpriseSheet/RollResultSheet all set 150) slides the panel off and calls back into Sheet.CloseFromSwipe.
  • Page-scroll lock, read from the DOM (khSheet.syncLock), not from any one caller's state — because sheets stack (a history sheet over a detail sheet), a caller-driven lock would unlock the page out from under a sheet still showing. Sheet calls syncLock() on every render and on Dispose().
  • Stacking, assigned at runtime by khSheet.restack() (called from syncLock). Each open sheet gets a z-index above the one it opened over, and its backdrop one below that, so the newest sheet always covers the rest and its backdrop blocks them. A new sheet needs no z-index and no modifier class. Ordering is by the order sheets opened, not their position in the markup — a page can declare an inner sheet above the one it opens over (Tonight declares its rating prompt above the song detail), which DOM order would invert. Confirm popovers sit above every sheet and are left alone.

The contract

<Sheet Open="Item is not null" AriaLabel="Performance history"
       ClosePx="150" OnClose="OnClose">
    @if (Item is { } item) { ... }
</Sheet>
  • Open defaults to true — a sheet already guarded by the host's own @if can just wrap the content (Razor rejects a bare @{ } inside child content, so the default exists to make that pattern work).
  • OnClose fires from the ✕, the backdrop, and a pull-down dismiss unless OnSwipeDismiss is wired.
  • OnSwipeDismiss fires instead of OnClose when a pull-down means something other than "cancel". RatingPromptSheet is the example: pulling down there logs the sing unrated (same as its Skip button), not "discard and lose the rating" — see its DismissFromSwipeAsync.
  • Never hand-roll khSheet.register/setLock in a page. Wrap Sheet instead — the DOM-read syncLock approach avoids the lock-stranding bug where a sheet closed by touch swipe-dismiss skips normal teardown.

QrCodeSheet.razor — display only

The sheet takes pre-rendered SVG (Svg, a MarkupString) rather than the text to encode, so the UI layer carries no encoder dependency; encoding is IQrCodeService (KHost.Mobile.Infrastructure/Services/QrCodeService.cs), resolved by the page. Swapping the encoder package touches that one class.

Two constraints the CSS enforces, both about whether a phone can actually read the code:

  • Fixed light colors in both themes. .qr-code sets a white background and the SVG's own dark modules are left alone, rather than inheriting --kh-surface/--kh-text. A theme-tinted or inverted code is where phone scanners start failing, so this is the one place the dark theme is deliberately ignored.
  • Sized in module units. QrCodeService.ToSvg emits a viewBox measured in modules with the spec's 4-module quiet zone and no pixel width/height, so .qr-code scales it with CSS instead of re-encoding per size.

JS interop modules (src/KHost.Mobile/wwwroot/js/)

File Global register(...) signature [JSInvokable] callbacks Used by
sheet.js khSheet register(sheet, dotNetRef, {closeMethod, closePx}) closeMethod (default CloseDetailFromSwipe, e.g. Sheet.CloseFromSwipe) Sheet.razor
swipe.js khSwipe register(container, dotNetRef, options) — see below tapMethod, holdMethod, removeMethod (all named per-list) Song/venue/singer lists, PerformanceHistorySheet
press-hold.js khPressHold register(el, dotNetRef, {holdMs, tapMethod, holdMethod}) named tapMethod/holdMethod SurpriseFab.razor
album-art.js khAlbumArt set(id, streamRef) → blob: URL; revoke(id); revokeAll() none (called from C#, not into it) AlbumArtService
art-visibility.js khArtVisibility register(dotNetRef, {method}) (idempotent, re-callable per render) method (default VisibleArtChanged) Any surface with data-art-song elements
insets.js khInsets set(top, bottom) none MainLayout.razor (from ISafeAreaInsets)
numeric-input.js khNumeric register() — scans input.num-year:not([data-num-bound]) none SongDetailSheet edit form (release-year field)
range.js khRange register() — binds #f-year-lo/#f-year-hi by id none MySongs.razor year-range filter
scroll.js khScroll + khInfinite track(key)/untrack(key)/restore(key)/toTop()/toSong(id); khInfinite.observe(sentinel, dotNetRef) khInfinite calls LoadMore MySongs.razor (per-singer scroll + infinite paging)
singer.js khSinger apply(hex | falsy) none SingerChip.razor
theme.js khTheme current(), apply(theme), toggle() none MainLayout.razor header toggle; also called from an inline <head> script pre-paint
tonight-drag.js khTonight register(container, dotNetRef) ReorderTonight(ids) Tonight.razor
tutorial.js khTutorial position(hole, caret, tip, selector), reset(...), clear() none TutorialOverlay.razor

swipe.js in depth

One pointer-event state machine, event-delegated on a stable container, serving the song, venue and singer row lists (and, with tapMethod: null, PerformanceHistorySheet's performance rows). A single register(container, dotNetRef, options) call binds it (idempotent via container._khSwipeBound); everything list-specific is named in options:

Option Default Meaning
idAttr data-song-id attribute the row's id lives on
swipingClass song-row--swiping class applied while dragging
tapMethod OpenDetail [JSInvokable] called with the row id on a clean tap; pass null explicitly to opt a list out of tapping entirely (omitting the key keeps the song-table default)
removeMethod RemoveById called with the row id once a swipe-left commits
holdMethod null called with the row id once the ~500 ms hold dwell completes; omitted = no hold support
holdingClass is-holding class applied to the row while a hold is armed
swipeEnabled true set false to disable swipe-to-remove entirely (tap/hold only)

Press-and-hold semantics: the dwell is HOLD_MS = 500 (matching the platform long-press context-menu timing). A hold that fires owns the gesture — the follow-up pointerup/click is swallowed (swallowNextClick, armed on release, not on fire — a completed hold can still open something under the finger, e.g. PerformanceHistorySheet's date editor, that a trailing click would otherwise dismiss instantly). Movement past TAP_SLOP (10px, either axis) cancels a pending hold. Venues and Singers use holdMethod to set-and-pin the active row, confirmed by IHaptics.LongPress() from the C# side (see below) — the row's re-render (an "Active" badge) is the only visual confirmation otherwise.

pointerup/pointercancel are bound on window, not the container: a hold that opened an overlay over the row means the release lands on that overlay instead, so a container-bound listener would never fire and strand active, killing every later gesture on the list. Each registration's handler checks pointerId ownership before acting, so sharing window across multiple registered lists is safe.

The IHaptics naming trap

Services/IHaptics.cs is not named IHapticFeedback — MAUI Essentials' global usings already bring Microsoft.Maui.Devices.IHapticFeedback into scope, and reusing that name would collide. IHaptics.LongPress() is best-effort: silent no-op with no hardware, haptics off system-wide, or IAppSettings.HapticsEnabled off. Used from SurpriseFab.razor (Hold()) and the swipe-driven set-active gesture on Venues/Singers.

Interop conventions

  • JS interop only in OnAfterRenderAsync, never OnInitializedAsync — the target element isn't in the DOM until after render. Sheet, SongDetailSheet (numeric guard), PerformanceHistorySheet, SurpriseFab all follow this.
  • Bind-once flag. A _bound/_xBound field (component-side) or a DOM dataset marker (el._khSheetBound, container._khSwipeBound, data-num-bound) stops register from double-binding on every re-render. Where the panel/element is torn down and remounted (a sheet closing then reopening), the component-side flag is reset to false on close so the next open rebinds against the fresh element (Sheet, PerformanceHistorySheet).
  • DotNetObjectReference lifetime. Created lazily (_selfRef ??= DotNetObjectReference.Create(this)) once per component instance, not per bind, and disposed in IDisposable.Dispose(). Components exposing [JSInvokable] callbacks (Sheet, PerformanceHistorySheet, SurpriseFab) all implement IDisposable for this.
  • InvokeAsync(StateHasChanged) vs bare StateHasChanged(). An async continuation off the Blazor sync context — a store's Changed event handler, a Task.Delay continuation — must marshal back via InvokeAsync(StateHasChanged) (see NavMenu.RefreshOnUiAsync, SingerChip.ReloadOnUiAsync, PerformanceHistorySheet.DismissUndoAfterDelay). A [JSInvokable] method or a synchronous UI event handler is already running on the sync context, so it calls bare StateHasChanged() (see PerformanceHistorySheet.EditDateById, SingerEditSheet's field setters).

Layout & navigation

Layout/MainLayout.razor is the shell. It's gated on _ready, set only after the singer bootstrap (ISingerStore.EnsureSeededAsync + resolving the active singer from IAppSettings.LastActiveSingerId) completes — the per-singer stores can't load until the active singer is known, so no personal page renders before then; an app-boot splash shows meanwhile. It also:

  • Renders the header (brand lockup, VenueChip, SingerChip, the ⋮ menu) and <main> (holding UpdateBanner then @Body).
  • Pushes native safe-area insets to CSS via khInsets.set (ISafeAreaInsets, re-pushed on Insets.Changed — Android's WebView never fills env(safe-area-inset-*) itself; app.css layers the JS-set --kh-inset-* vars over env() with max(), so iOS where env() already works is unaffected).
  • Owns Android back-button routing via BackButtonOverlayGuard (Services/BackButtonOverlayGuard.cs) — TryCloseTopOverlay closes the ⋮ menu on a back press instead of navigating away; SplitButton, SingerChip, and VenueChip each register their own guard the same way for their own popover.
  • Reads khTheme.current() once mounted to sync the ☀️/🌙 menu icon with whatever the pre-paint inline script (or OS prefers-color-scheme) already resolved.

Layout/NavMenu.razor is the bottom tab bar — Tonight then My Songs — rendered by MainLayout only when Settings.TonightEnabled; with it off, the whole bar is hidden and navigation runs entirely through the header ⋮ menu (Venues / Singers / Import / Export / Settings / About). Tonight's tab shows a badge of remaining (!Completed) entries, refreshed off ITonightStore.Changed.

Layout/SingerChip.razor / Layout/VenueChip.razor are near-identical header chip + dropdown switchers (mirrored patterns — see each's own wiki page: Singers, Venues). Both register a BackButtonOverlayGuard for their popover and subscribe to their store's Changed plus the relevant IAppSession changed event.

Layout/UpdateBanner.razor shows once per launch when IAppUpdateService.GetStatusAsync() (memoized in the service, so only the first component to ask hits the network) reports a newer GitHub release; ✕ dismisses for the session via Updates.Dismiss().

Theming & CSS

src/KHost.Mobile/wwwroot/app.css defines --kh- design tokens on :root (--kh-primary, --kh-bg, --kh-surface, --kh-text, --kh-border, --kh-danger, --kh-warn, --kh-star-hot/--kh-star-cool, --kh-shadow, etc.), consumed everywhere instead of hardcoded colors — the file's own comment calls out color-mix() on the primary token rather than a hardcoded rgba(), since the primary is overridden per-singer at runtime.

Light/dark: the base :root values are light. A @media (prefers-color-scheme: dark) block scoped to :root:not([data-theme]) supplies the dark palette when the OS asks for dark and the user hasn't picked explicitly. :root[data-theme="dark"] supplies the same values for an explicit choice (no [data-theme="light"] block needed — the unscoped :root is already light, and the dark media query excludes anything with [data-theme] set). js/theme.js drives data-theme and persists the choice to localStorage['kh-theme']; an inline script in index.html's <head> applies the stored value before first paint to avoid a flash — keep both in sync on the storage key if it ever changes.

BEM naming throughout: block__element, block--modifier, is-/active state classes (sheet__close, song-row--swiping, is-holding, is-open).

Per-singer tint: js/singer.js's khSinger.apply(hex) overrides --kh-primary/--kh-primary-strong/--kh-primary-contrast directly on <html>.style (inline, so it outranks the stylesheet's token declarations without touching the stylesheet itself). --kh-primary-contrast is pinned to white — every singer palette color is dark enough for white text. SingerChip.OnAfterRenderAsync calls it only when _active?.Color actually changed (_appliedColor guard), and passes a falsy value to clear back to the brand violet.

Accessibility: reachable equivalents for gestures

Every press-and-hold and swipe in the app has a reachable, tappable equivalent, because no assistive-tech gesture maps to a long press:

Gesture Reachable equivalent Where
Press-and-hold a venue row to set it active The detail sheet's Active toggle Venues.razor / VenueEditSheet pattern (see Venues)
Press-and-hold a singer row to switch to them SingerEditSheet's "Switch to this singer" button (only shown for a non-active existing singer) SingerEditSheet.razor
Press-and-hold the 🎲 FAB for draw options RollResultSheet's Options button SurpriseFab.razor / RollResultSheet.razor
Swipe-left to remove (song/venue/singer rows, performance history rows) No hold/swipe-only actions here are destructive-only — each list also exposes a delete affordance in its detail sheet (e.g. SingerEditSheet's Delete singer) respective edit sheets

PerformanceHistorySheet additionally spells out both gestures in a literal on-screen hint ("Swipe a row left to remove it · press and hold a date to change it") since a whole sheet of otherwise-undiscoverable row gestures has no single equivalent control to point to.

Adding a new component

Follow the pattern in Conventions → "Pattern: Blazor component":

  1. Markup in the .razor, C# in a sibling .razor.cs partial (public sealed partial class) — an @code block is a rule violation. No scoped .razor.css; all styling goes in wwwroot/app.css using the --kh- tokens and BEM naming. @implements moves to the partial, while @inherits has to stay in the markup, since the generated half always declares a base class.
  2. @inject, never [Inject]; give injected services short semantic field names (Store, Settings, JS) matching the rest of the codebase. Reach for the small stateless helper interfaces the same way — ITimeFormatter, IRatingScorer, ISurprisePicker, ISongLinkBuilder, IKaraFunVenueUrlParser, IDateTimeInputConverter, ISingerProfileCodec — rather than a static call, since this project can't see their Infrastructure/Clients implementations directly.
  3. Wrap Sheet.razor if it's a bottom sheet — don't hand-roll khSheet.register/setLock. Pass Open/OnClose, and OnSwipeDismiss only if a pull-down should mean something other than "close".
  4. Load data in OnInitializedAsync; if subscribing to a store's Changed (or an IAppSession event), implement IDisposable and unsubscribe.
  5. Any JS interop goes in OnAfterRenderAsync behind a bind-once flag; if it registers [JSInvokable] callbacks, own a DotNetObjectReference<T> and dispose it.
  6. Event handlers are async Task, never async void; a fire-and-forget call is an explicit _ = FooAsync() with its own try/catch.
  7. InvokeAsync(StateHasChanged) from an async continuation off the sync context; bare StateHasChanged() from a synchronous handler or a [JSInvokable] method.
  8. Document every [Parameter] with a <summary>.

See also

  • Architecture — the store/session/settings layer these components sit on top of.
  • Conventions — the full coding-convention reference this page follows.
  • Building & testing — how to build and run each platform head, and the Playwright UI-automation tools for driving these components on a device.
  • Venues, Singers — the press-and-hold / swipe list pattern in product-facing detail, including VenueChip/SingerChip behavior.
  • Surprise Me — SurpriseFab, SurpriseSheet, RollResultSheet and the draw rules behind them.

Clone this wiki locally