diff --git a/Panel.qml b/Panel.qml index 9e5e331..36cbce5 100644 --- a/Panel.qml +++ b/Panel.qml @@ -20,8 +20,12 @@ Panel { property var repos: [] property var worktrees: [] property string filterText: "" + property string sortMode: "recency" property int selectedIndex: 0 + property string selectedID: "" property bool cursorActive: false + property bool listing: true + property bool refreshQueued: false property string pendingPath: "" property bool repoFormOpen: false // In-flight Herdr routing: createForHerdr marks a `timber create` @@ -44,14 +48,26 @@ Panel { property int contentSpacing: Style.spacing.md property int rowHeight: Math.max(Style.space(44), Style.font.body + Style.spacing.rowPaddingX * 2) property int maxVisibleRows: 8 + readonly property int actionSize: Style.space(22) + readonly property int actionsWidth: root.actionSize * 3 + Style.space(4) * 2 + readonly property real popupWidth: { + var widest = 0 + for (var i = 0; i < displayModel.count; i++) { + var item = displayModel.get(i) + var nameWidth = rowFontMetrics.advanceWidth((item.kind === "create" ? "+ " : "") + item.value) + var badgesWidth = badgeFontMetrics.advanceWidth(item.statusText) + badgeFontMetrics.advanceWidth(item.todoText) + if (item.statusText && item.todoText) badgesWidth += Style.space(4) + widest = Math.max(widest, nameWidth + badgesWidth) + } + // Row insets, gaps, reserved actions, popup padding, and rendering slop. + var chrome = Style.space(48) + root.actionsWidth + panel.padding * 2 + return Math.max(Style.space(300), Math.min(widest + chrome, Style.space(600))) + } readonly property int visibleRows: Math.max(1, Math.min(displayModel.count, root.maxVisibleRows)) readonly property int listHeight: root.visibleRows * root.rowHeight + (root.visibleRows - 1) * Style.space(4) - // Same enumeration timber's own zsh completion uses: registered repo - // names plus a scan of the worktree root. `timber list` is avoided on - // purpose — its styled two-per-row table still emits ANSI under - // NO_COLOR and it enriches every row with git status, so one missing - // worktree directory fails the whole listing. + // The filesystem scan owns membership. Optional JSON enrichment supplies + // Status/Todo badges without hiding rows if timber list fails. readonly property string listScript: [ 'data_home=${XDG_DATA_HOME:-$HOME/.local/share};', 'root=${TIMBER_WORKTREE_ROOT:-$HOME/worktrees};', @@ -64,9 +80,12 @@ Panel { 'printf "%s\\n" "$repos" | while IFS= read -r repo; do [ -n "$repo" ] || continue;', ' for d in "$root/$repo"/**/"$repo"; do [ -e "$d/.git" ] || continue;', ' parent=${d%/*}; name=${parent#"$root/$repo"/}; [ -n "$name" ] || continue;', - ' printf "W\\t%s@%s\\t%s\\n" "$name" "$repo" "$d";', + ' stamp=$(git -C "$d" log -1 --format=%ct 2>/dev/null) || stamp=$(stat -c %Y -- "$d" 2>/dev/null);', + ' printf "W\\t%s@%s\\t%s\\t%s\\n" "$name" "$repo" "$d" "$stamp";', ' done;', - 'done' + 'done;', + 'details=$(timber list --json 2>/dev/null) && printf "D\\t%s\\n" "$details";', + 'exit 0' ].join("\n") function refresh() { @@ -74,14 +93,33 @@ Panel { root.armedRemoveValue = "" root.filterText = "" root.selectedIndex = 0 + root.selectedID = "" root.cursorActive = false root.syncFilterField() + root.refreshInBackground() + } + + function refreshInBackground() { + if (listProc.running) { + root.refreshQueued = true + return + } listProc.running = true } + function presentFromCache() { + root.filterText = "" + root.selectedIndex = 0 + root.selectedID = "" + root.cursorActive = false + root.rebuildDisplay() + root.syncFilterField() + } + function setFilter(nextFilter) { root.filterText = nextFilter root.selectedIndex = 0 + root.selectedID = "" root.cursorActive = true root.rebuildDisplay() root.syncFilterField() @@ -117,44 +155,22 @@ Panel { } function applyListOutput(text) { - var repos = [] - var worktrees = [] - var lines = String(text || "").split("\n") - for (var i = 0; i < lines.length; i++) { - var line = lines[i] - if (!line) continue - var parts = line.split("\t") - if (parts[0] === "R" && parts[1]) repos.push({ name: parts[1] }) - else if (parts[0] === "W" && parts[1] && parts[2]) { - var split = TimberModel.splitValue(parts[1]) - if (split) worktrees.push({ name: split.name, repo: split.repo, path: parts[2] }) - } - } - root.repos = repos - root.worktrees = worktrees + var listing = TimberModel.parseListing(text) + root.repos = listing.repos + root.worktrees = listing.worktrees root.rebuildDisplay() } function rebuildDisplay() { // Any list change (filter edit, fresh listing) disarms delete. root.armedRemoveValue = "" - var items = TimberModel.itemsForTerm(root.repos, root.worktrees, root.filterText) + var items = TimberModel.itemsForTerm(root.repos, root.worktrees, root.filterText, root.sortMode) displayModel.clear() for (var i = 0; i < items.length; i++) { - var path = "" - if (items[i].kind === "open") { - for (var j = 0; j < root.worktrees.length; j++) { - if (root.worktrees[j].name === items[i].name && root.worktrees[j].repo === items[i].repo) { - path = root.worktrees[j].path - break - } - } - } - displayModel.append({ kind: items[i].kind, name: items[i].name, repo: items[i].repo, value: items[i].value, path: path }) + displayModel.append(items[i]) } - if (displayModel.count === 0) root.selectedIndex = 0 - else if (root.selectedIndex >= displayModel.count) root.selectedIndex = displayModel.count - 1 - else if (root.selectedIndex < 0) root.selectedIndex = 0 + root.selectedIndex = TimberModel.selectedItemIndex(items, root.selectedID) + root.selectedID = items.length ? TimberModel.itemID(items[root.selectedIndex]) : "" Qt.callLater(function() { if (displayModel.count > 0) resultList.positionViewAtIndex(root.selectedIndex, ListView.Contain) }) @@ -267,13 +283,39 @@ Panel { onOpenedChanged: if (opened) { root.closeRepoForm() - root.refresh() + root.presentFromCache() + root.refreshInBackground() Qt.callLater(function() { filterField.forceActiveFocus() }) } // Moving selection to another row disarms a pending delete, so an // armed (red) icon can never trail behind navigation. - onSelectedIndexChanged: root.armedRemoveValue = "" + onSelectedIndexChanged: { + root.armedRemoveValue = "" + if (selectedIndex >= 0 && selectedIndex < displayModel.count) + root.selectedID = TimberModel.itemID(displayModel.get(selectedIndex)) + } + + Component.onCompleted: root.refreshInBackground() + + Timer { + interval: 60000 + running: true + repeat: true + onTriggered: if (!root.opened) root.refreshInBackground() + } + + FontMetrics { + id: rowFontMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.title + } + + FontMetrics { + id: badgeFontMetrics + font.family: root.fontFamily + font.pixelSize: Style.font.body + } ListModel { id: displayModel } @@ -376,12 +418,17 @@ Panel { id: listProc command: ["bash", "-lc", root.listScript] stdout: StdioCollector { + id: listStdout waitForEnd: true - onStreamFinished: root.applyListOutput(text) } onExited: function(code) { - if (code !== 0 && displayModel.count === 0) - root.notifyFailure("worktree list", "timber repo list exited " + code) + root.listing = false + if (code === 0) root.applyListOutput(listStdout.text) + else root.notifyFailure("worktree list", "filesystem scan exited " + code) + if (root.refreshQueued) { + root.refreshQueued = false + Qt.callLater(root.refreshInBackground) + } } } @@ -405,7 +452,7 @@ Panel { // The quickfilter owns typing, so it takes focus on open (with a // visible text cursor) instead of the bare key catcher. focusTarget: filterField - contentWidth: panel.fittedContentWidth(Style.space(400)) + contentWidth: panel.fittedContentWidth(root.popupWidth) contentHeight: panel.fittedContentHeight(panelColumn.implicitHeight, Style.space(560)) // Raw key handling instead of PanelKeyCatcher: the quickfilter is a @@ -553,6 +600,23 @@ Panel { } } + ButtonGroup { + anchors.horizontalCenter: parent.horizontalCenter + options: [ + { value: "recency", label: "Recency" }, + { value: "repo", label: "Repo" }, + { value: "worktree", label: "Worktree" } + ] + value: root.sortMode + focusable: false + foreground: root.foreground + fontFamily: root.fontFamily + onChanged: function(value) { + root.sortMode = value + root.rebuildDisplay() + } + } + // Form fronting `timber repo add [--name] [--alias]`. // Enter in any field submits; Tab walks the fields and buttons via // the normal focus chain (the key handler above stands aside while @@ -626,6 +690,13 @@ Panel { spacing: Style.space(4) boundsBehavior: Flickable.StopAtBounds + HoverHandler { + onHoveredChanged: if (!hovered) { + root.cursorActive = false + root.armedRemoveValue = "" + } + } + // Plain item instead of CursorSurface: selection is a slim // accent marker at the leading edge, not a full-row box. delegate: Item { @@ -634,6 +705,8 @@ Panel { required property string kind required property string value required property string path + required property string statusText + required property string todoText readonly property bool selected: root.cursorActive && index === root.selectedIndex @@ -656,14 +729,49 @@ Panel { textFormat: Text.PlainText anchors.fill: parent anchors.leftMargin: Style.space(12) - anchors.rightMargin: actionsRow.implicitWidth + Style.space(20) + anchors.rightMargin: badgesRow.implicitWidth + actionsRow.implicitWidth + Style.space(28) verticalAlignment: Text.AlignVCenter text: (row.kind === "create" ? "+ " : "") + row.value color: root.foreground opacity: row.kind === "create" && !row.selected ? 0.72 : 1.0 font.family: root.fontFamily font.pixelSize: Style.font.title - elide: Text.ElideRight + elide: Text.ElideMiddle + } + + Row { + id: badgesRow + anchors.right: actionsRow.left + anchors.rightMargin: Style.space(8) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(4) + + Text { + textFormat: Text.PlainText + text: row.statusText + visible: text !== "" + color: root.foreground + opacity: 0.7 + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + Text { + textFormat: Text.PlainText + text: row.todoText + visible: text !== "" + color: root.foreground + opacity: 0.7 + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + } + + HoverHandler { + onHoveredChanged: if (hovered) { + root.cursorActive = true + root.selectedIndex = row.index + } } MouseArea { @@ -688,32 +796,36 @@ Panel { // than opening Zed. Row { id: actionsRow - visible: row.selected + width: root.actionsWidth + opacity: row.selected ? 1 : 0.15 anchors.right: parent.right anchors.rightMargin: Style.space(8) anchors.verticalCenter: parent.verticalCenter spacing: Style.space(4) SvgActionButton { + size: root.actionSize iconSource: "zed.svg" tooltipText: row.kind === "open" ? "Open in Zed" : "Create and open in Zed" foreground: root.foreground fontFamily: root.fontFamily enabled: !createProc.running && !herdrProc.running - onClicked: root.openInZed(row.index) + onClicked: if (row.selected) root.openInZed(row.index) } SvgActionButton { + size: root.actionSize iconSource: "herdr.svg" tooltipText: row.kind === "open" ? "Open in Herdr" : "Create in Herdr" foreground: root.foreground fontFamily: root.fontFamily enabled: !createProc.running && !herdrProc.running - onClicked: root.openInHerdr(row.index) + onClicked: if (row.selected) root.openInHerdr(row.index) } PanelActionButton { - visible: row.kind === "open" + size: root.actionSize + opacity: row.kind === "open" ? 1 : 0 // nf-md-delete (U+F0159): the destructive-row glyph the // first-party bluetooth panel uses for Forget. // Monochrome until the first click arms it; red while @@ -722,8 +834,8 @@ Panel { tooltipText: (row.value === root.armedRemoveValue ? "Click again to remove " : "Remove ") + row.value foreground: row.value === root.armedRemoveValue ? Color.urgent : root.foreground fontFamily: root.fontFamily - enabled: !removeProc.running - onClicked: root.armOrRemoveIndex(row.index) + enabled: row.kind === "open" && !removeProc.running + onClicked: if (row.selected) root.armOrRemoveIndex(row.index) } } } @@ -733,7 +845,7 @@ Panel { textFormat: Text.PlainText visible: displayModel.count === 0 width: parent.width - text: root.worktrees.length === 0 ? "No worktrees yet — type name@repo to create one" : "No matches" + text: root.listing ? "Loading worktrees…" : (root.worktrees.length === 0 ? "No worktrees yet — type name@repo to create one" : "No matches") color: root.foreground opacity: 0.7 font.family: root.fontFamily diff --git a/README.md b/README.md index 7208a89..3a9eeb4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,8 @@ # omarchy-timber Omarchy overlay plugin that fronts [`timber`](https://github.com/nnutter/timber) -managed Git worktrees, mirroring `timber tui`: fuzzy-filter the existing -worktrees, type `name@repo` to create, `enter` to open in Zed, or use -the trailing Zed/Herdr logo icons to open in Zed or a Herdr space. +managed Git worktrees, with the shared features of [macos-timber](https://github.com/nnutter/macos-timber). +Fuzzy-filter the existing worktrees, type `name@repo` to create, press `enter` to open in Zed, or use the trailing Zed/Herdr icons to open in Zed or a Herdr space. ## Requirements @@ -28,12 +27,31 @@ overlay revision, disable and re-enable once so the entry moves from ## Use +The plugin loads worktrees at startup and refreshes once a minute while the panel is closed. +Opening shows the cached rows immediately, then refreshes without clearing the filter or changing the selected worktree. + Click the bar icon or run: ```bash omarchy-shell io.github.nnutter.omarchy-timber toggle ``` +The centered sort picker offers **Recency** (default), **Repo**, and **Worktree**. +Recency uses the newest commit timestamp, with directory modification time as a fallback. +Changing the sort preserves the selected row. + +Existing rows show the `timber ls` Status and Todo badges: + +- Status shows `merged`, `↑N`, `↓N`, or `error`, without the upstream suffix. +- Todo shows `done/total` only when checklist items exist. +- Missing or unreadable JSON details hide badges without hiding the worktree. + +The popup grows to fit names and badges within width and screen bounds. +Long names truncate in the middle so the repository remains visible. +Row actions remain dimmed when unselected. +Leaving the list disarms deletion and dims every row. +Arrow keys restore active selection. + Keys: the header is a quickfilter field — type to filter (`@` narrows to repos) with native cursor editing (`←` / `→`, `home` / `end`, `backspace`, `ctrl+u` to clear), `↓` / `↑` move, @@ -74,13 +92,18 @@ mise run test # TimberModel unit tests (runs check first) mise run install # test, then copy into ~/.config/omarchy/plugins and rescan ``` -`qmllint` cannot come from mise (Qt is not in the registry) and -quickshell ships as a system package, so validate `Timber.qml` by -summoning the installed plugin on a live Omarchy machine. +`qmllint` cannot come from mise because Qt is not in the registry. +The check task uses the system `qmllint` when available. +Quickshell also ships as a system package. +Validate `Panel.qml` on a live Omarchy machine to check rendering, keyboard navigation, mouse-leave behavior, scrolling, and screen bounds. ## Notes -Worktrees are enumerated the way timber's own zsh completion does -(`timber repo list -q` plus a scan of `$TIMBER_WORKTREE_ROOT`) rather -than parsing `timber list`, whose styled table still emits ANSI under -`NO_COLOR` and fails as a whole when one worktree directory is missing. +Worktrees are enumerated the way timber's own zsh completion does: `timber repo list -q` plus a scan of `$TIMBER_WORKTREE_ROOT`. +The filesystem scan owns membership. +`timber list --json` only enriches scanned rows with Status/Todo details. +Its failure does not invalidate the scan. + +Omarchy owns the bar, plugin enablement, and shell startup. +The macOS Quit menu, Open at Login toggle, app icon, and packaging have no plugin equivalent. +The Omarchy repository form retains its optional alias field. diff --git a/TimberModel.js b/TimberModel.js index 5e8f625..46621e2 100644 --- a/TimberModel.js +++ b/TimberModel.js @@ -6,6 +6,41 @@ // worktrees:[{ name: "feature/login", repo: "timber" }] // items: [{ kind: "open"|"create", name, repo, value: "name@repo" }] +// Parse the repository/worktree records produced by the filesystem scan. +function parseListing(text) { + var repos = [] + var worktrees = [] + var details = {} + var lines = String(text || "").split("\n") + for (var i = 0; i < lines.length; i++) { + var parts = lines[i].split("\t") + if (parts[0] === "D") { + try { + var rows = JSON.parse(lines[i].slice(2)) + if (Array.isArray(rows)) { + for (var j = 0; j < rows.length; j++) { + var row = rows[j] + if (row && typeof row.name === "string" && typeof row.repo === "string") + details["worktree:" + worktreeValue(row)] = row + } + } + } catch (error) { + // Optional enrichment must never invalidate the filesystem listing. + } + } else if (parts[0] === "R" && parts[1]) repos.push({ name: parts[1] }) + else if (parts[0] === "W" && parts[1] && parts[2]) { + var split = splitValue(parts[1]) + if (split) worktrees.push({ name: split.name, repo: split.repo, path: parts[2], lastCommitAt: Number(parts[3]) || 0 }) + } + } + for (var k = 0; k < worktrees.length; k++) { + var detail = details["worktree:" + worktreeValue(worktrees[k])] || {} + worktrees[k].statusText = listStatusText(detail) + worktrees[k].todoText = todoText(detail) + } + return { repos: repos, worktrees: worktrees } +} + // Case-insensitive fuzzy match: every char of term appears in order. function fuzzyMatch(term, target) { var t = String(term || "").toLowerCase() @@ -95,15 +130,46 @@ function filterWorktrees(term, worktrees) { return out } +// Mirror timber ls Status without its upstream suffix. +function listStatusText(detail) { + if (detail.statusError === true) return "error" + if (detail.merged === true) return "merged" + var parts = [] + if (typeof detail.ahead === "number" && detail.ahead > 0) parts.push("↑" + detail.ahead) + if (typeof detail.behind === "number" && detail.behind > 0) parts.push("↓" + detail.behind) + return parts.join(" ") +} + +function todoText(detail) { + if (typeof detail.todoTotal !== "number" || detail.todoTotal <= 0) return "" + var done = typeof detail.todoDone === "number" ? detail.todoDone : 0 + return done + "/" + detail.todoTotal +} + +function compareText(a, b) { + return a < b ? -1 : (a > b ? 1 : 0) +} + +// Sort a copy. Missing or tied commit dates fall back to name@repo. +function sortWorktrees(worktrees, mode) { + return worktrees.slice().sort(function(a, b) { + if (mode === "repo") return compareText(a.repo, b.repo) || compareText(a.name, b.name) + if (mode === "worktree") return compareText(a.name, b.name) || compareText(a.repo, b.repo) + var dateOrder = (b.lastCommitAt || 0) - (a.lastCommitAt || 0) + return dateOrder || compareText(worktreeValue(a), worktreeValue(b)) + }) +} + // Mirror wizardItemsForTerm: existing worktrees first, then one `create` // row per matching repo when the term is a qualified `name@repo`. -function itemsForTerm(repos, worktrees, term) { +function itemsForTerm(repos, worktrees, term, sort) { + worktrees = sortWorktrees(worktrees || [], sort || "recency") var t = String(term || "") var items = [] var ranks = filterWorktrees(t, worktrees || []) for (var i = 0; i < ranks.length; i++) { var w = (worktrees || [])[ranks[i].index] - items.push({ kind: "open", name: w.name, repo: w.repo, value: worktreeValue(w) }) + items.push({ kind: "open", name: w.name, repo: w.repo, value: worktreeValue(w), path: w.path || "", statusText: w.statusText || "", todoText: w.todoText || "" }) } var termParts = cutLast(t, "@") @@ -115,11 +181,24 @@ function itemsForTerm(repos, worktrees, term) { for (var k = 0; k < repoRanks.length; k++) { var repo = (repos || [])[repoRanks[k].index] if (hasWorktree(worktrees || [], termParts.before, repo.name)) continue - items.push({ kind: "create", name: termParts.before, repo: repo.name, value: termParts.before + "@" + repo.name }) + items.push({ kind: "create", name: termParts.before, repo: repo.name, value: termParts.before + "@" + repo.name, path: "", statusText: "", todoText: "" }) } return items } +// Kind distinguishes a create row from an existing worktree of the same name. +function itemID(item) { + return item.kind + ":" + item.value +} + +// Keep selection on the same row when a refresh changes its position. +function selectedItemIndex(items, selectedID) { + for (var i = 0; i < items.length; i++) { + if (itemID(items[i]) === selectedID) return i + } + return 0 +} + function splitValue(value) { var parts = cutLast(value, "@") if (!parts.qualified || !parts.before || !parts.after) return null diff --git a/tests/model.test.mjs b/tests/model.test.mjs index 5767b0d..52fc639 100644 --- a/tests/model.test.mjs +++ b/tests/model.test.mjs @@ -9,7 +9,7 @@ vm.createContext(sandbox); // TimberModel.js declares bare functions (QML import style), so export // them explicitly for the test context. vm.runInContext( - src + "\n;globalThis.__timberModel = { itemsForTerm, splitValue, repoAddArgs, createArgs, herdrSpaceArgs, armOrConfirmRemove };", + src + "\n;globalThis.__timberModel = { itemsForTerm, splitValue, repoAddArgs, createArgs, herdrSpaceArgs, armOrConfirmRemove, selectedItemIndex, parseListing };", sandbox, ); const { @@ -19,6 +19,8 @@ const { createArgs, herdrSpaceArgs, armOrConfirmRemove, + selectedItemIndex, + parseListing, } = sandbox.__timberModel; const repos = [{ name: "timber" }, { name: "persona" }]; @@ -36,23 +38,23 @@ const kinds = (items) => Array.from(items, (item) => item.kind); describe("itemsForTerm", () => { it("lists every worktree on an empty term", () => { assert.deepEqual(values(itemsForTerm(repos, worktrees, "")), [ + "alpha@persona", "alpha@timber", "beta@persona", - "alpha@persona", ]); }); it("fuzzy-filters on the worktree half", () => { assert.deepEqual(values(itemsForTerm(repos, worktrees, "alp")), [ - "alpha@timber", "alpha@persona", + "alpha@timber", ]); }); it("keeps every repo while the repo half is empty", () => { assert.deepEqual(values(itemsForTerm(repos, worktrees, "alpha@")), [ - "alpha@timber", "alpha@persona", + "alpha@timber", ]); }); @@ -81,6 +83,70 @@ describe("itemsForTerm", () => { }); }); +describe("Status and Todo enrichment", () => { + const scan = "R\ttimber\nW\talpha@timber\t/tmp/alpha\t100\n"; + const display = (json) => { + const listing = parseListing(scan + "D\t" + json + "\n"); + return itemsForTerm(listing.repos, listing.worktrees, ""); + }; + for (const [detail, status, todo] of [ + [{ ahead: 2, behind: 3, todoDone: 1, todoTotal: 4 }, "↑2 ↓3", "1/4"], + [{ merged: true, ahead: 2, todoDone: 4, todoTotal: 4 }, "merged", "4/4"], + [{ statusError: true, merged: true, ahead: 2 }, "error", ""], + [{ behind: 3, todoTotal: 2 }, "↓3", "0/2"], + [{ ahead: 0, behind: 0, todoTotal: 0 }, "", ""], + [{ ahead: "2", merged: "false", todoTotal: "4" }, "", ""], + ]) { + it(`renders ${JSON.stringify(detail)} as quiet or explicit badges`, () => { + const items = display(JSON.stringify([{ name: "alpha", repo: "timber", upstream: "origin/main", ...detail }])); + assert.equal(items[0].statusText, status); + assert.equal(items[0].todoText, todo); + assert.equal(items[0].path, "/tmp/alpha"); + }); + } + it("keeps scanned rows when enrichment is absent, malformed, or unrelated", () => { + for (const json of ["", "not JSON", "{}", "null", '[null, {"name":"ghost","repo":"timber","ahead":5}]']) { + const items = display(json); + assert.deepEqual(values(items), ["alpha@timber"]); + assert.equal(items[0].statusText, ""); + assert.equal(items[0].todoText, ""); + } + }); + it("never transfers badges to a create suggestion", () => { + const listing = parseListing(scan + 'D\t[{"name":"ghost","repo":"timber","ahead":5}]\n'); + const items = itemsForTerm(listing.repos, listing.worktrees, "ghost@timber"); + assert.deepEqual(kinds(items), ["create"]); + assert.equal(items[0].statusText, ""); + assert.equal(items[0].todoText, ""); + }); +}); + +describe("display sorting", () => { + const rows = [ + { name: "z", repo: "a", lastCommitAt: 200 }, + { name: "a", repo: "z", lastCommitAt: 100 }, + { name: "a", repo: "a", lastCommitAt: 200 }, + { name: "b", repo: "a" }, + ]; + for (const [mode, expected] of [ + [undefined, ["a@a", "z@a", "a@z", "b@a"]], + ["repo", ["a@a", "b@a", "z@a", "a@z"]], + ["worktree", ["a@a", "a@z", "b@a", "z@a"]], + ]) { + it(`orders filtered rows by ${mode || "recency by default"}`, () => { + assert.deepEqual(values(itemsForTerm([], rows, "@a", mode)), expected.filter(v => v.endsWith("@a"))); + assert.deepEqual(values(itemsForTerm([], rows, "", mode)), expected); + assert.equal(rows[0].name, "z", "sorting does not reorder the cache"); + }); + } + it("uses scan timestamps and tolerates old records without a date", () => { + const listing = parseListing("R\ttimber\nW\told@timber\t/tmp/old\nW\tnew@timber\t/tmp/new\t300\n"); + const items = itemsForTerm(listing.repos, listing.worktrees, ""); + assert.deepEqual(values(items), ["new@timber", "old@timber"]); + assert.equal(items[0].path, "/tmp/new"); + }); +}); + describe("repoAddArgs", () => { it("builds timber repo add argv with name and alias", () => { assert.deepEqual( @@ -176,6 +242,19 @@ describe("armOrConfirmRemove", () => { }); }); +describe("selection across refreshes", () => { + it("follows the selected worktree through insertion and reordering", () => { + const rows = [ + { kind: "open", value: "new@timber" }, + { kind: "create", value: "alpha@timber" }, + { kind: "open", value: "alpha@timber" }, + ]; + assert.equal(selectedItemIndex(rows, "open:alpha@timber"), 2); + assert.equal(selectedItemIndex(rows, "open:removed@timber"), 0); + assert.equal(selectedItemIndex([], "open:alpha@timber"), 0); + }); +}); + describe("splitValue", () => { it("splits on the last @ so slashes survive in names", () => { // Spread into this realm: splitValue returns a vm-context object.