Public: anyone can read this; the crew can change it.
The cloud tree's lists sort by any column, from the one line, at every door #17750
Merged 9h 59m ago, live in production
sold/leaf-table-2 → main 0 commits
15 files
changed +464
−69
- docs/features/infra.md
- src/actions/infra.ts
- src/cloud/tree.ts
- src/http/mcp/tools/infra.ts
- src/list/line.ts
- src/list/order.ts
- src/tui/screens/cloudtree.ts
- src/tui/ui/list.ts
- src/web/keymap.ts
- src/web/list.ts
- src/web/pages/cloud_tree.ts
- test/cloud-filter-lines.test.ts
- test/cloud-tree.test.ts
- test/list-line.test.ts
- test/list-order.test.ts
docs/features/infra.md +3 −1
| @@ -103,7 +103,9 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro | ||
| 103 | 103 | - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. One resource says "About $12.00 a month at list price", or "No list price is known for it" and which bill any cost is inside, with no region's total beside it. An ECS service says "Its tasks, about $9.02 a month at list price", and only the tasks are added. A bill's Tax line says it is included in the AWS total. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added. |
| 104 | 104 | - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`. |
| 105 | 105 | - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost, created. `!` negates a term or a word (`!web`), a comma means any of, and the sign carries on over it (`cost:>10,20`) until a value has its own (`cost:>10,=20`). `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. Quotes are literal: `name:"old web"` holds a space, and `region:"none"` is the word and not the empty value. `created:` takes an age (`<7d` is younger, `>7d` older, `s m h d w`) or a date (`>2026-12-01` is after that day, UTC unless it has an offset). `machine:i-111` is an id, read as text. It is in the URL as `?q=`. |
| 106 | - **A line that cannot be read whole** still draws rows, and the page and the terminal say what was made of it. An unknown property is text and the near one is named; a sign on a property without an order is left out; `sort:` and `group:` are words this list cannot do yet. A bad `cost:` or `created:`, and what is past 12 words or 200 characters, narrow nothing. The `infra` tool names the first sort in `problems` and refuses the second (`invalid_filter`, with the place). The language is `src/list/line.ts`, for every list to share. | |
| 106 | - **A line that cannot be read whole** still draws rows, and the page and the terminal say what was made of it. An unknown property is text and the near one is named; a sign on a property without an order is left out; a sort by what is no property keeps the order; `group:` is a word this list cannot do yet. A bad `cost:` or `created:`, and what is past 12 words or 200 characters, narrow nothing. The `infra` tool names the first sort in `problems` and refuses the second (`invalid_filter`, with the place). The language is `src/list/line.ts`, for every list to share. | |
| 107 | - **Sort.** `sort:cost`, `sort:-created,name`: `-` is the largest, the newest or Z first, 3 at most, what is not known last both ways, and `web-2` is before `web-10`. It orders the lists (the pane, the terminal's, the `infra` tool's), never the tree, whose branches carry bills that are no sum of rows. Without one a list is costliest first. A column's heading is a link that writes it, and `S` types `sort:` in the line, on the page and in the terminal. The table is `src/web/list.ts` and `src/tui/ui/list.ts`, over `src/list/order.ts`. | |
| 108 | - **Not known.** A comparison never holds for what is not known, so the page, the terminal and the tool (`unknown`: `left`, and `among` the rows under a `!`) say how many it could not judge: "3 more have no known created date." Add `,unknown` to see them. | |
| 107 | 109 | - **Changed with the shared language:** `!web` and `!machine:i-111` negate and a leading `"` quotes (both were part of the word); `sort:`, `group:` and `created:` were text; `cost:=10`, `cost:>10,=20` and `cost:>10,<5` were refused; a sign left out and a long line's rest are now said; over MCP `cost:abc` and `cost:none` listed everything and are refused. `test/cloud-filter-lines.test.ts` holds each, and every line that kept its rows. |
| 108 | 110 | - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data). |
| 109 | 111 | - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same. |
src/actions/infra.ts +2 −2
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | import type { App } from "../app.ts"; |
| 17 | 17 | import { accountReads, projectsOf, refreshProjects } from "../cloud/projects.ts"; |
| 18 | 18 | import { containersOf } from "../cloud/containers.ts"; |
| 19 | import { cloudTree, parseCloudQuery, type CloudView } from "../cloud/tree.ts"; | |
| 19 | import { cloudTree, cloudUnknowns, parseCloudQuery, type CloudView } from "../cloud/tree.ts"; | |
| 20 | 20 | import { requestConsole, type ProviderConsole } from "../cloud/provider_console.ts"; |
| 21 | 21 | import { gatedFetch } from "../cloud/gate.ts"; |
| 22 | 22 | import { resolveSecrets } from "../core/secret_store.ts"; |
| @@ -836,7 +836,7 @@ export function cloudResources(app: App, actor: User | undefined, line: string, | ||
| 836 | 836 | const [projects, reads] = [projectsOf(app.db), accountReads(app.db)]; |
| 837 | 837 | const inside = containersOf(app.db, who.value, now); |
| 838 | 838 | const whole = cloudTree(projects, reads, held, parseCloudQuery(""), now, inside); |
| 839 | return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, held: held.length, now }); | |
| 839 | return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, unknown: cloudUnknowns(whole, q, now), held: held.length, now }); | |
| 840 | 840 | } |
| 841 | 841 | |
| 842 | 842 | /** |
src/cloud/tree.ts +41 −8
| @@ -15,7 +15,8 @@ import { dollars } from "./prices.ts"; | ||
| 15 | 15 | import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts"; |
| 16 | 16 | import { agoWords } from "../kernel/ago.ts"; |
| 17 | 17 | import { LABEL, isProvider } from "./providers.ts"; |
| 18 | import { holds, parseLine, wordsOf, type Line, type List } from "../list/line.ts"; | |
| 18 | import { fieldOf, holds, parseLine, wordsOf, type Line, type List } from "../list/line.ts"; | |
| 19 | import { sorted, sortSays, unknownSays, unknownsOf, type Unknown } from "../list/order.ts"; | |
| 19 | 20 | |
| 20 | 21 | /** What some resources cost a month, and how much of that is known. */ |
| 21 | 22 | export interface Money { |
| @@ -359,6 +360,8 @@ export interface CloudView { | ||
| 359 | 360 | */ |
| 360 | 361 | readonly whole: CloudNode; |
| 361 | 362 | readonly q: CloudQuery; |
| 363 | /** What the line's comparisons could not judge, over the whole tree. */ | |
| 364 | readonly unknown: readonly Unknown[]; | |
| 362 | 365 | /** How many accounts the forge holds; none is its own state. */ |
| 363 | 366 | readonly held: number; |
| 364 | 367 | readonly now: number; |
| @@ -390,7 +393,7 @@ export function resourcesOf(n: CloudNode): CloudNode[] { | ||
| 390 | 393 | export const costliestOf = (n: CloudNode): CloudNode[] => resourcesOf(n).sort(costliest); |
| 391 | 394 | |
| 392 | 395 | /** Where a list stops short, what it leaves out and how to see it; empty when it names them all. */ |
| 393 | export const cutSays = (shown: number, more: number, how: string): string => (more <= 0 ? "" : `${shown.toLocaleString("en-US")} named here, the costliest first; ${more.toLocaleString("en-US")} more: ${how}`); | |
| 396 | export const cutSays = (shown: number, more: number, how: string, order = "the costliest first"): string => (more <= 0 ? "" : `${shown.toLocaleString("en-US")} named here, ${order}; ${more.toLocaleString("en-US")} more: ${how}`); | |
| 394 | 397 | |
| 395 | 398 | // ---- the filter line ---- |
| 396 | 399 | |
| @@ -425,8 +428,10 @@ const LIST: List<Placed> = { | ||
| 425 | 428 | { name: "for", type: "text", of: ({ r }) => r.label, blank: "none" }, |
| 426 | 429 | { name: "app", type: "text", of: ({ r }) => r.partOf?.app ?? "", blank: "unknown" }, |
| 427 | 430 | { name: "cost", type: "number", of: ({ r }) => r.cents, blank: "unknown", takes: "dollars a month, like cost:>10" }, |
| 428 | { name: "created", type: "time", of: ({ r }) => r.createdAt, blank: "unknown", takes: "an age or a date, like created:<7d or created:>2026-12-01" }, | |
| 431 | { name: "created", type: "time", of: ({ r }) => r.createdAt, blank: "unknown", noun: "created date", takes: "an age or a date, like created:<7d or created:>2026-12-01" }, | |
| 429 | 432 | ], |
| 433 | columns: ["name", "kind", "state", "size", "region", "created", "cost"], | |
| 434 | most: { chars: 200, words: 12 }, | |
| 430 | 435 | }; |
| 431 | 436 | |
| 432 | 437 | /** The properties a filter line takes, as every door lists them. */ |
| @@ -440,19 +445,47 @@ export interface CloudQuery { | ||
| 440 | 445 | readonly problems: readonly string[]; |
| 441 | 446 | } |
| 442 | 447 | |
| 448 | const placed = (whole: CloudNode, n: CloudNode): Placed => ({ r: n.resource!, project: nodeAt(whole, n.path.slice(0, 3))?.name ?? "" }); | |
| 449 | ||
| 450 | /** | |
| 451 | * Every resource under a node in the line's own order, the costliest first where it has none: the | |
| 452 | * lists, not the tree, whose branches carry bills that are no sum of rows. | |
| 453 | */ | |
| 454 | export const listedOf = (v: CloudView, n: CloudNode): CloudNode[] => sorted(LIST, v.q.line, costliestOf(n), (c) => placed(v.whole, c)); | |
| 455 | ||
| 456 | /** The order of a list in words, after "the first 200, ". */ | |
| 457 | export const orderSays = (q: CloudQuery): string => (q.line.sort.length === 0 ? "the costliest first" : sortSays(LIST, q.line)); | |
| 458 | ||
| 459 | /** What a comparison could not judge: rows left out, or let in, for a value that is not known. */ | |
| 460 | export const cloudUnknowns = (whole: CloudNode, q: CloudQuery, now: number): Unknown[] => (q.line.terms.length === 0 ? [] : unknownsOf(LIST, q.line, resourcesOf(whole).map((n) => placed(whole, n)), now)); | |
| 461 | ||
| 462 | /** The columns of a list of resources. */ | |
| 463 | export const CLOUD_COLUMNS = LIST.columns!.map((name) => ({ field: fieldOf(LIST.fields, name)!, label: `${name.charAt(0).toUpperCase()}${name.slice(1)}` })); | |
| 464 | ||
| 465 | /** A resource's cell, as every door says it; the page draws its own name and cost. */ | |
| 466 | export function cloudCell(n: CloudNode, field: string): string { | |
| 467 | const r = n.resource!; | |
| 468 | if (field === "name") return n.name; | |
| 469 | if (field === "state") return unused(r) ? "unattached" : r.state; | |
| 470 | if (field === "created") return r.createdAt === "" ? "not known" : `${r.createdAt.slice(0, 10)}${createdLabel(r) === "Created" ? "" : ", or changed"}`; | |
| 471 | if (field === "cost") return [moneyMark(n.money).mark, moneyMark(n.money).sum].filter((x) => x !== "").join(" "); | |
| 472 | return field === "kind" ? r.kind : field === "size" ? r.size : r.region; | |
| 473 | } | |
| 474 | ||
| 443 | 475 | /** A filter line for the cloud tree, in the language every list shares (`list/line.ts`). */ |
| 444 | 476 | export function parseCloudQuery(typed: string): CloudQuery { |
| 445 | const line = parseLine(typed, LIST.fields, { chars: 200, words: 12 }); | |
| 477 | const line = parseLine(typed, LIST); | |
| 446 | 478 | return { text: line.text, line, problems: line.problems.filter((p) => p.level === "slip" || p.level === "wide").map((p) => p.says) }; |
| 447 | 479 | } |
| 448 | 480 | |
| 449 | 481 | /** |
| 450 | * What every door says beside the rows: the line's problems, how its marks, quotes and dates were | |
| 451 | * read, and, with nothing found, what is half typed in it. | |
| 482 | * What every door says beside the rows, the most needed first: the line's problems (with nothing | |
| 483 | * found, also what is half typed), the rows a value not known left out, and how its marks, quotes | |
| 484 | * and dates were read. | |
| 452 | 485 | */ |
| 453 | export function readingOf(v: CloudView): string[] { | |
| 486 | export function readingOf(v: CloudView): { readonly problems: string[]; readonly unknown: string[]; readonly words: string[] } { | |
| 454 | 487 | const half = v.root.count > 0 ? [] : v.q.line.problems.filter((p) => p.level === "half" && p.says !== "").map((p) => p.says); |
| 455 | return [...v.q.problems, ...half, ...wordsOf(v.q.line, LIST.fields)]; | |
| 488 | return { problems: [...v.q.problems, ...half], unknown: unknownSays(LIST, v.unknown), words: wordsOf(v.q.line, LIST.fields) }; | |
| 456 | 489 | } |
| 457 | 490 | |
| 458 | 491 | /** One offered narrowing: the term it adds, its words, and how many resources it would leave. */ |
src/http/mcp/tools/infra.ts +10 −9
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { cloudLinesFresh } from "../../../actions/cloud_says.ts"; |
| 2 | 2 | import { infraCode } from "../../../cloud/infra_read.ts"; |
| 3 | 3 | import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts"; |
| 4 | import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, moneyWords, nodeAt, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts"; | |
| 4 | import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts"; | |
| 5 | 5 | import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts"; |
| 6 | 6 | import { machineView } from "../../../actions/machine_view.ts"; |
| 7 | 7 | import { bindBucket, readBucket } from "../../../actions/bucket.ts"; |
| @@ -27,15 +27,15 @@ function attachedTo(whole: CloudNode, n: CloudNode): { id: string; name?: string | ||
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 29 | /** |
| 30 | * Cloud resources a page at a time, the costliest first, each with the app it is part of (null when | |
| 30 | * Cloud resources a page at a time, in the order given, each with the app it is part of (null when | |
| 31 | 31 | * none is known) and what it is attached to, beside `rest`. `says` ends with how many more there |
| 32 | 32 | * are, so no list reads as whole when it is not. |
| 33 | 33 | */ |
| 34 | function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: string, rest: object): Answer { | |
| 34 | function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: string, rest: object, order?: string): Answer { | |
| 35 | 35 | const page = pageRows(nodes, (n) => n.path.join("/"), args); |
| 36 | 36 | if (!page.ok) return page; |
| 37 | 37 | const { items, next_cursor } = page.value as { items: CloudNode[]; next_cursor: string | null }; |
| 38 | const more = next_cursor === null ? "" : cutSays(items.length, nodes.length - nodes.indexOf(items.at(-1)!) - 1, "pass next_cursor as cursor, or narrow the filter"); | |
| 38 | const more = next_cursor === null ? "" : cutSays(items.length, nodes.length - nodes.indexOf(items.at(-1)!) - 1, "pass next_cursor as cursor, or narrow the filter", order); | |
| 39 | 39 | return good({ |
| 40 | 40 | says: more === "" ? says : `${says.replace(/\.$/, "")}. ${more}`, |
| 41 | 41 | ...rest, |
| @@ -53,7 +53,7 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: | ||
| 53 | 53 | export const tool: Tool = { |
| 54 | 54 | name: "infra", |
| 55 | 55 | listedTo: "admin", |
| 56 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 56 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 57 | 57 | description: "Machines, spend.", |
| 58 | 58 | inputSchema: { |
| 59 | 59 | type: "object", |
| @@ -80,15 +80,16 @@ export const tool: Tool = { | ||
| 80 | 80 | const names = Array.isArray(args["names"]) ? args["names"].slice(0, 20).map((n) => s(n, 40)) : []; |
| 81 | 81 | const id = s(args["id"], 300); |
| 82 | 82 | if (action === "list" && id !== "") { |
| 83 | // A filter line, /infra's own: every cloud resource it leaves, the costliest first. | |
| 83 | // A filter line, /infra's own: every cloud resource it leaves, in its own order. | |
| 84 | 84 | const v = cloudResources(ctx.app, user, id); |
| 85 | 85 | if (!v.ok) return bad("not_found", "no such tool here"); |
| 86 | 86 | const wide = refusalOf(v.value.q.line); |
| 87 | 87 | if (wide !== undefined) return bad("invalid_filter", `${wide.says} (at character ${wide.at + 1}) Nothing was listed, because without that part the line finds more than was asked. The fields are ${CLOUD_PROPS.join(", ")}.`); |
| 88 | const all = costliestOf(v.value.root); | |
| 88 | const all = listedOf(v.value, v.value.root); | |
| 89 | const reading = readingOf(v.value); | |
| 89 | 90 | const f = findingOf(v.value); |
| 90 | const says = [f.found, f.cost, f.caveat, ...readingOf(v.value)].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". "); | |
| 91 | return named(v.value.whole, all, args, says, { problems: v.value.q.problems }); | |
| 91 | const says = [f.found, f.cost, f.caveat, ...reading.problems, ...reading.unknown, ...reading.words].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". "); | |
| 92 | return named(v.value.whole, all, args, says, { problems: v.value.q.problems, unknown: v.value.unknown }, orderSays(v.value.q)); | |
| 92 | 93 | } |
| 93 | 94 | if (action === "list") { |
| 94 | 95 | const v = infraOf(ctx.app, user); |
src/list/line.ts +70 −18
| @@ -28,12 +28,21 @@ export interface Field<R> { | ||
| 28 | 28 | readonly blank?: "none" | "unknown"; |
| 29 | 29 | /** For a field with an order: what it takes, as the sentence about a bad value says it. */ |
| 30 | 30 | readonly takes?: string; |
| 31 | /** What is not known when it is empty, where its name does not say it: "created date". */ | |
| 32 | readonly noun?: string; | |
| 31 | 33 | } |
| 32 | 34 | |
| 33 | export interface List<R> { | |
| 35 | /** What a line can ask of a list, without its rows. */ | |
| 36 | export interface Shape<F = Named> { | |
| 37 | readonly fields: readonly F[]; | |
| 38 | /** The fields its table shows, in order. With these it can be sorted, by any field. */ | |
| 39 | readonly columns?: readonly string[]; | |
| 40 | readonly most?: { readonly chars: number; readonly words: number }; | |
| 41 | } | |
| 42 | ||
| 43 | export interface List<R> extends Shape<Field<R>> { | |
| 34 | 44 | /** What plain words look in, its parts apart by line breaks. */ |
| 35 | 45 | readonly text: (r: R) => string; |
| 36 | readonly fields: readonly Field<R>[]; | |
| 37 | 46 | } |
| 38 | 47 | |
| 39 | 48 | interface Choice { |
| @@ -44,7 +53,7 @@ interface Choice { | ||
| 44 | 53 | readonly literal: boolean; |
| 45 | 54 | } |
| 46 | 55 | |
| 47 | interface Term { | |
| 56 | export interface Term { | |
| 48 | 57 | /** Null is plain text, somewhere in the row. */ |
| 49 | 58 | readonly field: string | null; |
| 50 | 59 | readonly not: boolean; |
| @@ -67,6 +76,10 @@ export interface Line { | ||
| 67 | 76 | /** As typed, within the list's limit. */ |
| 68 | 77 | readonly text: string; |
| 69 | 78 | readonly terms: readonly Term[]; |
| 79 | /** The first decides, the next its ties; `down` is the largest, the newest or Z first. */ | |
| 80 | readonly sort: readonly { readonly field: string; readonly down: boolean }[]; | |
| 81 | /** Where each `sort:` is in the text. */ | |
| 82 | readonly sortAt: readonly (readonly [number, number])[]; | |
| 70 | 83 | readonly problems: readonly Problem[]; |
| 71 | 84 | /** Its last quote is not closed, so nothing can be added after it. */ |
| 72 | 85 | readonly open: boolean; |
| @@ -80,8 +93,8 @@ const AGE = /^(\d+(?:\.\d+)?)([smhdw])$/; | ||
| 80 | 93 | const DATE = /^\d{4}-\d\d-\d\d(?:t\d\d:\d\d(?::\d\d)?(?:z|[+-]\d\d:\d\d)?)?$/; |
| 81 | 94 | const SPAN = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 } as const; |
| 82 | 95 | |
| 83 | const fieldOf = <F extends { readonly name: string }>(fields: readonly F[], name: string): F | undefined => fields.find((f) => f.name.toLowerCase() === name.toLowerCase()); | |
| 84 | const ordered = (f: Pick<Named, "type">): boolean => f.type === "number" || f.type === "time"; | |
| 96 | export const fieldOf = <F extends { readonly name: string }>(fields: readonly F[], name: string): F | undefined => fields.find((f) => f.name.toLowerCase() === name.toLowerCase()); | |
| 97 | export const ordered = (f: Pick<Named, "type">): boolean => f.type === "number" || f.type === "time"; | |
| 85 | 98 | |
| 86 | 99 | const cents = (value: string): number | undefined => (/^\$?\d+(\.\d+)?$/.test(value) ? Math.round(Number(value.replace("$", "")) * 100) : undefined); |
| 87 | 100 | |
| @@ -109,12 +122,15 @@ function unknownField(name: string, fields: readonly Named[]): string { | ||
| 109 | 122 | } |
| 110 | 123 | |
| 111 | 124 | /** A line's terms and what is wrong with it. It never fails: what cannot be read is a problem. */ |
| 112 | export function parseLine(line: string, fields: readonly Named[], most: { readonly chars: number; readonly words: number } = { chars: 500, words: 20 }): Line { | |
| 125 | export function parseLine(line: string, list: Shape): Line { | |
| 126 | const { fields, columns, most = { chars: 500, words: 20 } } = list; | |
| 113 | 127 | const whole = line.trim(); |
| 114 | 128 | // Cut inside an emoji, half of it is left, and no link can encode that. |
| 115 | 129 | const text = whole.slice(0, most.chars).toWellFormed(); |
| 116 | 130 | const terms: Term[] = []; |
| 117 | 131 | const problems: Problem[] = []; |
| 132 | const sort: { field: string; down: boolean }[] = []; | |
| 133 | const sortAt: [number, number][] = []; | |
| 118 | 134 | let i = 0; |
| 119 | 135 | let open = false; |
| 120 | 136 | const space = (at: number): boolean => at >= text.length || /\s/.test(text[at]!); |
| @@ -136,6 +152,25 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon | ||
| 136 | 152 | return { value: (value + text.slice(from, i)).toLowerCase(), literal }; |
| 137 | 153 | }; |
| 138 | 154 | |
| 155 | /** The keys after `sort:`, 3 at most in a line; one this list cannot sort by is left out. */ | |
| 156 | const sortKeys = (at: number): void => { | |
| 157 | let keys = 0; | |
| 158 | for (; ; i++) { | |
| 159 | const down = text[i] === "-"; | |
| 160 | if (down) i++; | |
| 161 | const { value } = word(true); | |
| 162 | const f = fieldOf(fields, value); | |
| 163 | if (value !== "") keys++; | |
| 164 | if (value !== "" && f === undefined) problem(at, "slip", `This list cannot sort by "${short(value)}"; it can by ${fields.map((x) => x.name).join(", ")}.`); | |
| 165 | else if (f !== undefined && !sort.some((k) => k.field === f.name)) { | |
| 166 | if (sort.length < 3) sort.push({ field: f.name, down }); | |
| 167 | else problem(at, "slip", `A line sorts by 3 fields at most, so ${f.name} is left out.`); | |
| 168 | } | |
| 169 | if (text[i] !== ",") break; | |
| 170 | } | |
| 171 | if (keys === 0) problem(at, "half", ""); | |
| 172 | }; | |
| 173 | ||
| 139 | 174 | for (let count = 0; ; count++) { |
| 140 | 175 | while (i < text.length && space(i)) i++; |
| 141 | 176 | if (i >= text.length) break; |
| @@ -148,8 +183,20 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon | ||
| 148 | 183 | const m = HEAD.exec(text); |
| 149 | 184 | const quoted = m?.[2]?.replace(/\\(["\\])/g, "$1"); |
| 150 | 185 | const name = quoted ?? m?.[3] ?? ""; |
| 151 | const f = m === null ? undefined : fieldOf(fields, name); | |
| 152 | 186 | const view = /^(sort|group)$/i.exec(m?.[3] ?? "")?.[1]!.toLowerCase(); |
| 187 | // A field with one of those names is quoted. | |
| 188 | const f = m === null || view !== undefined ? undefined : fieldOf(fields, name); | |
| 189 | ||
| 190 | if (m !== null && view === "sort" && columns !== undefined) { | |
| 191 | i += m[0].length; | |
| 192 | if (m[1] === "") sortKeys(at); | |
| 193 | else { | |
| 194 | word(false); | |
| 195 | problem(at, "slip", "sort: takes no mark before it: write sort:-name for the largest, the newest or Z first."); | |
| 196 | } | |
| 197 | sortAt.push([at, Math.min(i, text.length)]); | |
| 198 | continue; | |
| 199 | } | |
| 153 | 200 | |
| 154 | 201 | if (m !== null && (f !== undefined || view !== undefined)) { |
| 155 | 202 | i += m[0].length; |
| @@ -205,7 +252,7 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon | ||
| 205 | 252 | } |
| 206 | 253 | if (open) problem(text.lastIndexOf('"'), "half", "The quote is not closed, so all after it is in it."); |
| 207 | 254 | if (whole.length > most.chars) problem(most.chars, "wide", `A line here is at most ${most.chars} characters, so this is left out: ${short(whole.slice(most.chars).toWellFormed().trim())}`); |
| 208 | return { text, terms, problems, open }; | |
| 255 | return { text, terms, sort, sortAt, problems, open }; | |
| 209 | 256 | } |
| 210 | 257 | |
| 211 | 258 | /** |
| @@ -223,28 +270,33 @@ function timeHolds(have: number, c: Choice, now: number): boolean { | ||
| 223 | 270 | return c.op === "<" ? have < from : c.op === "<=" ? have < to : c.op === ">" ? have >= to : c.op === ">=" ? have >= from : have >= from && have < to; |
| 224 | 271 | } |
| 225 | 272 | |
| 273 | /** Whether a row has no value for a field; a time that is no date is none. */ | |
| 274 | export function blankIn<R>(f: Field<R>, r: R): boolean { | |
| 275 | const have = f.of(r); | |
| 276 | return have === null || have === "" || (f.type === "time" && Number.isNaN(Date.parse(String(have)))); | |
| 277 | } | |
| 278 | ||
| 226 | 279 | function choiceHolds<R>(f: Field<R>, c: Choice, r: R, now: number): boolean { |
| 227 | 280 | const have = f.of(r); |
| 228 | const at = f.type === "time" ? Date.parse(String(have)) : 0; | |
| 229 | const empty = have === null || have === "" || Number.isNaN(at); | |
| 281 | const empty = blankIn(f, r); | |
| 230 | 282 | if (!c.literal && c.value === f.blank) return empty; |
| 231 | 283 | // A comparison never holds for what is not known. |
| 232 | 284 | if (empty) return false; |
| 233 | 285 | if (f.type === "number") return compared(Number(have), c.op, cents(c.value)!); |
| 234 | if (f.type === "time") return timeHolds(at, c, now); | |
| 286 | if (f.type === "time") return timeHolds(Date.parse(String(have)), c, now); | |
| 235 | 287 | const value = String(have).toLowerCase(); |
| 236 | 288 | return f.type === "word" ? value === c.value : f.type === "start" ? value.startsWith(c.value) : value.includes(c.value); |
| 237 | 289 | } |
| 238 | 290 | |
| 239 | /** Whether every term holds for one row. */ | |
| 240 | export function holds<R>(list: List<R>, line: Line, r: R, now: number): boolean { | |
| 241 | return line.terms.every((t) => { | |
| 242 | const f = t.field === null ? undefined : fieldOf(list.fields, t.field)!; | |
| 243 | const text = f === undefined ? list.text(r).toLowerCase() : ""; | |
| 244 | return t.any.some((c) => (f === undefined ? text.includes(c.value) : choiceHolds(f, c, r, now))) !== t.not; | |
| 245 | }); | |
| 291 | export function termHolds<R>(list: List<R>, t: Term, r: R, now: number): boolean { | |
| 292 | const f = t.field === null ? undefined : fieldOf(list.fields, t.field)!; | |
| 293 | const text = f === undefined ? list.text(r).toLowerCase() : ""; | |
| 294 | return t.any.some((c) => (f === undefined ? text.includes(c.value) : choiceHolds(f, c, r, now))) !== t.not; | |
| 246 | 295 | } |
| 247 | 296 | |
| 297 | /** Whether every term holds for one row. */ | |
| 298 | export const holds = <R>(list: List<R>, line: Line, r: R, now: number): boolean => line.terms.every((t) => termHolds(list, t, r, now)); | |
| 299 | ||
| 248 | 300 | /** How the parts that can be read two ways were read: a mark, quotes, an age and a date. */ |
| 249 | 301 | export function wordsOf(line: Line, fields: readonly Named[]): string[] { |
| 250 | 302 | return line.terms.flatMap((t): string[] => { |
src/list/order.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * The order of a list, and what a comparison could not judge, from its one line (`line.ts`). Pure: | |
| 3 | * the page, the terminal and the tools draw the same order and the same counts. | |
| 4 | */ | |
| 5 | ||
| 6 | import { blankIn, fieldOf, ordered, termHolds, type Field, type Line, type List } from "./line.ts"; | |
| 7 | ||
| 8 | /** Text with numbers inside, as people read it: `web-2` before `web-10`. */ | |
| 9 | const READ = new Intl.Collator("en", { numeric: true, sensitivity: "base" }); | |
| 10 | ||
| 11 | /** | |
| 12 | * The items as the line's `sort:` puts them; a copy. What is not known is last whichever way it | |
| 13 | * runs, and ties keep the order they came in. | |
| 14 | */ | |
| 15 | export function sorted<R, T>(list: List<R>, line: Line, items: readonly T[], rowOf: (t: T) => R): T[] { | |
| 16 | const by = line.sort.map((k) => ({ ...k, f: fieldOf(list.fields, k.field)! })); | |
| 17 | if (by.length === 0) return [...items]; | |
| 18 | const key = (f: Field<R>, r: R): string | number | null => (blankIn(f, r) ? null : f.type === "time" ? Date.parse(String(f.of(r))) : f.of(r)); | |
| 19 | return items | |
| 20 | .map((item) => ({ item, keys: by.map((k) => key(k.f, rowOf(item))) })) | |
| 21 | .sort((a, b) => { | |
| 22 | for (const [i, k] of by.entries()) { | |
| 23 | const [x, y] = [a.keys[i]!, b.keys[i]!]; | |
| 24 | if (x === null || y === null) { | |
| 25 | if (x !== y) return x === null ? 1 : -1; | |
| 26 | continue; | |
| 27 | } | |
| 28 | const n = typeof x === "number" && typeof y === "number" ? x - y : READ.compare(String(x), String(y)); | |
| 29 | if (n !== 0) return k.down ? -n : n; | |
| 30 | } | |
| 31 | return 0; | |
| 32 | }) | |
| 33 | .map((x) => x.item); | |
| 34 | } | |
| 35 | ||
| 36 | /** The order in words: "sorted by created, newest first". */ | |
| 37 | export const sortSays = (list: Pick<List<never>, "fields">, line: Line): string => | |
| 38 | `sorted by ${line.sort | |
| 39 | .map((k) => { | |
| 40 | const [up, down] = { number: ["smallest", "largest"], time: ["oldest", "newest"], other: ["A", "Z"] }[((t) => (t === "number" || t === "time" ? t : "other"))(fieldOf(list.fields, k.field)!.type)]; | |
| 41 | return `${k.field}, ${k.down ? down : up} first`; | |
| 42 | }) | |
| 43 | .join(", then ")}`; | |
| 44 | ||
| 45 | /** A field's name as a line writes it. */ | |
| 46 | const written = (name: string): string => (/^[a-z][\w-]*$/i.test(name) && !/^(sort|group)$/i.test(name) ? name : `"${name.replace(/["\\]/g, "\\$&")}"`); | |
| 47 | ||
| 48 | /** | |
| 49 | * The line a heading leads to: numbers and times the largest or newest first and text A first, then | |
| 50 | * the other way, then the list's own order. | |
| 51 | */ | |
| 52 | export function sortLine(line: Line, f: Pick<Field<never>, "name" | "type">): string { | |
| 53 | const now = line.sort.length === 1 && line.sort[0]!.field === f.name ? line.sort[0] : undefined; | |
| 54 | const next = now === undefined ? { down: ordered(f) } : now.down === ordered(f) ? { down: !now.down } : undefined; | |
| 55 | let rest = ""; | |
| 56 | let from = 0; | |
| 57 | for (const [at, end] of line.sortAt) { | |
| 58 | rest += line.text.slice(from, at); | |
| 59 | from = end; | |
| 60 | } | |
| 61 | return [(rest + line.text.slice(from)).trim(), next === undefined ? "" : `sort:${next.down ? "-" : ""}${written(f.name)}`].filter((x) => x !== "").join(" "); | |
| 62 | } | |
| 63 | ||
| 64 | /** Rows whose value for a compared field is not known: left out for that alone, or let in by `!`. */ | |
| 65 | export interface Unknown { | |
| 66 | readonly field: string; | |
| 67 | readonly left: number; | |
| 68 | readonly among: number; | |
| 69 | } | |
| 70 | ||
| 71 | export function unknownsOf<R>(list: List<R>, line: Line, rows: readonly R[], now: number): Unknown[] { | |
| 72 | const compared = line.terms.flatMap((t) => { | |
| 73 | const f = t.field === null ? undefined : fieldOf(list.fields, t.field); | |
| 74 | return f === undefined || !ordered(f) || f.blank !== "unknown" || t.any.length === 0 || t.any.some((c) => !c.literal && c.value === f.blank) ? [] : [{ t, f }]; | |
| 75 | }); | |
| 76 | if (compared.length === 0) return []; | |
| 77 | const count = new Map(compared.map(({ f }) => [f.name, { left: 0, among: 0 }])); | |
| 78 | for (const r of rows) { | |
| 79 | const failed = line.terms.filter((t) => !termHolds(list, t, r, now)); | |
| 80 | const blank = compared.filter(({ f }) => blankIn(f, r)); | |
| 81 | const alone = failed.length > 0 && failed.every((t) => blank.some((b) => b.t === t)); | |
| 82 | const fields = new Set(failed.length === 0 ? blank.map((b) => b.f.name) : alone ? blank.filter((b) => failed.includes(b.t)).map((b) => b.f.name) : []); | |
| 83 | for (const name of fields) count.get(name)![failed.length === 0 ? "among" : "left"]++; | |
| 84 | } | |
| 85 | return [...count].map(([field, n]) => ({ field, ...n })).filter((n) => n.left + n.among > 0); | |
| 86 | } | |
| 87 | ||
| 88 | /** "3 more have no known created date." */ | |
| 89 | export const unknownSays = (list: Pick<List<never>, "fields">, all: readonly Unknown[]): string[] => | |
| 90 | all.flatMap((u) => { | |
| 91 | const noun = fieldOf(list.fields, u.field)?.noun ?? u.field; | |
| 92 | const say = (n: number, of: string): string[] => (n === 0 ? [] : [`${n.toLocaleString("en-US")} ${of} ${n === 1 ? "has" : "have"} no known ${noun}.`]); | |
| 93 | return [...say(u.left, "more"), ...say(u.among, "of these")]; | |
| 94 | }); |
src/tui/screens/cloudtree.ts +19 −6
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { cloudResources, readProjectsNow } from "../../actions/infra.ts"; |
| 9 | import { cloudName, CONTAINER_COST, containersSay, costLine, costliestOf, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, readingOf, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts"; | |
| 9 | import { cloudCell, CLOUD_COLUMNS, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView } from "../../cloud/tree.ts"; | |
| 10 | 10 | import { dollars } from "../../cloud/prices.ts"; |
| 11 | 11 | import { keyOf } from "../../web/keymap.ts"; |
| 12 | 12 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -15,6 +15,7 @@ import type { Session } from "../session.ts"; | ||
| 15 | 15 | import { style } from "../term/style.ts"; |
| 16 | 16 | import { truncate, wrap } from "../term/width.ts"; |
| 17 | 17 | import { fill, len, split } from "../ui/layout.ts"; |
| 18 | import { tableLines } from "../ui/list.ts"; | |
| 18 | 19 | import { accountScreen } from "./cloud_account.ts"; |
| 19 | 20 | import { Filter, ListState, Scroll, ago, drawLines, hitList, openOnWeb } from "./common.ts"; |
| 20 | 21 | import type { PaletteEntry } from "./entries.ts"; |
| @@ -41,7 +42,7 @@ const markOf = (n: CloudNode): string => { | ||
| 41 | 42 | const PANE_LINES = 200; |
| 42 | 43 | |
| 43 | 44 | /** What a node says when it is open: its cost first, then its facts or its costliest resources. */ |
| 44 | export function cloudLines(v: CloudView, n: CloudNode): string[] { | |
| 45 | export function cloudLines(v: CloudView, n: CloudNode, width = 80): string[] { | |
| 45 | 46 | const cost = n.container !== undefined ? CONTAINER_COST : costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n)); |
| 46 | 47 | const head = [n.path.map((p, i) => (i === 0 ? cloudName(p) : (nodeAt(v.whole, n.path.slice(0, i + 1))?.name ?? p))).join(" ▸ "), cost]; |
| 47 | 48 | const read = n.readAt === "" ? "" : `Read ${ago(n.readAt)}${n.trouble.length === 0 && isStale(n.path[0]!, n.readAt, v.now) ? " (old)" : ""}`; |
| @@ -54,14 +55,15 @@ export function cloudLines(v: CloudView, n: CloudNode): string[] { | ||
| 54 | 55 | return [...head, "", ...facts, `${createdLabel(n.resource).padEnd(12)} ${n.resource.createdAt.slice(0, 10) || "not known"}`, read, ...(n.children.length === 0 ? [] : ["", containersSay(n), ...n.children.map((c) => `${c.name} · ${c.container!.state} · ${c.container!.memory}`)])]; |
| 55 | 56 | const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : []; |
| 56 | 57 | const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`; |
| 57 | const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter"); | |
| 58 | const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter", orderSays(v.q)); | |
| 59 | const rows = listedOf(v, n).slice(0, PANE_LINES).map((c) => CLOUD_COLUMNS.map(({ field }) => cloudCell(c, field.name))); | |
| 58 | 60 | return [ |
| 59 | 61 | ...head, |
| 60 | 62 | ...(read === "" ? [] : [read]), |
| 61 | 63 | ...trouble, |
| 62 | 64 | ...(n.note === "" ? [] : [`${n.note}.`]), |
| 63 | 65 | ...(goes.length === 0 ? [] : ["", "Where it goes", ...goes.map((c) => line(dollars(c.cents), `${c.says} · ${c.where}${c.hint === "" ? "" : ` · ${c.hint}`}`))]), |
| 64 | ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, PANE_LINES).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state].filter((x) => x !== "").join(" · ")}`)), ...(cut === "" ? [] : [cut])]), | |
| 66 | ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...tableLines(CLOUD_COLUMNS, v.q.line, rows, width), ...(cut === "" ? [] : [cut])]), | |
| 65 | 67 | ]; |
| 66 | 68 | } |
| 67 | 69 | |
| @@ -76,7 +78,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 76 | 78 | let note = ""; |
| 77 | 79 | /** The pane's width as last drawn: a reason is read whole, so its line wraps. */ |
| 78 | 80 | let room = 80; |
| 79 | const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n).flatMap((l) => (l.length <= room ? [l] : wrap(l, room))); | |
| 81 | const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n, room).flatMap((l) => (l.length <= room ? [l] : wrap(l, room))); | |
| 80 | 82 | let kept: { readonly query: string; readonly view: CloudView | undefined } | undefined; |
| 81 | 83 | |
| 82 | 84 | /** |
| @@ -115,6 +117,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 115 | 117 | binding(["enter", "l"], "open / expand"), |
| 116 | 118 | binding(["h"], "collapse"), |
| 117 | 119 | binding([keyOf("search")], "filter: kind: cloud: region: cost:>10 text"), |
| 120 | binding([keyOf("sort")], "sort the list: name, cost, -created"), | |
| 118 | 121 | binding(["tab"], "tree / what is open"), |
| 119 | 122 | binding(["a"], "check the account: what was not read, and the fix"), |
| 120 | 123 | binding(["w"], "open on the web"), |
| @@ -131,7 +134,10 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 131 | 134 | const total = v.q.text === "" ? costLine(v.root) || (v.root.count === 0 ? "" : [`${v.root.count} resources, no price known`, unreadLine(v.root)].filter((x) => x !== "").join(", ")) : [f.found, f.caveat, f.cost].filter((x) => x !== "").join(" · "); |
| 132 | 135 | const says = note !== "" ? note : v.held === 0 ? "No cloud account is attached: press I on Cloud accounts, or open /settings/cloud." : total === "" ? "Nothing read yet: press P to read every account now." : total; |
| 133 | 136 | const reading = readingOf(v); |
| 134 | const said = wrap([...reading, ...(v.q.problems.length > 0 ? [] : [says])].join(" "), area.w).slice(0, f.caveat === "" && reading.length === 0 ? 2 : 3); | |
| 137 | // Where three lines are not enough, how the line was read is what is cut. | |
| 138 | const beside = [...reading.unknown, ...reading.words]; | |
| 139 | const ended = beside.length === 0 || /[.…:]$/.test(says) ? says : `${says}.`; | |
| 140 | const said = wrap([...reading.problems, ended, ...beside].join(" "), area.w).slice(0, f.caveat === "" && reading.problems.length + beside.length === 0 ? 2 : 3); | |
| 135 | 141 | const [head, box, body] = split(area, "v", [len(said.length), len(1), fill(1)]); |
| 136 | 142 | said.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.fg, c.bg), head!.x + head!.w)); |
| 137 | 143 | const caret = filter.render(s, box!, c, "/ kind:volume cloud:aws cost:>10"); |
| @@ -195,6 +201,13 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 195 | 201 | if (focus === "tree" && state.key(e, all.length)) return true; |
| 196 | 202 | if (e.ctrl || e.alt) return false; |
| 197 | 203 | const n = all[state.index]?.node; |
| 204 | if (e.key === keyOf("sort")) { | |
| 205 | // The one line, with the word typed: a sort is part of the view it makes. | |
| 206 | focus = "tree"; | |
| 207 | filter.open(); | |
| 208 | if (!/(^|\s)sort:$/.test(filter.query)) filter.query = `${filter.query} sort:`.trimStart(); | |
| 209 | return true; | |
| 210 | } | |
| 198 | 211 | if (e.key === "P") { |
| 199 | 212 | note = "Reading every account…"; |
| 200 | 213 | void readProjectsNow(f.app, f.user).then((done) => { |
src/tui/ui/list.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * A list as lines of text, for every screen: the columns `src/web/list.ts` draws. The last columns | |
| 3 | * go first when there is no room, and the first one gives way before a column goes. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { Line } from "../../list/line.ts"; | |
| 7 | import { displayWidth, truncate } from "../term/width.ts"; | |
| 8 | ||
| 9 | /** The first column is never cut under this many cells while another can go. */ | |
| 10 | const LEAD = 16; | |
| 11 | const GAP = 2; | |
| 12 | ||
| 13 | export function tableLines(columns: readonly { readonly field: { readonly name: string; readonly type: string }; readonly label: string }[], line: Line, rows: readonly (readonly string[])[], width: number): string[] { | |
| 14 | const first = line.sort[0]; | |
| 15 | const head = columns.map((c) => `${c.label}${first?.field === c.field.name ? (first.down ? " ↓" : " ↑") : ""}`); | |
| 16 | const wide = head.map((h, i) => Math.max(displayWidth(h), ...rows.map((r) => displayWidth(r[i]!)))); | |
| 17 | let shown = columns.length; | |
| 18 | const rest = (): number => wide.slice(1, shown).reduce((n, w) => n + w + GAP, 0); | |
| 19 | while (shown > 1 && rest() + Math.min(LEAD, wide[0]!) > width) shown--; | |
| 20 | const size = [Math.max(1, Math.min(wide[0]!, width - rest())), ...wide.slice(1, shown)]; | |
| 21 | return [head, ...rows].map((cells) => | |
| 22 | size | |
| 23 | .map((w, i) => { | |
| 24 | const text = truncate(cells[i]!, w); | |
| 25 | const gap = " ".repeat(Math.max(0, w - displayWidth(text))); | |
| 26 | return columns[i]!.field.type === "number" ? gap + text : text + gap; | |
| 27 | }) | |
| 28 | .join(" ".repeat(GAP)) | |
| 29 | .trimEnd(), | |
| 30 | ); | |
| 31 | } |
src/web/keymap.ts +1 −1
| @@ -101,7 +101,7 @@ export const VERBS = { | ||
| 101 | 101 | now: { key: "n", label: "Now", what: "Jump to now", kinds: ["space"] }, |
| 102 | 102 | nextBody: { key: "]", label: "Next", what: "Go to the next body", kinds: ["space"] }, |
| 103 | 103 | prevBody: { key: "[", label: "Previous", what: "Go to the previous body", kinds: ["space"] }, |
| 104 | sort: { key: "S", label: "Sort", what: "Sort the table by the other measure (CPU, memory)", kinds: ["table"] }, | |
| 104 | sort: { key: "S", label: "Sort", what: "Sort the list (on System, by the other measure: CPU, memory)", kinds: ["table"] }, | |
| 105 | 105 | set: { key: "Enter", label: "Set", what: "Set the figure to what it shows", kinds: ["figure"] }, |
| 106 | 106 | undo: { key: "z", label: "Undo", what: "Put back what was just done", kinds: ["any"] }, |
| 107 | 107 | edit: { key: "e", label: "Propose a change", what: "Propose a change to the file", kinds: ["file"] }, |
src/web/list.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | /** | |
| 2 | * A list as a table, for every page: its columns are the list's (`src/list/line.ts`), and a heading | |
| 3 | * is a link that rewrites `sort:` in the line, so a view is always its address. No script. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { Field, Line } from "../list/line.ts"; | |
| 7 | import { sortLine } from "../list/order.ts"; | |
| 8 | import { html, type Html } from "./html.ts"; | |
| 9 | ||
| 10 | export interface TableOf<T> { | |
| 11 | readonly columns: readonly { readonly field: Pick<Field<never>, "name" | "type">; readonly label: string }[]; | |
| 12 | readonly line: Line; | |
| 13 | readonly rows: readonly T[]; | |
| 14 | readonly cell: (row: T, field: string) => Html | string; | |
| 15 | /** Where a line leads, on this page. */ | |
| 16 | readonly href: (line: string) => string; | |
| 17 | readonly caption: string; | |
| 18 | } | |
| 19 | ||
| 20 | export function listTable<T>(o: TableOf<T>): Html { | |
| 21 | const first = o.line.sort[0]; | |
| 22 | const num = (type: string): Html | null => (type === "number" ? html` class="num"` : null); | |
| 23 | return html`<div class="table-scroll"><table class="table" data-dense data-sortable data-sticky-lead> | |
| 24 | <caption class="sr-only">${o.caption}</caption> | |
| 25 | <thead><tr>${o.columns.map( | |
| 26 | (c) => html`<th scope="col"${num(c.field.type)}${first?.field === c.field.name ? html` aria-sort="${first.down ? "descending" : "ascending"}"` : null}>${ | |
| 27 | // After a quote that is not closed, a sort would be inside it. | |
| 28 | o.line.open ? c.label : html`<a href="${o.href(sortLine(o.line, c.field))}">${c.label}</a>` | |
| 29 | }</th>`, | |
| 30 | )}</tr></thead> | |
| 31 | <tbody>${o.rows.map((r) => html`<tr>${o.columns.map((c) => html`<td${num(c.field.type)}>${o.cell(r, c.field.name)}</td>`)}</tr>`)}</tbody> | |
| 32 | </table></div>`; | |
| 33 | } |
src/web/pages/cloud_tree.ts +20 −18
| @@ -13,7 +13,10 @@ | ||
| 13 | 13 | import { |
| 14 | 14 | CLOUD_PROPS, |
| 15 | 15 | cloudName, |
| 16 | costliestOf, | |
| 16 | cloudCell, | |
| 17 | CLOUD_COLUMNS, | |
| 18 | listedOf, | |
| 19 | orderSays, | |
| 17 | 20 | createdLabel, |
| 18 | 21 | facetsOf, |
| 19 | 22 | readingOf, |
| @@ -48,6 +51,7 @@ import { emptySection } from "../empty_words.ts"; | ||
| 48 | 51 | import { html, raw, type Html } from "../html.ts"; |
| 49 | 52 | import { icon } from "../icons.ts"; |
| 50 | 53 | import { keyOf } from "../keymap.ts"; |
| 54 | import { listTable } from "../list.ts"; | |
| 51 | 55 | import { btn, copyField, crumbs, hintAttr, row, rowList, time } from "../ui.ts"; |
| 52 | 56 | import { codeLayout, COLUMN_WINDOW } from "./explorer.ts"; |
| 53 | 57 | import { treeStep } from "./family_tree_js.ts"; |
| @@ -108,7 +112,7 @@ function level(v: CloudView, n: CloudNode, current: readonly string[], openAll: | ||
| 108 | 112 | </details><a class="ex-file ex-total" tabindex="-1" href="${href}" aria-label="${c.name}: ${moneyWords(c.money) || "no resources"}">${cost(c)}</a></li>`; |
| 109 | 113 | }), |
| 110 | 114 | ...(n.empty === 0 ? [] : [html`<li><span class="muted">${n.empty} more with nothing in ${n.empty === 1 ? "it" : "them"}</span></li>`]), |
| 111 | ...(n.children.length > shown.length ? [html`<li><a class="ex-more" href="${cloudHref(n.path, v.q)}" data-ex-page>All ${n.children.length.toLocaleString("en-US")}, costliest first</a></li>`] : []), | |
| 115 | ...(n.children.length > shown.length ? [html`<li><a class="ex-more" href="${cloudHref(n.path, v.q)}" data-ex-page>All ${n.children.length.toLocaleString("en-US")}, ${orderSays(v.q)}</a></li>`] : []), | |
| 112 | 116 | ]); |
| 113 | 117 | } |
| 114 | 118 | |
| @@ -118,13 +122,14 @@ export const cloudBranch = (v: CloudView, n: CloudNode): Html => level(v, n, n.p | ||
| 118 | 122 | /** The region a filter swaps: the narrowings it offers, what it left, and the tree. */ |
| 119 | 123 | export function cloudList(v: CloudView, current: readonly string[]): Html { |
| 120 | 124 | const { root, q } = v; |
| 125 | const reading = readingOf(v); | |
| 121 | 126 | const filtering = q.text !== ""; |
| 122 | 127 | const openAll = root.count <= (filtering ? OPEN_ALL : OPEN_SMALL); |
| 123 | 128 | return html`<div id="cloud-list" data-q="${q.text}"> |
| 124 | ${readingOf(v).map((p) => html`<p class="small" role="status">${p}</p>`)} | |
| 129 | ${[...reading.problems, ...reading.unknown, ...reading.words].map((p) => html`<p class="small" role="status">${p}</p>`)} | |
| 125 | 130 | <p class="ex-facets small">${facetsOf(root, q).map( |
| 126 | 131 | (f) => html`<a href="${withQuery("/infra", { ...q, text: `${q.text} ${f.term}`.trim() })}" data-term="${f.term}">${f.term} <span class="num muted">${f.count}</span></a> `, |
| 127 | )}</p> | |
| 132 | )}${q.line.open || root.count < 2 ? null : html`<a href="${withQuery("/infra", { ...q, text: `${q.text} sort:`.trim() })}" data-term="sort:" data-shortcut="${keyOf("sort")}" ${hintAttr(keyOf("sort"))}>sort:</a>`}</p> | |
| 128 | 133 | ${filtering ? html`<p class="small"><a href="/infra">Clear the filter</a></p>` : null} |
| 129 | 134 | ${marks(root)} |
| 130 | 135 | ${level(v, root, current, openAll)} |
| @@ -199,27 +204,24 @@ function largest(v: CloudView, n: CloudNode, most = 6): Html { | ||
| 199 | 204 | } |
| 200 | 205 | |
| 201 | 206 | /** |
| 202 | * Every resource at or under a node, the costliest first, and once above them what has no price. | |
| 207 | * Every resource at or under a node, in the line's order, and once above them what has no price. | |
| 203 | 208 | */ |
| 204 | 209 | function listed(v: CloudView, n: CloudNode): Html { |
| 205 | const all = costliestOf(n); | |
| 210 | const all = listedOf(v, n); | |
| 206 | 211 | if (all.length === 0) return html`<p>${v.q.text === "" ? "Nothing here." : "Nothing here matches the filter."}</p>`; |
| 207 | 212 | const bare = all.filter((c) => c.resource!.cents === null).length; |
| 208 | 213 | // A filter's headline has said how many. |
| 209 | 214 | return html`<h2 class="${v.q.text !== "" && n.path.length === 0 ? "sr-only" : ""}">${all.length.toLocaleString("en-US")} ${all.length === 1 ? "resource" : "resources"}</h2> |
| 210 | 215 | ${bare === 0 ? null : html`<p class="muted small">– ${bare === all.length ? "none has a price of its own" : `${bare.toLocaleString("en-US")} without a price of ${bare === 1 ? "its" : "their"} own`}.</p>`} |
| 211 | ${rowList( | |
| 212 | all.slice(0, PANE_ROWS).map((c) => | |
| 213 | row({ | |
| 214 | href: cloudHref(c.path, v.q), | |
| 215 | title: c.name, | |
| 216 | meta: html`${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state, c.resource!.size, c.resource!.region].filter((x) => x !== "").join(" · ")}`, | |
| 217 | trail: cost(c), | |
| 218 | }), | |
| 219 | ), | |
| 220 | { label: "Resources, costliest first" }, | |
| 221 | )} | |
| 222 | ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, costliest first: filter to see the rest.</p>` : null}`; | |
| 216 | ${listTable({ | |
| 217 | columns: CLOUD_COLUMNS, | |
| 218 | line: v.q.line, | |
| 219 | rows: all.slice(0, PANE_ROWS), | |
| 220 | cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? cost(c) : cloudCell(c, field)), | |
| 221 | href: (text) => cloudHref(n.path, { ...v.q, text }), | |
| 222 | caption: `Resources, ${orderSays(v.q)}`, | |
| 223 | })} | |
| 224 | ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}`; | |
| 223 | 225 | } |
| 224 | 226 | |
| 225 | 227 | /** With nothing open: where the money goes and what the forge runs, or what the filter found. */ |
test/cloud-filter-lines.test.ts +1 −1
| @@ -76,7 +76,7 @@ const DELIBERATE: readonly (readonly [string, string, string])[] = [ | ||
| 76 | 76 | ['"vol-1"', "B", "nothing: the quotes were part of the word"], |
| 77 | 77 | ['name:"web"', "A", "nothing: the quotes were part of the word"], |
| 78 | 78 | ['state:"running"', "AE", "nothing: the quotes were part of the word"], |
| 79 | ["sort:-cost", "ABCDEF !", "nothing: it was text, and is a word of the language this list does not have yet"], | |
| 79 | ["sort:-cost", "ABCDEF", "nothing: it was text, and is the order"], | |
| 80 | 80 | ["sort:", "ABCDEF", "nothing: it was text"], |
| 81 | 81 | ["group:region", "ABCDEF !", "nothing: it was text, as sort:"], |
| 82 | 82 | ["created:>7d", "", "nothing: it was text, and is a field"], |
test/cloud-tree.test.ts +43 −2
| @@ -11,6 +11,7 @@ import { tmpdir } from "node:os"; | ||
| 11 | 11 | import { join } from "node:path"; |
| 12 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 13 | 13 | import { cloudResources } from "../src/actions/infra.ts"; |
| 14 | import { keyOf } from "../src/web/keymap.ts"; | |
| 14 | 15 | import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, tiesOf, type CloudNode, type CloudView } from "../src/cloud/tree.ts"; |
| 15 | 16 | import { aboutContext, aboutLine } from "../src/core/talk_about.ts"; |
| 16 | 17 | import { createSession } from "../src/core/sessions.ts"; |
| @@ -361,8 +362,8 @@ test("ECS clusters, services and tasks are drawn, labelled and counted, in the t | ||
| 361 | 362 | expect(lines).toContain("4 resources"); |
| 362 | 363 | for (const [kind, title, , state] of things) { |
| 363 | 364 | expect(explorer).toContain(`<span class="truncate">${title}</span><span class="ex-kind">${kind}`); |
| 364 | expect(pane).toContain(`${kind} · ${state}`); | |
| 365 | expect(lines).toContain(`${title} · ${kind} · ${state}`); | |
| 365 | expect(pane).toContain(`<td>${kind}</td><td>${state}</td>`); | |
| 366 | expect(lines).toMatch(new RegExp(`^${title} +${kind} +${state} `, "m")); | |
| 366 | 367 | } |
| 367 | 368 | for (const [kind, found] of [["cluster", "1 cluster"], ["service", "1 service"], ["task", "2 tasks"]] as const) { |
| 368 | 369 | expect(await (await get(`/infra?q=${encodeURIComponent(`account:ecs kind:${kind}`)}`)).text()).toContain(found); |
| @@ -651,6 +652,46 @@ test("the infra tool's list says what each resource is attached to: ids it can o | ||
| 651 | 652 | expect((await mcpTool(servers.url, token, "infra", { action: "list", id: "account:tied kind:machine" })).value.resources[0].attachedTo).toBeNull(); |
| 652 | 653 | }); |
| 653 | 654 | |
| 655 | test("one sort at every door, over the lists and not the tree, with what a comparison could not judge", async () => { | |
| 656 | ownAccount("aws", "sorts"); | |
| 657 | project("aws", "sorts", "us-east-1"); | |
| 658 | for (const [id, cents] of [["volume:s-1", 300], ["volume:s-2", -1], ["volume:s-10", 100]] as const) resource("aws", "sorts", "us-east-1", id, cents); | |
| 659 | app.db.run("UPDATE cloud_resource SET created_at = '' WHERE cloud_resource_id = 'volume:s-2'"); | |
| 660 | const token = createToken(app.db, alice.id, "sorts", "admin").token; | |
| 661 | for (const [sort, want] of [["", ["s-1", "s-10", "s-2"]], ["sort:cost", ["s-10", "s-1", "s-2"]], ["sort:-name", ["s-10", "s-2", "s-1"]], ["sort:name", ["s-1", "s-2", "s-10"]]] as const) { | |
| 662 | const line = `account:sorts ${sort}`.trim(); | |
| 663 | const pane = await (await get(`/infra/-/aws/sorts?fragment=1&q=${encodeURIComponent(line)}`)).text(); | |
| 664 | expect([sort, [...pane.slice(pane.indexOf("<tbody>")).matchAll(/<td><a [^>]*>([^<]+)</g)].map((m) => m[1]!)]).toEqual([sort, [...want]]); | |
| 665 | const told = await mcpTool(servers.url, token, "infra", { action: "list", id: line }); | |
| 666 | expect(told.value.resources.map((r: { name: string }) => r.name)).toEqual([...want]); | |
| 667 | const lines = cloudLines(view(line), at(view(line), "aws", "sorts")); | |
| 668 | expect(lines.flatMap((l) => /^s-\d+/.exec(l) ?? [])).toEqual([...want]); | |
| 669 | } | |
| 670 | // The tree keeps its own order, whose branches carry bills. | |
| 671 | expect(at(view("account:sorts sort:cost"), "aws", "sorts", "us-east-1").children.map((c) => c.name)).toEqual(["s-1", "s-10", "s-2"]); | |
| 672 | const line = "account:sorts created:<900w"; | |
| 673 | expect((await mcpTool(servers.url, token, "infra", { action: "list", id: line })).value.unknown).toEqual([{ field: "created", left: 1, among: 0 }]); | |
| 674 | expect(await (await get(`/infra?q=${encodeURIComponent(line)}`)).text()).toContain("1 more has no known created date."); | |
| 675 | const page = await (await get("/infra?q=account%3Asorts")).text(); | |
| 676 | expect(page).toContain('data-term="sort:"'); | |
| 677 | expect(page).toContain(`data-shortcut="${keyOf("sort")}"`); | |
| 678 | // The terminal: the key types the word; a problem is first, and how the line was read is last. | |
| 679 | const terminal = headlessTerminal(120, 30); | |
| 680 | const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false }); | |
| 681 | tui.start(); | |
| 682 | tui.ctx.push(cloudTreeScreen(session, tui.ctx)); | |
| 683 | await settleApp(tui); | |
| 684 | for (const k of `/${line} !zzz kind:>volume\r${keyOf("sort")}-cost\r`) terminal.feed(k); | |
| 685 | await settleApp(tui); | |
| 686 | const said = tui.screen.toText().replace(/\s+/g, " "); | |
| 687 | tui.stop?.(); | |
| 688 | expect(said).toContain(`${line} !zzz kind:>volume sort:-cost`); | |
| 689 | const places = ["takes no comparison", "2 volumes matching", "1 more has no known created date"].map((x) => said.indexOf(x)); | |
| 690 | expect(places.every((p, i) => p >= 0 && p > (places[i - 1] ?? -1))).toBe(true); | |
| 691 | for (const table of ["cloud_resource", "cloud_project"]) app.db.run(`DELETE FROM ${table} WHERE cloud_account_id = 'sorts'`); | |
| 692 | app.db.run("DELETE FROM cloud_account WHERE name = 'sorts'"); | |
| 693 | }); | |
| 694 | ||
| 654 | 695 | test("a date says what it is: an S3 bucket's may be its last change, and one that is missing is not known", async () => { |
| 655 | 696 | account("aws", "dates"); |
| 656 | 697 | project("aws", "dates", "us-east-1"); |
test/list-line.test.ts +3 −3
| @@ -25,7 +25,7 @@ const ROWS: readonly Row[] = [ | ||
| 25 | 25 | { name: "", kind: 'say "hi"', cents: null, made: "" }, |
| 26 | 26 | { name: "unit:7", kind: "c\\d", cents: 500, made: "2026-12-01T23:59:59Z" }, |
| 27 | 27 | ]; |
| 28 | const read = (line: string) => parseLine(line, FIELDS); | |
| 28 | const read = (line: string) => parseLine(line, { fields: FIELDS }); | |
| 29 | 29 | /** The rows a line holds for, by number. */ |
| 30 | 30 | const rows = (line: string): string => ROWS.flatMap((r, i) => (holds(LIST, read(line), r, NOW) ? [i] : [])).join(""); |
| 31 | 31 | const levels = (line: string): string => read(line).problems.map((p) => p.level).join(" "); |
| @@ -71,9 +71,9 @@ test("a problem says what it is, and only a wide one is refused", () => { | ||
| 71 | 71 | |
| 72 | 72 | test("past the list's limit the rest is left out, named, and wide", () => { |
| 73 | 73 | const most = { chars: 20, words: 2 }; |
| 74 | const words = parseLine("a b c d", FIELDS, most); | |
| 74 | const words = parseLine("a b c d", { fields: FIELDS, most }); | |
| 75 | 75 | expect([words.terms.length, words.problems[0]]).toEqual([2, { at: 4, says: "A line here is at most 2 words, so this is left out: c d", level: "wide" }]); |
| 76 | const chars = parseLine(`${"a".repeat(20)} kind:x`, FIELDS, most); | |
| 76 | const chars = parseLine(`${"a".repeat(20)} kind:x`, { fields: FIELDS, most }); | |
| 77 | 77 | expect([chars.text, refusalOf(chars)?.says]).toEqual(["a".repeat(20), "A line here is at most 20 characters, so this is left out: kind:x"]); |
| 78 | 78 | }); |
| 79 | 79 |
test/list-order.test.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * The order a line gives a list, what a heading does to the line, and the rows a comparison could | |
| 3 | * not judge (`src/list/order.ts`); and the table both faces draw from them. | |
| 4 | */ | |
| 5 | import { expect, test } from "bun:test"; | |
| 6 | import { parseLine, type List } from "../src/list/line.ts"; | |
| 7 | import { sorted, sortLine, sortSays, unknownSays, unknownsOf } from "../src/list/order.ts"; | |
| 8 | import { tableLines } from "../src/tui/ui/list.ts"; | |
| 9 | import { listTable } from "../src/web/list.ts"; | |
| 10 | ||
| 11 | interface Row { | |
| 12 | readonly name: string; | |
| 13 | readonly cents: number | null; | |
| 14 | readonly made: string; | |
| 15 | } | |
| 16 | const NOW = Date.parse("2026-12-02T12:00:00Z"); | |
| 17 | const LIST: List<Row> = { | |
| 18 | text: (r) => r.name, | |
| 19 | fields: [ | |
| 20 | { name: "name", type: "text", of: (r) => r.name }, | |
| 21 | { name: "cost", type: "number", of: (r) => r.cents, blank: "unknown", takes: "dollars" }, | |
| 22 | { name: "created", type: "time", of: (r) => r.made, blank: "unknown", takes: "an age or a date", noun: "created date" }, | |
| 23 | { name: "Sort", type: "text", of: () => "" }, | |
| 24 | ], | |
| 25 | columns: ["name", "cost", "created"], | |
| 26 | }; | |
| 27 | const ROWS: readonly Row[] = [ | |
| 28 | { name: "web-10", cents: 900, made: "2026-12-02T11:00:00Z" }, | |
| 29 | { name: "web-2", cents: null, made: "" }, | |
| 30 | { name: "Api", cents: 10_000, made: "2026-11-01T00:00:00+02:00" }, | |
| 31 | { name: "", cents: 900, made: "soon" }, | |
| 32 | ]; | |
| 33 | const read = (line: string) => parseLine(line, LIST); | |
| 34 | const order = (line: string): string => sorted(LIST, read(line), ROWS.map((r, i) => ({ r, i })), (x) => x.r).map((x) => x.i).join(""); | |
| 35 | ||
| 36 | test.each([ | |
| 37 | ["", "0123"], ["sort:name", "2103"], ["sort:-name", "0123"], ["sort:cost", "0321"], ["sort:-cost", "2031"], ["sort:created", "2013"], ["sort:-created", "0213"], | |
| 38 | ["sort:cost,name", "0321"], ["sort:cost,-created", "0321"], ["sort:cost sort:-name", "0321"], ["SORT:-Cost", "2031"], ['sort:-"cost"', "2031"], ["sort:nope,-cost", "2031"], ["sort:cost,-cost", "0321"], | |
| 39 | ] as const)("%p puts the rows as %p: not known is last both ways, and ties keep their order", (line, want) => { | |
| 40 | expect(order(line)).toBe(want); | |
| 41 | }); | |
| 42 | ||
| 43 | test("a sort the list cannot do, a mark and a fourth key are said; half typed is not", () => { | |
| 44 | const says = (line: string): string => read(line).problems.map((p) => `${p.level}: ${p.says}`).join(" "); | |
| 45 | expect(says("sort:labels")).toBe('slip: This list cannot sort by "labels"; it can by name, cost, created, Sort.'); | |
| 46 | expect(says("-sort:cost")).toStartWith("slip: sort: takes no mark before it"); | |
| 47 | expect(read("-sort:cost").sort).toEqual([]); | |
| 48 | expect(says('sort:name,cost,created,"sort"')).toBe("slip: A line sorts by 3 fields at most, so Sort is left out."); | |
| 49 | for (const line of ["sort:", "sort:-", "sort:,"]) expect(says(line)).toBe("half: "); | |
| 50 | expect(parseLine("sort:cost", { fields: LIST.fields }).problems[0]!.says).toBe("This list cannot sort."); | |
| 51 | }); | |
| 52 | ||
| 53 | test("a heading goes largest, newest or A first, then the other way, then back to the list's own order", () => { | |
| 54 | const press = (line: string, name: string): string => sortLine(read(line), LIST.fields.find((f) => f.name === name)!); | |
| 55 | expect([press("web", "cost"), press("web sort:-cost", "cost"), press("web sort:cost", "cost")]).toEqual(["web sort:-cost", "web sort:cost", "web"]); | |
| 56 | expect([press("", "name"), press("sort:name", "name"), press("sort:-name", "name")]).toEqual(["sort:name", "sort:-name", ""]); | |
| 57 | expect(press('sort:name "a sort:name b" sort:-cost cost:>1', "created")).toBe('"a sort:name b" cost:>1 sort:-created'); | |
| 58 | expect(press("", "Sort")).toBe('sort:"Sort"'); | |
| 59 | expect(read(press("", "Sort")).sort).toEqual([{ field: "Sort", down: false }]); | |
| 60 | }); | |
| 61 | ||
| 62 | test("the order in words", () => { | |
| 63 | expect(sortSays(LIST, read("sort:-created,cost,name"))).toBe("sorted by created, newest first, then cost, smallest first, then name, A first"); | |
| 64 | }); | |
| 65 | ||
| 66 | test("a comparison says how many rows it could not judge: left out for that alone, or let in by !", () => { | |
| 67 | const says = (line: string): string => unknownSays(LIST, unknownsOf(LIST, read(line), ROWS, NOW)).join(" "); | |
| 68 | expect(says("created:<7d")).toBe("2 more have no known created date."); | |
| 69 | expect(says("created:<7d web")).toBe("1 more has no known created date."); | |
| 70 | expect(says("created:<7d api")).toBe(""); | |
| 71 | expect(says("cost:>5 created:<7d")).toBe("1 more has no known cost. 2 more have no known created date."); | |
| 72 | expect(says("!created:<7d")).toBe("2 of these have no known created date."); | |
| 73 | for (const line of ["", "web", "cost:unknown", "created:<7d,unknown", "!cost:unknown", "name:web", "cost:,"]) expect(says(line)).toBe(""); | |
| 74 | }); | |
| 75 | ||
| 76 | const COLUMNS = LIST.columns!.map((name) => ({ field: LIST.fields.find((f) => f.name === name)!, label: name })); | |
| 77 | ||
| 78 | test("the web's table: a heading is a link that rewrites the line, and the sorted one says its way", () => { | |
| 79 | const draw = (line: string): string => | |
| 80 | String(listTable({ columns: COLUMNS, line: read(line), rows: ROWS, cell: (r, f) => (f === "name" ? r.name : "<b>"), href: (q) => `/x?q=${encodeURIComponent(q)}`, caption: "Rows" })); | |
| 81 | expect(draw("web sort:-cost")).toContain('aria-sort="descending"><a href="/x?q=web%20sort%3Acost">cost</a>'); | |
| 82 | expect(draw("web")).not.toContain("aria-sort"); | |
| 83 | expect(draw('"web')).not.toContain("<a href"); | |
| 84 | expect(draw("web")).not.toContain("<b>"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("the terminal's table: columns line up, the last go when there is no room, the name is never all gone", () => { | |
| 88 | const lines = (width: number): string[] => tableLines(COLUMNS, read("sort:-cost"), [["a-long-name-of-a-thing", "$9.00", "2026-12-02"], ["b", "–", "not known"]], width); | |
| 89 | expect(lines(80)).toEqual(["name cost ↓ created", "a-long-name-of-a-thing $9.00 2026-12-02", "b – not known"]); | |
| 90 | expect(lines(30)[1]).toBe("a-long-name-of-a-thing $9.00"); | |
| 91 | expect(lines(10)[1]!.length).toBeLessThanOrEqual(10); | |
| 92 | for (const w of [1, 5, 16, 24, 36, 40]) for (const l of lines(w)) expect(l.length).toBeLessThanOrEqual(w); | |
| 93 | }); |
new above
offline