Under the hood

`@outl/shared`: the pure helpers

@outl/shared: the pure helpers

Every pure function in the shared library, with the Rust source each one mirrors.

Moved out of crates/outl-frontend-shared/CLAUDE.md, which is loaded into the model’s context on every session in that crate. The catalog is reference: you look an entry up before writing a helper, you do not read it top to bottom. The decision rule for what may enter the library stayed in that file.

The surface is three pages, so grep all of them at once: grep -n 'symbol' docs/frontend-shared-*.md.

PageWhat it lists
frontend-shared-views.mdComponents and the view pieces both clients render
frontend-shared-wire.mdThe DTOs the Rust backend serialises, and the typed invoke() wrappers
frontend-shared-logic.mdPure helpers: paste, autocomplete, outline walks, journal math, caret navigation
ConceptEntryMirrors (Rust)
EMPTY_REMINDER_NOTICE + reminderHasText(r) — what a reminder row says when its block has no text of its own (remind:: 3pm on an empty bullet), and the predicate that decides. Both GUI clients label that row with it and keep it tappable, so a second copy would tell one user two things about one block; reminders.test.ts also denies the wordings that claim the block was deleted, which it was not (outl_actions::reminders drops anything with no enclosing page). Deliberately apart from commands-reminders.ts, so a test that mocks the commands module still sees the real sentence@outl/shared/remindersNo Rust mirror — copy only. The row itself comes from outl_actions::reminders listing a live block with an empty body
groupTasksByPage(tasks) → TaskGroup<T>[] ({ slug, tasks }) — one section per page for a task list, in order of first appearance, so a page keeps the position its best-ranked row earned and its later rows join that section instead of opening a second one. The parameter is structural ({ source_slug }), not the TaskHit DTO, for the reason it does not live in api/overview.ts beside listOpenTasks: both clients mock that module wholesale, which would replace this with undefined in exactly the tests that render a grouped list — same split EMPTY_REMINDER_NOTICE has from commands-reminders.ts. It never ranks; the order arrives decided. It is shared because it was not: TasksPanel.tsx and TasksSheet.tsx each had a copy, both folding only adjacent rows, so a page holding a DOING and a TODO got two headings on both clients@outl/shared/tasksno Rust mirror — sectioning only. The order comes from outl_tauri_shared::commands::tasks::collect_open_tasks
installForegroundRefresh(deps) / drainOnce(deps) — land the captures waiting in the inbox (RFC 0363) on mount, on every return to the foreground (visibilitychange and focus, since a desktop window regains focus without a visibility change), and when the native side calls window.__outlCapturesArrived(). Shared because the trigger is identical and only the writer differs by platform: an iOS widget / App Intent / share extension, an Android share target, or outl capture on a desktop. deps.pull reloads the view and deps.notify says what landed; a failed drain is quiet and leaves the capture for next time. drainMessage reports skipped as well as landed — a file the drain could not read stays in the inbox, so saying nothing means the capture silently never appears and the only trace is a tracing::warn!@outl/shared/capturedrain_capture_inbox (outl_tauri_shared::capture_inbox) over outl_actions::capture
backlinkEditTarget(link) → {pageId, blockId} | null — which (page, block) a gesture on a backlink row mutates; null for an orphan (the citing block lives outside any page), whose row every client leaves inert. backlinkCommitPlan({sourcePageId, openPageId}) → {applyView, refetchBacklinks} — what a cross-page reply may touch: applyView is true only when the source page is the open one, which a page citing itself makes reachable, and the refetch is unconditional because deciding when a mutation elsewhere cannot change what cites this page is a second opinion about the backlink index. backlinkCreatedElsewhere(page, side, openPageId) → string | null — the sentence after a create, since the new block cites nothing and so is a backlink of no page that no row will render. It takes a resolved PageMeta (no unreachable fallback), names no client’s own chrome (a group header on the desktop, a card header on the phone) and stays inside a toast’s width; a test pins both. null when the source page is the open one, where it would be a lie: the owner decides whether there is a sentence, so no client gates it@outl/shared/backlink-editno Rust mirror — the decisions are client-side. The TUI says its own terminal-shaped version in create_beside_a_backlink, and the strict write underneath is outl_tauri_shared::commands::backlink_edit::edit_backlink_block
caretExit(key, text, start, end) → CaretExit | null and resolveCaretExit(blocks, id, exit) → CaretLandingTarget | null — cross-block caret nav in Insert mode: the outline reads as one continuous document, so ← at offset 0 lands at the end of the block above, → at the end lands at the start of the one below, and ↑ / ↓ on the block’s first / last line carry the column over. The one owner of both halves — does this keystroke leave the block and which block does it hand the caret to — so what a client keeps is only what it alone knows: which blocks are on screen, and how it enters Insert. Three rules worth not undoing. Offsets are codepoints (convert with utf16OffsetToCharOffset on the way in); a non-empty selection always answers null, because an arrow collapses a selection in place on every platform and hijacking that would make the first arrow after a drag jump to another block; and resolveCaretExit indexes flattenVisible rather than calling nextVisibleId / previousVisibleId, because those read a missing id as the first block — so a block a peer deleted mid-edit would teleport the caret to the top of the page. CaretLandingTarget carries the neighbour’s wire text beside the offset, because the offset was measured against it: a client that re-fetched the block and seeded its editor from the DTO’s split text would land the caret a TODO short. A line here is a logical \n line, never a soft-wrapped visual one — the same rule the TUI ships, and the module doc carries why both alternatives are worse@outl/shared/caret-navoutl_tui::input::{cross_block_nav_eligible, cross_block_step} + EditBuffer::move_up / move_down
looksLikeOutline@outl/shared/pasteoutl_actions::paste::looks_like_outline
hasMultipleParagraphs@outl/shared/pastemirror of split_paragraphs(...).length > 1 in outl_actions::paste — gate that decides whether plain text needs the structured backend path
htmlToOutlMarkdown@outl/shared/pasteRich-clipboard text/html → outl markdown via Turndown, configured for the outl dialect (*italic* not _italic_, **bold**, - bullets collapsed to 2-space nesting, ~~strike~~, inline <img alt> → its alt text so Slack :emoji: survives). No Rust mirror — HTML only reaches the GUI webview clients; the resulting markdown then rides the same paste_markdown_at backend path as any paste
choosePasteRoute(html, plain) → PasteRoute@outl/shared/pasteThe one owner of the paste-with-formatting routing decision (rich = HTML converted to markdown; structured = plain outline / multi-paragraph; native = trivial, let the browser splice). Desktop handlePaste and mobile onPaste both call it, so the gate can’t drift between clients — it used to be duplicated inline in each handler
utf16OffsetToCharOffset@outl/shared/paste(runtime gap — UTF-16 ↔ codepoint, no Rust mirror)
charOffsetToUtf16Offset(text, charOffset) — the inverse, for an offset coming back from the backend (PasteReply.host_caret). Clamps past the end rather than running off it. The composition with utf16OffsetToCharOffset rounds up through a surrogate pair, which paste.test.ts pins — the opposite reading would land a caret before text the user just pasted@outl/shared/paste(runtime gap — no Rust mirror)
pasteEditorUpdate(reply) → { text, caret } | null — what an editor has to become after a paste, with the caret already in UTF-16 units. The one owner of two decisions: whether the paste touched the block being edited (host_text present, not truthy — pasting over a whole selection legitimately empties it) and where the caret lands. Every client holds that block as a draft seeded once, so re-rendering the outline is not enough: a caret paste rewrites that exact block, and an editor left on the pre-paste string commits it back over the paste on the next Esc / blur (#488). Applying it stays per client — mobile parks the caret twice around a programmatic value = for WKWebView, the desktop does not@outl/shared/pastereads outl_actions::PasteOutcome’s host_text / host_caret. Never re-derive either as “where I pasted plus what I sent” — the merge may have inserted a separating space
detectRefContext (four kinds: page [[…]], block ((…)), mention @…, tag #…), autoClose/DeletePair, insertPair/Text, applySuggestion. A tag has no closer and stops at whitespace, which is what tells it from a mention (@Thiago Avelino keeps its space) and from a markdown heading (# has one). The fence check is separate, because whitespace cannot catch #!/bin/sh@outl/shared/autocompleteoutl_tui::actions::overlay::detect_trigger
detectSlashContext / applySlashContext (+ SlashContext) — word-initial /command trigger + token removal on accept, powering the desktop’s inline slash menu. Word-initial = block start or right after whitespace, detect_trigger’s rule verbatim; it read value[0] !== "/" for months, so nota / opened nothing in a GUI while the same keystrokes opened the menu in the terminal. In autocomplete/slash.ts, re-exported from index.ts (the emoji.ts answer to the same ratchet)@outl/shared/autocompleteoutl_tui::actions::autocomplete::detect_trigger
autoPairBracket (single (/[/{ auto-pair + closer step-over; autoDeletePair also collapses empty ()/[]/{})@outl/shared/autocompleteoutl_tui::input::insert (insert_pair) + EditBuffer::delete_pair_back
tableElementToMarkdown(table, convert) + looksLikeTable / looksLikeTabular — the clipboard side. Turndown ships no table rule, so a pasted <table> used to collapse into a run of cell text; the two detectors gate the backend round trip for a markdown table and for a spreadsheet’s tab-separated text/plain@outl/shared/pastetableElementToMarkdown is TypeScript-only (HTML never reaches Rust); the detectors mirror outl_actions::paste::looks_like_table / looks_like_tabular
Content-transformer registry + cache (loadTransformers, transformerFor(lang) → PluginTransformer | null, runTransform(blockId, transformer, body) cached by (blockId, body)) — the lang → transformer Solid signal both clients load once per workspace open, plus the per-fence result cache (a failed transform drops its key so a later render retries; a reload clears the cache since results may now differ)@outl/shared/plugins/transformer-registryno Rust mirror — client lifecycle glue over plugin_transformers / plugin_transform, identical on both clients
rawTextWithTodo(block) — wire-format text with the task prefix (TODO / DOING / DONE ) reattached, what every client’s editor shows so the user can erase / type the prefix@outl/shared/outlinemirror of outl_actions::split_todo in reverse (keep in sync with TASK_PREFIXES)
visibleRangeSlice(anchor, cursor, outline) — the ids a selection range covers, DFS visible order. One owner for what every range op walks on both GUI clients, because the alternative was a comment in each client saying the copies matched. null when an endpoint is unset or no longer visible: indexOf returns -1 and ids.slice(-1, hi + 1) is the last block of the page, not an empty range, so three of the four copies this replaced turned a stale anchor into a silent one-block op@outl/shared/outlineone flattenVisible walk, where visualRangeIds plus a caller re-flattening cost two
cycleTodo(raw) — none → TODO → DOING → DONE → none on wire-format text, quote prefix peeled and re-emitted in canonical order (TODO > body, never TODO > TODO body). The editing path: a client mid-edit holds the text in a textarea draft seeded once, so routing the toggle through the backend updated the outline behind a stale draft and the new state only appeared on leaving Insert. Clients splice this into the draft instead, the way the TUI mutates its EditBuffer. The stop list (TASK_PREFIXES) must match outl_actions::todo exactly — this function exists to skip the round trip, so a cycle that disagrees shows the user a state the op log never receives@outl/shared/outlinemirror of outl_actions::todo::cycle_todo (same pair rawTextWithTodo tracks)
Outline walks — findBlock, flattenNodes (DFS preorder, returns BlockNodes), countDescendants, plus the id-returning selection walks: flattenVisible (skips collapsed subtrees), flattenAll (every id, zR), flattenParents (zM fold-all targets — mirror of outl-tui’s collect_collapse_candidates), nextVisibleId / previousVisibleId (vim j/k; previous returns null at the top, never the current block), visualRangeIds / visualRangeSet (memoise the Set at the parent — per-row predicates are O(N²)) / isInVisualRange@outl/shared/outlineoutl-tui’s outline walks (collect_collapse_candidates for flattenParents); pure functions over BlockNode[], no invoke
soleTokenValue(tokens, kind) / collectTokenValues(outline, kinds) (outline/token-walk.ts) — the two walks ((blk-…)), !((blk-…)) and ![[page]] share, written once. Both kinds asked the same questions and differed only in which kind counted, so there were two copies of each — and the copied part was the subtle part: the whitespace-only skip, the second-match rejection, and WRAPPERS, the list of token kinds whose inner is descended. That last one is the drift that reaches a user: add a wrapper kind, update one copy, and a ((ref)) inside it resolves while a ![[page]] inside it silently does not, on the same screen. Its own module so page-embed.ts can import it without a cycle@outl/shared/outline (internal; the four named wrappers are the public surface)no Rust mirror
embedOnlyHandle(tokens) → string | null — the embed handle when a block’s tokens are a single !((blk-X)) embed (whitespace-only plain tokens ignored); null for mixed prose, a bare ((…)) ref, or two embeds. Gate for whether to expand <EmbeddedSubtree /> under a block@outl/shared/outlinemirror of outl-tui’s embed_only_handle (view/embed.rs)
collectBlockRefHandles(outline) → string[] — distinct blockref + embed handles across an outline (DFS on children, descends bold/italic/strike inner), de-duped by first appearance. Lets a client batch-resolve every handle in one resolveEmbeds call before render@outl/shared/outlineno Rust mirror — client-side pre-resolve pass
pageEmbedOnlyName(tokens) → string | null and collectPageEmbedNames(outline) → string[] — the ![[page]] twins of the two rows above, rule for rule (whitespace-only plain ignored; mixed prose, two embeds or a bare [[ref]] → null; the collection walk descends inner and de-dupes). Deliberately not merged with their block-embed twins into one function: a block holding both a !((blk-x)) and a ![[page]] is mixed prose to each of them, which is the answer each already gives, and a merged helper would have to report which kind it found so every caller could branch on it@outl/shared/outline (src/outline/page-embed.ts)pageEmbedOnlyName has no Rust mirror yet (the TUI has no page-embed expansion); collectPageEmbedNames is a client-side pre-resolve pass
createPageKey(page, select, equals?) — the one owner of “did the open page change?”. Every client replaces the page object on every reply, mutations included (applyPageState / applyView), so a tracked source read straight off it fires on each keystroke-commit — and on() does not stop that: it makes a dependency explicit and never compares values. This is a createMemo with a name, undefined while no page is open (which also keeps a createResource idle). It exists because the rule was documented and false: the desktop’s backlinks fetch blanked its rows and unmounted the section for an O(blocks-in-workspace) scan on every block created or deleted, and its sidebar rewrote localStorage synchronously on every commit — both under on(() => appState.page?.slug, …), one of them under a comment claiming it fired once per navigation. Do not reach for it when the effect must re-run on every reply and only behave differently on a real change (installPageChangeEffect repairs a stale selection when the outline lands); the file’s own doc owns that distinction. page-key.parity.test.ts is the net, and it reads both clients’ sources: the shape is refused on its own, with a declared exception per file and a reason@outl/shared/navigation (src/navigation/page-key.ts)no Rust mirror — Solid reactivity only
lateSectionVisible({ answered, count, keepWhenEmpty }) — whether a section fed by a reply that lands after the first paint is on screen: a first load draws nothing, a refetch keeps its rows, an empty state is an answer and never a guess. Both GUI backlinks surfaces were on the wrong side of it in mirror-image ways (a skeleton that collapsed back to nothing; “Linked from 0” over a scan still running). The file’s own doc is the owner of the rule, the measurement and what each case costs — read it before changing the predicate@outl/shared/outline (src/outline/late-section.ts)no Rust mirror. It is the half root CLAUDE.md’s “shows its own placeholder in its own section” leaves open (UX.md → Never block a keystroke)
sameCrumbTrail(a, b) — do two ancestor trails name the same chain of blocks, compared by id (all-or-nothing, not a shared-prefix count)? Generic over { id }, so it works for both BacklinkCrumb and FocusCrumb. Drives the backlinks panel’s breadcrumb collapse: consecutive references inside the same branch render the trail once@outl/shared/outlinemirrored by outl-tui’s local same_trail in view/backlinks.rs (no upstream Rust owner — each Rust client keeps its own copy since the comparison is render-local)
focusSubtree(blocks, blockId) → FocusView { root, breadcrumb } | null (+ FocusCrumb { id, text }) — zoom/focus: the subtree to render as the new root plus the ancestor breadcrumb (page-top first, parent last). null = stale zoom target (block deleted/moved) → caller drops the zoom. Zoom is local view state, never a Tauri round-trip (the client already holds the whole outline)@outl/shared/outlineno Rust mirror — zoom is frontend-only view state
Journal slug + calendar math — parseJournalSlug / formatJournalSlug / journalSlugToDate (local-time parse; new Date("YYYY-MM-DD") is midnight UTC and renders the previous day in negative-offset timezones), daysInMonth, MONTH_NAMES, DAY_LABELS (Sunday-first, mobile sheet) / DAY_LABELS_MONDAY_FIRST (TUI-style, desktop sidebar), mondayIndex, prevMonth / nextMonth (pure year-rollover). The calendar chrome stays per-client — only the math/parsing is shared. monthIndex is 0-based everywhere (JS Date convention)@outl/shared/journalthe YYYY-MM-DD journal slug contract (outl_actions date slugs); no Rust mirror for the grid math
createDayClock(deps) → { today, refresh } + shouldWakeToToday(…) + nextDayCheckDelay(now, maxMs?) + WAKE_AFTER_MS / MAX_DAY_CHECK_MS — the one owner of “which day is it” for a client that stays open across midnight. The value is always the backend’s today_slug; the browser clock only decides when to ask, and because a configured [calendar] timezone puts midnight somewhere the browser does not know about, that delay is capped at an hour. Re-asks on the local-midnight tick, on visibilitychange and on focus/blur (a desktop window regains focus without a visibility change). wake is opt-in: coming back to a client left on another day opens today, never on the midnight tick itself and never mid-edit (UX.md principles 1 and 6). The desktop had two frozen copies of this fact before it existed — a createResource keyed on the page slug, which only re-ran on navigation, and a new Date() in the sidebar calendar’s body, which was also on the wrong clock — so a window left open overnight called yesterday “Today” and ringed yesterday on the calendar. shouldWakeToToday was outl-mobile’s lib/wake-to-today.ts, promoted whole@outl/shared/journal (src/journal/day-clock.ts, re-exported)no Rust mirror; the day comes from today_slug_cmd over outl_actions::clock
journalHeading(slug, todaySlug, locale?) → { title, date } | null — what a journal header calls its day: Today / Yesterday / Tomorrow relative to todaySlug, else the weekday, plus the full locale date. todaySlug is the backend’s today_slug (configured timezone, outl_actions::clock), never the browser clock; null while unknown gives every day its weekday. null for a slug that is not a real date, so the caller falls back to the slug. Desktop PageTitle and mobile JournalHeader both call it@outl/shared/journalno Rust mirror; the day anchor comes from today_slug_cmd
refReplacement(page, opts?) — the page name spliced in when a ref suggestion is accepted: journals insert their ISO slug, everything else (and every @ mention) inserts the title (bug #88 was the chip strip writing the slug). { tag: true } inserts the slug whatever the kind, because # ends at the first space and a title like “Deep Work” would write #Deep and leave the rest as prose@outl/shared/autocompleteno Rust mirror — pairs with applySuggestion
installFileDrop(handlers) → Promise<UnlistenFn> — wires the Tauri webview’s onDragDropEvent (onEnter/onOver/onLeave optional, onDrop(paths, blockId) required); resolves the hit-tested block id under the drop from the raw physical-pixel position. physicalToCss(position, dpr) (HiDPI physical→CSS), blockIdFromElement(el) / blockIdAtPhysical(position) (.closest("[data-block-id]") hit-test), joinAssetMarkdowns(markdowns) (space-join, drop empties), appendMarkdownToBlock(existing, markdown) (space-separated append, no leading space on an empty block) are the pure helpers underneath, unit-tested; installFileDrop itself needs a real webview. Desktop and mobile both wire it identically so the drop geometry can’t drift between clients@outl/shared/drag-dropno Rust mirror — OS drag-drop only reaches the GUI webview clients; the import itself rides importAssetFile