// The screen: the primary sidebar, the open project, the dialogs, and the status
// bar. The theme follows the selected color scheme and appearance override.

///|
/// A path in two parts, for a place that is too small for it. The view shortens `head`
/// first, because the last names tell two projects apart.
// Only the tests compare the parts and write them as text.
#warnings("-unused_value")
#derive(Eq, Debug)
priv struct PathParts {
  head : String
  tail : String
}

///|
/// Splits a path before its last two names. A path with less than four parts is
/// complete in `tail`.
fn PathParts::of_path(path : String) -> PathParts {
  // Only a path of Windows starts with no `/`, and there `\` separates the names.
  let separator = if path.has_prefix("/") { "/" } else { "\\" }
  let names = path.split(separator).map(name => name.to_owned()).to_array()
  guard names.length() >= 4 else { { head: "", tail: path, } }
  let first = names.length() - 2
  {
    head: names[:first].join(separator),
    tail: separator + names[first:].join(separator),
  }
}

///|
/// The text of the status bar for the connection.
fn connection_text(connection : ConnectionState) -> String {
  match connection {
    Connecting => "Connecting…"
    Connected => "Connected"
    Reconnecting => "Reconnecting…"
    // The main area says what happened.
    Restarted | Stopped => "Not connected"
  }
}

///|
/// The text of the status bar for the kind of the view.
fn surface_text(surface : @app.Surface) -> String {
  match surface {
    Browser => "Browser"
    Desktop => "Desktop"
  }
}

///|
/// What a view says after it ended. The view shows `command` as code.
priv struct EndText {
  title : String
  before : String
  command : String
  after : String
}

///|
/// The text of a view that ended, or `None` for a view that is in use.
fn EndText::of_view(
  connection : ConnectionState,
  surface : @app.Surface,
  instance : @app.InstanceName,
) -> EndText? {
  let command = surface.open_command(instance)
  match connection {
    Restarted =>
      Some({
        title: "Session ended",
        before: "Mission Control restarted. Run ",
        command,
        after: " to open it again.",
      })
    Stopped =>
      Some({
        title: "Mission Control stopped.",
        before: "Run ",
        command,
        after: " to start it again.",
      })
    Connecting | Connected | Reconnecting => None
  }
}

///|
/// The colors of the UI over the ones of `rui`. Each color is for both themes, so the
/// page needs no script to follow the operating system.
let theme_tokens : String = build_theme_tokens()

