Public: anyone can read this; the crew can change it.
Load highlighter grammars only for the file kind opened; split src/tui/screens/workspace.ts #17109
Merged 41h 34m ago, live in production
mason/forge:mason/16804-load-highlighter-grammars-only-for-the-f → main 0 commits fork 3 threads · 3 unresolved
5 files
changed +1476
−1449
src/tui/screens/workspace.ts +16 −1449
| @@ -49,11 +49,8 @@ import { setDecisionsBy } from "../../actions/repos.ts"; | ||
| 49 | 49 | import { stopMirroring } from "../../actions/mirror_target.ts"; |
| 50 | 50 | import { getMirrorTarget, mirrorLine } from "../../core/migrate_mirror.ts"; |
| 51 | 51 | import { canAdmin, canWrite, DECISIONS_BY, getRepoById, type Repo } from "../../core/repos.ts"; |
| 52 | import type { TreeEntry } from "../../git/read.ts"; | |
| 53 | import { parseUnifiedDiff, type Diff } from "../../git/diff.ts"; | |
| 54 | import { renderDiff as renderPatch } from "../ui/diff.ts"; | |
| 55 | 52 | import { hasMember, jsonOutlineText, NO_MEMBER, openMember } from "../../web/render/json-big.ts"; |
| 56 | import { fileKind, isEnvExample, isJsonPath, kindByName, NO_BYTES, RENDER_CAP, sniffType } from "../../web/render/kinds.ts"; | |
| 53 | import { isJsonPath, kindByName, sniffType } from "../../web/render/kinds.ts"; | |
| 57 | 54 | import { tailOf, tailSentence } from "../../web/log_tail.ts"; |
| 58 | 55 | import { downloadHref } from "../../web/pages/media.ts"; |
| 59 | 56 | import { hexdump, HEX_BYTES } from "../../web/render/hexdump.ts"; |
| @@ -63,45 +60,10 @@ import { isModelPath, modelFacts } from "../../web/render/model-facts.ts"; | ||
| 63 | 60 | import { measureDxfTyped, parseDxf } from "../../web/render/dxf.ts"; |
| 64 | 61 | import { measureTyped, unitFor } from "../../web/render/measure.ts"; |
| 65 | 62 | import type { RepoFacts, RepoSource } from "../../view/source.ts"; |
| 66 | import { detectLanguage, highlightLines } from "../../web/highlight.ts"; | |
| 67 | import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts"; | |
| 68 | import { MAX_COLUMNS, parseCsv, type Table } from "../../text/csv.ts"; | |
| 69 | import { isNumericColumn, sortRows } from "../../text/csv-sort.ts"; | |
| 70 | import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts"; | |
| 71 | import { isKmlPath, kmlTable } from "./kml.ts"; | |
| 72 | import { pcdFacts } from "../../web/render/pcd.ts"; | |
| 73 | import { gcodeFacts, parseGcode } from "../../web/render/gcode.ts"; | |
| 74 | import { ifcFacts, ifcTreeRows, readIfc, typeWords } from "../../text/ifc.ts"; | |
| 75 | import { readStep, stepFacts } from "../../web/render/step.ts"; | |
| 76 | import { parseOtio } from "../../web/render/otio.ts"; | |
| 77 | import { parseEdl } from "../../web/render/edl.ts"; | |
| 78 | import { ROW_CAP as TIMELINE_ROW_CAP } from "../../web/render/timeline-table.ts"; | |
| 79 | import { parseHar, ROW_CAP as HAR_ROW_CAP, duration as harDuration } from "../../web/render/har.ts"; | |
| 80 | import { gpxFacts, parseGpx } from "../../web/render/gpx.ts"; | |
| 81 | import { CASE_CAP, parseJunit } from "../../web/render/junit.ts"; | |
| 82 | import { nest, parseEntries } from "../../web/render/feed-xml.ts"; | |
| 83 | import { parseOpenApi } from "../../web/render/openapi.ts"; | |
| 84 | import { parseDockerfile } from "../../web/render/dockerfile.ts"; | |
| 85 | import { parseWorkflow } from "../../web/render/workflow.ts"; | |
| 86 | import { parseGraphql } from "../../web/render/graphql.ts"; | |
| 87 | import { parseMbox } from "../../web/render/mbox.ts"; | |
| 88 | import { parseProto } from "../../web/render/proto.ts"; | |
| 89 | import { parseIni } from "../../web/render/ini.ts"; | |
| 90 | import { parseRtf } from "../../web/render/rtf.ts"; | |
| 91 | import { parseXml, type XmlNode } from "../../web/render/xml.ts"; | |
| 92 | import { parseSql } from "../../web/render/sql.ts"; | |
| 93 | import { RESULT_CAP, parseSarif } from "../../web/render/sarif.ts"; | |
| 94 | import { RECORD_CAP, parseLcov, worstFirst, type Ratio } from "../../web/render/lcov.ts"; | |
| 95 | import { EVENT_CAP, parseIcs } from "../../web/render/ics.ts"; | |
| 96 | import { fileSize } from "../../web/ui.ts"; | |
| 97 | import { parseEml } from "../../web/render/eml-parse.ts"; | |
| 98 | import { parsePackage, ROW_CAP as PKG_ROW_CAP } from "../../web/render/package-json.ts"; | |
| 99 | import { parseEnv, ROW_CAP as ENV_ROW_CAP } from "../../web/render/env.ts"; | |
| 100 | import { CARD_CAP, parseVcf } from "../../web/render/vcf-parse.ts"; | |
| 101 | import { CUE_CAP, parseSubtitles } from "../../web/render/subtitles.ts"; | |
| 102 | import { isJsonlPath, kindView, type KindLines } from "./workspace_kinds.ts"; | |
| 63 | import { type Table } from "../../text/csv.ts"; | |
| 64 | import { isJsonlPath } from "./workspace_kinds.ts"; | |
| 103 | 65 | import { sheetView } from "./workspace_sheet.ts"; |
| 104 | import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts"; | |
| 66 | import { sqliteStep, sqliteView } from "./workspace_sqlite.ts"; | |
| 105 | 67 | import { officeView } from "./workspace_office.ts"; |
| 106 | 68 | import { parquetView } from "./workspace_parquet.ts"; |
| 107 | 69 | import { bibView } from "./workspace_bib.ts"; |
| @@ -111,35 +73,15 @@ import { registryView } from "./workspace_registry.ts"; | ||
| 111 | 73 | import { factsView } from "./workspace_facts.ts"; |
| 112 | 74 | import { depsView } from "./workspace_deps.ts"; |
| 113 | 75 | import { cadView } from "./workspace_cad.ts"; |
| 114 | import { layoutTable, type Grid } from "../ui/grid.ts"; | |
| 115 | 76 | import type { Ctx, Screen } from "../app/app.ts"; |
| 116 | import { stripAnsi } from "../term/ansi.ts"; | |
| 117 | 77 | import { binding, type Binding } from "../app/keys.ts"; |
| 118 | 78 | import type { KeyEvent } from "../term/input.ts"; |
| 119 | import { | |
| 120 | G, | |
| 121 | type Rect, | |
| 122 | type Screen as Surface, | |
| 123 | type Span, | |
| 124 | } from "../term/screen.ts"; | |
| 125 | import { BOLD, STRIKE, UNDERLINE, style } from "../term/style.ts"; | |
| 126 | import { | |
| 127 | clusters, | |
| 128 | displayWidth, | |
| 129 | expandTabs, | |
| 130 | pad, | |
| 131 | truncate, | |
| 132 | } from "../term/width.ts"; | |
| 133 | import { Editor } from "../ui/editor.ts"; | |
| 134 | import { fileIcon, looksLikeImage, type IconSet } from "../ui/icons.ts"; | |
| 135 | import { | |
| 136 | drawImage, | |
| 137 | humanBytes, | |
| 138 | prepareImage, | |
| 139 | type TerminalImage, | |
| 140 | } from "../ui/image.ts"; | |
| 79 | import { G, type Rect, type Screen as Surface } from "../term/screen.ts"; | |
| 80 | import { BOLD, style } from "../term/style.ts"; | |
| 81 | import { displayWidth, truncate } from "../term/width.ts"; | |
| 82 | import { looksLikeImage } from "../ui/icons.ts"; | |
| 83 | import { drawImage, humanBytes, prepareImage, type TerminalImage } from "../ui/image.ts"; | |
| 141 | 84 | import { fill, len, split } from "../ui/layout.ts"; |
| 142 | import { renderMarkdown, type Line } from "../ui/markdown.ts"; | |
| 143 | 85 | import { archiveNote } from "../ui/archive-note.ts"; |
| 144 | 86 | import { usdNote } from "../ui/usd-note.ts"; |
| 145 | 87 | import { holdsExif, readExif } from "../../web/render/exif.ts"; |
| @@ -149,7 +91,7 @@ import { blendNote } from "../ui/blend-note.ts"; | ||
| 149 | 91 | import { mediaNote } from "../ui/media-note.ts"; |
| 150 | 92 | import { plainReason } from "../../web/render/renderers.ts"; |
| 151 | 93 | import { undrawable, UNDRAWN } from "../../web/render/undrawable.ts"; |
| 152 | import { tokColor, type Tokens } from "../ui/theme.ts"; | |
| 94 | import { type Tokens } from "../ui/theme.ts"; | |
| 153 | 95 | import { card, emptyState, input, noteLines, scrollbar } from "../ui/widgets.ts"; |
| 154 | 96 | import type { Session } from "../session.ts"; |
| 155 | 97 | import { aboutScreen } from "./about.ts"; |
| @@ -178,7 +120,6 @@ import { runsScreen } from "./runs.ts"; | ||
| 178 | 120 | import { |
| 179 | 121 | Filter, |
| 180 | 122 | ListState, |
| 181 | Scroll, | |
| 182 | 123 | confirmScreen, |
| 183 | 124 | drawFacts, |
| 184 | 125 | drawLines, |
| @@ -275,13 +216,12 @@ import { | ||
| 275 | 216 | whereSpans, |
| 276 | 217 | whereStrip, |
| 277 | 218 | } from "./where.ts"; |
| 278 | ||
| 279 | /** | |
| 280 | * The mark a rendered markdown tab wears — `README.md ¶`. From the safe set | |
| 281 | * in `term/screen.ts` (documented in `docs/DESIGN.md`): it is the one glyph | |
| 282 | * in that set that already means "formatted prose", and `v` takes it off. | |
| 283 | */ | |
| 284 | const PROSE_MARK = G.para; | |
| 219 | import { isTablePath, isSubtitlePath, isIcsPath, isVcfPath, isGpxPath, isSarifPath, isLcovPath, isOpenApiPath, isDockerfilePath, isJunitPath, isGeoJsonPath } from "./workspace_tables.ts"; | |
| 220 | import { type Node, nodeOf, flatten, findNode, landing } from "./workspace_tree.ts"; | |
| 221 | import { isMarkdownPath, Tab, type CacheEntry } from "./workspace_tab.ts"; | |
| 222 | import { drawRefPill, drawTabBar, drawTree, drawCode, tableStatus, tableProblem, drawTable } from "./workspace_draw.ts"; | |
| 223 | export { harTable, timelineTable } from "./workspace_tables.ts"; | |
| 224 | export { buildLines } from "./workspace_tab.ts"; | |
| 285 | 225 | |
| 286 | 226 | /** Blobs kept per workspace; a session revisits the same handful. */ |
| 287 | 227 | const CACHE_LIMIT = 24; |
| @@ -296,1014 +236,6 @@ function formatSize(bytes: number): string { | ||
| 296 | 236 | return `${(bytes / 1024 / 1024).toFixed(1)} M`; |
| 297 | 237 | } |
| 298 | 238 | |
| 299 | // ---- the explorer's model ---- | |
| 300 | ||
| 301 | interface Node { | |
| 302 | readonly path: string; | |
| 303 | readonly name: string; | |
| 304 | readonly type: "tree" | "blob"; | |
| 305 | readonly size: number; | |
| 306 | readonly depth: number; | |
| 307 | expanded: boolean; | |
| 308 | loading: boolean; | |
| 309 | /** Null until the directory has been listed once. */ | |
| 310 | children: Node[] | null; | |
| 311 | } | |
| 312 | ||
| 313 | function nodeOf(entry: TreeEntry, parent: string, depth: number): Node { | |
| 314 | return { | |
| 315 | path: parent === "" ? entry.name : `${parent}/${entry.name}`, | |
| 316 | name: entry.name, | |
| 317 | type: entry.type === "tree" ? "tree" : "blob", | |
| 318 | size: entry.size, | |
| 319 | depth, | |
| 320 | expanded: false, | |
| 321 | loading: false, | |
| 322 | children: null, | |
| 323 | }; | |
| 324 | } | |
| 325 | ||
| 326 | /** Depth-first walk of what is currently expanded — the rows on screen. */ | |
| 327 | function flatten(nodes: readonly Node[], out: Node[] = []): Node[] { | |
| 328 | for (const node of nodes) { | |
| 329 | out.push(node); | |
| 330 | if (node.expanded && node.children !== null) flatten(node.children, out); | |
| 331 | } | |
| 332 | return out; | |
| 333 | } | |
| 334 | ||
| 335 | function findNode(nodes: readonly Node[], path: string): Node | undefined { | |
| 336 | for (const node of nodes) { | |
| 337 | if (node.path === path) return node; | |
| 338 | if (path.startsWith(`${node.path}/`) && node.children !== null) { | |
| 339 | const hit = findNode(node.children, path); | |
| 340 | if (hit !== undefined) return hit; | |
| 341 | } | |
| 342 | } | |
| 343 | return undefined; | |
| 344 | } | |
| 345 | ||
| 346 | /** The file a repository opens on: its README, else the first file there. */ | |
| 347 | function landing(nodes: readonly Node[]): Node | undefined { | |
| 348 | const readme = nodes.find( | |
| 349 | (n) => n.type === "blob" && /^readme(\.|$)/i.test(n.name), | |
| 350 | ); | |
| 351 | return readme ?? nodes.find((n) => n.type === "blob"); | |
| 352 | } | |
| 353 | ||
| 354 | // ---- a file, as a tab ---- | |
| 355 | ||
| 356 | /** | |
| 357 | * Styled rows plus the plain text behind them. The gutter is *not* in the | |
| 358 | * spans: the pane draws line numbers itself, so they stay pinned while the | |
| 359 | * code scrolls sideways under them. | |
| 360 | */ | |
| 361 | function isLogPath(path: string): boolean { | |
| 362 | return /\.(log|ansi)$/i.test(path); | |
| 363 | } | |
| 364 | ||
| 365 | export function buildLines( | |
| 366 | text: string, | |
| 367 | path: string, | |
| 368 | c: Tokens, | |
| 369 | ): { plain: string[]; lines: Span[][] } { | |
| 370 | // A terminal log carries escapes; the viewer shows its text, never drives | |
| 371 | // the terminal or prints "[31m" as if it were the log. | |
| 372 | const clean = isLogPath(path) && text.includes("\x1b") ? stripAnsi(text) : text; | |
| 373 | // A private key's body is never drawn: one notice line stands in, as on the page. | |
| 374 | const body = holdsPrivateKey(clean) ? PRIVATE_KEY_NOTICE : clean.replace(/\n$/, ""); | |
| 375 | const plain = body.split("\n").map((l) => expandTabs(l)); | |
| 376 | // The first line is handed to the detector too: a `#!/usr/bin/env python3` | |
| 377 | // with no extension, a `.zshrc`, a vim modeline. The name is the strong | |
| 378 | // signal and the line is the fallback, which is the detector's own order. | |
| 379 | const language = detectLanguage(path, plain[0] ?? ""); | |
| 380 | const lines = highlightLines(plain.join("\n"), language).map( | |
| 381 | (tokens): Span[] => | |
| 382 | tokens.map((t) => ({ | |
| 383 | text: t.text, | |
| 384 | style: style(tokColor(c, t), c.bg), | |
| 385 | })), | |
| 386 | ); | |
| 387 | return { plain, lines }; | |
| 388 | } | |
| 389 | ||
| 390 | type TabMode = "view" | "edit"; | |
| 391 | type FindMode = "off" | "find" | "replace"; | |
| 392 | /** What a path is, as far as the file pane is concerned. */ | |
| 393 | type TabKind = "image" | "markdown" | "patch" | "code"; | |
| 394 | ||
| 395 | /** `.csv` and `.tsv`: files that read as a table. */ | |
| 396 | function isTablePath(path: string): boolean { | |
| 397 | return /\.[ct]sv$/i.test(path); | |
| 398 | } | |
| 399 | ||
| 400 | /** `.srt` and `.vtt`: a transcript, drawn as the same two-column table. */ | |
| 401 | function isSubtitlePath(path: string): boolean { | |
| 402 | return /\.(srt|vtt)$/i.test(path); | |
| 403 | } | |
| 404 | ||
| 405 | /** The cues of a subtitle file as a table: start time, text. Shares the web's parser. */ | |
| 406 | function subtitleTable(source: string): { table: Table; unread: number } { | |
| 407 | const { cues, failures } = parseSubtitles(source); | |
| 408 | const shown = cues.slice(0, CUE_CAP); | |
| 409 | return { | |
| 410 | unread: failures.length, | |
| 411 | table: { | |
| 412 | header: ["Start", "Text"], | |
| 413 | rows: shown.map((c) => [c.start, c.text]), | |
| 414 | more: cues.length - shown.length, | |
| 415 | delimiter: ",", | |
| 416 | columns: 2, | |
| 417 | }, | |
| 418 | }; | |
| 419 | } | |
| 420 | ||
| 421 | /** `.ics`: a calendar, drawn as a table of its events. */ | |
| 422 | function isIcsPath(path: string): boolean { | |
| 423 | return /\.ics$/i.test(path); | |
| 424 | } | |
| 425 | ||
| 426 | /** | |
| 427 | * The events of a calendar as a table; null when the file is not a calendar. Shares the web's | |
| 428 | * parser. | |
| 429 | */ | |
| 430 | function icsTable(source: string): { table: Table; unread: number } | null { | |
| 431 | const cal = parseIcs(source); | |
| 432 | if ("error" in cal) return null; | |
| 433 | const shown = cal.events.slice(0, EVENT_CAP); | |
| 434 | return { | |
| 435 | unread: cal.skipped, | |
| 436 | table: { | |
| 437 | header: ["Start", "End", "Summary", "Location"], | |
| 438 | rows: shown.map((e) => [e.start, e.end, e.summary, e.location]), | |
| 439 | more: cal.events.length - shown.length, | |
| 440 | delimiter: ",", | |
| 441 | columns: 4, | |
| 442 | }, | |
| 443 | }; | |
| 444 | } | |
| 445 | ||
| 446 | /** `.vcf` and `.vcard`: contacts, drawn as a table of people. */ | |
| 447 | function isVcfPath(path: string): boolean { | |
| 448 | return /\.(vcf|vcard)$/i.test(path); | |
| 449 | } | |
| 450 | ||
| 451 | /** | |
| 452 | * The cards of a contacts file as a table; null when the file is not one. Shares the web's parser. | |
| 453 | */ | |
| 454 | function vcfTable(source: string): Table | null { | |
| 455 | const parsed = parseVcf(source); | |
| 456 | if ("error" in parsed || parsed.total === 0) return null; | |
| 457 | const shown = parsed.cards.slice(0, CARD_CAP); | |
| 458 | return { | |
| 459 | header: ["Name", "Organisation", "Email", "Phone"], | |
| 460 | rows: shown.map((c) => c.malformed ? [`(${c.name})`, "—", "—", "—"] : [c.name, c.org, c.emails.join(", "), c.phones.join(", ")]), | |
| 461 | more: parsed.total - shown.length, | |
| 462 | delimiter: ",", | |
| 463 | columns: 4, | |
| 464 | }; | |
| 465 | } | |
| 466 | ||
| 467 | /** | |
| 468 | * The variables of a `.env.example` as a table; null when it holds none. Shares the web's parser. | |
| 469 | */ | |
| 470 | function envTable(source: string): Table | null { | |
| 471 | const doc = parseEnv(source); | |
| 472 | if (doc.total === 0) return null; | |
| 473 | const dash = (v: string): string => (v === "" ? "—" : v); | |
| 474 | const rows: string[][] = []; | |
| 475 | let last = ""; | |
| 476 | for (const r of doc.rows.slice(0, ENV_ROW_CAP)) { | |
| 477 | if (r.group !== "" && r.group !== last) rows.push([`# ${r.group}`, "", ""]); | |
| 478 | last = r.group; | |
| 479 | rows.push([r.name, dash(r.value), dash(r.comment)]); | |
| 480 | } | |
| 481 | return { header: ["Name", "Example", "Comment"], rows, more: doc.total - doc.rows.length, delimiter: ",", columns: 3 }; | |
| 482 | } | |
| 483 | ||
| 484 | /** | |
| 485 | * A `package.json` as Section/Name/Value rows; null when it is not a JSON object. Shares the web's | |
| 486 | * parser. | |
| 487 | */ | |
| 488 | function packageTable(source: string): Table | null { | |
| 489 | const doc = parsePackage(source); | |
| 490 | if (doc === undefined) return null; | |
| 491 | const rows: string[][] = []; | |
| 492 | if (doc.name !== "") rows.push(["package", doc.name, doc.version]); | |
| 493 | if (doc.facts.length > 0) rows.push(["facts", doc.facts.join(" · "), ""]); | |
| 494 | let more = 0; | |
| 495 | for (const s of doc.sections) { | |
| 496 | for (const [k, v] of s.rows.slice(0, PKG_ROW_CAP)) rows.push([s.title, k, v]); | |
| 497 | more += s.total - s.rows.length; | |
| 498 | } | |
| 499 | if (rows.length === 0) return null; | |
| 500 | return { header: ["Section", "Name", "Value"], rows, more, delimiter: ",", columns: 3 }; | |
| 501 | } | |
| 502 | ||
| 503 | /** `.eml`: a message, drawn as rows of its headers, body and attachments. */ | |
| 504 | function isEmlPath(path: string): boolean { | |
| 505 | return /\.eml$/i.test(path); | |
| 506 | } | |
| 507 | ||
| 508 | const EML_BODY_LINES = 200; | |
| 509 | ||
| 510 | /** The message as Field/Value rows; null when the file is not one. Shares the web's parser. */ | |
| 511 | function emlTable(source: Uint8Array): Table | null { | |
| 512 | const m = parseEml(source); | |
| 513 | if ("error" in m) return null; | |
| 514 | const rows: string[][] = m.headers.map(([k, v]) => [k, v]); | |
| 515 | if (m.fromHtml) rows.push(["Note", "only an HTML part; tags stripped"]); | |
| 516 | const lines = m.body.split("\n"); | |
| 517 | for (const line of lines.slice(0, EML_BODY_LINES)) rows.push(["", line]); | |
| 518 | if (lines.length > EML_BODY_LINES) rows.push(["Note", `body cut: ${lines.length - EML_BODY_LINES} more lines`]); | |
| 519 | for (const a of m.attachments) rows.push(["Attachment", `${a.name} · ${a.type} · ${fileSize(a.size)}`]); | |
| 520 | return { header: ["Field", "Value"], rows, more: 0, delimiter: ",", columns: 2 }; | |
| 521 | } | |
| 522 | ||
| 523 | /** `.gpx`: a GPS track, drawn as a table of its facts (track, distance, climb, points). */ | |
| 524 | function isGpxPath(path: string): boolean { | |
| 525 | return /\.gpx$/i.test(path); | |
| 526 | } | |
| 527 | ||
| 528 | /** The facts of a track as a table; null when the file is not a track. Shares the web's parser. */ | |
| 529 | function gpxTable(source: string, path: string): Table | null { | |
| 530 | const parsed = parseGpx(source); | |
| 531 | if (parsed === undefined) return null; | |
| 532 | const rows = gpxFacts(parsed, path); | |
| 533 | // A track the scan stopped reading says so (the page's `CUT_NOTE`, short enough for a cell). | |
| 534 | if (parsed.cut === true) rows.push(["Read", "first part only"]); | |
| 535 | return { header: ["Fact", "Value"], rows, more: 0, delimiter: ",", columns: 2 }; | |
| 536 | } | |
| 537 | ||
| 538 | /** `.har`: a browser's captured session, drawn as a table of its requests. */ | |
| 539 | function isHarPath(path: string): boolean { | |
| 540 | return /\.har$/i.test(path); | |
| 541 | } | |
| 542 | ||
| 543 | /** | |
| 544 | * The requests of a HAR as a table; null when the file is not one. Shares the web's parser and row | |
| 545 | * cap. | |
| 546 | */ | |
| 547 | export function harTable(source: string): Table | null { | |
| 548 | const parsed = parseHar(source); | |
| 549 | if ("error" in parsed || parsed.entries.length === 0) return null; | |
| 550 | const shown = parsed.entries.slice(0, HAR_ROW_CAP); | |
| 551 | return { | |
| 552 | header: ["Method", "Status", "URL", "Size", "Time"], | |
| 553 | rows: shown.map((e) => [ | |
| 554 | e.method, | |
| 555 | e.status === 0 ? "-" : String(e.status), | |
| 556 | e.url, | |
| 557 | e.bytes === undefined ? "-" : fileSize(e.bytes), | |
| 558 | harDuration(e.ms), | |
| 559 | ]), | |
| 560 | more: parsed.entries.length - shown.length, | |
| 561 | delimiter: ",", | |
| 562 | columns: 5, | |
| 563 | }; | |
| 564 | } | |
| 565 | ||
| 566 | /** `.otio` / `.edl`: a video-edit timeline, drawn as a cut list. */ | |
| 567 | function isTimelinePath(path: string): boolean { | |
| 568 | const k = kindByName(path); | |
| 569 | return k === "otio" || k === "edl"; | |
| 570 | } | |
| 571 | ||
| 572 | /** | |
| 573 | * The clips of a timeline as one table, a track column first; the reason, as the page words | |
| 574 | * it, when it is not drawn. Shares the web's parsers and 1 MB cap. | |
| 575 | */ | |
| 576 | export function timelineTable(source: Uint8Array, path: string): Table | string { | |
| 577 | if (source.length > RENDER_CAP.otio) return "not drawn as a cut list: it is over 1 MB"; | |
| 578 | const text = new TextDecoder().decode(source); | |
| 579 | const parsed = kindByName(path) === "otio" ? parseOtio(text) : parseEdl(text); | |
| 580 | if ("error" in parsed) return `not drawn as a cut list: ${parsed.error}`; | |
| 581 | const all = parsed.timeline.tracks.flatMap((t) => t.cuts.map((c, i) => [t.name, String(i + 1), c.name, c.source, c.in, c.out, c.duration])); | |
| 582 | const rows = all.slice(0, TIMELINE_ROW_CAP); | |
| 583 | return { header: ["Track", "#", "Clip", "Source", "In", "Out", "Duration"], rows, more: all.length - rows.length, delimiter: ",", columns: 7 }; | |
| 584 | } | |
| 585 | ||
| 586 | /** `.sarif`: a scanner's findings, drawn as a table of level, rule, location and message. */ | |
| 587 | function isSarifPath(path: string): boolean { | |
| 588 | return /\.sarif$/i.test(path); | |
| 589 | } | |
| 590 | ||
| 591 | /** | |
| 592 | * The findings of a SARIF file as a table, tool by tool; the reason, as the page words it, when it | |
| 593 | * is not SARIF. Shares the web's parser. | |
| 594 | */ | |
| 595 | function sarifTable(source: string): Table | string { | |
| 596 | const parsed = parseSarif(source); | |
| 597 | if ("error" in parsed) return `not drawn as findings: ${parsed.error}`; | |
| 598 | const all = parsed.runs.flatMap((r) => | |
| 599 | r.results.map((f) => [f.level, f.rule, f.file === "" ? "-" : f.line > 0 ? `${f.file}:${f.line}` : f.file, f.message.replace(/\s+/g, " "), r.tool]), | |
| 600 | ); | |
| 601 | const rows = all.slice(0, RESULT_CAP); | |
| 602 | return { header: ["Level", "Rule", "Location", "Message", "Tool"], rows, more: all.length - rows.length, delimiter: ",", columns: 5 }; | |
| 603 | } | |
| 604 | ||
| 605 | /** | |
| 606 | * `lcov.info` / `.lcov`: a coverage tracefile, drawn as a table per source file, worst line | |
| 607 | * coverage first. | |
| 608 | */ | |
| 609 | function isLcovPath(path: string): boolean { | |
| 610 | return kindByName(path) === "lcov"; | |
| 611 | } | |
| 612 | ||
| 613 | /** | |
| 614 | * The coverage of an lcov file as a table; the reason, as the page words it, when it is not lcov. | |
| 615 | * Shares the web's parser. | |
| 616 | */ | |
| 617 | function lcovTable(source: string): Table | string { | |
| 618 | const parsed = parseLcov(source); | |
| 619 | if ("error" in parsed) return `not drawn as coverage: ${parsed.error}`; | |
| 620 | const pct = (r: Ratio | undefined): string => (r === undefined || r.found === 0 ? "-" : `${r.hit}/${r.found} ${(Math.floor((r.hit / r.found) * 1000) / 10).toFixed(1)}%`); | |
| 621 | const sorted = worstFirst(parsed.records); | |
| 622 | const rows = sorted.slice(0, RECORD_CAP).map((r) => [r.file, pct(r.lines), pct(r.functions), pct(r.branches)]); | |
| 623 | return { header: ["File", "Lines", "Functions", "Branches"], rows, more: sorted.length - rows.length, delimiter: ",", columns: 4 }; | |
| 624 | } | |
| 625 | ||
| 626 | /** An OpenAPI document by file name; whether its content is one is `openapiTable`'s to say. */ | |
| 627 | function isOpenApiPath(path: string): boolean { | |
| 628 | return kindByName(path) === "openapi"; | |
| 629 | } | |
| 630 | ||
| 631 | /** | |
| 632 | * The operations of an OpenAPI document as a table, tag by tag; null when the file is not one, | |
| 633 | * the reason when it is but cannot be drawn. Shares the web's parser. | |
| 634 | */ | |
| 635 | function openapiTable(text: string, path: string): Table | string | null { | |
| 636 | const parsed = parseOpenApi(text, path); | |
| 637 | if (parsed === "not") return null; | |
| 638 | if ("error" in parsed) return `not drawn as an API: ${parsed.error}`; | |
| 639 | const rows = parsed.groups.flatMap((g) => g.ops.map((o) => [g.tag === "" ? "-" : g.tag, o.method, o.path, o.deprecated ? `${o.summary} (deprecated)`.trim() : o.summary])); | |
| 640 | return { header: ["Tag", "Method", "Path", "Summary"], rows, more: parsed.more, delimiter: ",", columns: 4 }; | |
| 641 | } | |
| 642 | ||
| 643 | /** A Dockerfile by file name. */ | |
| 644 | function isDockerfilePath(path: string): boolean { | |
| 645 | return kindByName(path) === "dockerfile"; | |
| 646 | } | |
| 647 | ||
| 648 | /** | |
| 649 | * A Dockerfile as a table: per stage, its ports and ENV names, then one row per instruction; | |
| 650 | * the web's reason when it is not drawn. Shares the web's parser. | |
| 651 | */ | |
| 652 | function dockerfileTable(source: string): Table | string { | |
| 653 | const parsed = parseDockerfile(source); | |
| 654 | if ("error" in parsed) return `not drawn as a build: ${parsed.error}`; | |
| 655 | const rows: string[][] = []; | |
| 656 | for (const s of parsed.stages) { | |
| 657 | const title = s.image === "" ? "(before the first stage)" : `${s.image}${s.name === "" ? "" : ` as ${s.name}`}`; | |
| 658 | rows.push([title, "FROM", s.image]); | |
| 659 | if (s.ports.length > 0) rows.push([title, "EXPOSE", s.ports.join(" ")]); | |
| 660 | if (s.env.length > 0) rows.push([title, "ENV", s.env.join(" ")]); | |
| 661 | for (const r of s.rows) rows.push([title, r.keyword, r.args.replace(/\s+/g, " ")]); | |
| 662 | } | |
| 663 | return { header: ["Stage", "Instruction", "Arguments"], rows, more: parsed.total - parsed.shown, delimiter: ",", columns: 3 }; | |
| 664 | } | |
| 665 | ||
| 666 | /** A GitHub Actions workflow by file name. */ | |
| 667 | function isWorkflowPath(path: string): boolean { | |
| 668 | return kindByName(path) === "workflow"; | |
| 669 | } | |
| 670 | ||
| 671 | /** | |
| 672 | * A workflow as a table: the triggers, then per job its runner, needs and matrix, then one row | |
| 673 | * per step; the web's reason when it is not drawn. Shares the web's parser. | |
| 674 | */ | |
| 675 | function workflowTable(source: string): Table | string { | |
| 676 | const parsed = parseWorkflow(source); | |
| 677 | if ("error" in parsed) return `not drawn as a workflow: ${parsed.error}`; | |
| 678 | const rows: string[][] = [["-", "on", parsed.triggers.join(" ")]]; | |
| 679 | let more = parsed.jobsTotal - parsed.jobs.length; | |
| 680 | for (const j of parsed.jobs) { | |
| 681 | if (j.runsOn !== "") rows.push([j.id, "runs-on", j.runsOn]); | |
| 682 | if (j.needs.length > 0) rows.push([j.id, "needs", j.needs.join(" ")]); | |
| 683 | if (j.matrix.length > 0) rows.push([j.id, "matrix", j.matrix.join("; ")]); | |
| 684 | for (const s of j.steps) rows.push([j.id, s.kind === "" ? "step" : s.kind, [s.name, s.does].filter((t) => t !== "").join(": ").replace(/\s+/g, " ")]); | |
| 685 | more += j.stepsTotal - j.steps.length; | |
| 686 | } | |
| 687 | return { header: ["Job", "Kind", "Value"], rows, more, delimiter: ",", columns: 3 }; | |
| 688 | } | |
| 689 | ||
| 690 | /** A `.sql` file by name. */ | |
| 691 | function isSqlPath(path: string): boolean { | |
| 692 | return kindByName(path) === "sql"; | |
| 693 | } | |
| 694 | ||
| 695 | /** | |
| 696 | * A SQL file as a table: a row per column of each CREATE TABLE, one row per other statement; the | |
| 697 | * reason when it is not drawn. Shares the web's parser. | |
| 698 | */ | |
| 699 | function sqlTable(source: string): Table | string { | |
| 700 | const doc = parseSql(source); | |
| 701 | if (doc === null) return "not drawn as a schema: this file holds no SQL statements to draw"; | |
| 702 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 703 | const rows = doc.statements.flatMap((s) => | |
| 704 | s.kind === "other" | |
| 705 | ? [["-", s.line, "-", "-", "-", "-"]] | |
| 706 | : s.columns.map((c) => [s.name, c.name, dash(c.type), c.notNull ? "NOT NULL" : "-", c.primaryKey ? "PRIMARY KEY" : "-", dash(c.default)]), | |
| 707 | ); | |
| 708 | return { header: ["Table", "Column", "Type", "Null", "Key", "Default"], rows, more: doc.total - doc.statements.length, delimiter: ",", columns: 6 }; | |
| 709 | } | |
| 710 | ||
| 711 | /** A `.graphql` or `.gql` file by name. */ | |
| 712 | function isGraphqlPath(path: string): boolean { | |
| 713 | return kindByName(path) === "graphql"; | |
| 714 | } | |
| 715 | ||
| 716 | /** | |
| 717 | * A GraphQL schema as a table: a row per field or enum value of each block (roots first), one row | |
| 718 | * per other definition; the reason when it is not drawn. Shares the web's parser. | |
| 719 | */ | |
| 720 | function graphqlTable(source: string): Table | string { | |
| 721 | const doc = parseGraphql(source); | |
| 722 | if (doc === null) return "not drawn as a schema: this file holds no type, input, interface or enum to draw"; | |
| 723 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 724 | const rows = doc.blocks.flatMap((b) => | |
| 725 | b.kind === "other" | |
| 726 | ? [["-", b.text, "-", "-", "-"]] | |
| 727 | : [ | |
| 728 | ...(b.header === "" ? [] : [[`${b.extend ? "extend " : ""}${b.kind} ${b.name}`, "-", "-", "-", b.header]]), | |
| 729 | ...b.fields.map((f) => [`${b.extend ? "extend " : ""}${b.kind} ${b.name}`, f.name, dash(f.args), dash(f.type), dash(f.note)]), | |
| 730 | ...(b.fields.length === 0 && b.header === "" ? [[`${b.kind} ${b.name}`, "-", "-", "-", "-"]] : []), | |
| 731 | ], | |
| 732 | ); | |
| 733 | return { header: ["Block", "Field", "Arguments", "Type", "Directives"], rows, more: doc.total - doc.blocks.length, delimiter: ",", columns: 5 }; | |
| 734 | } | |
| 735 | ||
| 736 | /** | |
| 737 | * A mailbox as a table: a row per message (first 200), the rest counted. Shares the web's parser. | |
| 738 | */ | |
| 739 | function mboxTable(source: string): Table | string { | |
| 740 | const doc = parseMbox(source); | |
| 741 | if (doc === null) return "not drawn as a mailbox: this file does not start with a `From ` line"; | |
| 742 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 743 | const rows = doc.messages.map((m) => [dash(m.from), dash(m.subject), dash(m.date)]); | |
| 744 | return { header: ["From", "Subject", "Date"], rows, more: doc.total - doc.messages.length, delimiter: ",", columns: 3 }; | |
| 745 | } | |
| 746 | ||
| 747 | /** A .proto file as a table: a row per field, enum value or rpc. Shares the web's parser. */ | |
| 748 | function protoTable(source: string): Table | string { | |
| 749 | const doc = parseProto(source); | |
| 750 | if (doc === null) return "not drawn as an outline: this file holds no message, enum or service"; | |
| 751 | const rows = doc.blocks.flatMap((b) => { | |
| 752 | const at = `${b.kind} ${b.name}`; | |
| 753 | if (b.rows.length === 0) return [[at, "-", "-", "-"]]; | |
| 754 | return b.rows.map((r) => | |
| 755 | b.kind === "message" | |
| 756 | ? [at, r.name, `${r.a === "" ? "" : `${r.a} `}${r.b}`, r.c] | |
| 757 | : b.kind === "enum" | |
| 758 | ? [at, r.name, "-", r.b] | |
| 759 | : [at, r.name, `${r.a} -> ${r.b}`, "-"], | |
| 760 | ); | |
| 761 | }); | |
| 762 | return { header: ["Block", "Name", "Type", "Number"], rows, more: doc.total - doc.blocks.length, delimiter: ",", columns: 4 }; | |
| 763 | } | |
| 764 | ||
| 765 | /** Settings as a table: a row per key, its section beside it. Shares the web's parser. */ | |
| 766 | function iniTable(path: string, source: Uint8Array): Table | string { | |
| 767 | if (source.length > RENDER_CAP.ini) return "not drawn as settings: it is over 1 MB"; | |
| 768 | const doc = parseIni(new TextDecoder().decode(source), /\.properties$/i.test(path)); | |
| 769 | if (doc === null) return "not drawn as settings: this file holds no setting"; | |
| 770 | const rows = doc.sections.flatMap((sec) => sec.rows.map((r) => [sec.name === "" ? "-" : sec.name, r.key, r.value])); | |
| 771 | return { header: ["Section", "Key", "Value"], rows, more: doc.total - rows.length, delimiter: ",", columns: 3 }; | |
| 772 | } | |
| 773 | ||
| 774 | /** A rich text file as a table of its paragraphs. Shares the web's parser. */ | |
| 775 | function rtfTable(source: Uint8Array): Table | string { | |
| 776 | if (source.length > RENDER_CAP.rtf) return "not drawn as text: it is over 5 MB"; | |
| 777 | const doc = parseRtf(new TextDecoder("latin1").decode(source)); | |
| 778 | if (doc === null) return "not drawn as rich text: this file does not start with `{\\rtf`"; | |
| 779 | const rows = doc.paragraphs.filter((p) => p.trim() !== "").map((p) => [p]); | |
| 780 | if (rows.length === 0) return "this document holds no text"; | |
| 781 | return { header: ["Text"], rows, more: doc.truncated ? 1 : 0, delimiter: ",", columns: 1 }; | |
| 782 | } | |
| 783 | ||
| 784 | /** | |
| 785 | * An XML file as a table: a row per element in document order, indented by depth. Shares the web's | |
| 786 | * parser. | |
| 787 | */ | |
| 788 | function xmlTable(source: Uint8Array): Table | string { | |
| 789 | if (source.length > RENDER_CAP.xml) return "not drawn as a tree: it is over 5 MB"; | |
| 790 | const doc = parseXml(new TextDecoder().decode(source)); | |
| 791 | if (doc === null) return "not drawn as a tree: this file holds no XML element"; | |
| 792 | const rows: string[][] = []; | |
| 793 | const walk = (n: XmlNode, depth: number): void => { | |
| 794 | rows.push([`${" ".repeat(depth)}${n.name}`, n.attrs.map(([k, v]) => `${k}="${v}"`).join(" "), n.text]); | |
| 795 | for (const c of n.children) walk(c, depth + 1); | |
| 796 | }; | |
| 797 | walk(doc.root, 0); | |
| 798 | return { header: ["Element", "Attributes", "Text"], rows, more: doc.total - rows.length, delimiter: ",", columns: 3 }; | |
| 799 | } | |
| 800 | ||
| 801 | /** A JUnit report, by the web's own rule (file name, or root element). */ | |
| 802 | function isJunitPath(path: string, source: Uint8Array): boolean { | |
| 803 | return /\.xml$/i.test(path) && fileKind(path, source.subarray(0, 4096)) === "junit"; | |
| 804 | } | |
| 805 | ||
| 806 | /** | |
| 807 | * A JUnit report as a table: a totals row, then each failing case with its message; the reason when | |
| 808 | * it is not drawn. Shares the web's parser. | |
| 809 | */ | |
| 810 | function junitTable(source: string): Table | string { | |
| 811 | const parsed = parseJunit(source); | |
| 812 | if ("error" in parsed) return `not drawn as test results: ${parsed.error}`; | |
| 813 | const t = parsed.totals; | |
| 814 | const bad = parsed.suites.flatMap((s) => | |
| 815 | s.cases.filter((c) => c.status === "failed" || c.status === "error").map((c) => [c.status === "error" ? "error" : "failed", (c.classname === "" ? c.name : `${c.classname} › ${c.name}`) || "(unnamed)", c.message.replace(/\s+/g, " ")]), | |
| 816 | ); | |
| 817 | const rows = [["total", `${t.tests} tests`, `${t.failures + t.errors} of ${t.tests} tests fail · ${t.skipped} skipped`], ...bad.slice(0, CASE_CAP)]; | |
| 818 | return { header: ["Result", "Case", "Message"], rows, more: bad.length - Math.min(bad.length, CASE_CAP), delimiter: ",", columns: 3 }; | |
| 819 | } | |
| 820 | ||
| 821 | /** | |
| 822 | * An OPML or RSS/Atom/RDF file, by the web's own rule (extension, or the root element of `.xml`). | |
| 823 | */ | |
| 824 | function isFeedPath(path: string, source: Uint8Array): boolean { | |
| 825 | const k = fileKind(path, source.subarray(0, 4096)); | |
| 826 | return k === "opml" || k === "feed"; | |
| 827 | } | |
| 828 | ||
| 829 | /** | |
| 830 | * A subscription list or feed as a table of title, date and link; the reason when it is not drawn. | |
| 831 | * Shares the web's reader. | |
| 832 | */ | |
| 833 | function feedTable(source: string): Table | string { | |
| 834 | const doc = parseEntries(source); | |
| 835 | if ("error" in doc) return `not drawn as a list of entries: ${doc.error}`; | |
| 836 | const rows = doc.entries.map((e) => [nest(e.depth) + (e.title || "(untitled)"), e.date, e.link]); | |
| 837 | return { header: ["Title", "Date", "Link"], rows, more: doc.total - doc.entries.length, delimiter: ",", columns: 3 }; | |
| 838 | } | |
| 839 | ||
| 840 | /** | |
| 841 | * `.gcode`: a sliced print, drawn as a table of its facts (layers, box, filament, time). Shares the | |
| 842 | * web's parser. | |
| 843 | */ | |
| 844 | function isGcodePath(path: string): boolean { | |
| 845 | return /\.(gcode|gco)$/i.test(path); | |
| 846 | } | |
| 847 | ||
| 848 | function gcodeTable(source: string): Table | null { | |
| 849 | const parsed = parseGcode(source); | |
| 850 | if (parsed === undefined) return null; | |
| 851 | return { header: ["Fact", "Value"], rows: gcodeFacts(parsed).map(([k, v]) => [k, v]), more: 0, delimiter: ",", columns: 2 }; | |
| 852 | } | |
| 853 | ||
| 854 | /** | |
| 855 | * `.step` / `.stp`: a CAD part, drawn as a table of its header facts, entity types and products. | |
| 856 | * Shares the web's reader. | |
| 857 | */ | |
| 858 | function isStepPath(path: string): boolean { | |
| 859 | return /\.(step|stp)$/i.test(path); | |
| 860 | } | |
| 861 | ||
| 862 | function stepTable(source: string): Table | string { | |
| 863 | const card = readStep(source); | |
| 864 | if ("error" in card) return `not drawn as a part card: ${card.error}`; | |
| 865 | const rows: string[][] = [ | |
| 866 | ...stepFacts(card).map(([k, v]) => [k, v]), | |
| 867 | ...card.types.map(([t, c]) => ["Type " + t, c.toLocaleString("en")]), | |
| 868 | ...card.products.map((p, i) => ["Product " + String(i + 1), p]), | |
| 869 | ]; | |
| 870 | return { header: ["Fact", "Value"], rows, more: card.moreProducts, delimiter: ",", columns: 2 }; | |
| 871 | } | |
| 872 | ||
| 873 | /** | |
| 874 | * `.ifc`: a building model, drawn as its header facts, spatial tree and element counts. Shares the | |
| 875 | * reader. | |
| 876 | */ | |
| 877 | function isIfcPath(path: string): boolean { | |
| 878 | return /\.ifc$/i.test(path); | |
| 879 | } | |
| 880 | ||
| 881 | function ifcTable(source: Uint8Array): Table | string { | |
| 882 | if (source.length > RENDER_CAP.ifc) return "not drawn as a building model: it is too large to summarise"; | |
| 883 | const m = readIfc(new TextDecoder().decode(source)); | |
| 884 | if ("error" in m) return `not drawn as a building model: ${m.error}`; | |
| 885 | const rows: string[][] = [ | |
| 886 | ...ifcFacts(m).map(([k, v]) => [k, v]), | |
| 887 | ...ifcTreeRows(m).map(([d, level, name]) => [`${" ".repeat(d)}${level}`, name === "" ? "no name" : name]), | |
| 888 | ...m.elements.map(([t, c]) => [typeWords(t), c.toLocaleString("en")]), | |
| 889 | ]; | |
| 890 | return { header: ["Fact", "Value"], rows, more: m.treeMore, delimiter: ",", columns: 2 }; | |
| 891 | } | |
| 892 | ||
| 893 | /** `.geojson`: features, drawn as a table of their geometry type and properties. */ | |
| 894 | function isGeoJsonPath(path: string): boolean { | |
| 895 | return /\.geojson$/i.test(path); | |
| 896 | } | |
| 897 | ||
| 898 | /** The properties table of a GeoJSON file; null when it is not GeoJSON. Shares the web's parser. */ | |
| 899 | function geoJsonTable(source: string): Table | null { | |
| 900 | const parsed = parseGeoJson(source); | |
| 901 | if (parsed === undefined) return null; | |
| 902 | const { header, rows } = propertyRows(parsed.features); | |
| 903 | return { header, rows, more: Math.max(0, parsed.features.length - rows.length), delimiter: ",", columns: header.length }; | |
| 904 | } | |
| 905 | ||
| 906 | /** `README.md`, `NOTES.markdown`, `readme` — the prose a repo opens on. */ | |
| 907 | function isMarkdownPath(path: string): boolean { | |
| 908 | const name = path.slice(path.lastIndexOf("/") + 1); | |
| 909 | return fileKind(name, NO_BYTES) === "markdown" || /^readme(\.|$)/i.test(name); | |
| 910 | } | |
| 911 | ||
| 912 | /** `.patch` and `.diff`: a file the pull page's diff draws. */ | |
| 913 | function isPatchPath(path: string): boolean { | |
| 914 | return fileKind(path.slice(path.lastIndexOf("/") + 1), NO_BYTES) === "patch"; | |
| 915 | } | |
| 916 | ||
| 917 | class Tab { | |
| 918 | loading = true; | |
| 919 | /** Non-empty when there is a reason the bytes are not on screen. */ | |
| 920 | note = ""; | |
| 921 | noteTitle = "Not shown"; | |
| 922 | noteDetail = ""; | |
| 923 | /** The one line saying why this file is plain source; empty for ordinary text. */ | |
| 924 | why = ""; | |
| 925 | /** | |
| 926 | * Non-empty when `raw` is only the start of a larger file: the sentence that says so. It is never | |
| 927 | * edited. | |
| 928 | */ | |
| 929 | cut = ""; | |
| 930 | raw: Uint8Array | null = null; | |
| 931 | plain: string[] = []; | |
| 932 | lines: Span[][] = []; | |
| 933 | readonly scroll = new Scroll(); | |
| 934 | readonly search = new Filter(); | |
| 935 | hits: number[] = []; | |
| 936 | hit = 0; | |
| 937 | /** Horizontal scroll, in display columns, for the view mode. */ | |
| 938 | left = 0; | |
| 939 | editor: Editor | null = null; | |
| 940 | mode: TabMode = "view"; | |
| 941 | /** A file that does not exist at this ref yet. */ | |
| 942 | creating = false; | |
| 943 | /** The blob the buffer was read from (`null`: none), or undefined where nothing is compared. */ | |
| 944 | opened: string | null | undefined = undefined; | |
| 945 | find: FindMode = "off"; | |
| 946 | needle = ""; | |
| 947 | replacement = ""; | |
| 948 | replaceField: "find" | "with" = "find"; | |
| 949 | hint = ""; | |
| 950 | /** | |
| 951 | * A picture, when git handed us one. `looksLikeImage` is only an extension | |
| 952 | * filter, so this stays null for a `.png` that turned out to be text — the | |
| 953 | * bytes decide, never the name. | |
| 954 | */ | |
| 955 | image: TerminalImage | null = null; | |
| 956 | /** `v`: the picture, or the facts about it. */ | |
| 957 | showImage = true; | |
| 958 | /** | |
| 959 | * `v` on prose: the rendered document, or the source that made it. Prose | |
| 960 | * opens rendered because that is what a README is *for*; the source is one | |
| 961 | * keypress away and is what `e` always edits. | |
| 962 | */ | |
| 963 | rendered = true; | |
| 964 | /** The rendered document, and the width it was wrapped for. */ | |
| 965 | doc: Line[] = []; | |
| 966 | docPlain: string[] = []; | |
| 967 | /** The parsed diff of a patch file; null when the text is not a git diff. */ | |
| 968 | patch: Diff | null = null; | |
| 969 | docWidth = 0; | |
| 970 | /** `s` on a CSV/TSV: the aligned table, or the source behind it. */ | |
| 971 | asTable = true; | |
| 972 | /** The parsed file, when its name says table. Parse errors ride along. */ | |
| 973 | table: Table | null = null; | |
| 974 | grid: Grid = { header: "", rows: [] }; | |
| 975 | /** `o` on a CSV/TSV: the column its rows are ordered by, or null for file order. */ | |
| 976 | order: { column: number; descending: boolean } | null = null; | |
| 977 | /** An .xlsx's first sheet: the bytes are not text, so the table is all there is. */ | |
| 978 | sheet: Table | null = null; | |
| 979 | /** A SQLite file's bytes, kept so `>`/`<` and `}`/`{` can page it; null for any other file. */ | |
| 980 | db: Uint8Array | null = null; | |
| 981 | dbAt: SqliteAt = { table: 0, page: 1 }; | |
| 982 | /** | |
| 983 | * A big JSON file's prefix and size, kept so `m` can open one of its keys by byte range; null for | |
| 984 | * any other file. | |
| 985 | */ | |
| 986 | big: { readonly prefix: Uint8Array; readonly size: number } | null = null; | |
| 987 | /** Cues of a subtitle file that could not be read. */ | |
| 988 | unread = 0; | |
| 989 | /** Why a file whose name promises a view is shown as source instead; "" when nothing failed. */ | |
| 990 | fault = ""; | |
| 991 | /** The .ipynb / .log view, and the source it replaces while `s` has it up. */ | |
| 992 | kindLines: KindLines | null = null; | |
| 993 | sourceLines: KindLines | null = null; | |
| 994 | ||
| 995 | constructor(readonly path: string) {} | |
| 996 | ||
| 997 | get name(): string { | |
| 998 | return this.path.slice(this.path.lastIndexOf("/") + 1); | |
| 999 | } | |
| 1000 | ||
| 1001 | get kind(): TabKind { | |
| 1002 | if (this.image !== null) return "image"; | |
| 1003 | if (isPatchPath(this.path)) return "patch"; | |
| 1004 | return isMarkdownPath(this.path) ? "markdown" : "code"; | |
| 1005 | } | |
| 1006 | ||
| 1007 | /** True when the pane is showing prose rather than the bytes behind it. */ | |
| 1008 | get reading(): boolean { | |
| 1009 | if (!this.rendered || this.mode !== "view") return false; | |
| 1010 | return this.kind === "markdown" || (this.kind === "patch" && this.patch !== null); | |
| 1011 | } | |
| 1012 | ||
| 1013 | /** | |
| 1014 | * The table with its rows in `order`, and an arrow on that column's header; the table itself when | |
| 1015 | * unordered. | |
| 1016 | */ | |
| 1017 | ordered(table: Table): Table { | |
| 1018 | const o = this.order; | |
| 1019 | if (o === null || table.error !== undefined) return table; | |
| 1020 | const numeric = isNumericColumn(table.rows, o.column); | |
| 1021 | const header = table.header.map((h, i) => (i === o.column ? `${h} ${o.descending ? "▼" : "▲"}` : h)); | |
| 1022 | return { ...table, header, rows: sortRows(table.rows, o.column, numeric, o.descending) }; | |
| 1023 | } | |
| 1024 | ||
| 1025 | /** `o`: file order, then each column ascending and descending in turn, then file order again. */ | |
| 1026 | cycleOrder(): string { | |
| 1027 | const t = this.table; | |
| 1028 | if (t === null || t.error !== undefined || !isTablePath(this.path) || t.header.length === 0) return ""; | |
| 1029 | const o = this.order; | |
| 1030 | if (o === null) this.order = { column: 0, descending: false }; | |
| 1031 | else if (!o.descending) this.order = { column: o.column, descending: true }; | |
| 1032 | else this.order = o.column + 1 < t.header.length ? { column: o.column + 1, descending: false } : null; | |
| 1033 | this.grid = layoutTable(this.ordered(t)); | |
| 1034 | const now = this.order; | |
| 1035 | return now === null ? "in file order" : `by ${t.header[now.column]} ${now.descending ? "descending" : "ascending"}`; | |
| 1036 | } | |
| 1037 | ||
| 1038 | /** True when the pane is showing a CSV/TSV as columns. */ | |
| 1039 | get tabular(): boolean { | |
| 1040 | return ( | |
| 1041 | this.table !== null && | |
| 1042 | this.table.error === undefined && | |
| 1043 | this.table.header.length > 0 && | |
| 1044 | this.asTable && | |
| 1045 | this.mode === "view" | |
| 1046 | ); | |
| 1047 | } | |
| 1048 | ||
| 1049 | /** The lines `/` searches and `j` scrolls: whichever view is up. */ | |
| 1050 | get body(): string[] { | |
| 1051 | if (this.reading) return this.docPlain; | |
| 1052 | return this.tabular ? this.grid.rows : this.plain; | |
| 1053 | } | |
| 1054 | ||
| 1055 | /** Wrap the markdown for this width, and only when the width moved. */ | |
| 1056 | document(width: number, c: Tokens): void { | |
| 1057 | if (this.docWidth === width && this.doc.length > 0) return; | |
| 1058 | this.docWidth = width; | |
| 1059 | this.doc = | |
| 1060 | this.patch !== null | |
| 1061 | ? renderPatch(this.patch, Math.max(8, width), c) | |
| 1062 | : renderMarkdown(this.plain.join("\n"), Math.max(8, width), c); | |
| 1063 | this.docPlain = this.doc.map((line) => | |
| 1064 | line.map((span) => span.text).join(""), | |
| 1065 | ); | |
| 1066 | } | |
| 1067 | ||
| 1068 | /** Put up the notebook/log view or its source, whichever `asTable` says. */ | |
| 1069 | showKind(): void { | |
| 1070 | if (this.kindLines === null || this.sourceLines === null) return; | |
| 1071 | const shown = this.asTable ? this.kindLines : this.sourceLines; | |
| 1072 | this.plain = shown.plain; | |
| 1073 | this.lines = shown.lines; | |
| 1074 | } | |
| 1075 | ||
| 1076 | get modified(): boolean { | |
| 1077 | return this.creating || (this.editor !== null && this.editor.modified); | |
| 1078 | } | |
| 1079 | ||
| 1080 | /** Text the file would be committed with: the buffer if there is one. */ | |
| 1081 | bytes(): Uint8Array { | |
| 1082 | return this.editor?.toBytes() ?? this.raw ?? new Uint8Array(0); | |
| 1083 | } | |
| 1084 | ||
| 1085 | /** Make the buffer, once, from whatever git handed us. */ | |
| 1086 | buffer(): Editor | null { | |
| 1087 | if (this.editor !== null) return this.editor; | |
| 1088 | if (this.raw === null) return null; | |
| 1089 | this.editor = new Editor(this.raw, this.path); | |
| 1090 | return this.editor; | |
| 1091 | } | |
| 1092 | ||
| 1093 | /** Re-derive the read view from the buffer, so `esc` keeps the edits. */ | |
| 1094 | rebuild(c: Tokens): void { | |
| 1095 | const source = | |
| 1096 | this.editor === null | |
| 1097 | ? this.raw | |
| 1098 | : new TextEncoder().encode( | |
| 1099 | this.editor.lines.join("\n") + | |
| 1100 | (this.editor.finalNewline ? "\n" : ""), | |
| 1101 | ); | |
| 1102 | if (source === null) { | |
| 1103 | this.plain = []; | |
| 1104 | this.lines = []; | |
| 1105 | this.table = this.sheet; | |
| 1106 | if (this.sheet !== null) this.grid = layoutTable(this.sheet); | |
| 1107 | return; | |
| 1108 | } | |
| 1109 | const text = new TextDecoder().decode(source); | |
| 1110 | const built = buildLines(text, this.path, c); | |
| 1111 | if (isPatchPath(this.path)) { | |
| 1112 | const parsed = parseUnifiedDiff(text); | |
| 1113 | this.patch = parsed.files.length > 0 ? parsed : null; | |
| 1114 | } else this.patch = null; | |
| 1115 | this.plain = built.plain; | |
| 1116 | this.lines = built.lines; | |
| 1117 | this.unread = 0; | |
| 1118 | this.fault = ""; | |
| 1119 | this.kindLines = null; | |
| 1120 | this.sourceLines = built; | |
| 1121 | const kind = kindView(this.path, text, c); | |
| 1122 | if (kind?.table !== undefined) { | |
| 1123 | this.table = kind.table; | |
| 1124 | this.grid = layoutTable(kind.table); | |
| 1125 | } else if (kind !== null) { | |
| 1126 | this.kindLines = kind; | |
| 1127 | if (this.asTable && this.mode === "view") { | |
| 1128 | this.plain = kind.plain; | |
| 1129 | this.lines = kind.lines; | |
| 1130 | } | |
| 1131 | } | |
| 1132 | const api = isOpenApiPath(this.path) ? openapiTable(text, this.path) : null; | |
| 1133 | if (isSubtitlePath(this.path)) { | |
| 1134 | const subs = subtitleTable(new TextDecoder().decode(source)); | |
| 1135 | this.table = subs.table; | |
| 1136 | this.unread = subs.unread; | |
| 1137 | this.grid = layoutTable(this.table); | |
| 1138 | } else if (isIcsPath(this.path)) { | |
| 1139 | const cal = icsTable(new TextDecoder().decode(source)); | |
| 1140 | this.table = cal === null ? null : cal.table; | |
| 1141 | this.unread = cal === null ? 0 : cal.unread; | |
| 1142 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1143 | } else if (isVcfPath(this.path)) { | |
| 1144 | this.table = vcfTable(new TextDecoder().decode(source)); | |
| 1145 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1146 | } else if (isEnvExample(this.path)) { | |
| 1147 | this.table = envTable(new TextDecoder().decode(source)); | |
| 1148 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1149 | } else if (kindByName(this.path) === "package") { | |
| 1150 | this.table = packageTable(new TextDecoder().decode(source)); | |
| 1151 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1152 | } else if (isEmlPath(this.path)) { | |
| 1153 | this.table = emlTable(source); | |
| 1154 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1155 | } else if (isGpxPath(this.path)) { | |
| 1156 | this.table = gpxTable(new TextDecoder().decode(source), this.path); | |
| 1157 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1158 | } else if (isHarPath(this.path)) { | |
| 1159 | this.table = harTable(new TextDecoder().decode(source)); | |
| 1160 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1161 | } else if (isTimelinePath(this.path)) { | |
| 1162 | const cuts = timelineTable(source, this.path); | |
| 1163 | this.table = typeof cuts === "string" ? null : cuts; | |
| 1164 | this.fault = typeof cuts === "string" ? cuts : ""; | |
| 1165 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1166 | } else if (isSarifPath(this.path)) { | |
| 1167 | const findings = sarifTable(new TextDecoder().decode(source)); | |
| 1168 | this.table = typeof findings === "string" ? null : findings; | |
| 1169 | this.fault = typeof findings === "string" ? findings : ""; | |
| 1170 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1171 | } else if (isLcovPath(this.path)) { | |
| 1172 | const coverage = lcovTable(new TextDecoder().decode(source)); | |
| 1173 | this.table = typeof coverage === "string" ? null : coverage; | |
| 1174 | this.fault = typeof coverage === "string" ? coverage : ""; | |
| 1175 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1176 | } else if (api !== null) { | |
| 1177 | this.table = typeof api === "string" ? null : api; | |
| 1178 | this.fault = typeof api === "string" ? api : ""; | |
| 1179 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1180 | } else if (isDockerfilePath(this.path)) { | |
| 1181 | const build = dockerfileTable(new TextDecoder().decode(source)); | |
| 1182 | this.table = typeof build === "string" ? null : build; | |
| 1183 | this.fault = typeof build === "string" ? build : ""; | |
| 1184 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1185 | } else if (isWorkflowPath(this.path)) { | |
| 1186 | const flow = workflowTable(new TextDecoder().decode(source)); | |
| 1187 | this.table = typeof flow === "string" ? null : flow; | |
| 1188 | this.fault = typeof flow === "string" ? flow : ""; | |
| 1189 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1190 | } else if (isSqlPath(this.path)) { | |
| 1191 | const schema = sqlTable(new TextDecoder().decode(source)); | |
| 1192 | this.table = typeof schema === "string" ? null : schema; | |
| 1193 | this.fault = typeof schema === "string" ? schema : ""; | |
| 1194 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1195 | } else if (isGraphqlPath(this.path)) { | |
| 1196 | const schema = graphqlTable(new TextDecoder().decode(source)); | |
| 1197 | this.table = typeof schema === "string" ? null : schema; | |
| 1198 | this.fault = typeof schema === "string" ? schema : ""; | |
| 1199 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1200 | } else if (kindByName(this.path) === "mbox") { | |
| 1201 | const mail = mboxTable(new TextDecoder().decode(source)); | |
| 1202 | this.table = typeof mail === "string" ? null : mail; | |
| 1203 | this.fault = typeof mail === "string" ? mail : ""; | |
| 1204 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1205 | } else if (kindByName(this.path) === "proto") { | |
| 1206 | const outline = protoTable(new TextDecoder().decode(source)); | |
| 1207 | this.table = typeof outline === "string" ? null : outline; | |
| 1208 | this.fault = typeof outline === "string" ? outline : ""; | |
| 1209 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1210 | } else if (isJunitPath(this.path, source)) { | |
| 1211 | const results = junitTable(new TextDecoder().decode(source)); | |
| 1212 | this.table = typeof results === "string" ? null : results; | |
| 1213 | this.fault = typeof results === "string" ? results : ""; | |
| 1214 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1215 | } else if (isFeedPath(this.path, source)) { | |
| 1216 | const feed = feedTable(new TextDecoder().decode(source)); | |
| 1217 | this.table = typeof feed === "string" ? null : feed; | |
| 1218 | this.fault = typeof feed === "string" ? feed : ""; | |
| 1219 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1220 | } else if (["ini", "rtf", "xml"].includes(fileKind(this.path, source.subarray(0, 4096)))) { | |
| 1221 | const kind = fileKind(this.path, source.subarray(0, 4096)); | |
| 1222 | const made = kind === "ini" ? iniTable(this.path, source) : kind === "rtf" ? rtfTable(source) : xmlTable(source); | |
| 1223 | this.table = typeof made === "string" ? null : made; | |
| 1224 | this.fault = typeof made === "string" ? made : ""; | |
| 1225 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1226 | } else if (fileKind(this.path, source.subarray(0, 4096)) === "pcd") { | |
| 1227 | const cloud = pcdFacts(source); | |
| 1228 | this.table = typeof cloud === "string" ? null : { header: ["Fact", "Value"], rows: cloud, more: 0, delimiter: ",", columns: 2 }; | |
| 1229 | this.fault = typeof cloud === "string" ? cloud : ""; | |
| 1230 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1231 | } else if (isGcodePath(this.path)) { | |
| 1232 | this.table = gcodeTable(new TextDecoder().decode(source)); | |
| 1233 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1234 | } else if (isStepPath(this.path)) { | |
| 1235 | const part = stepTable(new TextDecoder().decode(source)); | |
| 1236 | this.table = typeof part === "string" ? null : part; | |
| 1237 | this.fault = typeof part === "string" ? part : ""; | |
| 1238 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1239 | } else if (isIfcPath(this.path)) { | |
| 1240 | const model = ifcTable(source); | |
| 1241 | this.table = typeof model === "string" ? null : model; | |
| 1242 | this.fault = typeof model === "string" ? model : ""; | |
| 1243 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1244 | } else if (isGeoJsonPath(this.path)) { | |
| 1245 | this.table = geoJsonTable(new TextDecoder().decode(source)); | |
| 1246 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1247 | } else if (isKmlPath(this.path)) { | |
| 1248 | this.table = kmlTable(new TextDecoder().decode(source)); | |
| 1249 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 1250 | } else if (isTablePath(this.path)) { | |
| 1251 | // The decoded source, not `plain`: `expandTabs` has eaten every tab there. | |
| 1252 | const delimiter = /\.tsv$/i.test(this.path) ? "\t" : undefined; | |
| 1253 | this.table = parseCsv(new TextDecoder().decode(source), { delimiter }); | |
| 1254 | // A re-read keeps the order only while its column is still in the header. | |
| 1255 | if (this.order !== null && this.order.column >= this.table.header.length) this.order = null; | |
| 1256 | this.grid = layoutTable(this.ordered(this.table)); | |
| 1257 | } else if (kind?.table === undefined) this.table = null; | |
| 1258 | // The rendered document is derived from the same text, so an edit, a | |
| 1259 | // theme switch or a re-read has to throw it away with everything else. | |
| 1260 | this.doc = []; | |
| 1261 | this.docPlain = []; | |
| 1262 | this.docWidth = 0; | |
| 1263 | if (this.search.query !== "") this.findHits(); | |
| 1264 | else this.hits = []; | |
| 1265 | } | |
| 1266 | ||
| 1267 | findHits(): void { | |
| 1268 | const q = this.search.query.toLowerCase(); | |
| 1269 | const lines = this.body; | |
| 1270 | this.hits = | |
| 1271 | q === "" | |
| 1272 | ? [] | |
| 1273 | : lines.flatMap((l, i) => (l.toLowerCase().includes(q) ? [i] : [])); | |
| 1274 | this.hit = 0; | |
| 1275 | if (this.hits[0] !== undefined) this.scroll.to(this.hits[0], lines.length); | |
| 1276 | } | |
| 1277 | ||
| 1278 | step(delta: number): boolean { | |
| 1279 | if (this.hits.length === 0) return false; | |
| 1280 | this.hit = (this.hit + delta + this.hits.length) % this.hits.length; | |
| 1281 | this.scroll.to(this.hits[this.hit]!, this.body.length); | |
| 1282 | return true; | |
| 1283 | } | |
| 1284 | } | |
| 1285 | ||
| 1286 | /** One blob, as the workspace keeps it: text, a picture, or a reason. */ | |
| 1287 | interface CacheEntry { | |
| 1288 | readonly note: string; | |
| 1289 | /** The note's heading; "Not shown" unless the file is something we name. */ | |
| 1290 | readonly noteTitle: string; | |
| 1291 | /** A last line under the note: where to get the file. */ | |
| 1292 | readonly noteDetail: string; | |
| 1293 | readonly cut?: string; | |
| 1294 | /** Why the file is plain source though its name says otherwise; stands above the text. */ | |
| 1295 | readonly why?: string; | |
| 1296 | readonly raw: Uint8Array | null; | |
| 1297 | readonly picture: Uint8Array | null; | |
| 1298 | readonly sheet: Table | null; | |
| 1299 | readonly db: Uint8Array | null; | |
| 1300 | readonly big?: { readonly prefix: Uint8Array; readonly size: number }; | |
| 1301 | /** | |
| 1302 | * The blob read (`null`: none there), sent back as `EditFile.was` so a save over a newer change | |
| 1303 | * refuses. | |
| 1304 | */ | |
| 1305 | readonly opened?: string | null; | |
| 1306 | } | |
| 1307 | 239 | |
| 1308 | 240 | // ---- what a workspace remembers between visits ---- |
| 1309 | 241 | |
| @@ -3704,371 +2636,6 @@ function findKey(t: Tab, e: KeyEvent): boolean { | ||
| 3704 | 2636 | return true; |
| 3705 | 2637 | } |
| 3706 | 2638 | |
| 3707 | // ---- drawing ---- | |
| 3708 | ||
| 3709 | /** `main ▾`, right-aligned on the where-strip's row. */ | |
| 3710 | function drawRefPill( | |
| 3711 | s: Surface, | |
| 3712 | r: Rect, | |
| 3713 | c: Tokens, | |
| 3714 | ref: string, | |
| 3715 | strip: readonly Span[], | |
| 3716 | ): void { | |
| 3717 | if (r.w <= 0 || r.h <= 0) return; | |
| 3718 | const label = `${truncate(ref === "" ? "…" : ref, 24)} ${G.caretDown}`; | |
| 3719 | const used = strip.reduce((sum, span) => sum + displayWidth(span.text), 0); | |
| 3720 | const x = r.x + r.w - displayWidth(label) - 1; | |
| 3721 | // Never draw over the strip: it says where the bytes came from, which is | |
| 3722 | // the more important of the two. | |
| 3723 | if (x <= r.x + used + 2) return; | |
| 3724 | s.text(x, r.y, label, style(c.accent, c.bg, BOLD), r.x + r.w); | |
| 3725 | } | |
| 3726 | ||
| 3727 | /** Where one tab landed: the whole chip, and the `✗` inside it if it has one. */ | |
| 3728 | interface TabHit { | |
| 3729 | readonly index: number; | |
| 3730 | readonly rect: Rect; | |
| 3731 | readonly close?: Rect; | |
| 3732 | } | |
| 3733 | ||
| 3734 | /** | |
| 3735 | * The tab bar. One row: the paths, the active one bold and underlined in the | |
| 3736 | * accent, a dot on anything modified, `¶` on prose being read rather than | |
| 3737 | * edited, and `‹ ›` when there are more than fit. | |
| 3738 | * | |
| 3739 | * The active tab wears a `✗`. Only the active one: a close box on every chip | |
| 3740 | * is a row of targets you can hit by accident, and the tab you mean to close | |
| 3741 | * is almost always the one you are looking at. | |
| 3742 | */ | |
| 3743 | function drawTabBar( | |
| 3744 | s: Surface, | |
| 3745 | r: Rect, | |
| 3746 | c: Tokens, | |
| 3747 | tabs: readonly Tab[], | |
| 3748 | active: number, | |
| 3749 | set: IconSet = "plain", | |
| 3750 | ): TabHit[] { | |
| 3751 | if (r.w <= 0 || r.h <= 0) return []; | |
| 3752 | s.fill(r, " ", style(c.mutedFg, c.bg)); | |
| 3753 | const right = r.x + r.w; | |
| 3754 | if (tabs.length === 0) { | |
| 3755 | s.text(r.x + 1, r.y, "no tabs open", style(c.faint, c.bg), right); | |
| 3756 | return []; | |
| 3757 | } | |
| 3758 | const hits: TabHit[] = []; | |
| 3759 | const count = `${plural(tabs.length, "tab")} `; | |
| 3760 | const room = Math.max(10, r.w - count.length - 2); | |
| 3761 | // The icon is nerd-only: the plain set's generic file mark before every | |
| 3762 | // path says nothing and costs two columns on the one row that has none. | |
| 3763 | const mark = (t: Tab): string => | |
| 3764 | set === "nerd" ? `${fileIcon(t.path, set)} ` : ""; | |
| 3765 | const label = (t: Tab): string => | |
| 3766 | ` ${mark(t)}${truncate(t.path, 30)}${t.modified ? " ●" : ""}${ | |
| 3767 | t.reading ? ` ${PROSE_MARK}` : "" | |
| 3768 | } `; | |
| 3769 | const widths = tabs.map( | |
| 3770 | (t, i) => displayWidth(label(t)) + (i === active ? 2 : 0) + 1, | |
| 3771 | ); | |
| 3772 | ||
| 3773 | // A window that contains the active tab and fits: grow left from it, then | |
| 3774 | // right, so the tab you are on is never the one that scrolled off. | |
| 3775 | let first = Math.max(0, Math.min(active, tabs.length - 1)); | |
| 3776 | let last = first; | |
| 3777 | let used = widths[first] ?? 0; | |
| 3778 | for (;;) { | |
| 3779 | const before = first > 0 ? (widths[first - 1] ?? 0) : Infinity; | |
| 3780 | const after = last + 1 < tabs.length ? (widths[last + 1] ?? 0) : Infinity; | |
| 3781 | if (after <= before && used + after <= room) { | |
| 3782 | used += after; | |
| 3783 | last++; | |
| 3784 | } else if (before < Infinity && used + before <= room) { | |
| 3785 | used += before; | |
| 3786 | first--; | |
| 3787 | } else break; | |
| 3788 | } | |
| 3789 | ||
| 3790 | let x = r.x; | |
| 3791 | if (first > 0) | |
| 3792 | x = s.text( | |
| 3793 | x, | |
| 3794 | r.y, | |
| 3795 | `${G.chevron === "›" ? "‹" : "<"}`, | |
| 3796 | style(c.faint, c.bg), | |
| 3797 | right, | |
| 3798 | ); | |
| 3799 | for (let i = first; i <= last; i++) { | |
| 3800 | const t = tabs[i]; | |
| 3801 | if (t === undefined) break; | |
| 3802 | const on = i === active; | |
| 3803 | const from = x; | |
| 3804 | x = s.text( | |
| 3805 | x, | |
| 3806 | r.y, | |
| 3807 | label(t), | |
| 3808 | style( | |
| 3809 | on ? c.accent : t.modified ? c.attn : c.mutedFg, | |
| 3810 | c.bg, | |
| 3811 | on ? BOLD | UNDERLINE : 0, | |
| 3812 | ), | |
| 3813 | right, | |
| 3814 | ); | |
| 3815 | let close: Rect | undefined; | |
| 3816 | if (on) { | |
| 3817 | close = { x, y: r.y, w: 2, h: 1 }; | |
| 3818 | x = s.text(x, r.y, `${G.cross} `, style(c.faint, c.bg), right); | |
| 3819 | } | |
| 3820 | hits.push({ | |
| 3821 | index: i, | |
| 3822 | rect: { x: from, y: r.y, w: x - from, h: 1 }, | |
| 3823 | ...(close === undefined ? {} : { close }), | |
| 3824 | }); | |
| 3825 | x += 1; | |
| 3826 | } | |
| 3827 | if (last < tabs.length - 1) s.text(x, r.y, "›", style(c.faint, c.bg), right); | |
| 3828 | s.text(right - count.length, r.y, count, style(c.faint, c.bg), right); | |
| 3829 | return hits; | |
| 3830 | } | |
| 3831 | ||
| 3832 | interface TreeDrawOpts { | |
| 3833 | readonly focused: boolean; | |
| 3834 | readonly openPaths: ReadonlySet<string>; | |
| 3835 | readonly modified: ReadonlySet<string>; | |
| 3836 | readonly pending: ReadonlySet<string>; | |
| 3837 | readonly currentPath: string; | |
| 3838 | readonly empty: string; | |
| 3839 | readonly icons: IconSet; | |
| 3840 | } | |
| 3841 | ||
| 3842 | /** | |
| 3843 | * The explorer rows. Indentation plus a caret is the whole grammar: `▸`/`▾` | |
| 3844 | * on a directory, a dot on a file with unsaved changes, a struck-through name | |
| 3845 | * on one marked for deletion, and the accent on whatever the file pane holds. | |
| 3846 | */ | |
| 3847 | function drawTree( | |
| 3848 | s: Surface, | |
| 3849 | r: Rect, | |
| 3850 | c: Tokens, | |
| 3851 | state: ListState, | |
| 3852 | nodes: readonly Node[], | |
| 3853 | o: TreeDrawOpts, | |
| 3854 | ): void { | |
| 3855 | if (r.w <= 0 || r.h <= 0) return; | |
| 3856 | if (nodes.length === 0) { | |
| 3857 | s.text( | |
| 3858 | r.x + 2, | |
| 3859 | r.y, | |
| 3860 | truncate(o.empty, Math.max(0, r.w - 2)), | |
| 3861 | style(c.faint, c.bg), | |
| 3862 | r.x + r.w, | |
| 3863 | ); | |
| 3864 | return; | |
| 3865 | } | |
| 3866 | const from = state.window(r.h, nodes.length); | |
| 3867 | const right = r.x + r.w - 1; | |
| 3868 | for (let i = 0; i < r.h; i++) { | |
| 3869 | const node = nodes[from + i]; | |
| 3870 | if (node === undefined) break; | |
| 3871 | const y = r.y + i; | |
| 3872 | const selected = from + i === state.index; | |
| 3873 | const bg = selected && o.focused ? c.muted : c.bg; | |
| 3874 | s.fill({ x: r.x, y, w: r.w - 1, h: 1 }, " ", style(c.fg, bg)); | |
| 3875 | let x = r.x + Math.min(node.depth * 2, Math.max(0, r.w - 8)); | |
| 3876 | const mark = | |
| 3877 | node.type === "tree" | |
| 3878 | ? node.loading | |
| 3879 | ? G.ellipsis | |
| 3880 | : node.expanded | |
| 3881 | ? G.caretDown | |
| 3882 | : G.caretRight | |
| 3883 | : " "; | |
| 3884 | // The caret is the expansion state and stays whatever the set. A Nerd | |
| 3885 | // Font adds the *kind* beside it — the plain set does not, because six | |
| 3886 | // shades of `▭` before six filenames is noise, not information. | |
| 3887 | const glyph = | |
| 3888 | o.icons === "nerd" | |
| 3889 | ? `${mark}${fileIcon(node.path, o.icons, { | |
| 3890 | directory: node.type === "tree", | |
| 3891 | open: node.expanded, | |
| 3892 | })} ` | |
| 3893 | : `${mark} `; | |
| 3894 | x = s.text(x, y, glyph, style(c.mutedFg, bg), right); | |
| 3895 | const doomed = o.pending.has(node.path); | |
| 3896 | const dirty = o.modified.has(node.path); | |
| 3897 | const current = node.type === "blob" && node.path === o.currentPath; | |
| 3898 | const label = node.type === "tree" ? `${node.name}/` : node.name; | |
| 3899 | const meta = doomed | |
| 3900 | ? "delete" | |
| 3901 | : dirty | |
| 3902 | ? "●" | |
| 3903 | : node.type === "blob" | |
| 3904 | ? "" | |
| 3905 | : ""; | |
| 3906 | const metaW = meta === "" ? 0 : meta.length + 1; | |
| 3907 | s.text( | |
| 3908 | x, | |
| 3909 | y, | |
| 3910 | truncate(label, Math.max(0, right - x - metaW)), | |
| 3911 | style( | |
| 3912 | doomed | |
| 3913 | ? c.danger | |
| 3914 | : current | |
| 3915 | ? c.accent | |
| 3916 | : o.openPaths.has(node.path) | |
| 3917 | ? c.fg | |
| 3918 | : node.type === "tree" | |
| 3919 | ? c.fg | |
| 3920 | : c.mutedFg, | |
| 3921 | bg, | |
| 3922 | (current || selected ? BOLD : 0) | (doomed ? STRIKE : 0), | |
| 3923 | ), | |
| 3924 | right - metaW, | |
| 3925 | ); | |
| 3926 | if (meta !== "") | |
| 3927 | s.text( | |
| 3928 | right - meta.length, | |
| 3929 | y, | |
| 3930 | meta, | |
| 3931 | style(doomed ? c.danger : c.attn, bg), | |
| 3932 | right, | |
| 3933 | ); | |
| 3934 | } | |
| 3935 | scrollbar(s, { x: r.x + r.w - 1, y: r.y, w: 1, h: r.h }, c, { | |
| 3936 | total: nodes.length, | |
| 3937 | offset: from, | |
| 3938 | }); | |
| 3939 | } | |
| 3940 | ||
| 3941 | /** The read view: a pinned gutter, syntax colour, and horizontal scrolling. */ | |
| 3942 | function drawCode(s: Surface, r: Rect, c: Tokens, t: Tab): void { | |
| 3943 | if (r.w <= 0 || r.h <= 0) return; | |
| 3944 | const total = t.plain.length; | |
| 3945 | const gutter = String(Math.max(1, total)).length + 1; | |
| 3946 | const textX = r.x + gutter; | |
| 3947 | const textW = Math.max(1, r.w - gutter - 1); | |
| 3948 | const from = t.scroll.window(r.h, total); | |
| 3949 | for (let i = 0; i < r.h; i++) { | |
| 3950 | const row = from + i; | |
| 3951 | if (row >= total) break; | |
| 3952 | const y = r.y + i; | |
| 3953 | const isHit = t.hits.includes(row); | |
| 3954 | const bg = isHit ? c.muted : c.bg; | |
| 3955 | s.fill({ x: r.x, y, w: Math.max(0, r.w - 1), h: 1 }, " ", style(c.fg, bg)); | |
| 3956 | s.text( | |
| 3957 | r.x, | |
| 3958 | y, | |
| 3959 | pad(String(row + 1), gutter - 1, "right"), | |
| 3960 | style(c.faint, bg), | |
| 3961 | textX, | |
| 3962 | ); | |
| 3963 | const spans = t.lines[row] ?? []; | |
| 3964 | if (t.left === 0 && bg === c.bg) { | |
| 3965 | s.spans(textX, y, spans, textX + textW); | |
| 3966 | } else { | |
| 3967 | drawShifted(s, textX, y, spans, t.left, textW, bg); | |
| 3968 | } | |
| 3969 | if (t.left > 0) s.set(textX - 1, y, G.chevron, style(c.faint, bg), textX); | |
| 3970 | } | |
| 3971 | scrollbar(s, { x: r.x + r.w - 1, y: r.y, w: 1, h: r.h }, c, { | |
| 3972 | total, | |
| 3973 | offset: from, | |
| 3974 | }); | |
| 3975 | } | |
| 3976 | ||
| 3977 | /** `80 rows, first 50 shown · 3 more columns`: what the table leaves out. */ | |
| 3978 | function tableStatus(table: Table, unread = 0, subs = false, events = false, facts = false, people = false, features = false, jsonl = false, findings = false, files = false, operations = false, instructions = false): string { | |
| 3979 | const rows = table.rows.length + table.more; | |
| 3980 | return `${plural(rows, subs ? "cue" : events ? "event" : people ? "contact" : facts ? "fact" : features ? "feature" : findings ? "finding" : files ? "file" : operations ? "operation" : instructions ? "instruction" : "row")}${ | |
| 3981 | unread > 0 | |
| 3982 | ? events | |
| 3983 | ? ` · ${plural(unread, "event")} could not be read, not shown` | |
| 3984 | : ` · ${unread} unreadable, check their arrow lines` | |
| 3985 | : "" | |
| 3986 | }${ | |
| 3987 | table.more > 0 | |
| 3988 | ? jsonl | |
| 3989 | ? `, ${plural(table.more, "more row")} not shown` | |
| 3990 | : `, first ${table.rows.length} shown` | |
| 3991 | : "" | |
| 3992 | }${ | |
| 3993 | table.columns > MAX_COLUMNS | |
| 3994 | ? ` · ${table.columns - MAX_COLUMNS} more columns` | |
| 3995 | : "" | |
| 3996 | }`; | |
| 3997 | } | |
| 3998 | ||
| 3999 | /** The one line a broken table file gets: where, and what. */ | |
| 4000 | function tableProblem(table: Table): string { | |
| 4001 | return table.error === undefined | |
| 4002 | ? "" | |
| 4003 | : `not a table: line ${table.error.line}, ${table.error.message}`; | |
| 4004 | } | |
| 4005 | ||
| 4006 | /** | |
| 4007 | * A table: the header pinned on the top row in bold, the data scrolling under | |
| 4008 | * it, `t.left` shifting both so a wide table can be read across. | |
| 4009 | */ | |
| 4010 | function drawTable(s: Surface, r: Rect, c: Tokens, t: Tab): void { | |
| 4011 | if (r.w <= 1 || r.h <= 1) return; | |
| 4012 | const textW = r.w - 1; | |
| 4013 | const rows = t.grid.rows; | |
| 4014 | const body = r.h - 1; | |
| 4015 | const from = t.scroll.window(body, rows.length); | |
| 4016 | const hits = new Set(t.hits); | |
| 4017 | s.fill({ x: r.x, y: r.y, w: textW, h: 1 }, " ", style(c.fg, c.bg)); | |
| 4018 | drawShifted( | |
| 4019 | s, | |
| 4020 | r.x, | |
| 4021 | r.y, | |
| 4022 | [{ text: t.grid.header, style: style(c.accent, c.bg, BOLD) }], | |
| 4023 | t.left, | |
| 4024 | textW, | |
| 4025 | c.bg, | |
| 4026 | ); | |
| 4027 | for (let i = 0; i < body; i++) { | |
| 4028 | const row = from + i; | |
| 4029 | if (row >= rows.length) break; | |
| 4030 | const y = r.y + 1 + i; | |
| 4031 | const bg = hits.has(row) ? c.muted : c.bg; | |
| 4032 | s.fill({ x: r.x, y, w: textW, h: 1 }, " ", style(c.fg, bg)); | |
| 4033 | drawShifted( | |
| 4034 | s, | |
| 4035 | r.x, | |
| 4036 | y, | |
| 4037 | [{ text: rows[row]!, style: style(c.fg, bg) }], | |
| 4038 | t.left, | |
| 4039 | textW, | |
| 4040 | bg, | |
| 4041 | ); | |
| 4042 | } | |
| 4043 | scrollbar(s, { x: r.x + r.w - 1, y: r.y + 1, w: 1, h: body }, c, { | |
| 4044 | total: rows.length, | |
| 4045 | offset: from, | |
| 4046 | }); | |
| 4047 | } | |
| 4048 | ||
| 4049 | /** Draw spans clipped to a window of display columns. */ | |
| 4050 | function drawShifted( | |
| 4051 | s: Surface, | |
| 4052 | x: number, | |
| 4053 | y: number, | |
| 4054 | spans: readonly Span[], | |
| 4055 | left: number, | |
| 4056 | width: number, | |
| 4057 | bg: number, | |
| 4058 | ): void { | |
| 4059 | const right = x + width; | |
| 4060 | let dcol = 0; | |
| 4061 | let cx = x; | |
| 4062 | for (const span of spans) { | |
| 4063 | for (const ch of clusters(span.text)) { | |
| 4064 | const w = displayWidth(ch); | |
| 4065 | if (dcol + w > left && dcol < left + width) | |
| 4066 | cx = s.text(cx, y, ch, { ...span.style, bg }, right); | |
| 4067 | dcol += w; | |
| 4068 | if (dcol >= left + width) return; | |
| 4069 | } | |
| 4070 | } | |
| 4071 | } | |
| 4072 | 2639 | |
| 4073 | 2640 | // ---- the doors other screens knock on ---- |
| 4074 | 2641 |
src/tui/screens/workspace_draw.ts added +386
| @@ -0,0 +1,386 @@ | ||
| 1 | /** | |
| 2 | * Drawing the workspace: the ref pill, the tab bar, the explorer, a file's code or table. | |
| 3 | */ | |
| 4 | import { MAX_COLUMNS, type Table } from "../../text/csv.ts"; | |
| 5 | import { G, type Rect, type Screen as Surface, type Span } from "../term/screen.ts"; | |
| 6 | import { BOLD, STRIKE, UNDERLINE, style } from "../term/style.ts"; | |
| 7 | import { clusters, displayWidth, pad, truncate } from "../term/width.ts"; | |
| 8 | import { fileIcon, type IconSet } from "../ui/icons.ts"; | |
| 9 | import { type Tokens } from "../ui/theme.ts"; | |
| 10 | import { scrollbar } from "../ui/widgets.ts"; | |
| 11 | import { ListState, plural } from "./common.ts"; | |
| 12 | import { type Node } from "./workspace_tree.ts"; | |
| 13 | import { Tab } from "./workspace_tab.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * The mark a rendered markdown tab wears — `README.md ¶`. From the safe set | |
| 17 | * in `term/screen.ts` (documented in `docs/DESIGN.md`): it is the one glyph | |
| 18 | * in that set that already means "formatted prose", and `v` takes it off. | |
| 19 | */ | |
| 20 | export const PROSE_MARK = G.para; | |
| 21 | ||
| 22 | // ---- drawing ---- | |
| 23 | ||
| 24 | /** `main ▾`, right-aligned on the where-strip's row. */ | |
| 25 | export function drawRefPill( | |
| 26 | s: Surface, | |
| 27 | r: Rect, | |
| 28 | c: Tokens, | |
| 29 | ref: string, | |
| 30 | strip: readonly Span[], | |
| 31 | ): void { | |
| 32 | if (r.w <= 0 || r.h <= 0) return; | |
| 33 | const label = `${truncate(ref === "" ? "…" : ref, 24)} ${G.caretDown}`; | |
| 34 | const used = strip.reduce((sum, span) => sum + displayWidth(span.text), 0); | |
| 35 | const x = r.x + r.w - displayWidth(label) - 1; | |
| 36 | // Never draw over the strip: it says where the bytes came from, which is | |
| 37 | // the more important of the two. | |
| 38 | if (x <= r.x + used + 2) return; | |
| 39 | s.text(x, r.y, label, style(c.accent, c.bg, BOLD), r.x + r.w); | |
| 40 | } | |
| 41 | ||
| 42 | /** Where one tab landed: the whole chip, and the `✗` inside it if it has one. */ | |
| 43 | export interface TabHit { | |
| 44 | readonly index: number; | |
| 45 | readonly rect: Rect; | |
| 46 | readonly close?: Rect; | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * The tab bar. One row: the paths, the active one bold and underlined in the | |
| 51 | * accent, a dot on anything modified, `¶` on prose being read rather than | |
| 52 | * edited, and `‹ ›` when there are more than fit. | |
| 53 | * | |
| 54 | * The active tab wears a `✗`. Only the active one: a close box on every chip | |
| 55 | * is a row of targets you can hit by accident, and the tab you mean to close | |
| 56 | * is almost always the one you are looking at. | |
| 57 | */ | |
| 58 | export function drawTabBar( | |
| 59 | s: Surface, | |
| 60 | r: Rect, | |
| 61 | c: Tokens, | |
| 62 | tabs: readonly Tab[], | |
| 63 | active: number, | |
| 64 | set: IconSet = "plain", | |
| 65 | ): TabHit[] { | |
| 66 | if (r.w <= 0 || r.h <= 0) return []; | |
| 67 | s.fill(r, " ", style(c.mutedFg, c.bg)); | |
| 68 | const right = r.x + r.w; | |
| 69 | if (tabs.length === 0) { | |
| 70 | s.text(r.x + 1, r.y, "no tabs open", style(c.faint, c.bg), right); | |
| 71 | return []; | |
| 72 | } | |
| 73 | const hits: TabHit[] = []; | |
| 74 | const count = `${plural(tabs.length, "tab")} `; | |
| 75 | const room = Math.max(10, r.w - count.length - 2); | |
| 76 | // The icon is nerd-only: the plain set's generic file mark before every | |
| 77 | // path says nothing and costs two columns on the one row that has none. | |
| 78 | const mark = (t: Tab): string => | |
| 79 | set === "nerd" ? `${fileIcon(t.path, set)} ` : ""; | |
| 80 | const label = (t: Tab): string => | |
| 81 | ` ${mark(t)}${truncate(t.path, 30)}${t.modified ? " ●" : ""}${ | |
| 82 | t.reading ? ` ${PROSE_MARK}` : "" | |
| 83 | } `; | |
| 84 | const widths = tabs.map( | |
| 85 | (t, i) => displayWidth(label(t)) + (i === active ? 2 : 0) + 1, | |
| 86 | ); | |
| 87 | ||
| 88 | // A window that contains the active tab and fits: grow left from it, then | |
| 89 | // right, so the tab you are on is never the one that scrolled off. | |
| 90 | let first = Math.max(0, Math.min(active, tabs.length - 1)); | |
| 91 | let last = first; | |
| 92 | let used = widths[first] ?? 0; | |
| 93 | for (;;) { | |
| 94 | const before = first > 0 ? (widths[first - 1] ?? 0) : Infinity; | |
| 95 | const after = last + 1 < tabs.length ? (widths[last + 1] ?? 0) : Infinity; | |
| 96 | if (after <= before && used + after <= room) { | |
| 97 | used += after; | |
| 98 | last++; | |
| 99 | } else if (before < Infinity && used + before <= room) { | |
| 100 | used += before; | |
| 101 | first--; | |
| 102 | } else break; | |
| 103 | } | |
| 104 | ||
| 105 | let x = r.x; | |
| 106 | if (first > 0) | |
| 107 | x = s.text( | |
| 108 | x, | |
| 109 | r.y, | |
| 110 | `${G.chevron === "›" ? "‹" : "<"}`, | |
| 111 | style(c.faint, c.bg), | |
| 112 | right, | |
| 113 | ); | |
| 114 | for (let i = first; i <= last; i++) { | |
| 115 | const t = tabs[i]; | |
| 116 | if (t === undefined) break; | |
| 117 | const on = i === active; | |
| 118 | const from = x; | |
| 119 | x = s.text( | |
| 120 | x, | |
| 121 | r.y, | |
| 122 | label(t), | |
| 123 | style( | |
| 124 | on ? c.accent : t.modified ? c.attn : c.mutedFg, | |
| 125 | c.bg, | |
| 126 | on ? BOLD | UNDERLINE : 0, | |
| 127 | ), | |
| 128 | right, | |
| 129 | ); | |
| 130 | let close: Rect | undefined; | |
| 131 | if (on) { | |
| 132 | close = { x, y: r.y, w: 2, h: 1 }; | |
| 133 | x = s.text(x, r.y, `${G.cross} `, style(c.faint, c.bg), right); | |
| 134 | } | |
| 135 | hits.push({ | |
| 136 | index: i, | |
| 137 | rect: { x: from, y: r.y, w: x - from, h: 1 }, | |
| 138 | ...(close === undefined ? {} : { close }), | |
| 139 | }); | |
| 140 | x += 1; | |
| 141 | } | |
| 142 | if (last < tabs.length - 1) s.text(x, r.y, "›", style(c.faint, c.bg), right); | |
| 143 | s.text(right - count.length, r.y, count, style(c.faint, c.bg), right); | |
| 144 | return hits; | |
| 145 | } | |
| 146 | ||
| 147 | export interface TreeDrawOpts { | |
| 148 | readonly focused: boolean; | |
| 149 | readonly openPaths: ReadonlySet<string>; | |
| 150 | readonly modified: ReadonlySet<string>; | |
| 151 | readonly pending: ReadonlySet<string>; | |
| 152 | readonly currentPath: string; | |
| 153 | readonly empty: string; | |
| 154 | readonly icons: IconSet; | |
| 155 | } | |
| 156 | ||
| 157 | /** | |
| 158 | * The explorer rows. Indentation plus a caret is the whole grammar: `▸`/`▾` | |
| 159 | * on a directory, a dot on a file with unsaved changes, a struck-through name | |
| 160 | * on one marked for deletion, and the accent on whatever the file pane holds. | |
| 161 | */ | |
| 162 | export function drawTree( | |
| 163 | s: Surface, | |
| 164 | r: Rect, | |
| 165 | c: Tokens, | |
| 166 | state: ListState, | |
| 167 | nodes: readonly Node[], | |
| 168 | o: TreeDrawOpts, | |
| 169 | ): void { | |
| 170 | if (r.w <= 0 || r.h <= 0) return; | |
| 171 | if (nodes.length === 0) { | |
| 172 | s.text( | |
| 173 | r.x + 2, | |
| 174 | r.y, | |
| 175 | truncate(o.empty, Math.max(0, r.w - 2)), | |
| 176 | style(c.faint, c.bg), | |
| 177 | r.x + r.w, | |
| 178 | ); | |
| 179 | return; | |
| 180 | } | |
| 181 | const from = state.window(r.h, nodes.length); | |
| 182 | const right = r.x + r.w - 1; | |
| 183 | for (let i = 0; i < r.h; i++) { | |
| 184 | const node = nodes[from + i]; | |
| 185 | if (node === undefined) break; | |
| 186 | const y = r.y + i; | |
| 187 | const selected = from + i === state.index; | |
| 188 | const bg = selected && o.focused ? c.muted : c.bg; | |
| 189 | s.fill({ x: r.x, y, w: r.w - 1, h: 1 }, " ", style(c.fg, bg)); | |
| 190 | let x = r.x + Math.min(node.depth * 2, Math.max(0, r.w - 8)); | |
| 191 | const mark = | |
| 192 | node.type === "tree" | |
| 193 | ? node.loading | |
| 194 | ? G.ellipsis | |
| 195 | : node.expanded | |
| 196 | ? G.caretDown | |
| 197 | : G.caretRight | |
| 198 | : " "; | |
| 199 | // The caret is the expansion state and stays whatever the set. A Nerd | |
| 200 | // Font adds the *kind* beside it — the plain set does not, because six | |
| 201 | // shades of `▭` before six filenames is noise, not information. | |
| 202 | const glyph = | |
| 203 | o.icons === "nerd" | |
| 204 | ? `${mark}${fileIcon(node.path, o.icons, { | |
| 205 | directory: node.type === "tree", | |
| 206 | open: node.expanded, | |
| 207 | })} ` | |
| 208 | : `${mark} `; | |
| 209 | x = s.text(x, y, glyph, style(c.mutedFg, bg), right); | |
| 210 | const doomed = o.pending.has(node.path); | |
| 211 | const dirty = o.modified.has(node.path); | |
| 212 | const current = node.type === "blob" && node.path === o.currentPath; | |
| 213 | const label = node.type === "tree" ? `${node.name}/` : node.name; | |
| 214 | const meta = doomed | |
| 215 | ? "delete" | |
| 216 | : dirty | |
| 217 | ? "●" | |
| 218 | : node.type === "blob" | |
| 219 | ? "" | |
| 220 | : ""; | |
| 221 | const metaW = meta === "" ? 0 : meta.length + 1; | |
| 222 | s.text( | |
| 223 | x, | |
| 224 | y, | |
| 225 | truncate(label, Math.max(0, right - x - metaW)), | |
| 226 | style( | |
| 227 | doomed | |
| 228 | ? c.danger | |
| 229 | : current | |
| 230 | ? c.accent | |
| 231 | : o.openPaths.has(node.path) | |
| 232 | ? c.fg | |
| 233 | : node.type === "tree" | |
| 234 | ? c.fg | |
| 235 | : c.mutedFg, | |
| 236 | bg, | |
| 237 | (current || selected ? BOLD : 0) | (doomed ? STRIKE : 0), | |
| 238 | ), | |
| 239 | right - metaW, | |
| 240 | ); | |
| 241 | if (meta !== "") | |
| 242 | s.text( | |
| 243 | right - meta.length, | |
| 244 | y, | |
| 245 | meta, | |
| 246 | style(doomed ? c.danger : c.attn, bg), | |
| 247 | right, | |
| 248 | ); | |
| 249 | } | |
| 250 | scrollbar(s, { x: r.x + r.w - 1, y: r.y, w: 1, h: r.h }, c, { | |
| 251 | total: nodes.length, | |
| 252 | offset: from, | |
| 253 | }); | |
| 254 | } | |
| 255 | ||
| 256 | /** The read view: a pinned gutter, syntax colour, and horizontal scrolling. */ | |
| 257 | export function drawCode(s: Surface, r: Rect, c: Tokens, t: Tab): void { | |
| 258 | if (r.w <= 0 || r.h <= 0) return; | |
| 259 | const total = t.plain.length; | |
| 260 | const gutter = String(Math.max(1, total)).length + 1; | |
| 261 | const textX = r.x + gutter; | |
| 262 | const textW = Math.max(1, r.w - gutter - 1); | |
| 263 | const from = t.scroll.window(r.h, total); | |
| 264 | for (let i = 0; i < r.h; i++) { | |
| 265 | const row = from + i; | |
| 266 | if (row >= total) break; | |
| 267 | const y = r.y + i; | |
| 268 | const isHit = t.hits.includes(row); | |
| 269 | const bg = isHit ? c.muted : c.bg; | |
| 270 | s.fill({ x: r.x, y, w: Math.max(0, r.w - 1), h: 1 }, " ", style(c.fg, bg)); | |
| 271 | s.text( | |
| 272 | r.x, | |
| 273 | y, | |
| 274 | pad(String(row + 1), gutter - 1, "right"), | |
| 275 | style(c.faint, bg), | |
| 276 | textX, | |
| 277 | ); | |
| 278 | const spans = t.lines[row] ?? []; | |
| 279 | if (t.left === 0 && bg === c.bg) { | |
| 280 | s.spans(textX, y, spans, textX + textW); | |
| 281 | } else { | |
| 282 | drawShifted(s, textX, y, spans, t.left, textW, bg); | |
| 283 | } | |
| 284 | if (t.left > 0) s.set(textX - 1, y, G.chevron, style(c.faint, bg), textX); | |
| 285 | } | |
| 286 | scrollbar(s, { x: r.x + r.w - 1, y: r.y, w: 1, h: r.h }, c, { | |
| 287 | total, | |
| 288 | offset: from, | |
| 289 | }); | |
| 290 | } | |
| 291 | ||
| 292 | /** `80 rows, first 50 shown · 3 more columns`: what the table leaves out. */ | |
| 293 | export function tableStatus(table: Table, unread = 0, subs = false, events = false, facts = false, people = false, features = false, jsonl = false, findings = false, files = false, operations = false, instructions = false): string { | |
| 294 | const rows = table.rows.length + table.more; | |
| 295 | return `${plural(rows, subs ? "cue" : events ? "event" : people ? "contact" : facts ? "fact" : features ? "feature" : findings ? "finding" : files ? "file" : operations ? "operation" : instructions ? "instruction" : "row")}${ | |
| 296 | unread > 0 | |
| 297 | ? events | |
| 298 | ? ` · ${plural(unread, "event")} could not be read, not shown` | |
| 299 | : ` · ${unread} unreadable, check their arrow lines` | |
| 300 | : "" | |
| 301 | }${ | |
| 302 | table.more > 0 | |
| 303 | ? jsonl | |
| 304 | ? `, ${plural(table.more, "more row")} not shown` | |
| 305 | : `, first ${table.rows.length} shown` | |
| 306 | : "" | |
| 307 | }${ | |
| 308 | table.columns > MAX_COLUMNS | |
| 309 | ? ` · ${table.columns - MAX_COLUMNS} more columns` | |
| 310 | : "" | |
| 311 | }`; | |
| 312 | } | |
| 313 | ||
| 314 | /** The one line a broken table file gets: where, and what. */ | |
| 315 | export function tableProblem(table: Table): string { | |
| 316 | return table.error === undefined | |
| 317 | ? "" | |
| 318 | : `not a table: line ${table.error.line}, ${table.error.message}`; | |
| 319 | } | |
| 320 | ||
| 321 | /** | |
| 322 | * A table: the header pinned on the top row in bold, the data scrolling under | |
| 323 | * it, `t.left` shifting both so a wide table can be read across. | |
| 324 | */ | |
| 325 | export function drawTable(s: Surface, r: Rect, c: Tokens, t: Tab): void { | |
| 326 | if (r.w <= 1 || r.h <= 1) return; | |
| 327 | const textW = r.w - 1; | |
| 328 | const rows = t.grid.rows; | |
| 329 | const body = r.h - 1; | |
| 330 | const from = t.scroll.window(body, rows.length); | |
| 331 | const hits = new Set(t.hits); | |
| 332 | s.fill({ x: r.x, y: r.y, w: textW, h: 1 }, " ", style(c.fg, c.bg)); | |
| 333 | drawShifted( | |
| 334 | s, | |
| 335 | r.x, | |
| 336 | r.y, | |
| 337 | [{ text: t.grid.header, style: style(c.accent, c.bg, BOLD) }], | |
| 338 | t.left, | |
| 339 | textW, | |
| 340 | c.bg, | |
| 341 | ); | |
| 342 | for (let i = 0; i < body; i++) { | |
| 343 | const row = from + i; | |
| 344 | if (row >= rows.length) break; | |
| 345 | const y = r.y + 1 + i; | |
| 346 | const bg = hits.has(row) ? c.muted : c.bg; | |
| 347 | s.fill({ x: r.x, y, w: textW, h: 1 }, " ", style(c.fg, bg)); | |
| 348 | drawShifted( | |
| 349 | s, | |
| 350 | r.x, | |
| 351 | y, | |
| 352 | [{ text: rows[row]!, style: style(c.fg, bg) }], | |
| 353 | t.left, | |
| 354 | textW, | |
| 355 | bg, | |
| 356 | ); | |
| 357 | } | |
| 358 | scrollbar(s, { x: r.x + r.w - 1, y: r.y + 1, w: 1, h: body }, c, { | |
| 359 | total: rows.length, | |
| 360 | offset: from, | |
| 361 | }); | |
| 362 | } | |
| 363 | ||
| 364 | /** Draw spans clipped to a window of display columns. */ | |
| 365 | export function drawShifted( | |
| 366 | s: Surface, | |
| 367 | x: number, | |
| 368 | y: number, | |
| 369 | spans: readonly Span[], | |
| 370 | left: number, | |
| 371 | width: number, | |
| 372 | bg: number, | |
| 373 | ): void { | |
| 374 | const right = x + width; | |
| 375 | let dcol = 0; | |
| 376 | let cx = x; | |
| 377 | for (const span of spans) { | |
| 378 | for (const ch of clusters(span.text)) { | |
| 379 | const w = displayWidth(ch); | |
| 380 | if (dcol + w > left && dcol < left + width) | |
| 381 | cx = s.text(cx, y, ch, { ...span.style, bg }, right); | |
| 382 | dcol += w; | |
| 383 | if (dcol >= left + width) return; | |
| 384 | } | |
| 385 | } | |
| 386 | } |
src/tui/screens/workspace_tab.ts added +467
| @@ -0,0 +1,467 @@ | ||
| 1 | /** | |
| 2 | * A file as a tab: its buffer, scroll, search and edits, and the blob the workspace keeps for it. | |
| 3 | */ | |
| 4 | import { parseUnifiedDiff, type Diff } from "../../git/diff.ts"; | |
| 5 | import { renderDiff as renderPatch } from "../ui/diff.ts"; | |
| 6 | import { fileKind, isEnvExample, kindByName, NO_BYTES } from "../../web/render/kinds.ts"; | |
| 7 | import { detectLanguage, highlightLines } from "../../web/highlight.ts"; | |
| 8 | import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts"; | |
| 9 | import { parseCsv, type Table } from "../../text/csv.ts"; | |
| 10 | import { isNumericColumn, sortRows } from "../../text/csv-sort.ts"; | |
| 11 | import { isKmlPath, kmlTable } from "./kml.ts"; | |
| 12 | import { pcdFacts } from "../../web/render/pcd.ts"; | |
| 13 | import { kindView, type KindLines } from "./workspace_kinds.ts"; | |
| 14 | import { type SqliteAt } from "./workspace_sqlite.ts"; | |
| 15 | import { layoutTable, type Grid } from "../ui/grid.ts"; | |
| 16 | import { stripAnsi } from "../term/ansi.ts"; | |
| 17 | import { type Span } from "../term/screen.ts"; | |
| 18 | import { style } from "../term/style.ts"; | |
| 19 | import { expandTabs } from "../term/width.ts"; | |
| 20 | import { Editor } from "../ui/editor.ts"; | |
| 21 | import { type TerminalImage } from "../ui/image.ts"; | |
| 22 | import { renderMarkdown, type Line } from "../ui/markdown.ts"; | |
| 23 | import { tokColor, type Tokens } from "../ui/theme.ts"; | |
| 24 | import { Filter, Scroll } from "./common.ts"; | |
| 25 | import { isTablePath, isSubtitlePath, subtitleTable, isIcsPath, icsTable, isVcfPath, vcfTable, envTable, packageTable, isEmlPath, emlTable, isGpxPath, gpxTable, isHarPath, harTable, isTimelinePath, timelineTable, isSarifPath, sarifTable, isLcovPath, lcovTable, isOpenApiPath, openapiTable, isDockerfilePath, dockerfileTable, isWorkflowPath, workflowTable, isSqlPath, sqlTable, isGraphqlPath, graphqlTable, mboxTable, protoTable, iniTable, rtfTable, xmlTable, isJunitPath, junitTable, isFeedPath, feedTable, isGcodePath, gcodeTable, isStepPath, stepTable, isIfcPath, ifcTable, isGeoJsonPath, geoJsonTable } from "./workspace_tables.ts"; | |
| 26 | // ---- a file, as a tab ---- | |
| 27 | ||
| 28 | /** | |
| 29 | * Styled rows plus the plain text behind them. The gutter is *not* in the | |
| 30 | * spans: the pane draws line numbers itself, so they stay pinned while the | |
| 31 | * code scrolls sideways under them. | |
| 32 | */ | |
| 33 | export function isLogPath(path: string): boolean { | |
| 34 | return /\.(log|ansi)$/i.test(path); | |
| 35 | } | |
| 36 | ||
| 37 | export function buildLines( | |
| 38 | text: string, | |
| 39 | path: string, | |
| 40 | c: Tokens, | |
| 41 | ): { plain: string[]; lines: Span[][] } { | |
| 42 | // A terminal log carries escapes; the viewer shows its text, never drives | |
| 43 | // the terminal or prints "[31m" as if it were the log. | |
| 44 | const clean = isLogPath(path) && text.includes("\x1b") ? stripAnsi(text) : text; | |
| 45 | // A private key's body is never drawn: one notice line stands in, as on the page. | |
| 46 | const body = holdsPrivateKey(clean) ? PRIVATE_KEY_NOTICE : clean.replace(/\n$/, ""); | |
| 47 | const plain = body.split("\n").map((l) => expandTabs(l)); | |
| 48 | // The first line is handed to the detector too: a `#!/usr/bin/env python3` | |
| 49 | // with no extension, a `.zshrc`, a vim modeline. The name is the strong | |
| 50 | // signal and the line is the fallback, which is the detector's own order. | |
| 51 | const language = detectLanguage(path, plain[0] ?? ""); | |
| 52 | const lines = highlightLines(plain.join("\n"), language).map( | |
| 53 | (tokens): Span[] => | |
| 54 | tokens.map((t) => ({ | |
| 55 | text: t.text, | |
| 56 | style: style(tokColor(c, t), c.bg), | |
| 57 | })), | |
| 58 | ); | |
| 59 | return { plain, lines }; | |
| 60 | } | |
| 61 | ||
| 62 | export type TabMode = "view" | "edit"; | |
| 63 | export type FindMode = "off" | "find" | "replace"; | |
| 64 | /** What a path is, as far as the file pane is concerned. */ | |
| 65 | export type TabKind = "image" | "markdown" | "patch" | "code"; | |
| 66 | ||
| 67 | ||
| 68 | export function isMarkdownPath(path: string): boolean { | |
| 69 | const name = path.slice(path.lastIndexOf("/") + 1); | |
| 70 | return fileKind(name, NO_BYTES) === "markdown" || /^readme(\.|$)/i.test(name); | |
| 71 | } | |
| 72 | ||
| 73 | /** `.patch` and `.diff`: a file the pull page's diff draws. */ | |
| 74 | export function isPatchPath(path: string): boolean { | |
| 75 | return fileKind(path.slice(path.lastIndexOf("/") + 1), NO_BYTES) === "patch"; | |
| 76 | } | |
| 77 | ||
| 78 | export class Tab { | |
| 79 | loading = true; | |
| 80 | /** Non-empty when there is a reason the bytes are not on screen. */ | |
| 81 | note = ""; | |
| 82 | noteTitle = "Not shown"; | |
| 83 | noteDetail = ""; | |
| 84 | /** The one line saying why this file is plain source; empty for ordinary text. */ | |
| 85 | why = ""; | |
| 86 | /** | |
| 87 | * Non-empty when `raw` is only the start of a larger file: the sentence that says so. It is never | |
| 88 | * edited. | |
| 89 | */ | |
| 90 | cut = ""; | |
| 91 | raw: Uint8Array | null = null; | |
| 92 | plain: string[] = []; | |
| 93 | lines: Span[][] = []; | |
| 94 | readonly scroll = new Scroll(); | |
| 95 | readonly search = new Filter(); | |
| 96 | hits: number[] = []; | |
| 97 | hit = 0; | |
| 98 | /** Horizontal scroll, in display columns, for the view mode. */ | |
| 99 | left = 0; | |
| 100 | editor: Editor | null = null; | |
| 101 | mode: TabMode = "view"; | |
| 102 | /** A file that does not exist at this ref yet. */ | |
| 103 | creating = false; | |
| 104 | /** The blob the buffer was read from (`null`: none), or undefined where nothing is compared. */ | |
| 105 | opened: string | null | undefined = undefined; | |
| 106 | find: FindMode = "off"; | |
| 107 | needle = ""; | |
| 108 | replacement = ""; | |
| 109 | replaceField: "find" | "with" = "find"; | |
| 110 | hint = ""; | |
| 111 | /** | |
| 112 | * A picture, when git handed us one. `looksLikeImage` is only an extension | |
| 113 | * filter, so this stays null for a `.png` that turned out to be text — the | |
| 114 | * bytes decide, never the name. | |
| 115 | */ | |
| 116 | image: TerminalImage | null = null; | |
| 117 | /** `v`: the picture, or the facts about it. */ | |
| 118 | showImage = true; | |
| 119 | /** | |
| 120 | * `v` on prose: the rendered document, or the source that made it. Prose | |
| 121 | * opens rendered because that is what a README is *for*; the source is one | |
| 122 | * keypress away and is what `e` always edits. | |
| 123 | */ | |
| 124 | rendered = true; | |
| 125 | /** The rendered document, and the width it was wrapped for. */ | |
| 126 | doc: Line[] = []; | |
| 127 | docPlain: string[] = []; | |
| 128 | /** The parsed diff of a patch file; null when the text is not a git diff. */ | |
| 129 | patch: Diff | null = null; | |
| 130 | docWidth = 0; | |
| 131 | /** `s` on a CSV/TSV: the aligned table, or the source behind it. */ | |
| 132 | asTable = true; | |
| 133 | /** The parsed file, when its name says table. Parse errors ride along. */ | |
| 134 | table: Table | null = null; | |
| 135 | grid: Grid = { header: "", rows: [] }; | |
| 136 | /** `o` on a CSV/TSV: the column its rows are ordered by, or null for file order. */ | |
| 137 | order: { column: number; descending: boolean } | null = null; | |
| 138 | /** An .xlsx's first sheet: the bytes are not text, so the table is all there is. */ | |
| 139 | sheet: Table | null = null; | |
| 140 | /** A SQLite file's bytes, kept so `>`/`<` and `}`/`{` can page it; null for any other file. */ | |
| 141 | db: Uint8Array | null = null; | |
| 142 | dbAt: SqliteAt = { table: 0, page: 1 }; | |
| 143 | /** | |
| 144 | * A big JSON file's prefix and size, kept so `m` can open one of its keys by byte range; null for | |
| 145 | * any other file. | |
| 146 | */ | |
| 147 | big: { readonly prefix: Uint8Array; readonly size: number } | null = null; | |
| 148 | /** Cues of a subtitle file that could not be read. */ | |
| 149 | unread = 0; | |
| 150 | /** Why a file whose name promises a view is shown as source instead; "" when nothing failed. */ | |
| 151 | fault = ""; | |
| 152 | /** The .ipynb / .log view, and the source it replaces while `s` has it up. */ | |
| 153 | kindLines: KindLines | null = null; | |
| 154 | sourceLines: KindLines | null = null; | |
| 155 | ||
| 156 | constructor(readonly path: string) {} | |
| 157 | ||
| 158 | get name(): string { | |
| 159 | return this.path.slice(this.path.lastIndexOf("/") + 1); | |
| 160 | } | |
| 161 | ||
| 162 | get kind(): TabKind { | |
| 163 | if (this.image !== null) return "image"; | |
| 164 | if (isPatchPath(this.path)) return "patch"; | |
| 165 | return isMarkdownPath(this.path) ? "markdown" : "code"; | |
| 166 | } | |
| 167 | ||
| 168 | /** True when the pane is showing prose rather than the bytes behind it. */ | |
| 169 | get reading(): boolean { | |
| 170 | if (!this.rendered || this.mode !== "view") return false; | |
| 171 | return this.kind === "markdown" || (this.kind === "patch" && this.patch !== null); | |
| 172 | } | |
| 173 | ||
| 174 | /** | |
| 175 | * The table with its rows in `order`, and an arrow on that column's header; the table itself when | |
| 176 | * unordered. | |
| 177 | */ | |
| 178 | ordered(table: Table): Table { | |
| 179 | const o = this.order; | |
| 180 | if (o === null || table.error !== undefined) return table; | |
| 181 | const numeric = isNumericColumn(table.rows, o.column); | |
| 182 | const header = table.header.map((h, i) => (i === o.column ? `${h} ${o.descending ? "▼" : "▲"}` : h)); | |
| 183 | return { ...table, header, rows: sortRows(table.rows, o.column, numeric, o.descending) }; | |
| 184 | } | |
| 185 | ||
| 186 | /** `o`: file order, then each column ascending and descending in turn, then file order again. */ | |
| 187 | cycleOrder(): string { | |
| 188 | const t = this.table; | |
| 189 | if (t === null || t.error !== undefined || !isTablePath(this.path) || t.header.length === 0) return ""; | |
| 190 | const o = this.order; | |
| 191 | if (o === null) this.order = { column: 0, descending: false }; | |
| 192 | else if (!o.descending) this.order = { column: o.column, descending: true }; | |
| 193 | else this.order = o.column + 1 < t.header.length ? { column: o.column + 1, descending: false } : null; | |
| 194 | this.grid = layoutTable(this.ordered(t)); | |
| 195 | const now = this.order; | |
| 196 | return now === null ? "in file order" : `by ${t.header[now.column]} ${now.descending ? "descending" : "ascending"}`; | |
| 197 | } | |
| 198 | ||
| 199 | /** True when the pane is showing a CSV/TSV as columns. */ | |
| 200 | get tabular(): boolean { | |
| 201 | return ( | |
| 202 | this.table !== null && | |
| 203 | this.table.error === undefined && | |
| 204 | this.table.header.length > 0 && | |
| 205 | this.asTable && | |
| 206 | this.mode === "view" | |
| 207 | ); | |
| 208 | } | |
| 209 | ||
| 210 | /** The lines `/` searches and `j` scrolls: whichever view is up. */ | |
| 211 | get body(): string[] { | |
| 212 | if (this.reading) return this.docPlain; | |
| 213 | return this.tabular ? this.grid.rows : this.plain; | |
| 214 | } | |
| 215 | ||
| 216 | /** Wrap the markdown for this width, and only when the width moved. */ | |
| 217 | document(width: number, c: Tokens): void { | |
| 218 | if (this.docWidth === width && this.doc.length > 0) return; | |
| 219 | this.docWidth = width; | |
| 220 | this.doc = | |
| 221 | this.patch !== null | |
| 222 | ? renderPatch(this.patch, Math.max(8, width), c) | |
| 223 | : renderMarkdown(this.plain.join("\n"), Math.max(8, width), c); | |
| 224 | this.docPlain = this.doc.map((line) => | |
| 225 | line.map((span) => span.text).join(""), | |
| 226 | ); | |
| 227 | } | |
| 228 | ||
| 229 | /** Put up the notebook/log view or its source, whichever `asTable` says. */ | |
| 230 | showKind(): void { | |
| 231 | if (this.kindLines === null || this.sourceLines === null) return; | |
| 232 | const shown = this.asTable ? this.kindLines : this.sourceLines; | |
| 233 | this.plain = shown.plain; | |
| 234 | this.lines = shown.lines; | |
| 235 | } | |
| 236 | ||
| 237 | get modified(): boolean { | |
| 238 | return this.creating || (this.editor !== null && this.editor.modified); | |
| 239 | } | |
| 240 | ||
| 241 | /** Text the file would be committed with: the buffer if there is one. */ | |
| 242 | bytes(): Uint8Array { | |
| 243 | return this.editor?.toBytes() ?? this.raw ?? new Uint8Array(0); | |
| 244 | } | |
| 245 | ||
| 246 | /** Make the buffer, once, from whatever git handed us. */ | |
| 247 | buffer(): Editor | null { | |
| 248 | if (this.editor !== null) return this.editor; | |
| 249 | if (this.raw === null) return null; | |
| 250 | this.editor = new Editor(this.raw, this.path); | |
| 251 | return this.editor; | |
| 252 | } | |
| 253 | ||
| 254 | /** Re-derive the read view from the buffer, so `esc` keeps the edits. */ | |
| 255 | rebuild(c: Tokens): void { | |
| 256 | const source = | |
| 257 | this.editor === null | |
| 258 | ? this.raw | |
| 259 | : new TextEncoder().encode( | |
| 260 | this.editor.lines.join("\n") + | |
| 261 | (this.editor.finalNewline ? "\n" : ""), | |
| 262 | ); | |
| 263 | if (source === null) { | |
| 264 | this.plain = []; | |
| 265 | this.lines = []; | |
| 266 | this.table = this.sheet; | |
| 267 | if (this.sheet !== null) this.grid = layoutTable(this.sheet); | |
| 268 | return; | |
| 269 | } | |
| 270 | const text = new TextDecoder().decode(source); | |
| 271 | const built = buildLines(text, this.path, c); | |
| 272 | if (isPatchPath(this.path)) { | |
| 273 | const parsed = parseUnifiedDiff(text); | |
| 274 | this.patch = parsed.files.length > 0 ? parsed : null; | |
| 275 | } else this.patch = null; | |
| 276 | this.plain = built.plain; | |
| 277 | this.lines = built.lines; | |
| 278 | this.unread = 0; | |
| 279 | this.fault = ""; | |
| 280 | this.kindLines = null; | |
| 281 | this.sourceLines = built; | |
| 282 | const kind = kindView(this.path, text, c); | |
| 283 | if (kind?.table !== undefined) { | |
| 284 | this.table = kind.table; | |
| 285 | this.grid = layoutTable(kind.table); | |
| 286 | } else if (kind !== null) { | |
| 287 | this.kindLines = kind; | |
| 288 | if (this.asTable && this.mode === "view") { | |
| 289 | this.plain = kind.plain; | |
| 290 | this.lines = kind.lines; | |
| 291 | } | |
| 292 | } | |
| 293 | const api = isOpenApiPath(this.path) ? openapiTable(text, this.path) : null; | |
| 294 | if (isSubtitlePath(this.path)) { | |
| 295 | const subs = subtitleTable(new TextDecoder().decode(source)); | |
| 296 | this.table = subs.table; | |
| 297 | this.unread = subs.unread; | |
| 298 | this.grid = layoutTable(this.table); | |
| 299 | } else if (isIcsPath(this.path)) { | |
| 300 | const cal = icsTable(new TextDecoder().decode(source)); | |
| 301 | this.table = cal === null ? null : cal.table; | |
| 302 | this.unread = cal === null ? 0 : cal.unread; | |
| 303 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 304 | } else if (isVcfPath(this.path)) { | |
| 305 | this.table = vcfTable(new TextDecoder().decode(source)); | |
| 306 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 307 | } else if (isEnvExample(this.path)) { | |
| 308 | this.table = envTable(new TextDecoder().decode(source)); | |
| 309 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 310 | } else if (kindByName(this.path) === "package") { | |
| 311 | this.table = packageTable(new TextDecoder().decode(source)); | |
| 312 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 313 | } else if (isEmlPath(this.path)) { | |
| 314 | this.table = emlTable(source); | |
| 315 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 316 | } else if (isGpxPath(this.path)) { | |
| 317 | this.table = gpxTable(new TextDecoder().decode(source), this.path); | |
| 318 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 319 | } else if (isHarPath(this.path)) { | |
| 320 | this.table = harTable(new TextDecoder().decode(source)); | |
| 321 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 322 | } else if (isTimelinePath(this.path)) { | |
| 323 | const cuts = timelineTable(source, this.path); | |
| 324 | this.table = typeof cuts === "string" ? null : cuts; | |
| 325 | this.fault = typeof cuts === "string" ? cuts : ""; | |
| 326 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 327 | } else if (isSarifPath(this.path)) { | |
| 328 | const findings = sarifTable(new TextDecoder().decode(source)); | |
| 329 | this.table = typeof findings === "string" ? null : findings; | |
| 330 | this.fault = typeof findings === "string" ? findings : ""; | |
| 331 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 332 | } else if (isLcovPath(this.path)) { | |
| 333 | const coverage = lcovTable(new TextDecoder().decode(source)); | |
| 334 | this.table = typeof coverage === "string" ? null : coverage; | |
| 335 | this.fault = typeof coverage === "string" ? coverage : ""; | |
| 336 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 337 | } else if (api !== null) { | |
| 338 | this.table = typeof api === "string" ? null : api; | |
| 339 | this.fault = typeof api === "string" ? api : ""; | |
| 340 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 341 | } else if (isDockerfilePath(this.path)) { | |
| 342 | const build = dockerfileTable(new TextDecoder().decode(source)); | |
| 343 | this.table = typeof build === "string" ? null : build; | |
| 344 | this.fault = typeof build === "string" ? build : ""; | |
| 345 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 346 | } else if (isWorkflowPath(this.path)) { | |
| 347 | const flow = workflowTable(new TextDecoder().decode(source)); | |
| 348 | this.table = typeof flow === "string" ? null : flow; | |
| 349 | this.fault = typeof flow === "string" ? flow : ""; | |
| 350 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 351 | } else if (isSqlPath(this.path)) { | |
| 352 | const schema = sqlTable(new TextDecoder().decode(source)); | |
| 353 | this.table = typeof schema === "string" ? null : schema; | |
| 354 | this.fault = typeof schema === "string" ? schema : ""; | |
| 355 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 356 | } else if (isGraphqlPath(this.path)) { | |
| 357 | const schema = graphqlTable(new TextDecoder().decode(source)); | |
| 358 | this.table = typeof schema === "string" ? null : schema; | |
| 359 | this.fault = typeof schema === "string" ? schema : ""; | |
| 360 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 361 | } else if (kindByName(this.path) === "mbox") { | |
| 362 | const mail = mboxTable(new TextDecoder().decode(source)); | |
| 363 | this.table = typeof mail === "string" ? null : mail; | |
| 364 | this.fault = typeof mail === "string" ? mail : ""; | |
| 365 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 366 | } else if (kindByName(this.path) === "proto") { | |
| 367 | const outline = protoTable(new TextDecoder().decode(source)); | |
| 368 | this.table = typeof outline === "string" ? null : outline; | |
| 369 | this.fault = typeof outline === "string" ? outline : ""; | |
| 370 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 371 | } else if (isJunitPath(this.path, source)) { | |
| 372 | const results = junitTable(new TextDecoder().decode(source)); | |
| 373 | this.table = typeof results === "string" ? null : results; | |
| 374 | this.fault = typeof results === "string" ? results : ""; | |
| 375 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 376 | } else if (isFeedPath(this.path, source)) { | |
| 377 | const feed = feedTable(new TextDecoder().decode(source)); | |
| 378 | this.table = typeof feed === "string" ? null : feed; | |
| 379 | this.fault = typeof feed === "string" ? feed : ""; | |
| 380 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 381 | } else if (["ini", "rtf", "xml"].includes(fileKind(this.path, source.subarray(0, 4096)))) { | |
| 382 | const kind = fileKind(this.path, source.subarray(0, 4096)); | |
| 383 | const made = kind === "ini" ? iniTable(this.path, source) : kind === "rtf" ? rtfTable(source) : xmlTable(source); | |
| 384 | this.table = typeof made === "string" ? null : made; | |
| 385 | this.fault = typeof made === "string" ? made : ""; | |
| 386 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 387 | } else if (fileKind(this.path, source.subarray(0, 4096)) === "pcd") { | |
| 388 | const cloud = pcdFacts(source); | |
| 389 | this.table = typeof cloud === "string" ? null : { header: ["Fact", "Value"], rows: cloud, more: 0, delimiter: ",", columns: 2 }; | |
| 390 | this.fault = typeof cloud === "string" ? cloud : ""; | |
| 391 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 392 | } else if (isGcodePath(this.path)) { | |
| 393 | this.table = gcodeTable(new TextDecoder().decode(source)); | |
| 394 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 395 | } else if (isStepPath(this.path)) { | |
| 396 | const part = stepTable(new TextDecoder().decode(source)); | |
| 397 | this.table = typeof part === "string" ? null : part; | |
| 398 | this.fault = typeof part === "string" ? part : ""; | |
| 399 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 400 | } else if (isIfcPath(this.path)) { | |
| 401 | const model = ifcTable(source); | |
| 402 | this.table = typeof model === "string" ? null : model; | |
| 403 | this.fault = typeof model === "string" ? model : ""; | |
| 404 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 405 | } else if (isGeoJsonPath(this.path)) { | |
| 406 | this.table = geoJsonTable(new TextDecoder().decode(source)); | |
| 407 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 408 | } else if (isKmlPath(this.path)) { | |
| 409 | this.table = kmlTable(new TextDecoder().decode(source)); | |
| 410 | if (this.table !== null) this.grid = layoutTable(this.table); | |
| 411 | } else if (isTablePath(this.path)) { | |
| 412 | // The decoded source, not `plain`: `expandTabs` has eaten every tab there. | |
| 413 | const delimiter = /\.tsv$/i.test(this.path) ? "\t" : undefined; | |
| 414 | this.table = parseCsv(new TextDecoder().decode(source), { delimiter }); | |
| 415 | // A re-read keeps the order only while its column is still in the header. | |
| 416 | if (this.order !== null && this.order.column >= this.table.header.length) this.order = null; | |
| 417 | this.grid = layoutTable(this.ordered(this.table)); | |
| 418 | } else if (kind?.table === undefined) this.table = null; | |
| 419 | // The rendered document is derived from the same text, so an edit, a | |
| 420 | // theme switch or a re-read has to throw it away with everything else. | |
| 421 | this.doc = []; | |
| 422 | this.docPlain = []; | |
| 423 | this.docWidth = 0; | |
| 424 | if (this.search.query !== "") this.findHits(); | |
| 425 | else this.hits = []; | |
| 426 | } | |
| 427 | ||
| 428 | findHits(): void { | |
| 429 | const q = this.search.query.toLowerCase(); | |
| 430 | const lines = this.body; | |
| 431 | this.hits = | |
| 432 | q === "" | |
| 433 | ? [] | |
| 434 | : lines.flatMap((l, i) => (l.toLowerCase().includes(q) ? [i] : [])); | |
| 435 | this.hit = 0; | |
| 436 | if (this.hits[0] !== undefined) this.scroll.to(this.hits[0], lines.length); | |
| 437 | } | |
| 438 | ||
| 439 | step(delta: number): boolean { | |
| 440 | if (this.hits.length === 0) return false; | |
| 441 | this.hit = (this.hit + delta + this.hits.length) % this.hits.length; | |
| 442 | this.scroll.to(this.hits[this.hit]!, this.body.length); | |
| 443 | return true; | |
| 444 | } | |
| 445 | } | |
| 446 | ||
| 447 | /** One blob, as the workspace keeps it: text, a picture, or a reason. */ | |
| 448 | export interface CacheEntry { | |
| 449 | readonly note: string; | |
| 450 | /** The note's heading; "Not shown" unless the file is something we name. */ | |
| 451 | readonly noteTitle: string; | |
| 452 | /** A last line under the note: where to get the file. */ | |
| 453 | readonly noteDetail: string; | |
| 454 | readonly cut?: string; | |
| 455 | /** Why the file is plain source though its name says otherwise; stands above the text. */ | |
| 456 | readonly why?: string; | |
| 457 | readonly raw: Uint8Array | null; | |
| 458 | readonly picture: Uint8Array | null; | |
| 459 | readonly sheet: Table | null; | |
| 460 | readonly db: Uint8Array | null; | |
| 461 | readonly big?: { readonly prefix: Uint8Array; readonly size: number }; | |
| 462 | /** | |
| 463 | * The blob read (`null`: none there), sent back as `EditFile.was` so a save over a newer change | |
| 464 | * refuses. | |
| 465 | */ | |
| 466 | readonly opened?: string | null; | |
| 467 | } |
src/tui/screens/workspace_tables.ts added +548
| @@ -0,0 +1,548 @@ | ||
| 1 | /** | |
| 2 | * Files that read as a table: each path test (`isXPath`) and the parse that turns the source into | |
| 3 | * rows (`xTable`). Split out of the workspace screen, which only asks which table a file is. | |
| 4 | */ | |
| 5 | import { fileKind, kindByName, RENDER_CAP } from "../../web/render/kinds.ts"; | |
| 6 | import { type Table } from "../../text/csv.ts"; | |
| 7 | import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts"; | |
| 8 | import { gcodeFacts, parseGcode } from "../../web/render/gcode.ts"; | |
| 9 | import { ifcFacts, ifcTreeRows, readIfc, typeWords } from "../../text/ifc.ts"; | |
| 10 | import { readStep, stepFacts } from "../../web/render/step.ts"; | |
| 11 | import { parseOtio } from "../../web/render/otio.ts"; | |
| 12 | import { parseEdl } from "../../web/render/edl.ts"; | |
| 13 | import { ROW_CAP as TIMELINE_ROW_CAP } from "../../web/render/timeline-table.ts"; | |
| 14 | import { parseHar, ROW_CAP as HAR_ROW_CAP, duration as harDuration } from "../../web/render/har.ts"; | |
| 15 | import { gpxFacts, parseGpx } from "../../web/render/gpx.ts"; | |
| 16 | import { CASE_CAP, parseJunit } from "../../web/render/junit.ts"; | |
| 17 | import { nest, parseEntries } from "../../web/render/feed-xml.ts"; | |
| 18 | import { parseOpenApi } from "../../web/render/openapi.ts"; | |
| 19 | import { parseDockerfile } from "../../web/render/dockerfile.ts"; | |
| 20 | import { parseWorkflow } from "../../web/render/workflow.ts"; | |
| 21 | import { parseGraphql } from "../../web/render/graphql.ts"; | |
| 22 | import { parseMbox } from "../../web/render/mbox.ts"; | |
| 23 | import { parseProto } from "../../web/render/proto.ts"; | |
| 24 | import { parseIni } from "../../web/render/ini.ts"; | |
| 25 | import { parseRtf } from "../../web/render/rtf.ts"; | |
| 26 | import { parseXml, type XmlNode } from "../../web/render/xml.ts"; | |
| 27 | import { parseSql } from "../../web/render/sql.ts"; | |
| 28 | import { RESULT_CAP, parseSarif } from "../../web/render/sarif.ts"; | |
| 29 | import { RECORD_CAP, parseLcov, worstFirst, type Ratio } from "../../web/render/lcov.ts"; | |
| 30 | import { EVENT_CAP, parseIcs } from "../../web/render/ics.ts"; | |
| 31 | import { fileSize } from "../../web/ui.ts"; | |
| 32 | import { parseEml } from "../../web/render/eml-parse.ts"; | |
| 33 | import { parsePackage, ROW_CAP as PKG_ROW_CAP } from "../../web/render/package-json.ts"; | |
| 34 | import { parseEnv, ROW_CAP as ENV_ROW_CAP } from "../../web/render/env.ts"; | |
| 35 | import { CARD_CAP, parseVcf } from "../../web/render/vcf-parse.ts"; | |
| 36 | import { CUE_CAP, parseSubtitles } from "../../web/render/subtitles.ts"; | |
| 37 | import { card } from "../ui/widgets.ts"; | |
| 38 | ||
| 39 | export function isTablePath(path: string): boolean { | |
| 40 | return /\.[ct]sv$/i.test(path); | |
| 41 | } | |
| 42 | ||
| 43 | /** `.srt` and `.vtt`: a transcript, drawn as the same two-column table. */ | |
| 44 | export function isSubtitlePath(path: string): boolean { | |
| 45 | return /\.(srt|vtt)$/i.test(path); | |
| 46 | } | |
| 47 | ||
| 48 | /** The cues of a subtitle file as a table: start time, text. Shares the web's parser. */ | |
| 49 | export function subtitleTable(source: string): { table: Table; unread: number } { | |
| 50 | const { cues, failures } = parseSubtitles(source); | |
| 51 | const shown = cues.slice(0, CUE_CAP); | |
| 52 | return { | |
| 53 | unread: failures.length, | |
| 54 | table: { | |
| 55 | header: ["Start", "Text"], | |
| 56 | rows: shown.map((c) => [c.start, c.text]), | |
| 57 | more: cues.length - shown.length, | |
| 58 | delimiter: ",", | |
| 59 | columns: 2, | |
| 60 | }, | |
| 61 | }; | |
| 62 | } | |
| 63 | ||
| 64 | /** `.ics`: a calendar, drawn as a table of its events. */ | |
| 65 | export function isIcsPath(path: string): boolean { | |
| 66 | return /\.ics$/i.test(path); | |
| 67 | } | |
| 68 | ||
| 69 | /** | |
| 70 | * The events of a calendar as a table; null when the file is not a calendar. Shares the web's | |
| 71 | * parser. | |
| 72 | */ | |
| 73 | export function icsTable(source: string): { table: Table; unread: number } | null { | |
| 74 | const cal = parseIcs(source); | |
| 75 | if ("error" in cal) return null; | |
| 76 | const shown = cal.events.slice(0, EVENT_CAP); | |
| 77 | return { | |
| 78 | unread: cal.skipped, | |
| 79 | table: { | |
| 80 | header: ["Start", "End", "Summary", "Location"], | |
| 81 | rows: shown.map((e) => [e.start, e.end, e.summary, e.location]), | |
| 82 | more: cal.events.length - shown.length, | |
| 83 | delimiter: ",", | |
| 84 | columns: 4, | |
| 85 | }, | |
| 86 | }; | |
| 87 | } | |
| 88 | ||
| 89 | /** `.vcf` and `.vcard`: contacts, drawn as a table of people. */ | |
| 90 | export function isVcfPath(path: string): boolean { | |
| 91 | return /\.(vcf|vcard)$/i.test(path); | |
| 92 | } | |
| 93 | ||
| 94 | /** | |
| 95 | * The cards of a contacts file as a table; null when the file is not one. Shares the web's parser. | |
| 96 | */ | |
| 97 | export function vcfTable(source: string): Table | null { | |
| 98 | const parsed = parseVcf(source); | |
| 99 | if ("error" in parsed || parsed.total === 0) return null; | |
| 100 | const shown = parsed.cards.slice(0, CARD_CAP); | |
| 101 | return { | |
| 102 | header: ["Name", "Organisation", "Email", "Phone"], | |
| 103 | rows: shown.map((c) => c.malformed ? [`(${c.name})`, "—", "—", "—"] : [c.name, c.org, c.emails.join(", "), c.phones.join(", ")]), | |
| 104 | more: parsed.total - shown.length, | |
| 105 | delimiter: ",", | |
| 106 | columns: 4, | |
| 107 | }; | |
| 108 | } | |
| 109 | ||
| 110 | /** | |
| 111 | * The variables of a `.env.example` as a table; null when it holds none. Shares the web's parser. | |
| 112 | */ | |
| 113 | export function envTable(source: string): Table | null { | |
| 114 | const doc = parseEnv(source); | |
| 115 | if (doc.total === 0) return null; | |
| 116 | const dash = (v: string): string => (v === "" ? "—" : v); | |
| 117 | const rows: string[][] = []; | |
| 118 | let last = ""; | |
| 119 | for (const r of doc.rows.slice(0, ENV_ROW_CAP)) { | |
| 120 | if (r.group !== "" && r.group !== last) rows.push([`# ${r.group}`, "", ""]); | |
| 121 | last = r.group; | |
| 122 | rows.push([r.name, dash(r.value), dash(r.comment)]); | |
| 123 | } | |
| 124 | return { header: ["Name", "Example", "Comment"], rows, more: doc.total - doc.rows.length, delimiter: ",", columns: 3 }; | |
| 125 | } | |
| 126 | ||
| 127 | /** | |
| 128 | * A `package.json` as Section/Name/Value rows; null when it is not a JSON object. Shares the web's | |
| 129 | * parser. | |
| 130 | */ | |
| 131 | export function packageTable(source: string): Table | null { | |
| 132 | const doc = parsePackage(source); | |
| 133 | if (doc === undefined) return null; | |
| 134 | const rows: string[][] = []; | |
| 135 | if (doc.name !== "") rows.push(["package", doc.name, doc.version]); | |
| 136 | if (doc.facts.length > 0) rows.push(["facts", doc.facts.join(" · "), ""]); | |
| 137 | let more = 0; | |
| 138 | for (const s of doc.sections) { | |
| 139 | for (const [k, v] of s.rows.slice(0, PKG_ROW_CAP)) rows.push([s.title, k, v]); | |
| 140 | more += s.total - s.rows.length; | |
| 141 | } | |
| 142 | if (rows.length === 0) return null; | |
| 143 | return { header: ["Section", "Name", "Value"], rows, more, delimiter: ",", columns: 3 }; | |
| 144 | } | |
| 145 | ||
| 146 | /** `.eml`: a message, drawn as rows of its headers, body and attachments. */ | |
| 147 | export function isEmlPath(path: string): boolean { | |
| 148 | return /\.eml$/i.test(path); | |
| 149 | } | |
| 150 | ||
| 151 | export const EML_BODY_LINES = 200; | |
| 152 | ||
| 153 | /** The message as Field/Value rows; null when the file is not one. Shares the web's parser. */ | |
| 154 | export function emlTable(source: Uint8Array): Table | null { | |
| 155 | const m = parseEml(source); | |
| 156 | if ("error" in m) return null; | |
| 157 | const rows: string[][] = m.headers.map(([k, v]) => [k, v]); | |
| 158 | if (m.fromHtml) rows.push(["Note", "only an HTML part; tags stripped"]); | |
| 159 | const lines = m.body.split("\n"); | |
| 160 | for (const line of lines.slice(0, EML_BODY_LINES)) rows.push(["", line]); | |
| 161 | if (lines.length > EML_BODY_LINES) rows.push(["Note", `body cut: ${lines.length - EML_BODY_LINES} more lines`]); | |
| 162 | for (const a of m.attachments) rows.push(["Attachment", `${a.name} · ${a.type} · ${fileSize(a.size)}`]); | |
| 163 | return { header: ["Field", "Value"], rows, more: 0, delimiter: ",", columns: 2 }; | |
| 164 | } | |
| 165 | ||
| 166 | /** `.gpx`: a GPS track, drawn as a table of its facts (track, distance, climb, points). */ | |
| 167 | export function isGpxPath(path: string): boolean { | |
| 168 | return /\.gpx$/i.test(path); | |
| 169 | } | |
| 170 | ||
| 171 | /** The facts of a track as a table; null when the file is not a track. Shares the web's parser. */ | |
| 172 | export function gpxTable(source: string, path: string): Table | null { | |
| 173 | const parsed = parseGpx(source); | |
| 174 | if (parsed === undefined) return null; | |
| 175 | const rows = gpxFacts(parsed, path); | |
| 176 | // A track the scan stopped reading says so (the page's `CUT_NOTE`, short enough for a cell). | |
| 177 | if (parsed.cut === true) rows.push(["Read", "first part only"]); | |
| 178 | return { header: ["Fact", "Value"], rows, more: 0, delimiter: ",", columns: 2 }; | |
| 179 | } | |
| 180 | ||
| 181 | /** `.har`: a browser's captured session, drawn as a table of its requests. */ | |
| 182 | export function isHarPath(path: string): boolean { | |
| 183 | return /\.har$/i.test(path); | |
| 184 | } | |
| 185 | ||
| 186 | /** | |
| 187 | * The requests of a HAR as a table; null when the file is not one. Shares the web's parser and row | |
| 188 | * cap. | |
| 189 | */ | |
| 190 | export function harTable(source: string): Table | null { | |
| 191 | const parsed = parseHar(source); | |
| 192 | if ("error" in parsed || parsed.entries.length === 0) return null; | |
| 193 | const shown = parsed.entries.slice(0, HAR_ROW_CAP); | |
| 194 | return { | |
| 195 | header: ["Method", "Status", "URL", "Size", "Time"], | |
| 196 | rows: shown.map((e) => [ | |
| 197 | e.method, | |
| 198 | e.status === 0 ? "-" : String(e.status), | |
| 199 | e.url, | |
| 200 | e.bytes === undefined ? "-" : fileSize(e.bytes), | |
| 201 | harDuration(e.ms), | |
| 202 | ]), | |
| 203 | more: parsed.entries.length - shown.length, | |
| 204 | delimiter: ",", | |
| 205 | columns: 5, | |
| 206 | }; | |
| 207 | } | |
| 208 | ||
| 209 | /** `.otio` / `.edl`: a video-edit timeline, drawn as a cut list. */ | |
| 210 | export function isTimelinePath(path: string): boolean { | |
| 211 | const k = kindByName(path); | |
| 212 | return k === "otio" || k === "edl"; | |
| 213 | } | |
| 214 | ||
| 215 | /** | |
| 216 | * The clips of a timeline as one table, a track column first; the reason, as the page words | |
| 217 | * it, when it is not drawn. Shares the web's parsers and 1 MB cap. | |
| 218 | */ | |
| 219 | export function timelineTable(source: Uint8Array, path: string): Table | string { | |
| 220 | if (source.length > RENDER_CAP.otio) return "not drawn as a cut list: it is over 1 MB"; | |
| 221 | const text = new TextDecoder().decode(source); | |
| 222 | const parsed = kindByName(path) === "otio" ? parseOtio(text) : parseEdl(text); | |
| 223 | if ("error" in parsed) return `not drawn as a cut list: ${parsed.error}`; | |
| 224 | const all = parsed.timeline.tracks.flatMap((t) => t.cuts.map((c, i) => [t.name, String(i + 1), c.name, c.source, c.in, c.out, c.duration])); | |
| 225 | const rows = all.slice(0, TIMELINE_ROW_CAP); | |
| 226 | return { header: ["Track", "#", "Clip", "Source", "In", "Out", "Duration"], rows, more: all.length - rows.length, delimiter: ",", columns: 7 }; | |
| 227 | } | |
| 228 | ||
| 229 | /** `.sarif`: a scanner's findings, drawn as a table of level, rule, location and message. */ | |
| 230 | export function isSarifPath(path: string): boolean { | |
| 231 | return /\.sarif$/i.test(path); | |
| 232 | } | |
| 233 | ||
| 234 | /** | |
| 235 | * The findings of a SARIF file as a table, tool by tool; the reason, as the page words it, when it | |
| 236 | * is not SARIF. Shares the web's parser. | |
| 237 | */ | |
| 238 | export function sarifTable(source: string): Table | string { | |
| 239 | const parsed = parseSarif(source); | |
| 240 | if ("error" in parsed) return `not drawn as findings: ${parsed.error}`; | |
| 241 | const all = parsed.runs.flatMap((r) => | |
| 242 | r.results.map((f) => [f.level, f.rule, f.file === "" ? "-" : f.line > 0 ? `${f.file}:${f.line}` : f.file, f.message.replace(/\s+/g, " "), r.tool]), | |
| 243 | ); | |
| 244 | const rows = all.slice(0, RESULT_CAP); | |
| 245 | return { header: ["Level", "Rule", "Location", "Message", "Tool"], rows, more: all.length - rows.length, delimiter: ",", columns: 5 }; | |
| 246 | } | |
| 247 | ||
| 248 | /** | |
| 249 | * `lcov.info` / `.lcov`: a coverage tracefile, drawn as a table per source file, worst line | |
| 250 | * coverage first. | |
| 251 | */ | |
| 252 | export function isLcovPath(path: string): boolean { | |
| 253 | return kindByName(path) === "lcov"; | |
| 254 | } | |
| 255 | ||
| 256 | /** | |
| 257 | * The coverage of an lcov file as a table; the reason, as the page words it, when it is not lcov. | |
| 258 | * Shares the web's parser. | |
| 259 | */ | |
| 260 | export function lcovTable(source: string): Table | string { | |
| 261 | const parsed = parseLcov(source); | |
| 262 | if ("error" in parsed) return `not drawn as coverage: ${parsed.error}`; | |
| 263 | const pct = (r: Ratio | undefined): string => (r === undefined || r.found === 0 ? "-" : `${r.hit}/${r.found} ${(Math.floor((r.hit / r.found) * 1000) / 10).toFixed(1)}%`); | |
| 264 | const sorted = worstFirst(parsed.records); | |
| 265 | const rows = sorted.slice(0, RECORD_CAP).map((r) => [r.file, pct(r.lines), pct(r.functions), pct(r.branches)]); | |
| 266 | return { header: ["File", "Lines", "Functions", "Branches"], rows, more: sorted.length - rows.length, delimiter: ",", columns: 4 }; | |
| 267 | } | |
| 268 | ||
| 269 | /** An OpenAPI document by file name; whether its content is one is `openapiTable`'s to say. */ | |
| 270 | export function isOpenApiPath(path: string): boolean { | |
| 271 | return kindByName(path) === "openapi"; | |
| 272 | } | |
| 273 | ||
| 274 | /** | |
| 275 | * The operations of an OpenAPI document as a table, tag by tag; null when the file is not one, | |
| 276 | * the reason when it is but cannot be drawn. Shares the web's parser. | |
| 277 | */ | |
| 278 | export function openapiTable(text: string, path: string): Table | string | null { | |
| 279 | const parsed = parseOpenApi(text, path); | |
| 280 | if (parsed === "not") return null; | |
| 281 | if ("error" in parsed) return `not drawn as an API: ${parsed.error}`; | |
| 282 | const rows = parsed.groups.flatMap((g) => g.ops.map((o) => [g.tag === "" ? "-" : g.tag, o.method, o.path, o.deprecated ? `${o.summary} (deprecated)`.trim() : o.summary])); | |
| 283 | return { header: ["Tag", "Method", "Path", "Summary"], rows, more: parsed.more, delimiter: ",", columns: 4 }; | |
| 284 | } | |
| 285 | ||
| 286 | /** A Dockerfile by file name. */ | |
| 287 | export function isDockerfilePath(path: string): boolean { | |
| 288 | return kindByName(path) === "dockerfile"; | |
| 289 | } | |
| 290 | ||
| 291 | /** | |
| 292 | * A Dockerfile as a table: per stage, its ports and ENV names, then one row per instruction; | |
| 293 | * the web's reason when it is not drawn. Shares the web's parser. | |
| 294 | */ | |
| 295 | export function dockerfileTable(source: string): Table | string { | |
| 296 | const parsed = parseDockerfile(source); | |
| 297 | if ("error" in parsed) return `not drawn as a build: ${parsed.error}`; | |
| 298 | const rows: string[][] = []; | |
| 299 | for (const s of parsed.stages) { | |
| 300 | const title = s.image === "" ? "(before the first stage)" : `${s.image}${s.name === "" ? "" : ` as ${s.name}`}`; | |
| 301 | rows.push([title, "FROM", s.image]); | |
| 302 | if (s.ports.length > 0) rows.push([title, "EXPOSE", s.ports.join(" ")]); | |
| 303 | if (s.env.length > 0) rows.push([title, "ENV", s.env.join(" ")]); | |
| 304 | for (const r of s.rows) rows.push([title, r.keyword, r.args.replace(/\s+/g, " ")]); | |
| 305 | } | |
| 306 | return { header: ["Stage", "Instruction", "Arguments"], rows, more: parsed.total - parsed.shown, delimiter: ",", columns: 3 }; | |
| 307 | } | |
| 308 | ||
| 309 | /** A GitHub Actions workflow by file name. */ | |
| 310 | export function isWorkflowPath(path: string): boolean { | |
| 311 | return kindByName(path) === "workflow"; | |
| 312 | } | |
| 313 | ||
| 314 | /** | |
| 315 | * A workflow as a table: the triggers, then per job its runner, needs and matrix, then one row | |
| 316 | * per step; the web's reason when it is not drawn. Shares the web's parser. | |
| 317 | */ | |
| 318 | export function workflowTable(source: string): Table | string { | |
| 319 | const parsed = parseWorkflow(source); | |
| 320 | if ("error" in parsed) return `not drawn as a workflow: ${parsed.error}`; | |
| 321 | const rows: string[][] = [["-", "on", parsed.triggers.join(" ")]]; | |
| 322 | let more = parsed.jobsTotal - parsed.jobs.length; | |
| 323 | for (const j of parsed.jobs) { | |
| 324 | if (j.runsOn !== "") rows.push([j.id, "runs-on", j.runsOn]); | |
| 325 | if (j.needs.length > 0) rows.push([j.id, "needs", j.needs.join(" ")]); | |
| 326 | if (j.matrix.length > 0) rows.push([j.id, "matrix", j.matrix.join("; ")]); | |
| 327 | for (const s of j.steps) rows.push([j.id, s.kind === "" ? "step" : s.kind, [s.name, s.does].filter((t) => t !== "").join(": ").replace(/\s+/g, " ")]); | |
| 328 | more += j.stepsTotal - j.steps.length; | |
| 329 | } | |
| 330 | return { header: ["Job", "Kind", "Value"], rows, more, delimiter: ",", columns: 3 }; | |
| 331 | } | |
| 332 | ||
| 333 | /** A `.sql` file by name. */ | |
| 334 | export function isSqlPath(path: string): boolean { | |
| 335 | return kindByName(path) === "sql"; | |
| 336 | } | |
| 337 | ||
| 338 | /** | |
| 339 | * A SQL file as a table: a row per column of each CREATE TABLE, one row per other statement; the | |
| 340 | * reason when it is not drawn. Shares the web's parser. | |
| 341 | */ | |
| 342 | export function sqlTable(source: string): Table | string { | |
| 343 | const doc = parseSql(source); | |
| 344 | if (doc === null) return "not drawn as a schema: this file holds no SQL statements to draw"; | |
| 345 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 346 | const rows = doc.statements.flatMap((s) => | |
| 347 | s.kind === "other" | |
| 348 | ? [["-", s.line, "-", "-", "-", "-"]] | |
| 349 | : s.columns.map((c) => [s.name, c.name, dash(c.type), c.notNull ? "NOT NULL" : "-", c.primaryKey ? "PRIMARY KEY" : "-", dash(c.default)]), | |
| 350 | ); | |
| 351 | return { header: ["Table", "Column", "Type", "Null", "Key", "Default"], rows, more: doc.total - doc.statements.length, delimiter: ",", columns: 6 }; | |
| 352 | } | |
| 353 | ||
| 354 | /** A `.graphql` or `.gql` file by name. */ | |
| 355 | export function isGraphqlPath(path: string): boolean { | |
| 356 | return kindByName(path) === "graphql"; | |
| 357 | } | |
| 358 | ||
| 359 | /** | |
| 360 | * A GraphQL schema as a table: a row per field or enum value of each block (roots first), one row | |
| 361 | * per other definition; the reason when it is not drawn. Shares the web's parser. | |
| 362 | */ | |
| 363 | export function graphqlTable(source: string): Table | string { | |
| 364 | const doc = parseGraphql(source); | |
| 365 | if (doc === null) return "not drawn as a schema: this file holds no type, input, interface or enum to draw"; | |
| 366 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 367 | const rows = doc.blocks.flatMap((b) => | |
| 368 | b.kind === "other" | |
| 369 | ? [["-", b.text, "-", "-", "-"]] | |
| 370 | : [ | |
| 371 | ...(b.header === "" ? [] : [[`${b.extend ? "extend " : ""}${b.kind} ${b.name}`, "-", "-", "-", b.header]]), | |
| 372 | ...b.fields.map((f) => [`${b.extend ? "extend " : ""}${b.kind} ${b.name}`, f.name, dash(f.args), dash(f.type), dash(f.note)]), | |
| 373 | ...(b.fields.length === 0 && b.header === "" ? [[`${b.kind} ${b.name}`, "-", "-", "-", "-"]] : []), | |
| 374 | ], | |
| 375 | ); | |
| 376 | return { header: ["Block", "Field", "Arguments", "Type", "Directives"], rows, more: doc.total - doc.blocks.length, delimiter: ",", columns: 5 }; | |
| 377 | } | |
| 378 | ||
| 379 | /** | |
| 380 | * A mailbox as a table: a row per message (first 200), the rest counted. Shares the web's parser. | |
| 381 | */ | |
| 382 | export function mboxTable(source: string): Table | string { | |
| 383 | const doc = parseMbox(source); | |
| 384 | if (doc === null) return "not drawn as a mailbox: this file does not start with a `From ` line"; | |
| 385 | const dash = (v: string): string => (v === "" ? "-" : v); | |
| 386 | const rows = doc.messages.map((m) => [dash(m.from), dash(m.subject), dash(m.date)]); | |
| 387 | return { header: ["From", "Subject", "Date"], rows, more: doc.total - doc.messages.length, delimiter: ",", columns: 3 }; | |
| 388 | } | |
| 389 | ||
| 390 | /** A .proto file as a table: a row per field, enum value or rpc. Shares the web's parser. */ | |
| 391 | export function protoTable(source: string): Table | string { | |
| 392 | const doc = parseProto(source); | |
| 393 | if (doc === null) return "not drawn as an outline: this file holds no message, enum or service"; | |
| 394 | const rows = doc.blocks.flatMap((b) => { | |
| 395 | const at = `${b.kind} ${b.name}`; | |
| 396 | if (b.rows.length === 0) return [[at, "-", "-", "-"]]; | |
| 397 | return b.rows.map((r) => | |
| 398 | b.kind === "message" | |
| 399 | ? [at, r.name, `${r.a === "" ? "" : `${r.a} `}${r.b}`, r.c] | |
| 400 | : b.kind === "enum" | |
| 401 | ? [at, r.name, "-", r.b] | |
| 402 | : [at, r.name, `${r.a} -> ${r.b}`, "-"], | |
| 403 | ); | |
| 404 | }); | |
| 405 | return { header: ["Block", "Name", "Type", "Number"], rows, more: doc.total - doc.blocks.length, delimiter: ",", columns: 4 }; | |
| 406 | } | |
| 407 | ||
| 408 | /** Settings as a table: a row per key, its section beside it. Shares the web's parser. */ | |
| 409 | export function iniTable(path: string, source: Uint8Array): Table | string { | |
| 410 | if (source.length > RENDER_CAP.ini) return "not drawn as settings: it is over 1 MB"; | |
| 411 | const doc = parseIni(new TextDecoder().decode(source), /\.properties$/i.test(path)); | |
| 412 | if (doc === null) return "not drawn as settings: this file holds no setting"; | |
| 413 | const rows = doc.sections.flatMap((sec) => sec.rows.map((r) => [sec.name === "" ? "-" : sec.name, r.key, r.value])); | |
| 414 | return { header: ["Section", "Key", "Value"], rows, more: doc.total - rows.length, delimiter: ",", columns: 3 }; | |
| 415 | } | |
| 416 | ||
| 417 | /** A rich text file as a table of its paragraphs. Shares the web's parser. */ | |
| 418 | export function rtfTable(source: Uint8Array): Table | string { | |
| 419 | if (source.length > RENDER_CAP.rtf) return "not drawn as text: it is over 5 MB"; | |
| 420 | const doc = parseRtf(new TextDecoder("latin1").decode(source)); | |
| 421 | if (doc === null) return "not drawn as rich text: this file does not start with `{\\rtf`"; | |
| 422 | const rows = doc.paragraphs.filter((p) => p.trim() !== "").map((p) => [p]); | |
| 423 | if (rows.length === 0) return "this document holds no text"; | |
| 424 | return { header: ["Text"], rows, more: doc.truncated ? 1 : 0, delimiter: ",", columns: 1 }; | |
| 425 | } | |
| 426 | ||
| 427 | /** | |
| 428 | * An XML file as a table: a row per element in document order, indented by depth. Shares the web's | |
| 429 | * parser. | |
| 430 | */ | |
| 431 | export function xmlTable(source: Uint8Array): Table | string { | |
| 432 | if (source.length > RENDER_CAP.xml) return "not drawn as a tree: it is over 5 MB"; | |
| 433 | const doc = parseXml(new TextDecoder().decode(source)); | |
| 434 | if (doc === null) return "not drawn as a tree: this file holds no XML element"; | |
| 435 | const rows: string[][] = []; | |
| 436 | const walk = (n: XmlNode, depth: number): void => { | |
| 437 | rows.push([`${" ".repeat(depth)}${n.name}`, n.attrs.map(([k, v]) => `${k}="${v}"`).join(" "), n.text]); | |
| 438 | for (const c of n.children) walk(c, depth + 1); | |
| 439 | }; | |
| 440 | walk(doc.root, 0); | |
| 441 | return { header: ["Element", "Attributes", "Text"], rows, more: doc.total - rows.length, delimiter: ",", columns: 3 }; | |
| 442 | } | |
| 443 | ||
| 444 | /** A JUnit report, by the web's own rule (file name, or root element). */ | |
| 445 | export function isJunitPath(path: string, source: Uint8Array): boolean { | |
| 446 | return /\.xml$/i.test(path) && fileKind(path, source.subarray(0, 4096)) === "junit"; | |
| 447 | } | |
| 448 | ||
| 449 | /** | |
| 450 | * A JUnit report as a table: a totals row, then each failing case with its message; the reason when | |
| 451 | * it is not drawn. Shares the web's parser. | |
| 452 | */ | |
| 453 | export function junitTable(source: string): Table | string { | |
| 454 | const parsed = parseJunit(source); | |
| 455 | if ("error" in parsed) return `not drawn as test results: ${parsed.error}`; | |
| 456 | const t = parsed.totals; | |
| 457 | const bad = parsed.suites.flatMap((s) => | |
| 458 | s.cases.filter((c) => c.status === "failed" || c.status === "error").map((c) => [c.status === "error" ? "error" : "failed", (c.classname === "" ? c.name : `${c.classname} › ${c.name}`) || "(unnamed)", c.message.replace(/\s+/g, " ")]), | |
| 459 | ); | |
| 460 | const rows = [["total", `${t.tests} tests`, `${t.failures + t.errors} of ${t.tests} tests fail · ${t.skipped} skipped`], ...bad.slice(0, CASE_CAP)]; | |
| 461 | return { header: ["Result", "Case", "Message"], rows, more: bad.length - Math.min(bad.length, CASE_CAP), delimiter: ",", columns: 3 }; | |
| 462 | } | |
| 463 | ||
| 464 | /** | |
| 465 | * An OPML or RSS/Atom/RDF file, by the web's own rule (extension, or the root element of `.xml`). | |
| 466 | */ | |
| 467 | export function isFeedPath(path: string, source: Uint8Array): boolean { | |
| 468 | const k = fileKind(path, source.subarray(0, 4096)); | |
| 469 | return k === "opml" || k === "feed"; | |
| 470 | } | |
| 471 | ||
| 472 | /** | |
| 473 | * A subscription list or feed as a table of title, date and link; the reason when it is not drawn. | |
| 474 | * Shares the web's reader. | |
| 475 | */ | |
| 476 | export function feedTable(source: string): Table | string { | |
| 477 | const doc = parseEntries(source); | |
| 478 | if ("error" in doc) return `not drawn as a list of entries: ${doc.error}`; | |
| 479 | const rows = doc.entries.map((e) => [nest(e.depth) + (e.title || "(untitled)"), e.date, e.link]); | |
| 480 | return { header: ["Title", "Date", "Link"], rows, more: doc.total - doc.entries.length, delimiter: ",", columns: 3 }; | |
| 481 | } | |
| 482 | ||
| 483 | /** | |
| 484 | * `.gcode`: a sliced print, drawn as a table of its facts (layers, box, filament, time). Shares the | |
| 485 | * web's parser. | |
| 486 | */ | |
| 487 | export function isGcodePath(path: string): boolean { | |
| 488 | return /\.(gcode|gco)$/i.test(path); | |
| 489 | } | |
| 490 | ||
| 491 | export function gcodeTable(source: string): Table | null { | |
| 492 | const parsed = parseGcode(source); | |
| 493 | if (parsed === undefined) return null; | |
| 494 | return { header: ["Fact", "Value"], rows: gcodeFacts(parsed).map(([k, v]) => [k, v]), more: 0, delimiter: ",", columns: 2 }; | |
| 495 | } | |
| 496 | ||
| 497 | /** | |
| 498 | * `.step` / `.stp`: a CAD part, drawn as a table of its header facts, entity types and products. | |
| 499 | * Shares the web's reader. | |
| 500 | */ | |
| 501 | export function isStepPath(path: string): boolean { | |
| 502 | return /\.(step|stp)$/i.test(path); | |
| 503 | } | |
| 504 | ||
| 505 | export function stepTable(source: string): Table | string { | |
| 506 | const card = readStep(source); | |
| 507 | if ("error" in card) return `not drawn as a part card: ${card.error}`; | |
| 508 | const rows: string[][] = [ | |
| 509 | ...stepFacts(card).map(([k, v]) => [k, v]), | |
| 510 | ...card.types.map(([t, c]) => ["Type " + t, c.toLocaleString("en")]), | |
| 511 | ...card.products.map((p, i) => ["Product " + String(i + 1), p]), | |
| 512 | ]; | |
| 513 | return { header: ["Fact", "Value"], rows, more: card.moreProducts, delimiter: ",", columns: 2 }; | |
| 514 | } | |
| 515 | ||
| 516 | /** | |
| 517 | * `.ifc`: a building model, drawn as its header facts, spatial tree and element counts. Shares the | |
| 518 | * reader. | |
| 519 | */ | |
| 520 | export function isIfcPath(path: string): boolean { | |
| 521 | return /\.ifc$/i.test(path); | |
| 522 | } | |
| 523 | ||
| 524 | export function ifcTable(source: Uint8Array): Table | string { | |
| 525 | if (source.length > RENDER_CAP.ifc) return "not drawn as a building model: it is too large to summarise"; | |
| 526 | const m = readIfc(new TextDecoder().decode(source)); | |
| 527 | if ("error" in m) return `not drawn as a building model: ${m.error}`; | |
| 528 | const rows: string[][] = [ | |
| 529 | ...ifcFacts(m).map(([k, v]) => [k, v]), | |
| 530 | ...ifcTreeRows(m).map(([d, level, name]) => [`${" ".repeat(d)}${level}`, name === "" ? "no name" : name]), | |
| 531 | ...m.elements.map(([t, c]) => [typeWords(t), c.toLocaleString("en")]), | |
| 532 | ]; | |
| 533 | return { header: ["Fact", "Value"], rows, more: m.treeMore, delimiter: ",", columns: 2 }; | |
| 534 | } | |
| 535 | ||
| 536 | /** `.geojson`: features, drawn as a table of their geometry type and properties. */ | |
| 537 | export function isGeoJsonPath(path: string): boolean { | |
| 538 | return /\.geojson$/i.test(path); | |
| 539 | } | |
| 540 | ||
| 541 | /** The properties table of a GeoJSON file; null when it is not GeoJSON. Shares the web's parser. */ | |
| 542 | export function geoJsonTable(source: string): Table | null { | |
| 543 | const parsed = parseGeoJson(source); | |
| 544 | if (parsed === undefined) return null; | |
| 545 | const { header, rows } = propertyRows(parsed.features); | |
| 546 | return { header, rows, more: Math.max(0, parsed.features.length - rows.length), delimiter: ",", columns: header.length }; | |
| 547 | } | |
| 548 |
src/tui/screens/workspace_tree.ts added +59
| @@ -0,0 +1,59 @@ | ||
| 1 | /** | |
| 2 | * The explorer's model: a tree of names the cursor moves over, flattened to the rows on screen. | |
| 3 | */ | |
| 4 | import { type TreeEntry } from "../../git/read.ts"; | |
| 5 | ||
| 6 | // ---- the explorer's model ---- | |
| 7 | ||
| 8 | export interface Node { | |
| 9 | readonly path: string; | |
| 10 | readonly name: string; | |
| 11 | readonly type: "tree" | "blob"; | |
| 12 | readonly size: number; | |
| 13 | readonly depth: number; | |
| 14 | expanded: boolean; | |
| 15 | loading: boolean; | |
| 16 | /** Null until the directory has been listed once. */ | |
| 17 | children: Node[] | null; | |
| 18 | } | |
| 19 | ||
| 20 | export function nodeOf(entry: TreeEntry, parent: string, depth: number): Node { | |
| 21 | return { | |
| 22 | path: parent === "" ? entry.name : `${parent}/${entry.name}`, | |
| 23 | name: entry.name, | |
| 24 | type: entry.type === "tree" ? "tree" : "blob", | |
| 25 | size: entry.size, | |
| 26 | depth, | |
| 27 | expanded: false, | |
| 28 | loading: false, | |
| 29 | children: null, | |
| 30 | }; | |
| 31 | } | |
| 32 | ||
| 33 | /** Depth-first walk of what is currently expanded — the rows on screen. */ | |
| 34 | export function flatten(nodes: readonly Node[], out: Node[] = []): Node[] { | |
| 35 | for (const node of nodes) { | |
| 36 | out.push(node); | |
| 37 | if (node.expanded && node.children !== null) flatten(node.children, out); | |
| 38 | } | |
| 39 | return out; | |
| 40 | } | |
| 41 | ||
| 42 | export function findNode(nodes: readonly Node[], path: string): Node | undefined { | |
| 43 | for (const node of nodes) { | |
| 44 | if (node.path === path) return node; | |
| 45 | if (path.startsWith(`${node.path}/`) && node.children !== null) { | |
| 46 | const hit = findNode(node.children, path); | |
| 47 | if (hit !== undefined) return hit; | |
| 48 | } | |
| 49 | } | |
| 50 | return undefined; | |
| 51 | } | |
| 52 | ||
| 53 | /** The file a repository opens on: its README, else the first file there. */ | |
| 54 | export function landing(nodes: readonly Node[]): Node | undefined { | |
| 55 | const readme = nodes.find( | |
| 56 | (n) => n.type === "blob" && /^readme(\.|$)/i.test(n.name), | |
| 57 | ); | |
| 58 | return readme ?? nodes.find((n) => n.type === "blob"); | |
| 59 | } |
new above
offline