diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db9d2aa..10ce8df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf - name: Install tsk run: | - curl -fsSL https://gettsk.sh/install.sh | TSK_VERSION=v0.13.0 sh + curl -fsSL https://gettsk.sh/install.sh | TSK_VERSION=v0.14.1 sh echo "$HOME/.local/bin" >> "$GITHUB_PATH" - run: tsk --version - run: cargo test --manifest-path src-tauri/Cargo.toml --test contract -- --ignored diff --git a/CHANGELOG.md b/CHANGELOG.md index 16f4a08..798c938 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- With tsk 0.14.0 or later, Rename… sets the tsk project title, and tskdeck shows the titles that tsk keeps, including ones set from the terminal board or by an agent. A refused name stays in the Rename Project sheet with tsk's reason. At launch, tskdeck moves the names it kept in its settings into tsk; a name that tsk refuses stays in the settings, and an alert lists it. With older tsk, tskdeck keeps the names in its settings as before. + ## [1.1.1] - 2026-11-06 ### Fixed diff --git a/README.md b/README.md index bbad077..1f9b7b9 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ tskdeck shows the board next to an always-visible sidebar of views, projects, th ## Requirements -- [tsk 0.13.0 or later](https://gettsk.sh/docs/install/) +- [tsk 0.13.0 or later](https://gettsk.sh/docs/install/). Project titles need tsk 0.14.0 or later. tskdeck finds `tsk` from the path set in settings, then the login shell's `PATH`, then the default install locations. It respects `TSK_STATE_DIR`. ## What works - Sidebar with Views (Desk, All projects), Projects, Threads and Assignees, each with a live task count. -- Project names: right-click a project in the sidebar and choose Rename… to give it a name tskdeck shows wherever the project appears. tsk keeps the project's path. +- Project names: right-click a project in the sidebar and choose Rename… to give it a name shown wherever the project appears. On tsk 0.14.0 or later the name is the tsk project title, so the terminal board and `tsk -p` use it too, and the names tskdeck kept in its settings move into tsk at launch. On older tsk, tskdeck keeps the name in its own settings. - Board with the NEEDS YOU, IN MOTION and ON DECK sections, plus group and sort controls. - Task view beside the board or as an overlay: title and notes edited in place, status, assignee and "runs after", steps, activity, and Done, Reply and Archive actions. - The blocked and review workflow: block and review cards, options, replies, approve and send back, and changing who a task waits on. Review checks are shown read-only. @@ -60,7 +60,7 @@ xattr -dr com.apple.quarantine /Applications/tskdeck.app ## Settings -tskdeck keeps its settings (open-task mode, keymap, path to `tsk`, update checks) in `settings.json` inside the app config directory for the identifier `com.s3rgiosan.tskdeck`: +tskdeck keeps its settings (open-task mode, keymap, path to `tsk`, update checks, and the project names not yet moved into tsk) in `settings.json` inside the app config directory for the identifier `com.s3rgiosan.tskdeck`: - macOS: `~/Library/Application Support/com.s3rgiosan.tskdeck/settings.json` - Linux: `$XDG_CONFIG_HOME/com.s3rgiosan.tskdeck/settings.json`, or `~/.config/com.s3rgiosan.tskdeck/settings.json` when `XDG_CONFIG_HOME` is unset @@ -89,7 +89,7 @@ npm test cargo test --manifest-path src-tauri/Cargo.toml ``` -The contract test runs the real `tsk` binary against a temporary store. It needs tsk 0.13.0 on `PATH`: +The contract test runs the real `tsk` binary against a temporary store. It needs tsk 0.14.0 or later on `PATH`: ```sh cargo test --manifest-path src-tauri/Cargo.toml --test contract -- --ignored diff --git a/package-lock.json b/package-lock.json index 26ee584..ab15462 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "tskdeck", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "tskdeck", - "version": "1.1.1", + "version": "1.2.0", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-dialog": "^2.8.4", diff --git a/package.json b/package.json index c3dfd13..540cdfb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tskdeck", "private": true, - "version": "1.1.1", + "version": "1.2.0", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 527c15e..452e14b 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4383,7 +4383,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tskdeck" -version = "1.1.1" +version = "1.2.0" dependencies = [ "async-trait", "dirs", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 436186a..a3d667f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tskdeck" -version = "1.1.1" +version = "1.2.0" description = "Unofficial desktop client for the tsk task board" authors = ["Sérgio Santos"] edition = "2024" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e4b70ef..f305f3d 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -12,7 +12,7 @@ use crate::tsk::args::{self, CaptureInput, EditInput, ListOptions, Scope, Status use crate::tsk::locate; use crate::tsk::model::{AddResult, TaskDetail, TaskRow}; use crate::tsk::runner::{Tsk, TskError}; -use crate::tsk::version::{MIN_TSK, parse_version}; +use crate::tsk::version::{MIN_TSK, PROJECT_TITLES_TSK, parse_version}; use crate::updates::{UPDATE_PROGRESS_EVENT, UpdateInfo, UpdateManager}; use crate::watch::StoreWatcher; @@ -33,6 +33,8 @@ pub struct TskInfo { pub version: String, pub supported: bool, pub minimum: String, + /// Whether this tsk keeps project titles. + pub project_titles: bool, } /// Finds the `tsk` binary from the user's setting, the login-shell `PATH` and the @@ -118,6 +120,7 @@ pub async fn tsk_info(state: State<'_, AppState>) -> Result { version: format!("{}.{}.{}", parsed.0, parsed.1, parsed.2), supported: parsed >= MIN_TSK, minimum: format!("{}.{}.{}", MIN_TSK.0, MIN_TSK.1, MIN_TSK.2), + project_titles: parsed >= PROJECT_TITLES_TSK, }) }) .await @@ -212,6 +215,20 @@ pub async fn set_archived( .await } +/// Shows the project at `path` under `title`, or under its folder name when `title` is `None`. +#[tauri::command] +pub async fn set_project_title( + state: State<'_, AppState>, + path: String, + title: Option, +) -> Result<(), TskError> { + with_tsk(&state, move |tsk| { + tsk.run(&args::project_title_args(&path, title.as_deref())) + .map(drop) + }) + .await +} + #[tauri::command] pub async fn get_settings(state: State<'_, AppState>) -> Result { let guard = state.settings.lock().map_err(|e| e.to_string())?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fb5d736..bb0d36a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -90,6 +90,7 @@ pub fn run() { commands::step, commands::reply, commands::set_archived, + commands::set_project_title, commands::get_settings, commands::save_settings, commands::relocate_tsk, diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index e37900c..f14614a 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -24,7 +24,8 @@ pub struct Settings { pub keymap: BTreeMap>, pub tsk_path: Option, pub sidebar_hidden: bool, - /// Names given to projects in tskdeck, keyed by the project's full path. + /// Names given to projects in tskdeck, keyed by the project's full path. tskdeck shows them + /// when tsk keeps no project titles; with titles, it holds only the names tsk has not taken yet. pub project_names: BTreeMap, /// Whether tskdeck looks for a newer release after launch and once a day. pub check_for_updates: bool, diff --git a/src-tauri/src/tsk/args.rs b/src-tauri/src/tsk/args.rs index 8dd1130..7e647b2 100644 --- a/src-tauri/src/tsk/args.rs +++ b/src-tauri/src/tsk/args.rs @@ -321,6 +321,16 @@ pub fn archive_args(number: u64, archived: bool) -> Vec { vec![command.into(), task(number)] } +/// Sets the title of the project at `path`, or removes it when `title` is `None`. +pub fn project_title_args(path: &str, title: Option<&str>) -> Vec { + let mut args = vec!["project".to_string(), "title".into(), path.to_string()]; + match title { + Some(title) => args.push(title.to_string()), + None => args.push("--clear".into()), + } + args +} + fn task(number: u64) -> String { format!("T{number}") } @@ -715,6 +725,18 @@ mod tests { assert_eq!(archive_args(7, false), s(&["unarchive", "T7"])); } + #[test] + fn project_title_sets_and_clears() { + assert_eq!( + project_title_args("/home/test/a", Some("Site A")), + s(&["project", "title", "/home/test/a", "Site A"]) + ); + assert_eq!( + project_title_args("/home/test/a", None), + s(&["project", "title", "/home/test/a", "--clear"]) + ); + } + #[test] fn list_options_use_plain_strings() { let o: ListOptions = serde_json::from_value( diff --git a/src-tauri/src/tsk/model.rs b/src-tauri/src/tsk/model.rs index 4acb03d..b070ef8 100644 --- a/src-tauri/src/tsk/model.rs +++ b/src-tauri/src/tsk/model.rs @@ -104,6 +104,9 @@ pub struct TaskRow { pub title: String, pub status: Status, pub project: Option, + /// The name the project shows under. tsk omits it when the project has no title. + #[serde(default)] + pub project_title: Option, pub thread: Option, pub assignee: Option, pub assignee_kind: Option, @@ -167,6 +170,8 @@ mod tests { serde_json::from_str(include_str!("../../tests/fixtures/rows.json")).unwrap(); assert_eq!(rows.len(), 4); assert_eq!(rows[0].project, None); + assert_eq!(rows[1].project_title, None); + assert_eq!(rows[2].project_title.as_deref(), Some("Client Site")); assert_eq!(rows[3].block.as_ref().unwrap().on, "task:7"); } diff --git a/src-tauri/src/tsk/version.rs b/src-tauri/src/tsk/version.rs index 29d3a71..ffac679 100644 --- a/src-tauri/src/tsk/version.rs +++ b/src-tauri/src/tsk/version.rs @@ -2,6 +2,9 @@ pub const MIN_TSK: (u32, u32, u32) = (0, 13, 0); +/// The first tsk that keeps project titles (`tsk project title`, `project_title` on rows). +pub const PROJECT_TITLES_TSK: (u32, u32, u32) = (0, 14, 0); + /// Reads `tsk 0.13.0` into `(0, 13, 0)`. pub fn parse_version(output: &str) -> Option<(u32, u32, u32)> { let token = output.trim().strip_prefix("tsk ")?.split_whitespace().next()?; @@ -34,4 +37,10 @@ mod tests { assert!((0, 12, 9) < MIN_TSK); assert!((0, 13, 1) >= MIN_TSK); } + + #[test] + fn project_titles_start_at_0_14_0() { + assert!((0, 13, 9) < PROJECT_TITLES_TSK); + assert!((0, 14, 0) >= PROJECT_TITLES_TSK); + } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0350fdf..5665d78 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "tskdeck", - "version": "1.1.1", + "version": "1.2.0", "identifier": "com.s3rgiosan.tskdeck", "build": { "beforeDevCommand": "npm run dev", diff --git a/src-tauri/tests/contract.rs b/src-tauri/tests/contract.rs index 321aaaf..b3db196 100644 --- a/src-tauri/tests/contract.rs +++ b/src-tauri/tests/contract.rs @@ -7,7 +7,7 @@ use std::path::Path; use tskdeck_lib::tsk::args::*; use tskdeck_lib::tsk::locate::{default_candidates, locate}; use tskdeck_lib::tsk::model::*; -use tskdeck_lib::tsk::runner::Tsk; +use tskdeck_lib::tsk::runner::{Tsk, TskError}; fn tsk_for(store: &Path) -> Tsk { let home = dirs::home_dir(); @@ -336,3 +336,56 @@ fn contract_steps_edit_status_and_scopes() { assert!(on_shelf(Shelf::Archived).is_empty()); assert!(on_shelf(Shelf::Done).iter().any(|r| r.number == n)); } + +#[test] +#[ignore] +fn contract_project_titles() { + let store = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let tsk = tsk_for(store.path()); + let added: AddResult = tsk + .json(&add_args(&CaptureInput { + project: Some(project.path().to_string_lossy().into_owned()), + ..capture("titled") + })) + .unwrap(); + // tsk stores the project's canonical path; tskdeck names a project by the path on its rows. + let path = detail(&tsk, added.number).row.project.expect("project row"); + + // tsk trims the title and joins inner whitespace + tsk.run(&project_title_args(&path, Some(" Site A "))) + .unwrap(); + assert_eq!( + detail(&tsk, added.number).row.project_title.as_deref(), + Some("Site A") + ); + let rows: Vec = tsk.json(&list_args(&Scope::All, &live())).unwrap(); + assert_eq!(rows[0].project_title.as_deref(), Some("Site A")); + + // refusals carry a code; a title in use elsewhere is taken whatever its case + let other = tempfile::tempdir().unwrap(); + let second: AddResult = tsk + .json(&add_args(&CaptureInput { + project: Some(other.path().to_string_lossy().into_owned()), + ..capture("other") + })) + .unwrap(); + let other_path = detail(&tsk, second.number) + .row + .project + .expect("project row"); + for (target, title, code) in [ + (&path, "a/b", "invalid-title"), + (&path, "desk", "invalid-title"), + (&other_path, "site a", "title-taken"), + ] { + match tsk.run(&project_title_args(target, Some(title))) { + Err(TskError::Refused { code: got, .. }) => assert_eq!(got, code), + other => panic!("expected {code} for {title}, got {other:?}"), + } + } + + // --clear removes the title, and tsk then omits the field + tsk.run(&project_title_args(&path, None)).unwrap(); + assert_eq!(detail(&tsk, added.number).row.project_title, None); +} diff --git a/src-tauri/tests/fixtures/rows.json b/src-tauri/tests/fixtures/rows.json index 4aeead8..373e816 100644 --- a/src-tauri/tests/fixtures/rows.json +++ b/src-tauri/tests/fixtures/rows.json @@ -1,6 +1,6 @@ [ {"id":"11111111-0000-4000-8000-000000000001","number":1,"title":"Sketch the launch checklist","status":"open","project":null,"thread":null,"assignee":null,"assignee_kind":null,"base":null,"after":[],"before":[]}, {"id":"11111111-0000-4000-8000-000000000002","number":2,"title":"Fix footer links","status":"ready","project":"/home/test/work/site","thread":"polish","assignee":"alice","assignee_kind":"human","base":"main","after":[{"task":1,"done":true}],"before":[],"group":"footer"}, - {"id":"11111111-0000-4000-8000-000000000003","number":3,"title":"Add contact form","status":"started","project":"/home/test/client/site","thread":null,"assignee":"bot-a","assignee_kind":"agent","base":null,"after":[],"before":[4]}, - {"id":"11111111-0000-4000-8000-000000000004","number":4,"title":"Publish release notes","status":"blocked","project":"/home/test/client/site","thread":null,"assignee":null,"assignee_kind":null,"base":null,"after":[{"task":3,"done":false}],"before":[],"block":{"why":"Waiting on copy","needs":null,"options":[],"on":"task:7","by":"bot-a","at":[1700000000,5],"edited":false,"replies":[],"answered":false}} + {"id":"11111111-0000-4000-8000-000000000003","number":3,"title":"Add contact form","status":"started","project":"/home/test/client/site","project_title":"Client Site","thread":null,"assignee":"bot-a","assignee_kind":"agent","base":null,"after":[],"before":[4]}, + {"id":"11111111-0000-4000-8000-000000000004","number":4,"title":"Publish release notes","status":"blocked","project":"/home/test/client/site","project_title":"Client Site","thread":null,"assignee":null,"assignee_kind":null,"base":null,"after":[{"task":3,"done":false}],"before":[],"block":{"why":"Waiting on copy","needs":null,"options":[],"on":"task:7","by":"bot-a","at":[1700000000,5],"edited":false,"replies":[],"answered":false}} ] diff --git a/src/api/client.ts b/src/api/client.ts index bd789ea..8602ed1 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -36,6 +36,9 @@ export const api = { invoke("reply", { number, text, send }), setArchived: (number: number, archived: boolean) => invoke("set_archived", { number, archived }), + /** Shows the project at `path` under `title`, or under its folder name when `title` is null. */ + setProjectTitle: (path: string, title: string | null) => + invoke("set_project_title", { path, title }), // Rejects with a plain string, not a TskError. getSettings: () => invoke("get_settings"), // Rejects with a plain string, not a TskError. diff --git a/src/api/types.ts b/src/api/types.ts index a0e7260..8a12c6b 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -60,6 +60,8 @@ export interface TaskRow { title: string; status: Status; project: string | null; + /** The name the project shows under; tsk omits it when the project has no title. */ + project_title?: string | null; thread: string | null; assignee: string | null; assignee_kind: string | null; @@ -184,7 +186,10 @@ export interface Settings { keymap: Record; tskPath: string | null; sidebarHidden: boolean; - /** Names given to projects in tskdeck, keyed by the project's full path. */ + /** + * Names given to projects in tskdeck, keyed by the project's full path. tskdeck shows them when tsk + * keeps no project titles; with titles, it holds only the names tsk has not taken yet. + */ projectNames: Record; /** Whether tskdeck looks for a newer release after launch and once a day. */ checkForUpdates: boolean; @@ -214,4 +219,6 @@ export interface TskInfo { version: string; supported: boolean; minimum: string; + /** Whether this tsk keeps project titles (tsk 0.14.0 and later). */ + projectTitles: boolean; } diff --git a/src/board/sidebar.test.ts b/src/board/sidebar.test.ts index 34aea60..2031a5f 100644 --- a/src/board/sidebar.test.ts +++ b/src/board/sidebar.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { row } from "../test/fixtures"; -import { onDesk, projectLabelsOf, scopeTitle, sidebarModel, sortByProject } from "./sidebar"; +import { onDesk, projectLabelsOf, projectNamesOf, scopeTitle, sidebarModel, sortByProject } from "./sidebar"; describe("sidebarModel", () => { it("disambiguates colliding basenames", () => { @@ -100,6 +100,23 @@ describe("projectLabelsOf", () => { }); }); +describe("projectNamesOf", () => { + const rows = [ + row({ project: "/home/test/a", project_title: "Alpha" }), + row({ project: "/home/test/b" }), + row({ project: null }), + ]; + const local = { "/home/test/b": "Beta" }; + + it("reads the titles tsk puts on the rows", () => { + expect(projectNamesOf(rows, true, local)).toEqual({ "/home/test/a": "Alpha" }); + }); + + it("uses the names kept in settings on a tsk without titles", () => { + expect(projectNamesOf(rows, false, local)).toBe(local); + }); +}); + describe("sortByProject", () => { it("keeps projects that share a label apart", () => { const rows = [ diff --git a/src/board/sidebar.ts b/src/board/sidebar.ts index 52b3eb9..d75437f 100644 --- a/src/board/sidebar.ts +++ b/src/board/sidebar.ts @@ -15,9 +15,22 @@ export interface SidebarModel { assignees: SidebarItem[]; } -/** Names given to projects in tskdeck, keyed by the project's full path. */ +/** Names of projects, keyed by the project's full path. */ export type ProjectNames = Record; +/** + * The project names to show: the titles tsk puts on `rows` when `titles` is true, or else the names + * kept in tskdeck's settings. + */ +export function projectNamesOf(rows: TaskRow[], titles: boolean, local: ProjectNames): ProjectNames { + if (!titles) return local; + const names: ProjectNames = {}; + for (const row of rows) { + if (row.project && row.project_title) names[row.project] = row.project_title; + } + return names; +} + export function sidebarModel(allRows: TaskRow[], names: ProjectNames = {}): SidebarModel { const deskCount = allRows.filter(onDesk).length; return { @@ -39,12 +52,12 @@ export function sidebarModel(allRows: TaskRow[], names: ProjectNames = {}): Side }; } -/** The name the sidebar gives a scope; a project with no rows left is named by its given name or its folder. */ /** True when both scopes name the same view, project, thread or assignee. */ export function sameScope(a: Scope, b: Scope): boolean { return JSON.stringify(a) === JSON.stringify(b); } +/** The name the sidebar gives a scope; a project with no rows left is named by its given name or its folder. */ export function scopeTitle(scope: Scope, model: SidebarModel, names: ProjectNames = {}): string { switch (scope.kind) { case "desk": diff --git a/src/components/Board.tsx b/src/components/Board.tsx index 6c7ccc7..a72a146 100644 --- a/src/components/Board.tsx +++ b/src/components/Board.tsx @@ -6,6 +6,7 @@ import { projectLabelsOf } from "../board/sidebar"; import { STATUS_LABELS } from "../board/status"; import { isTextTarget } from "../keys/keymap"; import { boardOrder, filterRows, useDeck } from "../state/store"; +import { useProjectNames } from "../state/projectNames"; import { Loading } from "./Loading"; import { SymbolIcon } from "./SymbolIcon"; @@ -187,17 +188,18 @@ export function Board(props: { onNewTask: () => void }) { const open = useDeck((s) => s.open); const setQuery = useDeck((s) => s.setQuery); const grouping = useDeck((s) => s.options.group); - const projectNames = useDeck((s) => s.settings.projectNames); const rows = useMemo(() => filterRows(allListed, query, searchIndex), [allListed, query, searchIndex]); const board = useMemo(() => buildBoard(rows, liveNumbersOf(allRows)), [rows, allRows]); const order = useMemo(() => boardOrder(rows, allRows), [rows, allRows]); + const shownRows = useMemo(() => [...allRows, ...allListed], [allRows, allListed]); + const projectNames = useProjectNames(shownRows); // tsk names a project group by its folder, so projects are grouped by path and headed by their label. const groupOf = useMemo((): GroupOf => { if (grouping !== "project") return TSK_GROUP; - const labels = projectLabelsOf([...allRows, ...allListed], projectNames); + const labels = projectLabelsOf(shownRows, projectNames); return (row) => (row.project ? { key: row.project, name: labels.get(row.project) ?? row.project } : TSK_GROUP(row)); - }, [grouping, allRows, allListed, projectNames]); + }, [grouping, shownRows, projectNames]); const list = useRef(null); function pick(row: TaskRow) { void open(row.number); diff --git a/src/components/CaptureDialog.tsx b/src/components/CaptureDialog.tsx index 829abf7..2756aa7 100644 --- a/src/components/CaptureDialog.tsx +++ b/src/components/CaptureDialog.tsx @@ -2,6 +2,7 @@ import { useMemo, useState } from "react"; import type { CaptureInput, Scope } from "../api/types"; import { scopeTitle, sidebarModel } from "../board/sidebar"; import { useDeck } from "../state/store"; +import { useProjectNames } from "../state/projectNames"; import { Modal } from "./Modal"; /** Where a task captured from `scope` lands: a project scope names the project, a thread scope the thread, an assignee scope the assignee; the rest is the desk. */ @@ -38,7 +39,10 @@ export function CaptureDialog(props: { onClose: () => void }) { const scope = useDeck((s) => s.scope); const capture = useDeck((s) => s.capture); const allRows = useDeck((s) => s.allRows); - const projectNames = useDeck((s) => s.settings.projectNames); + const listedRows = useDeck((s) => s.listedRows); + // The listed rows are included so a project with no live rows gets its name on the done or archived shelf. + const shownRows = useMemo(() => [...allRows, ...listedRows], [allRows, listedRows]); + const projectNames = useProjectNames(shownRows); const projectLabel = useMemo( () => scopeTitle(scope, sidebarModel(allRows, projectNames), projectNames), [scope, allRows, projectNames], diff --git a/src/components/RenameProjectDialog.tsx b/src/components/RenameProjectDialog.tsx index c3c4077..3b1d177 100644 --- a/src/components/RenameProjectDialog.tsx +++ b/src/components/RenameProjectDialog.tsx @@ -1,32 +1,45 @@ -import { useId, useState } from "react"; +import { useId, useRef, useState } from "react"; import { Modal } from "./Modal"; /** * Asks for the name tskdeck shows for a project, with the project's full path above the field so * projects that share a folder name can be told apart. `folderLabel` is the label the project has - * without a name; an empty field brings it back. + * without a name; an empty field brings it back. `onSubmit` resolves to tsk's refusal, which stays + * under the field so the name can be changed, or to null. */ export function RenameProjectDialog(props: { path: string; name: string; folderLabel: string; - onSubmit: (name: string) => void; + onSubmit: (name: string) => Promise; onClose: () => void; }) { const { path, folderLabel, onSubmit, onClose } = props; const [name, setName] = useState(props.name); + const [refusal, setRefusal] = useState(null); + const [busy, setBusy] = useState(false); const fieldId = useId(); const pathId = useId(); const helpId = useId(); + const refusalId = useId(); + const field = useRef(null); return (
{ + onSubmit={async (e) => { e.preventDefault(); - onSubmit(name.trim()); + if (busy) return; + setBusy(true); + const refused = await onSubmit(name.trim()); + // A null result closes the dialog, so only a refusal updates it. + if (refused !== null) { + setRefusal(refused); + setBusy(false); + field.current?.focus(); + } }} >

@@ -35,12 +48,20 @@ export function RenameProjectDialog(props: {

setName(e.target.value)} /> + {refusal !== null && ( + + )} Leave empty to use the folder name. @@ -49,7 +70,9 @@ export function RenameProjectDialog(props: { - +
diff --git a/src/components/Shell.test.tsx b/src/components/Shell.test.tsx index 02588ca..6612e42 100644 --- a/src/components/Shell.test.tsx +++ b/src/components/Shell.test.tsx @@ -38,6 +38,7 @@ vi.mock("../api/client", async (importOriginal) => { step: vi.fn(), reply: vi.fn(), setArchived: vi.fn(), + setProjectTitle: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), relocateTsk: vi.fn(), @@ -72,8 +73,8 @@ function subscriber void>(subscribe: (cb: T) => }) as T; } -async function mountWith(rows: TaskRow[]) { - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); +async function mountWith(rows: TaskRow[], { projectTitles = false } = {}) { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles }); vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, tskPath: null, sidebarHidden: false, projectNames: {}, checkForUpdates: true }); vi.mocked(api.listScope).mockResolvedValue(rows); vi.mocked(api.setStatus).mockResolvedValue(); @@ -164,7 +165,7 @@ describe("palette and settings keys", () => { describe("loading", () => { it("shows a spinner on the board until the first listing arrives", async () => { - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, tskPath: null, sidebarHidden: false, projectNames: {}, checkForUpdates: true }); vi.mocked(api.listScope).mockReturnValue(new Promise(() => {})); vi.mocked(onBoardChanged).mockResolvedValue(() => {}); @@ -241,7 +242,7 @@ describe("dialogs and errors", () => { expect(useDeck.getState().modalOpen).toBe(false); await userEvent.keyboard("{Control>},{/Control}"); expect(api.openSettings).toHaveBeenCalledTimes(1); - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); await userEvent.click(screen.getByRole("button", { name: "Check Again" })); await screen.findByRole("listbox", { name: "Tasks" }); expect(screen.queryByRole("dialog", { name: "New Task" })).not.toBeInTheDocument(); @@ -319,7 +320,7 @@ describe("tsk missing screen", () => { it("looks for tsk again from the check again button", async () => { await mountMissing(); - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.listScope).mockResolvedValue([row({ number: 3, status: "ready" })]); await userEvent.click(screen.getByRole("button", { name: "Check Again" })); expect(await screen.findByRole("listbox", { name: "Tasks" })).toBeInTheDocument(); @@ -578,7 +579,7 @@ describe("sidebar", () => { it("starts hidden when the saved settings say so", async () => { vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, tskPath: null, sidebarHidden: true, projectNames: {}, checkForUpdates: true }); - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.listScope).mockResolvedValue([row({ number: 3 })]); vi.mocked(onBoardChanged).mockResolvedValue(() => {}); render(); @@ -714,7 +715,7 @@ describe("tasks over the board", () => { describe("board empty state", () => { it("offers New Task when the board has no tasks", async () => { - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, tskPath: null, sidebarHidden: false, projectNames: {}, checkForUpdates: true }); vi.mocked(api.listScope).mockResolvedValue([]); vi.mocked(onBoardChanged).mockResolvedValue(() => {}); @@ -1075,7 +1076,7 @@ describe("project names", () => { }); it("starts the field with the project's current name", async () => { - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, @@ -1094,6 +1095,48 @@ describe("project names", () => { expect(within(dialog).getByRole("textbox", { name: "Name" })).toHaveValue("Alpha"); }); + it("renames a project through tsk and shows the title tsk keeps", async () => { + await mountWith([row({ number: 3, status: "started", project: path })], { projectTitles: true }); + vi.mocked(api.setProjectTitle).mockImplementation(async () => { + vi.mocked(api.listScope).mockResolvedValue([row({ number: 3, status: "started", project: path, project_title: "Alpha Site" })]); + }); + const sidebar = screen.getByRole("navigation", { name: "Views" }); + fireEvent.contextMenu(within(sidebar).getByText("wp-content")); + subscriber(onMenu)("pane-rename-project"); + const dialog = await screen.findByRole("dialog", { name: "Rename Project" }); + await userEvent.type(within(dialog).getByRole("textbox", { name: "Name" }), " Alpha Site {Enter}"); + expect(api.setProjectTitle).toHaveBeenCalledWith(path, "Alpha Site"); + await vi.waitFor(() => expect(screen.queryByRole("dialog", { name: "Rename Project" })).not.toBeInTheDocument()); + expect(within(sidebar).getByText("Alpha Site")).toBeInTheDocument(); + expect(api.saveSettings).not.toHaveBeenCalled(); + }); + + it("keeps the rename sheet open with tsk's refusal", async () => { + await mountWith([row({ number: 3, status: "started", project: path })], { projectTitles: true }); + vi.mocked(api.setProjectTitle).mockRejectedValue({ kind: "refused", code: "title-taken", message: "title alpha is used by /home/test/b" }); + const sidebar = screen.getByRole("navigation", { name: "Views" }); + fireEvent.contextMenu(within(sidebar).getByText("wp-content")); + subscriber(onMenu)("pane-rename-project"); + const dialog = await screen.findByRole("dialog", { name: "Rename Project" }); + const field = within(dialog).getByRole("textbox", { name: "Name" }); + await userEvent.type(field, "Alpha{Enter}"); + expect(await within(dialog).findByRole("alert")).toHaveTextContent("title alpha is used by /home/test/b"); + expect(field).toHaveValue("Alpha"); + expect(field).toHaveAttribute("aria-invalid", "true"); + expect(within(dialog).getByRole("button", { name: "Rename" })).toBeEnabled(); + }); + + it("starts the field with the title tsk keeps for the project", async () => { + await mountWith([row({ number: 3, status: "started", project: path, project_title: "Alpha" })], { projectTitles: true }); + const sidebar = screen.getByRole("navigation", { name: "Views" }); + fireEvent.contextMenu(within(sidebar).getByText("Alpha")); + subscriber(onMenu)("pane-rename-project"); + const dialog = await screen.findByRole("dialog", { name: "Rename Project" }); + const field = within(dialog).getByRole("textbox", { name: "Name" }); + expect(field).toHaveValue("Alpha"); + expect(field).toHaveAttribute("placeholder", "wp-content"); + }); + it("titles the window with a project's name", async () => { await mountWith([row({ number: 3, status: "started", project: path })]); useDeck.setState({ settings: { ...useDeck.getState().settings, projectNames: { [path]: "Alpha" } } }); diff --git a/src/components/Shell.tsx b/src/components/Shell.tsx index 0c42a9c..6e6c158 100644 --- a/src/components/Shell.tsx +++ b/src/components/Shell.tsx @@ -21,6 +21,7 @@ import type { Handler, Handlers } from "../keys/useKeymap"; import { useKeymap } from "../keys/useKeymap"; import { menuAccelerators, runMenuItem } from "../menu"; import type { DeckState } from "../state/store"; +import { useProjectNames } from "../state/projectNames"; import { failure, useDeck } from "../state/store"; import { checkForUpdatesNow, subscribeToUpdates } from "../updates/checks"; import { AssignDialog } from "./AssignDialog"; @@ -202,6 +203,7 @@ export function Shell() { const markMode = useDeck((s) => s.markMode); const scope = useDeck((s) => s.scope); const allRows = useDeck((s) => s.allRows); + const listedRows = useDeck((s) => s.listedRows); const options = useDeck((s) => s.options); const undoName = useDeck((s) => (s.irreversible === null ? (s.undo[s.undo.length - 1]?.label ?? null) : null)); const canUndo = useDeck((s) => s.irreversible !== null || s.undo.length > 0); @@ -226,7 +228,9 @@ export function Shell() { const slotOpen = (openTask !== null && !overlay) || drawer; const collapsed = width < NARROW_WIDTH && slotOpen; const sidebarHidden = settings.sidebarHidden || (collapsed && !sidebarShown); - const projectNames = settings.projectNames; + // The listed rows are included so a project with no live rows gets its name on the done or archived shelf. + const shownRows = useMemo(() => [...allRows, ...listedRows], [allRows, listedRows]); + const projectNames = useProjectNames(shownRows); const title = useMemo( () => scopeTitle(scope, sidebarModel(allRows, projectNames), projectNames), [scope, allRows, projectNames], @@ -304,7 +308,7 @@ export function Shell() { function folderLabel(path: string): string { const others = { ...projectNames }; delete others[path]; - return projectLabelsOf(allRows, others).get(path) ?? path; + return projectLabelsOf(shownRows, others).get(path) ?? path; } // Acts on what is on screen: a sidebar the narrow window collapsed shows without changing the // saved choice, and one shown over that collapse hides the same way. @@ -507,9 +511,10 @@ export function Shell() { name={projectNames[renaming] ?? ""} folderLabel={folderLabel(renaming)} onClose={() => setRenaming(null)} - onSubmit={(name) => { - setRenaming(null); - void useDeck.getState().renameProject(renaming, name); + onSubmit={async (name) => { + const refusal = await useDeck.getState().renameProject(renaming, name); + if (refusal === null) setRenaming(null); + return refusal; }} /> )} diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx index b8e1d69..efea582 100644 --- a/src/components/Sidebar.tsx +++ b/src/components/Sidebar.tsx @@ -7,6 +7,7 @@ import { resolveKeymap } from "../keys/keymap"; import type { Handler, Handlers } from "../keys/useKeymap"; import { useKeymap } from "../keys/useKeymap"; import { useDeck } from "../state/store"; +import { useProjectNames } from "../state/projectNames"; import { UpdateCard } from "../updates/UpdateCard"; import { usePullDownChoice } from "./PullDown"; import type { SymbolName } from "./SymbolIcon"; @@ -54,7 +55,8 @@ export function Sidebar(props: { onRename: (path: string) => void }) { const modalOpen = useDeck((s) => s.modalOpen); const selectScope = useDeck((s) => s.selectScope); const keymap = useMemo(() => resolveKeymap(settings.keymap), [settings.keymap]); - const model = useMemo(() => sidebarModel(allRows, settings.projectNames), [allRows, settings.projectNames]); + const projectNames = useProjectNames(allRows); + const model = useMemo(() => sidebarModel(allRows, projectNames), [allRows, projectNames]); // The project whose context menu is open. const menuProject = useRef(null); diff --git a/src/components/TaskPane.test.tsx b/src/components/TaskPane.test.tsx index 6ba1b3e..feefeac 100644 --- a/src/components/TaskPane.test.tsx +++ b/src/components/TaskPane.test.tsx @@ -23,6 +23,7 @@ vi.mock("../api/client", async (importOriginal) => { step: vi.fn(), reply: vi.fn(), setArchived: vi.fn(), + setProjectTitle: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), relocateTsk: vi.fn(), diff --git a/src/components/TaskPane.tsx b/src/components/TaskPane.tsx index e7ba048..597d5ee 100644 --- a/src/components/TaskPane.tsx +++ b/src/components/TaskPane.tsx @@ -11,6 +11,7 @@ import { isTextTarget, resolveKeymap } from "../keys/keymap"; import type { Handler, Handlers } from "../keys/useKeymap"; import { useKeymap } from "../keys/useKeymap"; import { useDeck } from "../state/store"; +import { useProjectNames } from "../state/projectNames"; import { dateOf, formatWhen } from "../when"; import { BlockCard } from "./BlockCard"; import { Clamp } from "./Clamp"; @@ -428,11 +429,14 @@ export function TaskPane() { const run = useDeck((s) => s.run); const keymap = useMemo(() => resolveKeymap(settings.keymap), [settings.keymap]); const allRows = useDeck((s) => s.allRows); - // The task is included so a project with no live rows left still gets its label. + // The task is included so a project with no live rows left still gets its label. It comes first, so the + // fresher listing's title wins while the task is read again. + const shownRows = useMemo(() => (task ? [task, ...allRows] : allRows), [allRows, task]); + const projectNames = useProjectNames(shownRows); const projectLabel = useMemo(() => { if (!task?.project) return "Desk"; - return projectLabelsOf([...allRows, task], settings.projectNames).get(task.project) ?? task.project; - }, [allRows, task, settings.projectNames]); + return projectLabelsOf(shownRows, projectNames).get(task.project) ?? task.project; + }, [shownRows, task, projectNames]); const [editingTitle, setEditingTitle] = useState(false); const [editingNotes, setEditingNotes] = useState(false); diff --git a/src/dev/mockTauri.ts b/src/dev/mockTauri.ts index aed57d2..757a42a 100644 --- a/src/dev/mockTauri.ts +++ b/src/dev/mockTauri.ts @@ -127,7 +127,7 @@ function listScope(scope: { kind: string; path?: string; name?: string }, option function handle(cmd: string, payload: Record = {}): unknown { switch (cmd) { case "tsk_info": - return { path: SETTINGS.tskPath, version: "1.0.0", supported: true, minimum: "1.0.0" }; + return { path: SETTINGS.tskPath, version: "1.0.0", supported: true, minimum: "1.0.0", projectTitles: true }; case "list_scope": return listScope(payload.scope as { kind: string }, payload.options as ListOptions); case "get_task": { @@ -139,6 +139,13 @@ function handle(cmd: string, payload: Record = {}): unknown { return SETTINGS; case "capture": return TASKS.length + 1; + case "set_project_title": { + const title = typeof payload.title === "string" ? payload.title : null; + const folded = title?.toLowerCase(); + if (folded === "desk") throw { kind: "refused", code: "invalid-title", message: "desk names the desk, not a project" }; + for (const r of TASKS) if (r.project === payload.path) r.project_title = title; + return null; + } case "set_status": case "edit_task": case "step": diff --git a/src/state/projectNames.ts b/src/state/projectNames.ts new file mode 100644 index 0000000..81e1dad --- /dev/null +++ b/src/state/projectNames.ts @@ -0,0 +1,12 @@ +import { useMemo } from "react"; +import type { TaskRow } from "../api/types"; +import type { ProjectNames } from "../board/sidebar"; +import { projectNamesOf } from "../board/sidebar"; +import { useDeck } from "./store"; + +/** The project names to show for `rows`: tsk's titles, or the names kept in settings on a tsk without titles. */ +export function useProjectNames(rows: TaskRow[]): ProjectNames { + const titles = useDeck((s) => s.tsk?.projectTitles ?? false); + const local = useDeck((s) => s.settings.projectNames); + return useMemo(() => projectNamesOf(rows, titles, local), [rows, titles, local]); +} diff --git a/src/state/search.test.ts b/src/state/search.test.ts index 75d2eda..38a9cff 100644 --- a/src/state/search.test.ts +++ b/src/state/search.test.ts @@ -17,6 +17,7 @@ vi.mock("../api/client", async (importOriginal) => { step: vi.fn(), reply: vi.fn(), setArchived: vi.fn(), + setProjectTitle: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), }, @@ -79,7 +80,7 @@ describe("search", () => { callback = cb; return () => {}; }); - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.getSettings).mockResolvedValue({ openMode: "beside", keymap: {}, tskPath: null, sidebarHidden: false, projectNames: {}, checkForUpdates: true }); vi.mocked(api.listScope).mockResolvedValue([row({ number: 1 })]); await useDeck.getState().init(); diff --git a/src/state/store.test.ts b/src/state/store.test.ts index dd1e189..853b24a 100644 --- a/src/state/store.test.ts +++ b/src/state/store.test.ts @@ -19,6 +19,7 @@ vi.mock("../api/client", async (importOriginal) => { step: vi.fn(), reply: vi.fn(), setArchived: vi.fn(), + setProjectTitle: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), relocateTsk: vi.fn(), @@ -33,7 +34,7 @@ beforeEach(() => { resetBoardSubscription(); vi.resetAllMocks(); useDeck.setState(useDeck.getInitialState(), true); - vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0" }); + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); vi.mocked(api.getSettings).mockResolvedValue(settings); vi.mocked(api.listScope).mockResolvedValue([row({ number: 1, status: "ready" })]); vi.mocked(onBoardChanged).mockResolvedValue(() => {}); @@ -334,6 +335,133 @@ describe("renameProject", () => { }); }); +describe("renameProject with project titles", () => { + const A = "/home/test/a"; + + beforeEach(async () => { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.14.0", supported: true, minimum: "0.13.0", projectTitles: true }); + vi.mocked(api.listScope).mockResolvedValue([row({ number: 1, status: "ready", project: A })]); + vi.mocked(api.saveSettings).mockResolvedValue(); + await useDeck.getState().init(); + }); + + it("sets the trimmed title in tsk and reads the board again", async () => { + vi.mocked(api.setProjectTitle).mockImplementation(async () => { + vi.mocked(api.listScope).mockResolvedValue([row({ number: 1, status: "ready", project: A, project_title: "Alpha" })]); + }); + expect(await useDeck.getState().renameProject(A, " Alpha ")).toBeNull(); + expect(api.setProjectTitle).toHaveBeenCalledWith(A, "Alpha"); + expect(useDeck.getState().allRows[0].project_title).toBe("Alpha"); + expect(api.saveSettings).not.toHaveBeenCalled(); + }); + + it("clears the title when the new name is blank", async () => { + vi.mocked(api.setProjectTitle).mockResolvedValue(); + expect(await useDeck.getState().renameProject(A, " ")).toBeNull(); + expect(api.setProjectTitle).toHaveBeenCalledWith(A, null); + }); + + it("resolves to tsk's refusal", async () => { + vi.mocked(api.setProjectTitle).mockRejectedValue({ kind: "refused", code: "invalid-title", message: "desk names the desk, not a project" }); + expect(await useDeck.getState().renameProject(A, "desk")).toBe("desk names the desk, not a project"); + }); + + it("resolves to a failure to read the board after the title was set", async () => { + vi.mocked(api.setProjectTitle).mockResolvedValue(); + vi.mocked(api.listScope).mockRejectedValue({ kind: "store", message: "store is locked" }); + expect(await useDeck.getState().renameProject(A, "Alpha")).toBe("store is locked"); + expect(useDeck.getState().error).toBeNull(); + }); + + it("refuses a name that starts with a dash without running tsk", async () => { + expect(await useDeck.getState().renameProject(A, "-x")).toBe("A project name can't start with “-”."); + expect(api.setProjectTitle).not.toHaveBeenCalled(); + }); + + it("drops a name kept in settings once tsk takes the title", async () => { + vi.mocked(api.setProjectTitle).mockResolvedValue(); + useDeck.setState({ settings: { ...useDeck.getState().settings, projectNames: { [A]: "Old", "/home/test/b": "Beta" } } }); + await useDeck.getState().renameProject(A, "Alpha"); + expect(useDeck.getState().settings.projectNames).toEqual({ "/home/test/b": "Beta" }); + }); +}); + +describe("moving project names into tsk", () => { + const A = "/home/test/a"; + const B = "/home/test/b"; + const C = "/home/test/c"; + + function launchWith(projectNames: Record, rows = [row({ number: 1, status: "ready", project: A })]) { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.14.0", supported: true, minimum: "0.13.0", projectTitles: true }); + vi.mocked(api.getSettings).mockResolvedValue({ ...settings, projectNames }); + vi.mocked(api.listScope).mockResolvedValue(rows); + vi.mocked(api.saveSettings).mockResolvedValue(); + return useDeck.getState().init(); + } + + it("sets each name as the project's title and removes it from settings", async () => { + vi.mocked(api.setProjectTitle).mockResolvedValue(); + await launchWith({ [A]: " Alpha ", [B]: "Beta" }); + expect(api.setProjectTitle).toHaveBeenCalledWith(A, "Alpha"); + expect(api.setProjectTitle).toHaveBeenCalledWith(B, "Beta"); + expect(api.saveSettings).toHaveBeenCalledWith(expect.objectContaining({ projectNames: {} })); + expect(useDeck.getState().settings.projectNames).toEqual({}); + expect(useDeck.getState().error).toBeNull(); + }); + + it("keeps a title tsk has already and drops the name", async () => { + await launchWith({ [A]: "Alpha" }, [row({ number: 1, status: "ready", project: A, project_title: "Kept" })]); + expect(api.setProjectTitle).not.toHaveBeenCalled(); + expect(useDeck.getState().settings.projectNames).toEqual({}); + }); + + it("keeps each refused name for the next launch and lists the refusals in one alert", async () => { + vi.mocked(api.setProjectTitle).mockImplementation(async (path) => { + if (path === B) throw { kind: "refused", code: "title-taken", message: "title beta is used by /home/test/z" }; + }); + await launchWith({ [A]: "Alpha", [B]: "Beta", [C]: "-x" }); + expect(api.setProjectTitle).not.toHaveBeenCalledWith(C, "-x"); + expect(useDeck.getState().settings.projectNames).toEqual({ [B]: "Beta", [C]: "-x" }); + expect(useDeck.getState().errorTitle).toBe("Some project names couldn't be moved to tsk"); + expect(useDeck.getState().error).toBe( + [ + "Beta (/home/test/b): title beta is used by /home/test/z", + "-x (/home/test/c): A project name can't start with “-”.", + "tskdeck keeps these names and tries again at the next launch.", + ].join("\n"), + ); + }); + + it("keeps a title tsk has for a project with only done tasks", async () => { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.14.0", supported: true, minimum: "0.13.0", projectTitles: true }); + vi.mocked(api.getSettings).mockResolvedValue({ ...settings, projectNames: { [B]: "Beta" } }); + vi.mocked(api.saveSettings).mockResolvedValue(); + vi.mocked(api.listScope).mockImplementation(async (_scope, options) => + options.shelf === "done" ? [row({ number: 2, status: "done", project: B, project_title: "Kept" })] : [], + ); + await useDeck.getState().init(); + expect(api.setProjectTitle).not.toHaveBeenCalled(); + expect(useDeck.getState().settings.projectNames).toEqual({}); + }); + + it("leaves the names for the next launch when tsk can't list the titled projects", async () => { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.14.0", supported: true, minimum: "0.13.0", projectTitles: true }); + vi.mocked(api.getSettings).mockResolvedValue({ ...settings, projectNames: { [A]: "Alpha" } }); + vi.mocked(api.listScope).mockRejectedValue({ kind: "store", message: "store is locked" }); + await useDeck.getState().init(); + expect(api.setProjectTitle).not.toHaveBeenCalled(); + expect(useDeck.getState().settings.projectNames).toEqual({ [A]: "Alpha" }); + }); + + it("leaves the names in settings on a tsk without titles", async () => { + vi.mocked(api.tskInfo).mockResolvedValue({ path: "/bin/tsk", version: "0.13.0", supported: true, minimum: "0.13.0", projectTitles: false }); + vi.mocked(api.getSettings).mockResolvedValue({ ...settings, projectNames: { [A]: "Alpha" } }); + await useDeck.getState().init(); + expect(api.setProjectTitle).not.toHaveBeenCalled(); + expect(useDeck.getState().settings.projectNames).toEqual({ [A]: "Alpha" }); + }); +}); + describe("sort by project", () => { const A = "/home/test/a/wordpress/wp-content"; const B = "/home/test/b/wordpress/wp-content"; diff --git a/src/state/store.ts b/src/state/store.ts index 21fa72e..f7ffcf8 100644 --- a/src/state/store.ts +++ b/src/state/store.ts @@ -18,7 +18,7 @@ import { groupChoices, sortChoices } from "../board/choices"; import { applyOptimistic } from "../board/optimistic"; import { buildBoard, liveNumbersOf } from "../board/sections"; import type { ProjectNames } from "../board/sidebar"; -import { onDesk, projectLabelsOf, sameScope, sortByProject } from "../board/sidebar"; +import { onDesk, projectLabelsOf, projectNamesOf, sameScope, sortByProject } from "../board/sidebar"; import type { Change, Command, UndoEntry } from "../board/undo"; import { inverseOf } from "../board/undo"; @@ -101,8 +101,11 @@ export interface DeckState { markStep: (delta: number) => void; clearMarks: () => void; saveSettings: (settings: Settings) => Promise; - /** Saves the name tskdeck shows for a project; a blank name clears it. */ - renameProject: (path: string, name: string) => Promise; + /** + * Names a project; a blank name brings back its folder name. tsk keeps the name as the project's + * title; a tsk without titles leaves it in tskdeck's settings. Resolves to tsk's refusal, or null. + */ + renameProject: (path: string, name: string) => Promise; /** Takes settings saved by another window; returns whether the tsk path changed. */ applySettings: (settings: Settings) => boolean; /** Looks for tsk again, for example after the path setting changed. */ @@ -133,9 +136,90 @@ export function filterRows(rows: TaskRow[], query: string, index: Map | null> { + try { + const shelves = await Promise.all(SHELVES.map((shelf) => api.listScope({ kind: "all" }, { ...LIVE, shelf }))); + return new Set(Object.keys(projectNamesOf(shelves.flat(), true, {}))); + } catch { + return null; + } +} + +const SHELVES = ["live", "done", "archived"] as const; + +let movingNames = false; + +/** The running move of project names into tsk; a rename waits for it. */ +let namesMoved: Promise = Promise.resolve(); + +/** + * Moves the project names kept in settings into tsk as project titles, one time. A project that has a + * title already keeps it. A name tsk refuses stays in settings for the next try, and one alert lists + * each refusal. When tsk can't list the titled projects, the names wait for the next launch. + */ +async function moveNamesToTsk(set: Set_, get: Get_): Promise { + const { tsk, settings } = get(); + const entries = Object.entries(settings.projectNames); + if (movingNames || !tsk?.projectTitles || entries.length === 0) return; + movingNames = true; + try { + const titled = await titledPaths(); + if (titled === null) return; + const done: string[] = []; + const refused: string[] = []; + let titledNow = false; + for (const [path, name] of entries) { + const title = name.trim(); + if (titled.has(path) || title === "") { + done.push(path); + continue; + } + const problem = titleProblem(title); + if (problem !== null) { + refused.push(`${title} (${path}): ${problem}`); + continue; + } + try { + await api.setProjectTitle(path, title); + done.push(path); + titledNow = true; + } catch (e) { + refused.push(`${title} (${path}): ${messageOf(e)}`); + } + } + if (done.length > 0) await queueSave(set, get, (current) => withoutNames(current, done)); + if (titledNow) await get().refresh(); + if (refused.length > 0) { + const text = [...refused, "tskdeck keeps these names and tries again at the next launch."].join("\n"); + set(failure("Some project names couldn't be moved to tsk", text)); + } + } finally { + movingNames = false; + } } /** Rows in the order the board shows them. */ @@ -402,6 +486,8 @@ export const useDeck = create()((set, get) => ({ if (tsk) set({ tsk }); if (!tsk || !tsk.supported) return; await get().refresh(); + namesMoved = moveNamesToTsk(set, get); + await namesMoved; if (onWindowFocus === null) { onWindowFocus = () => void get().refresh(); window.addEventListener("focus", onWindowFocus); @@ -431,7 +517,7 @@ export const useDeck = create()((set, get) => ({ const all = api.listScope({ kind: "all" }, LIVE); const [allRows, listed] = await Promise.all([all, listBoard(scope, options, all)]); if (seq !== refreshSeq) return; - const rows = listedOrder(listed, options, allRows, get().settings.projectNames); + const rows = listedOrder(listed, options, allRows, get()); const { cursor, pendingCursor, openTask, query, searchIndex, marks } = get(); // The board as last listed: an optimistic write may already have taken the cursor task off `rows`. const before = boardOrder(filterRows(get().listedRows, query, searchIndex), get().allRows); @@ -681,14 +767,36 @@ export const useDeck = create()((set, get) => ({ async renameProject(path, name) { const trimmed = name.trim(); - await queueSave(set, get, (current) => { - const projectNames = { ...current.projectNames }; - if (trimmed === "") delete projectNames[path]; - else projectNames[path] = trimmed; - return { ...current, projectNames }; - }); - const { rows, listedRows, options, allRows, settings } = get(); - const names = settings.projectNames; - set({ rows: listedOrder(rows, options, allRows, names), listedRows: listedOrder(listedRows, options, allRows, names) }); + if (!get().tsk?.projectTitles) { + await queueSave(set, get, (current) => { + const projectNames = { ...current.projectNames }; + if (trimmed === "") delete projectNames[path]; + else projectNames[path] = trimmed; + return { ...current, projectNames }; + }); + const { rows, listedRows, options, allRows } = get(); + set({ rows: listedOrder(rows, options, allRows, get()), listedRows: listedOrder(listedRows, options, allRows, get()) }); + return null; + } + const problem = trimmed === "" ? null : titleProblem(trimmed); + if (problem !== null) return problem; + await namesMoved; + try { + await api.setProjectTitle(path, trimmed === "" ? null : trimmed); + } catch (e) { + return messageOf(e); + } + const before = get().error; + // A name tskdeck still keeps for the project gives way to the title tsk has now. + const kept = get().settings.projectNames; + if (path in kept) await queueSave(set, get, (current) => withoutNames(current, [path])); + await get().refresh(); + // The dialog clears the store's failure when it closes, so a failure after the title was set stays in it. + const after = get().error; + if (after !== null && after !== before) { + set({ error: null, errorTitle: null, errorTask: null }); + return after; + } + return null; }, }));