///|
/// The rules that an inline style cannot have. `rui` has its styles inline and removes
/// the focus ring of its buttons, so a rule for one of them needs `!important`.
let page_styles : String = [
  (
    #|:root { color-scheme:light dark; background:light-dark(#f8faff,#081124); }
    #|body { margin:0; }
    #|/* The page does not scroll, so it needs no space for a scrollbar behind the sheet. */
    #|html { scrollbar-gutter:auto !important; }
    #|.mc-page { height:100vh; height:100dvh; overflow:hidden; }
    #|.mc-shell-root { display:flex; flex-direction:column; height:100%; min-height:0; background:var(--rui-background); color:var(--rui-foreground); }
    #|.mc-shell-root[data-appearance="light"] { color-scheme:light; }
    #|.mc-shell-root[data-appearance="dark"] { color-scheme:dark; }
  ),
  build_scheme_override_css(
    Minimal,
    "light-dark(rgba(9,9,11,0.1),rgba(255,255,255,0.1))",
  ),
  build_scheme_override_css(
    WarmEditorial,
    "light-dark(rgba(45,38,28,0.12),rgba(236,227,211,0.13))",
  ),
  (
    #|.mc-page :focus-visible { outline:2px solid var(--rui-ring) !important; outline-offset:2px; }
    #|.mc-page .mc-row:focus-visible, .mc-page input:focus-visible { outline-offset:-1px; }
    #|.mc-page input::placeholder { color:var(--rui-muted-foreground); opacity:1; }
    #|/* The box around the field of the palette has the ring, and not the field in it. */
    #|.mc-palette-field:focus-within { outline:2px solid var(--rui-ring); outline-offset:-1px; }
    #|.mc-page .mc-palette-field input:focus-visible { outline:none !important; }
    #|.mc-palette-field { display:flex; flex:none; align-items:center; gap:0.5rem; height:2.25rem; margin:0.25rem 0.25rem 0; padding-inline:0.5rem; border:1px solid var(--rui-border); border-radius:var(--rui-radius); background:var(--rui-input-background); color:var(--rui-muted-foreground); }
    #|.mc-palette-field input { color:var(--rui-foreground); }
    #|.mc-palette-note { margin:0; padding:0.5rem 0.75rem 0.25rem; font-size:0.8125rem; line-height:1.25rem; color:var(--rui-muted-foreground); }
    #|.mc-palette-empty { margin:0; padding:1.5rem 0.75rem; font-size:0.875rem; line-height:1.25rem; text-align:center; color:var(--rui-muted-foreground); }
    #|.mc-palette-note:empty, .mc-palette-empty:empty { padding:0; }
    #|.mc-palette-list { min-height:0; max-height:min(24rem,55dvh); overflow:hidden auto; outline:none; }
    #|.mc-palette-group { padding:0.25rem; }
    #|.mc-palette-heading { padding:0.375rem 0.5rem; font-size:0.75rem; line-height:1rem; font-weight:500; color:var(--rui-muted-foreground); }
    #|.mc-palette-entry { display:flex; align-items:center; min-height:2rem; box-sizing:border-box; padding:0.375rem 0.5rem; border-radius:calc(var(--rui-radius) - 0.25rem); font-size:0.875rem; line-height:1.25rem; cursor:pointer; -webkit-user-select:none; user-select:none; scroll-margin-block:0.25rem; }
    #|/* The name of the group is visible with its first entry. */
    #|.mc-palette-heading + .mc-palette-entry { scroll-margin-block-start:2.25rem; }
    #|.mc-palette-entry[aria-selected="true"] { background:var(--rui-accent); color:var(--rui-accent-foreground); }
    #|.mc-palette-entry[aria-disabled="true"] { cursor:not-allowed; }
    #|.mc-palette-entry[aria-disabled="true"] > * { opacity:0.5; }
    #|/* A closed dialog has no content, so it must not fade out. */
    #|.mc-page dialog, .mc-page dialog::backdrop { transition:none !important; }
    #|/* The sheet has the focus when it opens, and its edge is no control. */
    #|.mc-page [data-slot="sidebar"]:focus-visible { outline:none !important; }
    #|/* The title gets the focus when its control is gone, and it is no control. */
    #|.mc-page h1:focus-visible { outline:none !important; }
    #|.mc-page button:not(:disabled) { cursor:pointer; }
    #|.mc-page button[aria-disabled="true"] { cursor:not-allowed; opacity:0.45; }
    #|.mc-cut { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:pre; }
    #|.mc-path { display:flex; min-width:0; font-family:var(--mc-mono); font-size:0.75rem; font-weight:400; line-height:1.125rem; color:var(--rui-muted-foreground); }
    #|.mc-path > :first-child { flex:0 99999 auto; }
    #|.mc-path > :last-child { flex:0 1 auto; }
    #|.mc-row { position:relative; }
    #|.mc-row[aria-current]::before { content:""; position:absolute; inset-block:0.5rem; inset-inline-start:0; width:2px; border-radius:1px; background:var(--rui-primary); }
    #|.mc-warning { color:var(--mc-bad-fg); }
    #|.mc-dot { width:0.5rem; height:0.5rem; flex:none; border-radius:50%; background:var(--rui-muted-foreground); }
    #|.mc-dot[data-state="good"] { background:var(--mc-good); }
    #|.mc-dot[data-state="wait"] { background:var(--mc-wait); animation:mc-wait 1.6s ease-in-out infinite; }
    #|@keyframes mc-wait { 50% { opacity:0.35; } }
    #|@media (prefers-reduced-motion:reduce) { .mc-page *, .mc-page *::before { animation:none !important; transition:none !important; } }
    #|.mc-top { display:none; }
    #|.mc-hidden-primary-sidebar { display:inline-flex; }
    #|.mc-sidebar-splitter { position:relative; width:7px; margin-inline:-3px; flex:none; cursor:col-resize; z-index:12; touch-action:none; outline:none; }
    #|.mc-sidebar-splitter::after { content:""; position:absolute; inset-block:0; left:3px; width:2px; background:transparent; transition:background-color 120ms ease; }
    #|.mc-sidebar-splitter:hover::after, .mc-sidebar-splitter:focus-visible::after, .mc-sidebar-splitter[data-dragging="true"]::after { background:var(--mc-brand); }
    #|.mc-shell-root[data-resizing="true"] { user-select:none; -webkit-user-select:none; cursor:col-resize; }
    #|.mc-shell-root[data-resizing="true"] [data-slot="sidebar-shell"], .mc-shell-root[data-resizing="true"] [data-slot="sidebar"] { transition:none !important; }
    #|@media (max-width:47.99rem) {
    #|  .mc-page [data-slot="sidebar-shell"] { display:none; }
    #|  .mc-sidebar-splitter { display:none; }
    #|  .mc-top { display:flex; }
    #|  .mc-hidden-primary-sidebar { display:none; }
    #|}
    #|/* Adaptive Shell Styles */
    #|.mc-shell-main { display:flex; flex-direction:column; flex:1; min-width:0; min-height:0; overflow:auto; container-type:inline-size; }
    #|.mc-shell-bar { min-height:3rem; flex:none; display:grid; grid-template-columns:minmax(0,1fr) auto auto; align-items:center; gap:0.5rem; padding:0.375rem 0.875rem; border-bottom:1px solid var(--rui-border); background:var(--rui-card); }
    #|.mc-shell-bar-left { display:flex; align-items:center; gap:0.35rem; min-width:0; overflow:hidden; }
    #|.mc-shell-bar-persp { display:flex; align-items:center; justify-content:center; flex:none; }
    #|.mc-shell-bar-right { display:flex; align-items:center; justify-content:flex-end; gap:0.35rem; flex:none; }
    #|@container (max-width:44rem) {
    #|  .mc-shell-bar { grid-template-columns:minmax(0,1fr) auto; row-gap:0.375rem; padding:0.375rem 0.625rem; }
    #|  .mc-shell-bar-persp { grid-column:1 / -1; grid-row:2; }
    #|  .mc-shell-bar-right { grid-column:2; grid-row:1; }
    #|}
    #|@container (max-width:26rem) {
    #|  .mc-settings-label { display:none; }
    #|}
    #|.mc-perspective-stage { position:relative; display:flex; flex-direction:column; flex:1; min-width:0; min-height:0; overflow:hidden; container-type:inline-size; }
    #|.mc-persp-switch { display:inline-flex; align-items:center; gap:2px; padding:3px; border-radius:999px; border:1px solid var(--rui-border); background:var(--rui-background); }
    #|.mc-persp-btn { appearance:none; border:0; background:transparent; color:var(--rui-muted-foreground); font:inherit; font-size:0.75rem; font-weight:550; padding:0.25rem 0.75rem; border-radius:999px; display:inline-flex; align-items:center; gap:0.35rem; }
    #|.mc-persp-btn:hover { color:var(--rui-foreground); }
    #|.mc-persp-btn.active { background:var(--mc-brand-surface); color:var(--mc-brand-fg); box-shadow:inset 0 0 0 1px var(--mc-brand-border); font-weight:650; }
    #|.mc-persp-key { font-family:var(--mc-mono); font-size:0.625rem; opacity:0.6; }
    #|.mc-project-strip { flex:none; display:flex; align-items:center; justify-content:space-between; gap:0.75rem; flex-wrap:wrap; padding:0.75rem 1.25rem; border-bottom:1px solid var(--rui-border); background:var(--rui-background); }
    #|.mc-seg { display:inline-flex; flex-wrap:wrap; max-width:100%; gap:2px; padding:2px; border-radius:var(--rui-radius); border:1px solid var(--rui-border); background:var(--rui-card); }
    #|.mc-seg-btn { appearance:none; border:0; background:transparent; color:var(--rui-muted-foreground); font:inherit; font-size:0.75rem; font-weight:500; padding:0.25rem 0.625rem; border-radius:calc(var(--rui-radius) - 3px); }
    #|.mc-seg-btn:hover { color:var(--rui-foreground); }
    #|.mc-seg-btn.active { background:var(--mc-brand-surface); color:var(--mc-brand-fg); box-shadow:inset 0 0 0 1px var(--mc-brand-border); font-weight:600; }
    #|.mc-zen-board { display:grid; grid-template-columns:repeat(auto-fit,minmax(12.5rem,1fr)); gap:0.75rem; align-items:stretch; flex:1 1 auto; min-height:100%; }
    #|.mc-zen-col { position:relative; display:flex; flex-direction:column; gap:0.625rem; padding:0.75rem 0.6875rem; border-radius:0.6875rem; background:var(--rui-card); border:1px solid var(--rui-border); overflow:hidden; min-height:14rem; }
    #|.mc-zen-col::before { content:""; position:absolute; top:0; left:0; right:0; height:2.5px; background:var(--col-accent,var(--mc-cobalt)); opacity:0.85; }
    #|.mc-zen-card { display:flex; flex-direction:column; gap:0.5rem; padding:0.75rem; border-radius:0.5625rem; border:1px solid var(--rui-border); background:var(--rui-background); color:var(--rui-foreground); font:inherit; text-align:left; width:100%; }
    #|.mc-zen-card:hover { background:var(--rui-accent); }
    #|.mc-zen-card.selected { border-color:var(--mc-brand); box-shadow:0 0 0 1px var(--mc-brand-border); }
    #|.mc-seg-bar { display:flex; gap:3px; height:4px; width:100%; }
    #|.mc-seg-bar > span { flex:1; border-radius:999px; }
    #|.mc-seg-ok { background:var(--mc-good); }
    #|.mc-seg-warn { background:var(--mc-wait); }
    #|.mc-seg-miss { background:var(--rui-destructive); }
    #|.mc-pipe-row { display:grid; grid-template-columns:0.75rem 2.5rem minmax(8rem,1.4fr) minmax(6rem,1fr) 4.5rem 2.25rem 8.5rem; align-items:center; gap:0.625rem; padding:0.625rem 0.875rem; border-radius:0.5625rem; border:1px solid var(--rui-border); background:var(--rui-card); color:var(--rui-foreground); font:inherit; width:100%; box-sizing:border-box; }
    #|.mc-pipe-row:hover { background:var(--rui-accent); }
    #|.mc-pipe-row.selected { border-color:var(--mc-brand-border); background:var(--mc-brand-surface); }
    #|@container (max-width:46rem) {
    #|  .mc-pipe-row { display:flex; flex-wrap:wrap; align-items:center; gap:0.4rem 0.55rem; padding:0.625rem 0.75rem; }
    #|  .mc-pipe-title { flex:1 1 10rem; }
    #|  .mc-pipe-intent { flex:1 1 100%; padding-inline-start:1.25rem; }
    #|  .mc-pipe-meta { flex:0 0 auto; }
    #|  .mc-pipe-status { margin-inline-start:auto; }
    #|}
    #|.mc-surface-card { border-radius:0.625rem; border:1px solid var(--rui-border); background:var(--rui-card); }
    #|.mc-kicker { font-size:0.625rem; font-weight:700; text-transform:uppercase; letter-spacing:0.06em; color:var(--rui-muted-foreground); }
    #|.mc-grade { display:inline-flex; flex:none; align-items:center; justify-content:center; white-space:nowrap; font-family:var(--mc-mono); font-size:0.6875rem; font-weight:700; padding:0.125rem 0.45rem; border-radius:0.35rem; }
    #|.mc-grade-good { background:var(--mc-good-surface); color:var(--mc-good-fg); }
    #|.mc-grade-warn { background:var(--mc-wait-surface); color:var(--mc-wait-fg); }
    #|.mc-grade-bad { background:var(--rui-destructive-subtle); color:var(--mc-bad-fg); }
    #|.mc-pill-brand { font-size:0.6875rem; font-weight:600; padding:0.125rem 0.5rem; border-radius:999px; background:var(--mc-brand-surface); color:var(--mc-brand-fg); border:1px solid var(--mc-brand-border); }
    #|.mc-pill-warn { font-size:0.6875rem; font-weight:600; padding:0.125rem 0.5rem; border-radius:999px; background:var(--mc-wait-surface); color:var(--mc-wait-fg); }
    #|.mc-pill-good { font-size:0.6875rem; font-weight:600; padding:0.125rem 0.5rem; border-radius:999px; background:var(--mc-good-surface); color:var(--mc-good-fg); }
    #|.mc-chip-btn { appearance:none; border:1px solid var(--rui-border); background:var(--rui-background); color:var(--rui-foreground); font:inherit; font-size:0.75rem; padding:0.25rem 0.625rem; border-radius:999px; }
    #|.mc-chip-btn:hover { border-color:var(--mc-brand-border); }
    #|.mc-chip-btn.active { background:var(--mc-brand-surface); color:var(--mc-brand-fg); border-color:var(--mc-brand-border); font-weight:600; }
    #|.mc-chip-tag { font-family:var(--mc-mono); font-size:0.6875rem; padding:0.2rem 0.5rem; border-radius:0.375rem; background:var(--rui-background); border:1px solid var(--rui-border); }
    #|.mc-float-sheet { position:absolute; top:0.75rem; right:0.875rem; bottom:0.875rem; width:min(23rem,calc(100% - 1.75rem)); z-index:20; background:var(--rui-card); border:1px solid var(--rui-outline-border); border-radius:0.75rem; box-shadow:0 18px 46px rgba(0,0,0,0.4); display:flex; flex-direction:column; overflow:hidden; }
    #|.mc-gate-row { display:flex; align-items:flex-start; gap:0.5rem; padding:0.5rem 0.625rem; border-radius:0.45rem; background:var(--rui-background); border:1px solid var(--rui-border); font-size:0.75rem; }
    #|.mc-gate-row.fail { background:var(--mc-wait-surface); border-color:var(--mc-wait); }
    #|.mc-gate-row.pass { border-color:var(--mc-good); }
    #|.mc-review-grid { display:flex; flex:1; min-height:0; overflow:hidden; }
    #|.mc-review-outline { width:var(--mc-secondary-width,15.5rem); flex:none; min-height:0; display:flex; flex-direction:column; border-right:1px solid var(--rui-border); background:var(--rui-card); overflow:hidden; }
    #|.mc-review-canvas { flex:1; min-width:0; min-height:0; overflow:auto; padding:1.5rem 2rem 2.5rem; background:var(--rui-background); }
    #|.mc-review-canvas.code-mode { padding:1rem 1.25rem 1.25rem; display:flex; flex-direction:column; }
    #|.mc-review-companion { width:17.5rem; flex:none; min-height:0; display:flex; flex-direction:column; border-left:1px solid var(--rui-border); background:var(--rui-card); overflow:hidden; }
    #|.mc-pane-header { padding:0.75rem; border-bottom:1px solid var(--rui-border); display:flex; flex-direction:column; gap:0.5rem; flex:none; }
    #|.mc-pane-head-row { display:flex; align-items:center; justify-content:space-between; gap:0.375rem; min-width:0; }
    #|.mc-pane-title { font-size:0.8125rem; font-weight:620; letter-spacing:-0.01em; color:var(--rui-foreground); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    #|.mc-pane-count { font-size:0.6875rem; font-variant-numeric:tabular-nums; color:var(--rui-muted-foreground); white-space:nowrap; }
    #|.mc-pane-toggle-btn { appearance:none; border:1px solid transparent; border-radius:0.375rem; width:1.5rem; height:1.5rem; flex:none; display:inline-flex; align-items:center; justify-content:center; background:transparent; color:var(--rui-muted-foreground); padding:0; cursor:pointer; }
    #|.mc-pane-toggle-btn:hover { background:var(--rui-accent); color:var(--rui-foreground); border-color:var(--rui-border); }
    #|.mc-pane-rail { width:2.375rem; flex:none; display:flex; flex-direction:column; align-items:center; background:var(--rui-card); }
    #|.mc-pane-rail.left { border-right:1px solid var(--rui-border); }
    #|.mc-pane-rail.right { border-left:1px solid var(--rui-border); }
    #|.mc-pane-rail-btn { appearance:none; border:0; background:transparent; color:var(--rui-muted-foreground); width:100%; flex:1; display:flex; flex-direction:column; align-items:center; justify-content:flex-start; gap:0.75rem; padding:0.625rem 0.25rem; cursor:pointer; font:inherit; }
    #|.mc-pane-rail-btn:hover { background:var(--rui-accent); color:var(--rui-foreground); }
    #|.mc-pane-rail-label { writing-mode:vertical-rl; transform:rotate(180deg); font-size:0.75rem; font-weight:550; letter-spacing:0.01em; white-space:nowrap; }
    #|.mc-mobile-peek { display:none; }
    #|@container (max-width:48rem) {
    #|  .mc-review-grid { flex-direction:column; overflow-y:auto; overflow-x:hidden; }
    #|  .mc-review-outline { width:100%; border-right:0; border-bottom:1px solid var(--rui-border); flex:none; overflow:visible; }
    #|  .mc-review-outline > :nth-child(2) { max-height:11rem; }
    #|  .mc-secondary-splitter { display:none; }
    #|  .mc-pane-rail { width:100%; flex-direction:row; }
    #|  .mc-pane-rail.left { border-right:0; border-bottom:1px solid var(--rui-border); }
    #|  .mc-pane-rail.right { border-left:0; border-top:1px solid var(--rui-border); }
    #|  .mc-pane-rail-btn { flex-direction:row; justify-content:flex-start; padding:0.5rem 0.75rem; gap:0.5rem; }
    #|  .mc-pane-rail-label { writing-mode:horizontal-tb; transform:none; }
    #|  .mc-review-canvas { flex:none; overflow:visible; padding:1rem 1rem 1.5rem; }
    #|  .mc-review-canvas.code-mode { padding:0.75rem 0.75rem 1.25rem; }
    #|  .mc-review-companion { width:100%; border-left:0; border-top:1px solid var(--rui-border); flex:none; overflow:visible; }
    #|  .mc-mobile-peek { display:flex; flex-direction:column; gap:0.45rem; }
    #|}
    #|.mc-out-item { display:flex; align-items:flex-start; gap:0.5rem; padding:0.45rem 0.5rem; border-radius:0.5rem; border:1px solid transparent; background:transparent; color:var(--rui-muted-foreground); font:inherit; width:100%; }
    #|.mc-out-item:hover { background:var(--rui-accent); color:var(--rui-foreground); }
    #|.mc-out-item.active { background:var(--mc-brand-surface); border-color:var(--mc-brand-border); color:var(--rui-foreground); }
    #|.mc-out-num { width:1.125rem; height:1.125rem; flex:none; border-radius:50%; display:inline-flex; align-items:center; justify-content:center; font-family:var(--mc-mono); font-size:0.625rem; font-weight:700; border:1px solid var(--rui-border); }
    #|.mc-out-num.read { background:var(--mc-good-surface); color:var(--mc-good-fg); border-color:var(--mc-good); }
    #|.mc-delta-block { border-left:3px solid var(--mc-cobalt); padding:0.75rem 0.875rem; border-radius:0 0.5rem 0.5rem 0; background:var(--rui-card); display:flex; flex-direction:column; gap:0.5rem; }
    #|.mc-delta-block.warn { border-left-color:var(--mc-wait); }
    #|.mc-delta-block.added { border-left-color:var(--mc-good); }
    #|.mc-ears-kw { font-family:var(--mc-mono); font-size:0.75rem; font-weight:700; color:var(--mc-brand-fg); }
    #|.mc-diff-old { padding:0.375rem 0.625rem; border-radius:0.375rem; background:var(--rui-destructive-subtle); color:var(--rui-muted-foreground); text-decoration:line-through; font-size:0.8125rem; }
    #|.mc-diff-new { padding:0.45rem 0.625rem; border-radius:0.375rem; background:var(--mc-good-surface); font-size:0.8125rem; line-height:1.6; }
    #|.mc-dict-term { appearance:none; border:0; border-bottom:1.5px dotted var(--mc-cobalt); background:transparent; color:inherit; font:inherit; padding:0 2px; }
    #|.mc-dict-term:hover { background:var(--mc-cobalt-surface); }
    #|.mc-dict-term.deprecated { border-bottom:1.5px wavy var(--mc-wait); background:var(--mc-wait-surface); color:var(--mc-wait-fg); }
    #|.mc-tab-btn { flex:1; appearance:none; border:0; border-bottom:2px solid transparent; background:transparent; color:var(--rui-muted-foreground); font:inherit; font-size:0.75rem; font-weight:600; padding:0.375rem; }
    #|.mc-tab-btn.active { color:var(--rui-foreground); border-bottom-color:var(--mc-brand); }
    #|.mc-code-block { padding:0.75rem 0.875rem; border-radius:0.5rem; border:1px solid var(--rui-border); background:var(--mc-code-bg); font-family:var(--mc-mono); font-size:0.75rem; line-height:1.6; overflow:auto; white-space:pre-wrap; }
    #|/* Unified Monaco / moonbitlang/editor token palette (mtk1..mtk13) */
    #|.mtk1 { color:var(--vscode-editor-foreground); }
    #|.mtk2 { color:var(--vscode-editor-background); }
    #|.mtk3 { color:var(--vscode-token-keyword); }
    #|.mtk4 { color:var(--vscode-token-variable); }
    #|.mtk5 { color:var(--vscode-token-string); }
    #|.mtk6 { color:var(--vscode-token-number); }
    #|.mtk7 { color:var(--vscode-token-comment); font-style:italic; }
    #|.mtk8 { color:var(--vscode-token-punctuation); }
    #|.mtk9 { color:var(--vscode-token-type); }
    #|.mtk10 { color:var(--vscode-token-function); }
    #|.mtk11 { color:var(--vscode-token-string-escape); }
    #|.mtk12 { color:var(--vscode-token-regexp); }
    #|.mtk13 { color:var(--vscode-token-invalid); }
    #|.mtki { font-style:italic; }
    #|.mtkb { font-weight:650; }
    #|.mtku { text-decoration:underline; }
    #|.mtks { text-decoration:line-through; }
    #|/* Read-only moonbitlang/editor code viewer */
    #|.mc-code-viewer { display:flex; flex-direction:column; width:100%; border-radius:0.5rem; border:1px solid var(--rui-border); background:var(--mc-code-bg); overflow:hidden; min-width:0; }
    #|.mc-code-viewer.fill { flex:1; min-height:24rem; }
    #|.mc-code-viewer-bar { display:flex; flex:none; align-items:center; justify-content:space-between; gap:0.5rem; padding:0.35rem 0.75rem; border-bottom:1px solid var(--rui-border); background:var(--rui-card); }
    #|.mc-code-lang-pill { font-family:var(--mc-mono); font-size:0.625rem; font-weight:700; letter-spacing:0.04em; text-transform:uppercase; padding:0.08rem 0.4rem; border-radius:0.25rem; background:var(--rui-muted); color:var(--rui-foreground); border:1px solid var(--rui-border); }
    #|.mc-code-meta { font-family:var(--mc-mono); font-size:0.625rem; color:var(--rui-muted-foreground); }
    #|.mc-code-copy-btn { appearance:none; border:1px solid var(--rui-border); border-radius:0.3rem; background:transparent; color:var(--rui-muted-foreground); font-family:var(--mc-mono); font-size:0.625rem; font-weight:600; padding:0.15rem 0.45rem; cursor:pointer; }
    #|.mc-code-copy-btn:hover { background:var(--rui-accent); color:var(--rui-foreground); }
    #|.mc-code-viewer-body { padding:0.5rem 0; overflow:auto; font-family:var(--mc-mono); font-size:0.8125rem; line-height:1.65; color:var(--vscode-editor-foreground); outline:none; }
    #|.mc-code-viewer.fill .mc-code-viewer-body { flex:1; min-height:0; }
    #|.mc-code-viewer-body:focus-visible { box-shadow:inset 0 0 0 2px var(--rui-ring); }
    #|.mc-code-viewer-body.compact { max-height:14rem; font-size:0.75rem; }
    #|.moonbit-line { display:grid; grid-template-columns:max-content minmax(0,1fr); align-items:baseline; min-width:100%; width:max-content; }
    #|.moonbit-line:hover { background:color-mix(in srgb,var(--rui-foreground) 4%,transparent); }
    #|.moonbit-gutter { position:sticky; left:0; z-index:1; padding:0 0.75rem 0 0.625rem; text-align:right; white-space:pre; user-select:none; -webkit-user-select:none; color:var(--vscode-editorLineNumber-foreground); opacity:0.65; background:var(--mc-code-bg); border-right:1px solid var(--rui-border); }
    #|.moonbit-code { padding:0 1rem 0 0.875rem; white-space:pre; font-family:inherit; font-size:inherit; }
    #|.moonbit-skip { color:var(--rui-muted-foreground); font-style:italic; }
    #|/* Interactive CodeMirror 5 editor host & mechanics */
    #|.mc-studio-split { display:grid; grid-template-columns:minmax(18rem,1fr) minmax(28rem,1.85fr); gap:0.875rem; flex:1; min-height:24rem; }
    #|@media (max-width:64rem) { .mc-studio-split { grid-template-columns:1fr; min-height:0; } }
    #|.mc-cm-host { flex:1; min-height:24rem; display:flex; flex-direction:column; background:var(--mc-code-bg); overflow:hidden; }
    #|.mc-cm-host .CodeMirror { flex:1; height:100%; min-height:24rem; font-family:var(--mc-mono); font-size:0.8125rem; line-height:1.65; direction:ltr; position:relative; overflow:hidden; background:var(--mc-code-bg); color:var(--vscode-editor-foreground); }
    #|.mc-cm-host.readonly .CodeMirror { opacity:0.78; }
    #|.CodeMirror-lines { padding:0.5rem 0; cursor:text; min-height:1px; }
    #|.CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { padding:0 0.625rem; border-radius:0; border-width:0; background:transparent; font-family:inherit; font-size:inherit; margin:0; white-space:pre; word-wrap:normal; line-height:inherit; color:inherit; z-index:2; position:relative; overflow:visible; font-variant-ligatures:contextual; }
    #|.CodeMirror-wrap pre.CodeMirror-line, .CodeMirror-wrap pre.CodeMirror-line-like { word-wrap:break-word; white-space:pre-wrap; word-break:normal; }
    #|.CodeMirror-scroll { overflow:scroll !important; margin-bottom:-50px; margin-right:-50px; padding-bottom:50px; height:100%; outline:none; position:relative; z-index:0; }
    #|.CodeMirror-sizer { position:relative; border-right:50px solid transparent; }
    #|.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { position:absolute; z-index:6; display:none; outline:none; }
    #|.CodeMirror-vscrollbar { right:0; top:0; overflow-x:hidden; overflow-y:scroll; }
    #|.CodeMirror-hscrollbar { bottom:0; left:0; overflow-y:hidden; overflow-x:scroll; }
    #|.CodeMirror-scrollbar-filler { right:0; bottom:0; background:var(--mc-code-bg); }
    #|.CodeMirror-gutter-filler { left:0; bottom:0; background:var(--mc-code-bg); }
    #|.CodeMirror-gutters { position:absolute; left:0; top:0; min-height:100%; z-index:3; border-right:1px solid var(--rui-border); background:var(--mc-code-bg); white-space:nowrap; }
    #|.CodeMirror-gutter { white-space:normal; height:100%; display:inline-block; vertical-align:top; margin-bottom:-50px; }
    #|.CodeMirror-gutter-wrapper { position:absolute; z-index:4; background:none !important; border:none !important; }
    #|.CodeMirror-gutter-elt { position:absolute; cursor:default; z-index:4; }
    #|.CodeMirror-gutter-wrapper ::selection { background-color:transparent; }
    #|.CodeMirror-linenumber { padding:0 0.5rem 0 0.5rem; min-width:1.75rem; text-align:right; color:var(--vscode-editorLineNumber-foreground); opacity:0.65; white-space:nowrap; }
    #|.CodeMirror-cursor { position:absolute; pointer-events:none; border-left:1.5px solid var(--mc-brand); border-right:none; width:0; }
    #|.CodeMirror-code { outline:none; }
    #|.CodeMirror-scroll, .CodeMirror-sizer, .CodeMirror-gutter, .CodeMirror-gutters, .CodeMirror-linenumber { box-sizing:content-box; }
    #|.CodeMirror-measure { position:absolute; width:100%; height:0; overflow:hidden; visibility:hidden; }
    #|.CodeMirror-measure pre { position:static; }
    #|div.CodeMirror-cursors { visibility:hidden; position:relative; z-index:3; }
    #|div.CodeMirror-dragcursors { visibility:visible; }
    #|.CodeMirror-focused div.CodeMirror-cursors { visibility:visible; }
    #|.CodeMirror-linebackground { position:absolute; left:0; right:0; top:0; bottom:0; z-index:0; }
    #|.CodeMirror-selected { background:var(--mc-cobalt-surface); }
    #|.CodeMirror-focused .CodeMirror-selected { background:var(--mc-brand-surface); }
    #|.cm-tab { display:inline-block; text-decoration:inherit; }
    #|/* CodeMirror theme tokens bridged to --vscode-token-* */
    #|.cm-s-mc-theme .cm-keyword, .cm-s-mc-theme .cm-strong { color:var(--vscode-token-keyword); }
    #|.cm-s-mc-theme .cm-atom { color:var(--vscode-token-type); }
    #|.cm-s-mc-theme .cm-number { color:var(--vscode-token-number); }
    #|.cm-s-mc-theme .cm-def, .cm-s-mc-theme .cm-builtin { color:var(--vscode-token-function); }
    #|.cm-s-mc-theme .cm-variable, .cm-s-mc-theme .cm-variable-2 { color:var(--vscode-token-variable); }
    #|.cm-s-mc-theme .cm-variable-3, .cm-s-mc-theme .cm-type, .cm-s-mc-theme .cm-qualifier { color:var(--vscode-token-type); }
    #|.cm-s-mc-theme .cm-property, .cm-s-mc-theme .cm-attribute { color:var(--vscode-token-variable); }
    #|.cm-s-mc-theme .cm-tag, .cm-s-mc-theme .cm-header { color:var(--vscode-token-keyword); }
    #|.cm-s-mc-theme .cm-string, .cm-s-mc-theme .cm-string-2, .cm-s-mc-theme .cm-link { color:var(--vscode-token-string); }
    #|.cm-s-mc-theme .cm-comment, .cm-s-mc-theme .cm-meta, .cm-s-mc-theme .cm-hr { color:var(--vscode-token-comment); font-style:italic; }
    #|.cm-s-mc-theme .cm-operator, .cm-s-mc-theme .cm-punctuation, .cm-s-mc-theme .cm-bracket { color:var(--vscode-token-punctuation); }
    #|.cm-s-mc-theme .cm-error { color:var(--vscode-token-invalid); }
    #|.cm-s-mc-theme .cm-em { font-style:italic; }
    #|.mc-settings-page { position:absolute; inset:0; z-index:30; display:flex; background:var(--rui-background); overflow:hidden; }
    #|.mc-settings-rail { width:14.5rem; flex:none; display:flex; flex-direction:column; gap:0.2rem; padding:0.75rem 0.625rem; border-right:1px solid var(--rui-border); background:var(--rui-card); overflow:auto; }
    #|.mc-settings-main { flex:1; min-width:0; min-height:0; overflow:auto; padding:1.25rem 1.75rem 2rem; display:flex; flex-direction:column; }
    #|@media (max-width:48rem) {
    #|  .mc-settings-page { flex-direction:column; overflow-y:auto; }
    #|  .mc-settings-rail { width:100%; border-right:0; border-bottom:1px solid var(--rui-border); max-height:13rem; }
    #|  .mc-settings-main { flex:none; overflow:visible; padding:1rem; }
    #|}
    #|.mc-set-nav { display:flex; align-items:center; justify-content:space-between; gap:0.5rem; padding:0.45rem 0.625rem; border-radius:0.5rem; border:1px solid transparent; background:transparent; color:var(--rui-muted-foreground); font:inherit; font-size:0.75rem; font-weight:550; width:100%; }
    #|.mc-set-nav:hover { background:var(--rui-accent); color:var(--rui-foreground); }
    #|.mc-set-nav.active { background:var(--mc-brand-surface); border-color:var(--mc-brand-border); color:var(--rui-foreground); font-weight:650; }
    #|.mc-mockup-chip { display:inline-flex; align-items:center; gap:0.3rem; font-family:var(--mc-mono); font-size:0.6875rem; font-weight:650; padding:0.0625rem 0.5rem; border-radius:999px; background:var(--mc-wait-surface); color:var(--mc-wait-fg); border:1px solid var(--mc-wait); }
    #|/* Minimal Card Tree Sidebar */
    #|.mc-tree-card { --rui-sidebar-item-base-bg:transparent; --rui-sidebar-item-base-border:transparent; border-radius:0.5rem; }
    #|.mc-tree-card:hover { --rui-sidebar-item-bg:var(--rui-accent); --rui-sidebar-item-border:var(--rui-border); }
    #|.mc-tree-card.mc-tree-active { --rui-sidebar-item-base-bg:var(--mc-brand-surface); --rui-sidebar-item-base-border:var(--mc-brand-border); --rui-sidebar-item-bg:var(--mc-brand-surface); --rui-sidebar-item-border:var(--mc-brand-border); }
    #|.mc-tree-card.mc-tree-group { --rui-sidebar-item-base-bg:transparent; --rui-sidebar-item-base-border:transparent; }
    #|.mc-tree-card.mc-tree-group:hover { --rui-sidebar-item-bg:var(--rui-accent); --rui-sidebar-item-border:transparent; }
    #|.mc-tree-glyph { display:inline-flex; align-items:center; justify-content:center; flex:none; color:var(--rui-muted-foreground); }
    #|.mc-tree-glyph.mc-glyph-brand { color:var(--mc-brand); }
    #|.mc-tree-glyph.mc-glyph-branch { color:var(--mc-cobalt); }
    #|.mc-tree-glyph.mc-glyph-warn { color:var(--mc-wait); }
    #|.mc-tree-glyph.mc-glyph-danger { color:var(--rui-destructive); }
    #|.mc-tree-count { flex:none; font-family:var(--mc-mono); font-size:0.625rem; font-weight:650; line-height:1; padding:0.15rem 0.375rem; border-radius:999px; background:var(--rui-muted); color:var(--rui-muted-foreground); border:1px solid var(--rui-border); }
    #|.mc-ws-rail { position:relative; padding-inline-start:0.875rem; }
    #|.mc-ws-rail::before { content:""; position:absolute; inset-block:0; inset-inline-start:0.45rem; width:1px; background:var(--rui-border); }
    #|.mc-ws-card { position:relative; --rui-sidebar-item-base-bg:var(--rui-card); --rui-sidebar-item-base-border:var(--rui-border); border-radius:0.5rem; }
    #|.mc-ws-card:hover { --rui-sidebar-item-bg:var(--rui-accent); --rui-sidebar-item-border:var(--mc-brand-border); }
    #|.mc-ws-card[aria-current="true"] { --rui-sidebar-item-base-bg:var(--mc-brand-surface); --rui-sidebar-item-base-border:var(--mc-brand-border); --rui-sidebar-item-bg:var(--mc-brand-surface); --rui-sidebar-item-border:var(--mc-brand-border); }
    #|.mc-ws-card[aria-current="true"]::before { content:""; position:absolute; inset-block:0.35rem; inset-inline-start:0; width:2.5px; border-radius:2px; background:var(--mc-brand); }
    #|.mc-ws-dot { width:0.42rem; height:0.42rem; flex:none; border-radius:50%; background:var(--mc-brand); box-shadow:0 0 0 2px var(--mc-brand-surface); }
    #|.mc-ws-meta { display:inline-flex; align-items:center; gap:0.2rem; font-family:var(--mc-mono); font-size:0.625rem; font-weight:600; color:var(--rui-muted-foreground); }
    #|.mc-ws-meta.warn { color:var(--mc-wait-fg); }
    #|.mc-brand-btn { appearance:none; border:0; background:transparent; color:var(--rui-foreground); font:inherit; display:inline-flex; align-items:center; gap:0.5rem; min-width:0; flex:1 1 auto; padding:0.1875rem 0.25rem; margin:-0.1875rem -0.25rem; border-radius:0.45rem; text-align:left; }
    #|.mc-brand-btn:hover { background:var(--rui-accent); }
    #|.mc-brand-mark { width:1.375rem; height:1.375rem; flex:none; border-radius:0.375rem; display:inline-flex; align-items:center; justify-content:center; overflow:hidden; }
    #|.mc-brand-mark.monogram { background:var(--rui-primary); color:var(--rui-primary-foreground); font-size:0.6875rem; font-weight:750; letter-spacing:0.02em; }
    #|.mc-brand-mark.emoji { background:var(--rui-muted); border:1px solid var(--rui-border); font-size:0.875rem; line-height:1; }
    #|.mc-brand-mark img { width:100%; height:100%; object-fit:cover; display:block; }
    #|.mc-ws-pill { display:inline-flex; flex:0 2 auto; align-items:center; gap:0.35rem; min-width:0; max-width:12rem; overflow:hidden; font-family:var(--mc-mono); font-size:0.6875rem; font-weight:550; padding:0.175rem 0.5rem; border-radius:0.375rem; background:var(--rui-background); border:1px solid var(--rui-border); color:var(--rui-foreground); }
  ),
].join("\n")

