/**
* The state of the line above the transport.
*
* One store for two verbs' worth of typing, because it is one field: `/` and `:` put
* the caret in the same `` and differ only in what the next Enter means. Two
* stores would have to agree about the caret, and two caret-states on one element is
* the bug, not the design.
*
* What lives here, and what does not:
*
* - the *needle* does not — it is the library's, and lives in `lib/library/query.ts`
* with the server stamp that keeps one host's search from silently filtering
* another's. The line types it; the list reads it.
* - the *command text* does, and is deliberately not persisted. A search is a
* question you may be mid-typing when the page goes away; a command is a press,
* and the last thing typed at a prompt is the one thing you do not want back.
* - the *outcome* of the last command does, and dies on the next key — the same life
* the toolbar's share line has, for the same reason: it is feedback on a press, and
* feedback that outlives the thing it reported on becomes furniture.
*
* Two of the values are mirrored in plain variables beside their signals, the way
* `createPersistentSignal` is built (see lib/persist.ts for the why): a key handler
* reads them in the same task that wrote them — the input event that moved the text,
* then the Enter that runs it — and Solid defers commits, so reading the signal there
* can answer with the value from before the keystroke. `submit()` asking the signal
* what the line holds is how `:vol 40` becomes Enter on an empty prompt.
*
* The DOM handshake is an `attach`, not a portal: the store is asked to focus the
* field and it focuses the field it was handed. That is what components/LibraryView did
* with its `box` ref for as long as the query lived there, and the alternative — a
* nonce the component watches so it can call `focus()` on itself — is the same method
* call with a signal attached.
*/
import { createSignal, untrack, type Accessor } from "solid-js";
import { describe, runCommand, splitCommand } from "./commands";
/** What the next Enter means, and what the prompt says. */
export type CommandLineMode = "search" | "command";
/** The line left beside the prompt: a result, a refusal, or the readout of a word. */
export interface CommandLineNotice {
text: string;
bad: boolean;
}
/**
* What the mounted view owes the line, for the three keys the field cannot answer on
* its own.
*
* The line is app chrome — it sits beside the transport and survives navigation —
* while Enter in a search box is a question about a list: *which* row does this filter
* leave, and where does the cursor go when the caret is given back. Only the view
* knows. Registered rather than imported both ways, because the line must work with no
* view mounted (the 404 route, the login gate) and a view must not have to be the thing
* that owns the caret.
*/
export interface CommandLineHost {
/** `/` was pressed: show the view a search filters, if another one is up. */
prepareSearch(): void;
/** Enter in the search field, after the caret left: act on what the filter left. */
acceptSearch(): void;
/** Escape on an empty query: fall back to the list. */
dismissSearch(): void;
/**
* How many tracks the current needle leaves.
*
* A reactive read, not a snapshot: the line prints it beside the field, and the two
* have to be the same frame of the same filter as the rows underneath them.
*/
matches(): number | null;
}
export interface CommandLineStore {
/** `search` until `:` is typed, `command` until the field loses focus. */
mode: Accessor;
/** the imperative twin, for the key handler that reads what its own press wrote */
peekMode(): CommandLineMode;
/** Whether the caret is in the field — the line live, or furniture. */
focused: Accessor;
/** What the field holds in command mode. The search half reads the query store. */
command: Accessor;
/** ...and its imperative twin, for the same reason as `peekMode`. */
peekCommand(): string;
setCommand(value: string): void;
/**
* What the line says beside the prompt: the last command's outcome while the field is
* empty, and a running commentary on the word being typed once there is one.
*/
hint: Accessor;
/**
* What the mounted view says the current needle leaves, or null with no view up.
*
* Read straight through to the view rather than copied into a signal of this store's,
* which is the shape this had first and which the reactive diagnostics correctly
* called a tear: a write-through effect keeps a derived number one flush behind the
* rows it came from, so the line and the list paint two frames of one search. There
* is one number here, and one place it is computed.
*/
matches: Accessor;
attach(el: HTMLInputElement | null): void;
setHost(host: CommandLineHost | null): void;
/** `/` — the caret into the field, empty of the old query, which the caller removes. */
armSearch(): void;
/** `:` — the caret into the field with an empty command, whatever the query holds. */
armCommand(): void;
setFocused(value: boolean): void;
/**
* Enter in command mode. Returns whether the line may give the caret back: a word
* nobody recognises keeps the field open with its text intact, which is how a
* mistyped command gets finished rather than retyped.
*/
submit(): boolean;
/** `↑`/`↓` in command mode: the previous/next command typed this session. */
recall(dir: -1 | 1): string | null;
/** Enter in the search field, handed to the mounted view. */
acceptSearch(): void;
/** Escape on an empty query, handed to the mounted view. */
dismissSearch(): void;
/** Any other key takes the last outcome away, as the toolbar's lines do. */
clearNotice(): void;
}
/** How much of the typed history the line keeps. Enough for an evening of `:vol`. */
const HISTORY = 40;
export function createCommandLineStore(): CommandLineStore {
const [modeSignal, setModeSignal] = createSignal("search", {
name: "cli-mode",
});
const [focused, setFocusedSignal] = createSignal(false, {
name: "cli-focused",
});
const [commandSignal, setCommandOnly] = createSignal("", {
name: "cli-command",
});
const [notice, setNotice] = createSignal(null, {
name: "cli-notice",
});
// The synchronous truth for the two values a key handler reads after writing.
let mode: CommandLineMode = "search";
let command = "";
/** The field, for the two method calls the store makes on it. */
let box: HTMLInputElement | null = null;
/**
* The mounted view, and the notice that it changed.
*
* The plain value is the read path for the key handlers, which ask once per press and
* must see this press's registration rather than the flush's; the signal exists for
* `matches`, which is read inside a memo and so needs a dependency to follow.
*/
let host: CommandLineHost | null = null;
const [hostSeen, setHostSeen] = createSignal(0, { name: "cli-host-seen" });
/** Typed commands, oldest first, and the cursor `↑`/`↓` walk. */
let history: string[] = [];
let at = -1;
/**
* The readout, computed rather than stored, and computed here rather than in the
* component: what the line says about `:vol up` is a question about the command
* table, and the table lives next door.
*
* The typed text wins over the last outcome, because the outcome is about a press that
* is already over and the text is about the one being made.
*/
const hint: Accessor = () => {
const text = commandSignal().trim();
if (text) return describe(text);
return notice();
};
const matches: Accessor = () => {
// The nonce first: with no view mounted this computation would read nothing
// reactive, and so would never run again — leaving the count missing forever, which
// is what registering the host *after* this component mounted would otherwise do.
hostSeen();
return host?.matches() ?? null;
};
/** The one way the command text changes, so the mirror cannot drift from the signal. */
const writeCommand = (value: string) => {
command = value;
setCommandOnly(value);
};
const writeMode = (value: CommandLineMode) => {
mode = value;
setModeSignal(value);
};
const setFocused = (value: boolean) => {
setFocusedSignal(value);
// Out of the field is out of command mode: the line goes back to being the filter
// it looks like when nobody is typing at it, the prompt goes back to the
// caret-and-nothing the search half wears, and the half-typed command goes with it.
// A command is a press, not a draft: the last thing typed at a prompt is the last
// thing you want back when you press `:` again.
if (!value) {
writeMode("search");
writeCommand("");
at = -1;
}
};
return {
mode: modeSignal,
peekMode: () => mode,
focused,
command: commandSignal,
peekCommand: () => command,
setCommand: (value) => {
writeCommand(value);
// Typing is an answer to whatever the last press said.
setNotice(null);
// ...and any edit puts the history cursor back at the bottom, which is where a
// person who has started typing again expects `↑` to resume from.
at = -1;
},
hint,
matches,
attach: (el) => {
box = el;
// Detaching is the field going away, which is the one thing that can be said about
// the caret for certain: the store outlives the component that handed it an
// element (it is the page's line, not the mount's), so a mount ending has to end
// the typing with it. Left standing, the next mount — a reload in a test, a hot
// re-render in dev — would come up with a caret in a field it never focused and a
// command in it nobody typed.
if (!el) {
setFocusedSignal(false);
writeMode("search");
writeCommand("");
setNotice(null);
at = -1;
}
},
setHost: (h) => {
host = h;
setHostSeen((n) => n + 1);
},
armSearch: () => {
host?.prepareSearch();
writeMode("search");
// The field is always mounted, so focusing it is a method call rather than a
// render-then-find dance. `select()` is kept for whoever hands over a field
// that still holds text — the store does not own the needle, so it cannot
// empty it; the `/` handler that does own it clears the query before calling.
box?.focus();
box?.select();
},
armCommand: () => {
writeMode("command");
writeCommand("");
at = -1;
box?.focus();
box?.select();
},
setFocused,
submit: () => {
const raw = command.trim(); // the mirror: this press's text, not the last flush's
// An empty prompt has nothing to run and nothing to refuse: Enter there is the way
// out, the same key doing the same job it does in a search box.
if (!raw) return true;
const { outcome, ran } = runCommand(raw);
if (outcome instanceof Promise) {
// The verb's answer is a round-trip, so the press gets the verb and an
// ellipsis now and the server's words when they arrive. The identity check
// in the callback is what keeps that late line honest: `clearNotice`, the
// next submit, and typing all take the placeholder away, and a verdict
// arriving after one of those is not feedback on a press any more.
const pending: CommandLineNotice = { text: `${splitCommand(raw).word}…`, bad: false };
setNotice(pending);
outcome
.catch((e): CommandLineNotice => ({
text: e instanceof Error ? e.message : String(e),
bad: true,
}))
.then((line) => {
// A deliberate snapshot, hence untrack: this asks "is the line still the
// placeholder I left?", and a tracked read would answer it from a graph
// the answer itself keeps moving.
if (untrack(notice) === pending) setNotice(line);
});
} else {
setNotice(outcome);
}
if (!ran) return false; // leave the text up so it can be corrected in place
if (!history.includes(raw)) history.push(raw);
if (history.length > HISTORY) history = history.slice(-HISTORY);
at = -1;
writeCommand("");
return true;
},
recall: (dir) => {
if (!history.length) return null;
// -1 is the bottom of the list: nothing recalled, the line as it stands. The first
// `↑` takes the newest command from there, and walking off either end lands back on
// the empty line rather than wrapping — a line that cycles back to `:stop` while
// you are hunting for `:seek` has just run something.
const to = at < 0 ? history.length - 1 : at + dir;
if (to < 0 || to >= history.length) {
at = -1;
return "";
}
at = to;
return history[to] ?? null;
},
clearNotice: () => {
setNotice(null);
},
// Braced rather than an arrow returning the setter's value: a Solid setter hands back
// what it stored, and these methods are called from computations whose return value
// Solid reads as a cleanup.
//
// The two questions the field cannot ask about a list it cannot see. No host is no
// answer rather than a wrong one: the line still blurs and still keeps the query, it
// simply does not move a cursor it has no route to.
acceptSearch: () => {
host?.acceptSearch();
},
dismissSearch: () => {
host?.dismissSearch();
},
};
}