///|
/// The UI. `surface` is the kind of this view, and `instance` gave its page.
/// `primary_sidebar`, `color_scheme`, and `appearance` are the values kept by
/// the browser. `mac` is true on macOS, which has other shortcuts. The UI runs
/// the connection.
pub fn app(
  connection : Connection,
  surface~ : @app.Surface,
  instance~ : @app.InstanceName,
  primary_sidebar~ : PrimarySidebar,
  sidebar_width~ : SidebarWidth = SidebarWidth::default(),
  secondary_sidebar~ : SecondarySidebar = SecondaryShown,
  secondary_sidebar_width~ : SecondarySidebarWidth = SecondarySidebarWidth::default(),
  companion_panel~ : CompanionPanel = CompanionShown,
  mac~ : Bool,
  color_scheme~ : ColorScheme = Moonrockz,
  appearance~ : Appearance = System,
  brand~ : BrandConfig = BrandConfig::default(),
) -> @rabbita.Val[@html.Html] {
  let client = connection.client
  // `rui` gives the command that closes the sheet only to the view of the sidebar.
  let close_sheet = Ref(@cmd.none)
  let (model, emit) = @rabbita.create_state_with_init(
    init=emit => {
      (
        Model::Model(
          surface~,
          instance~,
          primary_sidebar~,
          sidebar_width~,
          secondary_sidebar~,
          secondary_sidebar_width~,
          companion_panel~,
          window=window_size(),
          color_scheme~,
          appearance~,
          brand~,
        ),
        @cmd.batch([
          run_connection(connection, emit),
          sync_sidebar_splitter_cmd(emit),
        ]),
      )
    },
    update=(model, msg, emit) => update(model, msg, emit, connection),
    subscriptions=(model, emit) => {
      let failed = error => emit(CallFailed(error))
      @sub.batch([
        // The shortcuts of a view that ended are the ones of the browser.
        if model.is_over() {
          @sub.batch([])
        } else {
          on_shortcuts(
            shortcut => {
              match model.shortcut_msg(shortcut) {
                // The sheet closes before a dialog opens over the page.
                Some(msg) => Some(@cmd.batch([close_sheet.val, emit(msg)]))
                None => None
              }
            },
            mac~,
          )
        },
        @sub.on_resize(
          @cmd.Emit(_ => {
            let window = window_size()
            match window {
              // A wide window has no button for the sheet.
              Wide => @cmd.batch([close_sheet.val, emit(WindowResized(window))])
              Small => emit(WindowResized(window))
            }
          }),
        ),
        @sub.on_url_changed(
          @cmd.Emit(url => {
            let hash = match url.fragment {
              Some(fragment) => "#\{fragment}"
              None => ""
            }
            emit(HashChanged(parse_route(hash)))
          }),
        ),
        @proton_rabbita.subscribe(
          @app.projects_changed,
          projects => emit(ProjectsListed(ReadOnlyArray::from_array(projects))),
          failed,
          client~,
        ),
        @proton_rabbita.subscribe(
          @app.workspaces_changed,
          changed => emit(WorkspacesChanged(changed)),
          failed,
          client~,
        ),
        @proton_rabbita.subscribe(
          @app.project_shown,
          shown => emit(ProjectShown(shown)),
          failed,
          client~,
        ),
        @proton_rabbita.subscribe(
          @app.app_stopping,
          _ => emit(AppStopping),
          failed,
          client~,
        ),
      ])
    },
  )
  @rui.sidebar_provider_with_input(
    input=model,
    style=["flex-direction:column;height:100%;min-height:0"],
    on_mobile_open_change=@cmd.Emit(open => {
      if open {
        @cmd.none
      } else {
        // `rui` gives the focus back after this command, if the button is there.
        @cmd.custom_cmd(scheduler => scheduler.add(keep_focus(main_title_id)))
      }
    }),
    (scope, model) => {
      close_sheet.val = @rui.sidebar_close_mobile(scope)
      screen(scope, model, emit, mac~)
    },
  ).view(screen => {
    @rui.theme(class="mc-page", style=[theme_tokens], [
      @html.style_tag(@html.text(page_styles)),
      screen,
    ])
  })
}

///|
fn window_size() -> WindowSize {
  if is_wide() {
    Wide
  } else {
    Small
  }
}

///|
/// The window has space for the primary sidebar. The limit is the one in `page_styles`.
extern "js" fn is_wide() -> Bool =
  #| () => matchMedia("(min-width:48rem)").matches

///|
/// Runs the connection until it ends. An error means that it cannot try at all.
fn run_connection(connection : Connection, emit : @cmd.Emit[Msg]) -> @cmd.Cmd {
  @cmd.custom_cmd(scheduler => {
    let send = msg => scheduler.add(emit(msg))
    @js_async.Promise::from_async(() => {
      (connection.run)(state => send(ConnectionChanged(state))) catch {
        error =>
          send(ConnectionFailed("Mission Control cannot connect: \{error}"))
      }
    })
    |> ignore
  })
}

///|
fn screen(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let body = match
    EndText::of_view(model.connection, model.surface, model.instance) {
    Some(text) => end_view(text)
    None => {
      let settings_open = model.settings is Open(_)
      let workspace_attrs = if settings_open {
        @html.Attrs::build().aria_hidden("true").attribute("inert", "")
      } else {
        @html.Attrs::build()
      }
      @html.div(
        style=["position:relative;display:flex;flex:1;min-width:0;min-height:0"],
        [
          @html.div(
            style=["display:flex;flex:1;min-width:0;min-height:0"],
            attrs=workspace_attrs,
            [
              match model.primary_sidebar {
                Shown =>
                  @html.fragment([
                    project_sidebar(scope, model, emit, mac~, mobile=false),
                    sidebar_splitter_view(model.sidebar_width, emit),
                  ])
                Hidden => @html.nothing
              },
              project_sidebar(scope, model, emit, mac~, mobile=true),
              main_area(scope, model, emit, mac~),
            ],
          ),
          match model.settings {
            Open(tab) => settings_overlay(model, tab, emit)
            Closed => @html.nothing
          },
        ],
      )
    }
  }
  @html.div(
    class="mc-shell-root",
    style=[
      "--rui-sidebar-width:\{model.sidebar_width.pixels()}px",
      "--mc-secondary-width:\{model.secondary_sidebar_width.pixels()}px",
    ],
    attrs=@html.Attrs::build()
      .data_set("scheme", model.color_scheme.stored())
      .data_set("appearance", model.appearance.stored()),
    [
      body,
      status_bar(model),
      // A dialog must be in the page before a command opens it.
      add_dialog(model, emit),
      stop_dialog(model, emit),
      palette(model, emit, mac~),
    ],
  )
}

///|
/// The primary sidebar. `mobile` is the sheet with the same content, which a button opens
/// on a small screen.
fn project_sidebar(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
  mobile~ : Bool,
) -> @html.Html {
  let close_sheet = if mobile {
    Some(@rui.sidebar_close_mobile(scope))
  } else {
    None
  }
  @rui.sidebar(
    scope,
    collapsible=SidebarFixed,
    mobile~,
    aria_label=if mobile { "Projects" } else { "Primary sidebar" },
    sidebar_parts(model, emit, mac~, close_sheet~),
  )
}

///|
/// The parts of the primary sidebar. `close_sheet` is there only in the sheet.
fn sidebar_parts(
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
  close_sheet~ : @cmd.Cmd?,
) -> Array[@html.Html] {
  // The sheet closes before the message, because a dialog opens over the page.
  let leave = (msg : Msg) => {
    match close_sheet {
      Some(close) => @cmd.batch([close, emit(msg)])
      None => emit(msg)
    }
  }
  let act = (action : Action) => {
    // The sheet stays for an action that does nothing.
    if action.enabled(model) {
      leave(ActionChosen(action))
    } else {
      emit(ActionChosen(action))
    }
  }
  [
    @rui.sidebar_header(
      style=[
        "flex-direction:row;align-items:center;gap:0.375rem;padding:0.75rem 1rem",
      ],
      [
        brand_header_button(
          model.brand,
          on_click=leave(OpenSettingsTab(Appearance)),
        ),
        match close_sheet {
          Some(close) =>
            @rui.button(
              variant=Ghost,
              size=IconSm,
              attrs=@html.Attrs::build().aria_label("Close the project list"),
              on_click=close,
              icon("M6 6l12 12M18 6L6 18"),
            )
          None => primary_sidebar_button(Hidden, emit, mac~)
        },
      ],
    ),
    @html.div(
      style=["flex:none;padding:0 0.75rem 0.25rem"],
      palette_button(leave(PaletteOpened), mac~),
    ),
    @rui.sidebar_content(
      @rui.sidebar_group([
        @rui.sidebar_group_label("Projects"),
        @rui.sidebar_group_action(
          title=AddProject.title(),
          aria_label=AddProject.title(),
          attrs=action_attrs(AddProject, model),
          style=["width:1.5rem;height:1.5rem;top:0.75rem"],
          on_click=act(AddProject),
          icon("M12 5v14M5 12h14"),
        ),
        @rui.sidebar_group_content(
          @rui.sidebar_menu(
            style=["gap:0.25rem"],
            project_rows(model, act, toggle=id => emit(ProjectTreeToggled(id))),
          ),
        ),
      ]),
    ),
    @rui.sidebar_footer(
      @rui.button(
        variant=Ghost,
        size=Sm,
        attrs=action_attrs(StopApp, model),
        style=["justify-content:flex-start"],
        on_click=act(StopApp),
        [icon("M12 4v8M7.5 6.8a7 7 0 1 0 9 0"), @html.text(StopApp.title())],
      ),
    ),
  ]
}

///|
/// The control that gives the primary sidebar this state.
fn primary_sidebar_button(
  state : PrimarySidebar,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let action = SetPrimarySidebar(state)
  @rui.button(
    variant=Ghost,
    size=IconSm,
    id=state.other().control_id(),
    title="\{action.title()} (\{ChangePrimarySidebar.text(mac~)})",
    attrs=@html.Attrs::build()
      .aria_label(action.title())
      .aria_keyshortcuts(ChangePrimarySidebar.aria(mac~)),
    on_click=emit(ActionChosen(action)),
    // A panel with a left part.
    icon(
      "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM9 3v18",
    ),
  )
}

///|
/// The control that opens the command palette.
fn palette_button(on_click : @cmd.Cmd, mac~ : Bool) -> @html.Html {
  @rui.button(
    variant=Outline,
    style=[
      "width:100%;justify-content:flex-start;font-weight:400;--rui-button-base-fg:var(--rui-muted-foreground)",
    ],
    attrs=@html.Attrs::build()
      .aria_haspopup("dialog")
      .aria_keyshortcuts(OpenPalette.aria(mac~)),
    on_click~,
    [
      icon("M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM16 16l4 4"),
      @html.span("Find…"),
      shortcut_hint(OpenPalette, mac~),
    ],
  )
}

///|
/// The rows of the projects, with the keys of their actions. When an open project has
/// more than one peer workspace and is not collapsed, nested minimal workspace cards
/// expand directly below it.
fn project_rows(
  model : Model,
  act : (Action) -> @cmd.Cmd,
  toggle~ : (@app.ProjectId) -> @cmd.Cmd,
) -> Map[String, @html.Html] {
  let rows : Map[String, @html.Html] = Map([])
  let active_ws = model.active_workspace_value()
  let active_ws_id = active_ws.map(ws => ws.id)
  for project in model.projects.unwrap_or([]) {
    let open = OpenProject(project)
    let is_open = model.open_id() == Some(project.id)
    let loaded_set = if is_open &&
      model.workspace_load(project.id) is Some(Ready(Populated(set))) {
      Some(set)
    } else {
      None
    }
    let has_multi = match loaded_set {
      Some(set) => set.length() > 1
      None => false
    }
    let expanded = has_multi && !model.is_project_collapsed(project.id)
    let active_for_project = if is_open {
      match active_ws {
        Some(ws) => Some(ws)
        None =>
          match loaded_set {
            Some(set) => Some(set.default_workspace())
            None => None
          }
      }
    } else {
      None
    }
    let ws_count = match loaded_set {
      Some(set) if set.length() > 1 => Some(set.length())
      _ => None
    }
    let project_grade = if is_open && model.has_perspectives() {
      Some(model.active_mockup().rollup_grade())
    } else {
      None
    }
    let project_summary = if is_open && model.has_perspectives() {
      Some(model.active_mockup().summary())
    } else {
      None
    }
    let active_live_mounts = active_for_project.bind(ws => {
      live_available_mounts(model.sources_load(ws.id))
    })
    rows[open.id().key()] = project_row(
      project,
      is_open~,
      has_multi~,
      expanded~,
      workspace_count=ws_count,
      active_workspace=active_for_project,
      grade=if expanded { None } else { project_grade },
      summary=if expanded { None } else { project_summary },
      live_mounts=if expanded { None } else { active_live_mounts },
      on_click=if has_multi { toggle(project.id) } else { act(open) },
    )
    if expanded {
      match loaded_set {
        Some(set) =>
          for ws in set.workspaces() {
            let ws_action = OpenWorkspace(project, ws)
            let is_active = active_ws_id == Some(ws.id)
            rows[ws_action.id().key()] = workspace_row(
              ws,
              is_active~,
              grade=project_grade,
              summary=project_summary,
              live_mounts=if is_active {
                live_available_mounts(model.sources_load(ws.id))
              } else {
                None
              },
              on_click=act(ws_action),
            )
          }
        None => ()
      }
    }
  }
  rows
}

///|
/// The primary scannable label for one workspace: its Git branch or detached
/// revision when versioned, or its workspace name for plain folders.
fn workspace_primary_label(workspace : @app.Workspace) -> String {
  match workspace.position {
    OnLine(line~, ..) => line.to_string()
    Unborn(line~) => "\{line} (unborn)"
    Detached(revision~) => "detached · \{revision.short()}"
    Unversioned => workspace.name.to_string()
  }
}

///|
/// Counts live available configured mounts when `sources` has loaded, or `None`
/// while unloaded (never substituting fake preview mount counts on sibling cards).
fn live_available_mounts(sources : SourcesLoad) -> Int32? {
  match sources {
    Ready(ws_sources) => {
      let mut count = 0
      for src in ws_sources.sources {
        if src is Mounted(Resolved(m)) && m.status == Available {
          count += 1
        }
      }
      Some(count)
    }
    Idle | Loading | Failed(_) => None
  }
}

///|
/// Compact Row 3 telemetry strip shared by 3-row sidebar workspace and project cards.
fn workspace_metrics_row(
  summary : WorkspaceSummary,
  live_mounts~ : Int32? = None,
  indent~ : String = "0",
) -> @html.Html {
  let metrics : Array[@html.Html] = []
  if summary.in_flight > 0 {
    metrics.push(
      @html.span(
        class="mc-ws-meta",
        title="\{summary.in_flight} items in flight (preview)",
        [glyph(Layers, size=Xs), @html.text("\{summary.in_flight} active")],
      ),
    )
  }
  if summary.open_warnings > 0 {
    metrics.push(
      @html.span(
        class="mc-ws-meta warn",
        title="\{summary.open_warnings} open review findings (preview)",
        [glyph(Warning, size=Xs), @html.text("\{summary.open_warnings} warn")],
      ),
    )
  }
  match live_mounts {
    Some(count) if count > 0 => {
      let label = if count == 1 { "1 mount" } else { "\{count} mounts" }
      metrics.push(
        @html.span(
          class="mc-ws-meta",
          title="\{count} available mounted sources",
          [glyph(Link, size=Xs), @html.text(label)],
        ),
      )
    }
    _ => ()
  }
  if metrics.is_empty() {
    @html.nothing
  } else {
    @html.span(
      class="mc-ws-row-metrics",
      style=[
        "display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;min-width:0;padding-inline-start:\{indent}",
      ],
      metrics,
    )
  }
}

///|
/// A 3-row minimal card for one peer workspace inside the sidebar tree rail:
/// Row 1: branch/position + grade + active dot
/// Row 2: active workflow item context
/// Row 3: compact preview telemetry strip
fn workspace_row(
  workspace : @app.Workspace,
  is_active~ : Bool,
  grade~ : Grade?,
  summary~ : WorkspaceSummary?,
  live_mounts~ : Int32? = None,
  on_click~ : @cmd.Cmd,
) -> @html.Html {
  let attrs = @html.Attrs::build()
  if is_active {
    attrs.aria_current("true") |> ignore
  }
  let pos_class = if is_active {
    "mc-tree-glyph mc-glyph-brand"
  } else {
    match workspace.position {
      OnLine(..) | Unborn(..) => "mc-tree-glyph mc-glyph-branch"
      Detached(..) => "mc-tree-glyph mc-glyph-warn"
      Unversioned => "mc-tree-glyph"
    }
  }
  let grade_badge = match (workspace.folder, grade) {
    (Present, Some(g)) =>
      @html.span(
        class=grade_class(g),
        style=["font-size:0.625rem;padding:0.0625rem 0.35rem;min-width:1.35rem"],
        title="Preview workspace grade: \{g.label()}",
        g.label(),
      )
    _ => @html.nothing
  }
  let trailing = match workspace.folder {
    Missing =>
      @html.span(
        class="mc-tree-glyph mc-glyph-danger",
        title=folder_not_found,
        glyph(Warning, size=Sm),
      )
    Present =>
      @html.span(
        style=["display:inline-flex;align-items:center;gap:0.35rem;flex:none"],
        [
          if is_active {
            @html.span(
              class="mc-ws-dot",
              title="Active workspace",
              @html.nothing,
            )
          } else {
            @html.nothing
          },
          grade_badge,
        ],
      )
  }
  let primary_label = workspace_primary_label(workspace)
  let context_row = match workspace.folder {
    Missing =>
      @html.span(
        class="mc-warning",
        style=["font-size:0.6875rem;line-height:1rem;font-weight:450"],
        folder_not_found,
      )
    Present =>
      match summary {
        Some(s) =>
          @html.span(
            class="mc-cut mc-ws-row-context",
            style=[
              "font-size:0.6875rem;line-height:1rem;color:var(--rui-muted-foreground)",
            ],
            s.active_item_title,
          )
        None => @html.nothing
      }
  }
  let metrics_row = match (workspace.folder, summary) {
    (Present, Some(s)) => workspace_metrics_row(s, live_mounts~)
    _ => @html.nothing
  }
  let ws_weight = if is_active { "600" } else { "500" }
  @rui.sidebar_menu_item(
    class="mc-ws-rail",
    @rui.sidebar_menu_button(
      is_active~,
      class="mc-ws-card",
      title="\{workspace.name} — \{workspace.path}",
      attrs~,
      on_click~,
      style=[
        "flex-direction:column;align-items:stretch;justify-content:center;gap:0.2rem;height:auto;padding:0.45rem 0.55rem",
      ],
      @html.span(
        style=["display:flex;flex-direction:column;gap:0.2rem;min-width:0"],
        [
          @html.span(
            style=["display:flex;align-items:center;gap:0.4rem;min-width:0"],
            [
              @html.span(
                class=pos_class,
                position_glyph(workspace.position, size=Md),
              ),
              @html.span(
                class="mc-cut",
                style=[
                  "flex:1 1 auto;font-size:0.78125rem;line-height:1.125rem;font-weight:\{ws_weight}",
                ],
                primary_label,
              ),
              trailing,
            ],
          ),
          context_row,
          metrics_row,
        ],
      ),
    ),
  )
}

///|
/// A 3-row minimal card (when open and collapsed or single-workspace) or
/// expandable tree header for one project in the sidebar.
fn project_row(
  project : @app.Project,
  is_open~ : Bool,
  has_multi~ : Bool,
  expanded~ : Bool,
  workspace_count~ : Int32?,
  active_workspace~ : @app.Workspace?,
  grade~ : Grade?,
  summary~ : WorkspaceSummary?,
  live_mounts~ : Int32? = None,
  on_click~ : @cmd.Cmd,
) -> @html.Html {
  let attrs = @html.Attrs::build()
  if is_open {
    attrs.aria_current("true") |> ignore
  }
  if has_multi {
    attrs.aria_expanded(if expanded { "true" } else { "false" }) |> ignore
  }
  let card_class = if expanded {
    "mc-tree-card mc-tree-group"
  } else if is_open {
    "mc-row mc-tree-card mc-tree-active"
  } else {
    "mc-row mc-tree-card"
  }
  let backend_glyph_class = if is_open {
    "mc-tree-glyph mc-glyph-brand"
  } else {
    "mc-tree-glyph"
  }
  let chevron = if has_multi {
    @html.span(
      class="mc-tree-glyph",
      glyph(if expanded { ChevronDown } else { ChevronRight }, size=Sm),
    )
  } else {
    @html.nothing
  }
  let grade_badge = match (project.folder, grade) {
    (Present, Some(g)) =>
      @html.span(
        class=grade_class(g),
        style=["font-size:0.625rem;padding:0.0625rem 0.35rem;min-width:1.35rem"],
        title="Preview workspace grade: \{g.label()}",
        g.label(),
      )
    _ => @html.nothing
  }
  let trailing = match (workspace_count, project.folder) {
    (_, Missing) =>
      @html.span(
        class="mc-tree-glyph mc-glyph-danger",
        title=folder_not_found,
        glyph(Warning, size=Md),
      )
    (Some(count), Present) =>
      @html.span(
        style=["display:inline-flex;align-items:center;gap:0.35rem;flex:none"],
        [
          @html.span(
            class="mc-tree-count",
            title="\{count} workspaces",
            count.to_string(),
          ),
          grade_badge,
        ],
      )
    (None, Present) =>
      if is_open {
        @html.span(
          style=["display:inline-flex;align-items:center;gap:0.35rem;flex:none"],
          [
            @html.span(class="mc-ws-dot", title="Open project", @html.nothing),
            grade_badge,
          ],
        )
      } else {
        @html.nothing
      }
  }
  let sub_indent = if has_multi { "2.2rem" } else { "1.3rem" }
  let subtitle : @html.Html = match project.folder {
    Missing =>
      @html.span(
        class="mc-warning",
        style=[
          "font-size:0.6875rem;line-height:1rem;font-weight:450;padding-inline-start:\{sub_indent}",
        ],
        folder_not_found,
      )
    Present =>
      match active_workspace {
        Some(ws) if !expanded && !(ws.position is Unversioned) => {
          let pos_class = match ws.position {
            OnLine(..) | Unborn(..) => "mc-tree-glyph mc-glyph-branch"
            Detached(..) => "mc-tree-glyph mc-glyph-warn"
            Unversioned => "mc-tree-glyph"
          }
          @html.span(
            style=[
              "display:flex;align-items:center;gap:0.35rem;min-width:0;padding-inline-start:\{sub_indent};font-size:0.6875rem;line-height:1rem;color:var(--rui-muted-foreground)",
            ],
            [
              @html.span(class=pos_class, position_glyph(ws.position, size=Xs)),
              @html.span(
                class="mc-cut",
                style=["font-family:var(--mc-mono)"],
                workspace_primary_label(ws),
              ),
            ],
          )
        }
        _ =>
          match (summary, project.caption) {
            (Some(s), _) if !expanded =>
              @html.span(
                class="mc-cut mc-ws-row-context",
                style=[
                  "font-size:0.6875rem;line-height:1rem;color:var(--rui-muted-foreground);padding-inline-start:\{sub_indent}",
                ],
                s.active_item_title,
              )
            (_, Some(caption)) =>
              @html.span(
                class="mc-cut",
                style=[
                  "font-size:0.6875rem;line-height:1rem;color:var(--rui-muted-foreground);padding-inline-start:\{sub_indent}",
                ],
                caption.to_string(),
              )
            (_, None) => @html.nothing
          }
      }
  }
  let metrics_row = match (project.folder, summary) {
    (Present, Some(s)) if !expanded =>
      workspace_metrics_row(s, live_mounts~, indent=sub_indent)
    _ => @html.nothing
  }
  let proj_weight = if is_open { "600" } else { "500" }
  @rui.sidebar_menu_item(
    @rui.sidebar_menu_button(
      is_active=is_open && !expanded,
      class=card_class,
      title=project.path,
      attrs~,
      on_click~,
      style=[
        "flex-direction:column;align-items:stretch;justify-content:center;gap:0.2rem;height:auto;padding:0.45rem 0.55rem",
      ],
      @html.span(
        style=["display:flex;flex-direction:column;gap:0.2rem;min-width:0"],
        [
          @html.span(
            style=["display:flex;align-items:center;gap:0.4rem;min-width:0"],
            [
              chevron,
              @html.span(
                class=backend_glyph_class,
                project_backend_glyph(project.backend, size=Lg),
              ),
              @html.span(
                class="mc-cut",
                style=[
                  "flex:1 1 auto;font-size:0.8125rem;line-height:1.15rem;font-weight:\{proj_weight}",
                ],
                project.title.to_string(),
              ),
              match project.parent {
                Some(parent) =>
                  @html.span(
                    class="mc-cut",
                    style=[
                      "flex:0 3 auto;font-size:0.75rem;color:var(--rui-muted-foreground)",
                    ],
                    parent,
                  )
                None => @html.nothing
              },
              trailing,
            ],
          ),
          subtitle,
          metrics_row,
        ],
      ),
    ),
  )
}

///|
/// The display title of a project over its optional caption and path, for a list.
fn project_lines(project : @app.Project) -> @html.Html {
  @html.span(
    style=["display:flex;flex-direction:column;gap:0.125rem;min-width:0"],
    [
      @html.span(style=["display:flex;gap:0.5rem;min-width:0"], [
        @html.span(
          class="mc-cut",
          style=["flex:0 1 auto;font-weight:500"],
          project.title.to_string(),
        ),
        match project.parent {
          Some(parent) =>
            @html.span(
              class="mc-cut",
              style=["flex:0 4 auto;color:var(--rui-muted-foreground)"],
              parent,
            )
          None => @html.nothing
        },
      ]),
      match project.caption {
        Some(caption) =>
          @html.span(
            class="mc-cut",
            style=[
              "font-size:0.75rem;line-height:1.125rem;color:var(--rui-muted-foreground)",
            ],
            caption.to_string(),
          )
        None => @html.nothing
      },
      short_path(project.path),
      match project.folder {
        Missing =>
          @html.span(
            class="mc-warning",
            style=["font-size:0.75rem;line-height:1.125rem;font-weight:400"],
            folder_not_found,
          )
        Present => @html.nothing
      },
    ],
  )
}

///|
let folder_not_found : String = "Folder not found"

///|
/// A path in one line. A long path loses characters before its last two names.
fn short_path(path : String) -> @html.Html {
  let { head, tail, } = PathParts::of_path(path)
  @html.span(class="mc-path", [
    @html.span(class="mc-cut", head),
    @html.span(class="mc-cut", tail),
  ])
}

///|
fn main_area(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  @html.main_(class="mc-shell-main", [
    @html.div(
      class="mc-top",
      style=[
        "align-items:center;gap:0.5rem;padding:0.5rem 0.75rem;border-bottom:1px solid var(--rui-border)",
      ],
      [
        @rui.sidebar_trigger(
          scope,
          mobile=true,
          aria_label="Show the project list",
          icon("M4 7h16M4 12h16M4 17h16"),
        ),
        brand_header_button(
          model.brand,
          on_click=emit(OpenSettingsTab(Appearance)),
        ),
      ],
    ),
    shell_top_bar(model, emit, mac~),
    match model.notice {
      Some(text) => notice(text, emit)
      None => @html.nothing
    },
    main_content(model, emit),
  ])
}

///|
/// A failure that has no other place.
fn notice(text : String, emit : @cmd.Emit[Msg]) -> @html.Html {
  @html.div(
    style=[
      "display:flex;align-items:flex-start;gap:0.5rem;margin:1rem 1.5rem 0;padding:0.5rem 0.5rem 0.5rem 0.75rem;border:1px solid var(--rui-destructive-border);border-radius:var(--rui-radius);background:var(--rui-destructive-subtle);font-size:0.875rem;line-height:1.25rem",
    ],
    attrs=@html.Attrs::build().role("alert"),
    [
      @html.span(
        style=[
          "flex:1;min-width:0;padding-block:0.25rem;overflow-wrap:anywhere",
        ],
        text,
      ),
      @rui.button(
        variant=Ghost,
        size=IconSm,
        attrs=@html.Attrs::build().aria_label("Close the message"),
        on_click=emit(NoticeDismissed),
        icon("M6 6l12 12M18 6L6 18"),
      ),
    ],
  )
}

///|
fn main_content(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  match (model.open_project(), model.projects) {
    (Some(project), _) => shell_project_view(project, model, emit)
    (None, None) =>
      message_view(
        if model.connection is Connected {
          "Reading the projects…"
        } else {
          connection_text(model.connection)
        },
        "",
        @html.nothing,
      )
    (None, Some(projects)) =>
      if projects.is_empty() {
        message_view(
          "Add a project to start",
          "A project is a folder on this computer.",
          @rui.button(
            attrs=action_attrs(AddProject, model),
            on_click=emit(ActionChosen(AddProject)),
            [icon("M12 5v14M5 12h14"), @html.text(AddProject.title())],
          ),
        )
      } else if model.open_id() is Some(_) {
        message_view(
          "This project is not in the list", "Select a different project from the list.",
          @html.nothing,
        )
      } else {
        message_view("Select a project", "", @html.nothing)
      }
  }
}

///|
/// A message in the center of the main area, with one action.
fn message_view(
  title : String,
  text : String,
  action : @html.Html,
) -> @html.Html {
  @html.div(
    style=[
      "display:flex;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:0.5rem;padding:2rem 1.5rem;text-align:center",
    ],
    [
      main_title(title),
      if text.is_empty() {
        @html.nothing
      } else {
        @html.p(style=[text_style, "max-width:26rem"], text)
      },
      @html.div(style=["margin-top:0.5rem"], action),
    ],
  )
}

///|
let title_style : String = "margin:0;font-size:1.125rem;line-height:1.625rem;font-weight:600;overflow-wrap:anywhere"

///|
/// The title of the main area. It gets the focus when the control that had it is gone.
fn main_title(text : String) -> @html.Html {
  @html.h1(
    id=main_title_id,
    style=[title_style],
    attrs=@html.Attrs::build().tabindex(-1),
    text,
  )
}

///|
let text_style : String = "margin:0;color:var(--rui-muted-foreground);font-size:0.875rem;line-height:1.375rem;text-wrap:pretty"

///|
/// The only thing of a view that ended.
fn end_view(text : EndText) -> @html.Html {
  @html.main_(
    style=["display:flex;flex:1;min-height:0;overflow:auto"],
    @html.div(
      style=[
        "display:flex;flex-direction:column;align-items:center;gap:0.5rem;margin:auto;padding:2rem 1.5rem;text-align:center",
      ],
      attrs=@html.Attrs::build().role("alert"),
      [
        main_title(text.title),
        @html.p(style=[text_style, "max-width:30rem"], [
          @html.text(text.before),
          @html.code(
            style=[
              "padding:0.125rem 0.375rem;border-radius:0.25rem;background:var(--rui-muted);color:var(--rui-foreground);font-family:var(--mc-mono);font-size:0.8125rem;white-space:nowrap",
            ],
            text.command,
          ),
          @html.text(text.after),
        ]),
      ],
    ),
  )
}

///|
fn status_bar(model : Model) -> @html.Html {
  let state = match model.connection {
    Connected => "good"
    Connecting | Reconnecting => "wait"
    Restarted | Stopped => "end"
  }
  let instance = match model.other_instance() {
    Some(name) =>
      @html.span(
        class="mc-cut",
        style=["font-weight:600;color:var(--rui-foreground)"],
        title="The name of this instance",
        name,
      )
    None => @html.nothing
  }
  let version = match model.info {
    Some(info) => @html.span(info.version.to_string())
    None => @html.nothing
  }
  @html.footer(
    style=[
      "display:flex;flex:none;align-items:center;gap:1rem;min-width:0;height:1.75rem;padding-inline:0.75rem;border-top:1px solid var(--rui-border);background:var(--rui-sidebar);color:var(--rui-muted-foreground);font-size:0.75rem;white-space:nowrap",
    ],
    [
      @html.span(
        style=["display:flex;align-items:center;gap:0.5rem"],
        attrs=@html.Attrs::build().role("status").aria_live("polite"),
        [
          @html.span(
            class="mc-dot",
            attrs=@html.Attrs::build()
              .aria_hidden("true")
              .data_set("state", state),
            @html.nothing,
          ),
          @html.span(connection_text(model.connection)),
        ],
      ),
      instance,
      @html.span(style=["flex:1"], @html.nothing),
      @html.span(surface_text(model.surface)),
      version,
    ],
  )
}

///|
/// The content is in the page only while the dialog is open. Then a new dialog has a
/// new input, and no text of the last one.
fn add_dialog(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  @rui.dialog(
    id=AddElement.id(),
    // A click outside must not lose the text.
    closedby="closerequest",
    on_close=@cmd.Emit(_ => emit(DialogClosed(AddElement))),
    attrs=@html.Attrs::build().aria_labelledby("add-title"),
    style=["width:min(calc(100% - 2rem),30rem)"],
    match model.dialog {
      AddDialog(path~, state~) => add_form(path, state, model, emit)
      _ => @html.nothing
    },
  )
}

///|
fn add_form(
  path : String,
  state : AddState,
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let (note_id, note) = match state {
    Refused(text) =>
      (
        "add-path-error",
        @rui.field_error(
          id="add-path-error",
          style=["overflow-wrap:anywhere"],
          text,
        ),
      )
    Typing | Browsing | Sending =>
      (
        "add-path-help",
        @rui.field_description(
          id="add-path-help",
          "Type the complete path of a folder on this computer.",
        ),
      )
  }
  let possible = AddProject.enabled(model)
  let refused = state is Refused(_)
  // The path does not change while the folder dialog is open or the server has it.
  let busy = state is (Browsing | Sending)
  // A browser cannot give the path of a folder to a page.
  let browse = match model.surface {
    Desktop =>
      @rui.button(
        variant=Outline,
        attrs=enabled_attrs(!busy),
        on_click=emit(BrowseChosen),
        "Browse…",
      )
    Browser => @html.nothing
  }
  @html.form(on_submit=emit(AddSubmitted), [
    @rui.dialog_header(@rui.dialog_title(id="add-title", "Add a project")),
    @rui.field(invalid=refused, [
      @rui.field_label(for_=add_path_id, "Folder path"),
      @html.div(style=["display:flex;gap:0.5rem"], [
        @rui.input(
          id=add_path_id,
          value=path,
          read_only=busy,
          required=true,
          invalid=refused,
          autofocus=true,
          auto_complete="off",
          on_input=@cmd.Emit(text => emit(PathTyped(text))),
          attrs=@html.Attrs::build()
            .aria_describedby(note_id)
            .spellcheck(false)
            .autocapitalize("off"),
          style=["flex:1;min-width:0;font-family:var(--mc-mono)"],
        ),
        browse,
      ]),
      note,
    ]),
    @rui.dialog_footer([
      @rui.button(variant=Outline, on_click=emit(CloseDialog), "Cancel"),
      @rui.button(
        type_="submit",
        attrs=enabled_attrs(possible && !busy),
        // The dialog is over the status bar, so the button has the state.
        if !possible {
          connection_text(model.connection)
        } else if state is Sending {
          "Adding…"
        } else {
          "Add project"
        },
      ),
    ]),
  ])
}

///|
/// The attributes of a button that the user can use now, or not. The button keeps the
/// focus, which the attribute `disabled` takes away. `step` ignores its message.
fn enabled_attrs(enabled : Bool) -> @html.Attrs {
  let attrs = @html.Attrs::build()
  if enabled {
    attrs
  } else {
    attrs.aria_disabled("true")
  }
}

///|
/// The attributes of the button for an action.
fn action_attrs(action : Action, model : Model) -> @html.Attrs {
  enabled_attrs(action.enabled(model))
}

///|
fn stop_dialog(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  let content = if model.dialog is ConfirmStop {
    @html.fragment([
      @rui.alert_dialog_header([
        @rui.alert_dialog_title(id="stop-title", "Stop Mission Control?"),
        @rui.alert_dialog_description(
          id="stop-text",
          "This stops Mission Control for each browser page and desktop window. Your projects stay in the list.",
        ),
      ]),
      @rui.alert_dialog_footer([
        @rui.button(
          variant=Outline,
          autofocus=true,
          on_click=emit(CloseDialog),
          "Cancel",
        ),
        @rui.button(
          variant=Destructive,
          attrs=action_attrs(StopApp, model),
          on_click=emit(StopConfirmed),
          "Stop Mission Control",
        ),
      ]),
    ])
  } else {
    @html.nothing
  }
  @rui.alert_dialog(
    id=StopElement.id(),
    on_close=@cmd.Emit(_ => emit(DialogClosed(StopElement))),
    attrs=@html.Attrs::build()
      .aria_labelledby("stop-title")
      .aria_describedby("stop-text"),
    content,
  )
}

///|
extern "js" fn page_icon_href() -> String =
  #| () => (typeof document !== "undefined" ? (document.querySelector('link[rel="icon"]')?.getAttribute("href") ?? "") : "")

///|
/// Renders the configurable brand mark (default Moonrockz Flight Director icon,
/// monogram badge, emoji mark, or uploaded raster image).
fn brand_emblem(mark : BrandMark) -> @html.Html {
  match mark {
    Moonrockz => {
      let href = page_icon_href()
      if !href.is_empty() {
        @html.span(
          class="mc-brand-mark",
          attrs=@html.Attrs::build().aria_hidden("true"),
          @html.img(src=href, alt=""),
        )
      } else {
        @html.span(
          class="mc-brand-mark monogram",
          attrs=@html.Attrs::build().aria_hidden("true"),
          "MC",
        )
      }
    }
    Monogram(mono) =>
      @html.span(
        class="mc-brand-mark monogram",
        attrs=@html.Attrs::build().aria_hidden("true"),
        mono.as_str(),
      )
    Emoji(emoji) =>
      @html.span(
        class="mc-brand-mark emoji",
        attrs=@html.Attrs::build().aria_hidden("true"),
        emoji.as_str(),
      )
    CustomImage(img) =>
      @html.span(
        class="mc-brand-mark",
        attrs=@html.Attrs::build().aria_hidden("true"),
        @html.img(src=img.as_str(), alt=""),
      )
  }
}

///|
/// Clickable brand emblem and title shown in the sidebar header and mobile bar.
fn brand_header_button(brand : BrandConfig, on_click~ : @cmd.Cmd) -> @html.Html {
  let title_text = brand.title.as_str()
  @html.button(
    class="mc-brand-btn",
    title="Customize appearance and branding",
    attrs=@html.Attrs::build().aria_label(
      "\{title_text} — Customize appearance and branding",
    ),
    on_click~,
    [
      brand_emblem(brand.mark),
      @html.span(
        class="mc-cut",
        style=["font-size:0.875rem;font-weight:650"],
        title_text,
      ),
    ],
  )
}

///|
/// Closed set of vector glyphs rendered inside sidebar cards, pills, and indicators.
priv enum Glyph {
  Folder
  Repo
  Branch
  Commit
  Layers
  Link
  Sun
  Moon
  Monitor
  ChevronDown
  ChevronRight
  Warning
}

///|
fn Glyph::path(self : Glyph) -> String {
  match self {
    Folder =>
      "M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"
    Repo =>
      "M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"
    Branch =>
      "M6 3v12M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 9a9 9 0 0 1-9 9"
    Commit => "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 12h6M15 12h6"
    Layers => "M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"
    Link =>
      "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
    Sun =>
      "M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10zM12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
    Moon => "M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"
    Monitor => "M2 4h20v12H2zM8 20h8M12 16v4"
    ChevronDown => "M6 9l6 6 6-6"
    ChevronRight => "M9 6l6 6-6 6"
    Warning =>
      "M10.3 3.9L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0zM12 9v4M12 17h.01"
  }
}

///|
/// Closed set of pixel sizes for vector glyphs in the workspace shell.
priv enum GlyphSize {
  Xs
  Sm
  Md
  Lg
  Icon
}

///|
fn GlyphSize::px(self : GlyphSize) -> Int32 {
  match self {
    Xs => 11
    Sm => 12
    Md => 13
    Lg => 14
    Icon => 16
  }
}

///|
/// Renders an SVG stroke path of 24 by 24 units at a typed size.
fn svg_stroke(line : String, size~ : GlyphSize) -> @html.Html {
  let px = size.px()
  @html.span(
    style=[
      "display:inline-flex;align-items:center;justify-content:center;flex:none",
    ],
    attrs=@html.Attrs::build().aria_hidden("true"),
    @svg.svg(
      width=px,
      height=px,
      view_box="0 0 24 24",
      attrs=@svg.Attrs::build().stroke_linecap("round").stroke_linejoin("round"),
      [@svg.path(d=line, fill="none", stroke="currentColor", stroke_width=2)],
    ),
  )
}

///|
/// An icon of 24 by 24 units, as one line. The text near it, or the label of its
/// button, has the meaning.
fn icon(line : String) -> @html.Html {
  svg_stroke(line, size=Icon)
}

///|
/// A typed 24x24 vector glyph for sidebar cards, pills, and compact indicators.
fn glyph(kind : Glyph, size~ : GlyphSize) -> @html.Html {
  svg_stroke(kind.path(), size~)
}

///|
/// The backend glyph for a project card: a repository icon for VCS-backed
/// projects and a folder icon for plain-folder projects.
fn project_backend_glyph(
  backend : @app.BackendId,
  size~ : GlyphSize,
) -> @html.Html {
  if backend == @app.BackendId::folder() {
    glyph(Folder, size~)
  } else {
    glyph(Repo, size~)
  }
}

///|
/// The position glyph for a workspace card or pill: branch, detached commit,
/// or plain folder.
fn position_glyph(position : @app.Position, size~ : GlyphSize) -> @html.Html {
  match position {
    OnLine(..) | Unborn(..) => glyph(Branch, size~)
    Detached(..) => glyph(Commit, size~)
    Unversioned => glyph(Folder, size~)
  }
}