#70 Renommer, déplacer, créer un dossier et supprimer plusieurs fichiers dans le panel Agents
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
658ef02 parent: 65c8f64 modified
.tickets/issues/0070-gerer-les-fichiers-du-panel-agents-renommer-supp.yaml +22 -2 | @@ -6,7 +6,7 @@ author: | ||
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-09T04:42:57.000Z |
| 9 | -updatedAt: 2026-11-09T04:42:57.000Z | |
| 9 | +updatedAt: 2026-11-09T05:09:11.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - kind::feature |
| 12 | 12 | - area::workspace |
| @@ -35,4 +35,24 @@ body: | | ||
| 35 | 35 | - Un fichier ouvert dans l'éditeur / l'aperçu suit son renommage, et se ferme s'il est supprimé. |
| 36 | 36 | - Tests Go + frontend ; textes EN + FR ; docs EN + FR. |
| 37 | 37 | tasks: [] |
| 38 | -comments: [] | |
| 38 | +comments: | |
| 39 | + - id: 1 | |
| 40 | + author: | |
| 41 | + name: k33g | |
| 42 | + email: ph.charriere@gmail.com | |
| 43 | + createdAt: 2026-11-09T05:09:11.000Z | |
| 44 | + body: | | |
| 45 | + Fait. | |
| 46 | + - Go : `Rename` et `MakeDir` dans l'interface `Workspace` ([local.go](internal/workspace/local.go), | |
| 47 | + [container.go](internal/workspace/container.go)), dans les tests de contrat (local et container alpine) ; | |
| 48 | + `workspace.Outermost` (un chemin dans un autre de la liste est ignoré) ; `WorkspaceService.RemoveAll`, | |
| 49 | + `Rename`, `Move`, `CreateFolder` avec les protections (rien n'est supprimé si l'un est protégé). | |
| 50 | + - [FilesTab.svelte](frontend/src/lib/agent/FilesTab.svelte) : sélection multiple (⌘/Ctrl-clic, ⇧-clic, ⌘A), | |
| 51 | + renommage en place (✏️, double-clic, F2 ; Entrée / Échap), déplacement par glisser-déposer ou | |
| 52 | + **Move to…**, nouveau dossier, suppression groupée avec une seule confirmation (Suppr, ⌘⌫), menu contextuel. | |
| 53 | + Un fichier ouvert suit son renommage ou son déplacement sans perdre ce qui est tapé. | |
| 54 | + Logique pure dans [fileSelection.ts](frontend/src/lib/fileSelection.ts), testée. | |
| 55 | + - Vérifié dans l'application (Linux, Xvfb) : colorisation, sélection, glisser-déposer, F2, menu, Move to…, | |
| 56 | + suppression de 2 fichiers vers la corbeille. | |
| 57 | + - Pas fait : **dupliquer** (copie de dossiers en local et dans un container) — à rouvrir si besoin. | |
| 58 | + - Textes EN + FR ; guide « fichiers et terminal » et référence `WorkspaceService` EN + FR. | |
| @@ -6,7 +6,7 @@ author: | |||
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-09T04:42:57.000Z | 8 | createdAt: 2026-11-09T04:42:57.000Z |
| 9 | -updatedAt: 2026-11-09T04:42:57.000Z | 9 | +updatedAt: 2026-11-09T05:09:11.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - kind::feature | 11 | - kind::feature |
| 12 | - area::workspace | 12 | - area::workspace |
| @@ -35,4 +35,24 @@ body: | | |||
| 35 | - Un fichier ouvert dans l'éditeur / l'aperçu suit son renommage, et se ferme s'il est supprimé. | 35 | - Un fichier ouvert dans l'éditeur / l'aperçu suit son renommage, et se ferme s'il est supprimé. |
| 36 | - Tests Go + frontend ; textes EN + FR ; docs EN + FR. | 36 | - Tests Go + frontend ; textes EN + FR ; docs EN + FR. |
| 37 | tasks: [] | 37 | tasks: [] |
| 38 | -comments: [] | 38 | +comments: |
| 39 | + - id: 1 | ||
| 40 | + author: | ||
| 41 | + name: k33g | ||
| 42 | + email: ph.charriere@gmail.com | ||
| 43 | + createdAt: 2026-11-09T05:09:11.000Z | ||
| 44 | + body: | | ||
| 45 | + Fait. | ||
| 46 | + - Go : `Rename` et `MakeDir` dans l'interface `Workspace` ([local.go](internal/workspace/local.go), | ||
| 47 | + [container.go](internal/workspace/container.go)), dans les tests de contrat (local et container alpine) ; | ||
| 48 | + `workspace.Outermost` (un chemin dans un autre de la liste est ignoré) ; `WorkspaceService.RemoveAll`, | ||
| 49 | + `Rename`, `Move`, `CreateFolder` avec les protections (rien n'est supprimé si l'un est protégé). | ||
| 50 | + - [FilesTab.svelte](frontend/src/lib/agent/FilesTab.svelte) : sélection multiple (⌘/Ctrl-clic, ⇧-clic, ⌘A), | ||
| 51 | + renommage en place (✏️, double-clic, F2 ; Entrée / Échap), déplacement par glisser-déposer ou | ||
| 52 | + **Move to…**, nouveau dossier, suppression groupée avec une seule confirmation (Suppr, ⌘⌫), menu contextuel. | ||
| 53 | + Un fichier ouvert suit son renommage ou son déplacement sans perdre ce qui est tapé. | ||
| 54 | + Logique pure dans [fileSelection.ts](frontend/src/lib/fileSelection.ts), testée. | ||
| 55 | + - Vérifié dans l'application (Linux, Xvfb) : colorisation, sélection, glisser-déposer, F2, menu, Move to…, | ||
| 56 | + suppression de 2 fichiers vers la corbeille. | ||
| 57 | + - Pas fait : **dupliquer** (copie de dossiers en local et dans un container) — à rouvrir si besoin. | ||
| 58 | + - Textes EN + FR ; guide « fichiers et terminal » et référence `WorkspaceService` EN + FR. | ||
modified
docs/en/how-to/work-with-an-agents-files.md +8 -4 | @@ -39,10 +39,14 @@ When an agent writes a document and gives a link to it in its answer, click the | ||
| 39 | 39 | |
| 40 | 40 | The link must lead to a file of the agent's folder: a path relative to the folder (`notes/plan.md`), an absolute path inside it (as the agent or this computer sees it), or a `file://` address of such a path. A link to a site opens the browser; any other link shows why the file cannot be shown, and nothing outside the folder is read. To get links that open, tell the agent in its `AGENTS.md`, e.g. "When you write a file, give a Markdown link to it, relative to your folder". |
| 41 | 41 | |
| 42 | -## Create or delete a file | |
| 42 | +## Create, rename, move or delete files | |
| 43 | 43 | |
| 44 | -- **Create**: select a folder (or a file in it), click **+ New file**, type a name, Enter. The file opens, empty. | |
| 45 | -- **Delete**: hover the entry and click **🗑** (or **Delete** under the editor), then confirm. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so. | |
| 44 | +- **Create**: select a folder (or a file in it), click **+ New file** (or **+ New folder**), type a name, Enter. A new file opens, empty. | |
| 45 | +- **Select several entries**: ⌘-click (Ctrl-click on Windows and Linux) adds an entry to the selection or takes it out; ⇧-click selects every row up to it; ⌘A (Ctrl+A) selects every row shown. The actions below then apply to the whole selection. | |
| 46 | +- **Rename**: hover the entry and click **✏️**, double-click it, or select it and press **F2**. Type the new name, Enter (Escape cancels). An open file follows its new name, even with unsaved changes. | |
| 47 | +- **Move**: drag entries onto a folder (or onto a file, to go next to it; below the rows for the top of the folder). Without the mouse, right-click → **Move to…** and type the folder (empty for the top). A folder never goes inside itself, and nothing replaces an entry that already has the name. | |
| 48 | +- **Right-click** an entry for a menu with all these actions, and **Show where it is**. | |
| 49 | +- **Delete**: hover the entry and click **🗑** (or **Delete** under the editor, or press **Delete** — ⌘⌫ on a Mac — in the tree), then confirm; with several entries selected, one confirmation covers them all. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so. | |
| 46 | 50 | |
| 47 | 51 | ## Protect files |
| 48 | 52 | |
| @@ -53,7 +57,7 @@ Some files must not be changed or deleted by mistake. Without writing anything, | ||
| 53 | 57 | protect: [notes/plan.md, "prompts/**"] |
| 54 | 58 | ``` |
| 55 | 59 | |
| 56 | -A protected file shows 🔒 instead of 🗑 and opens read only; a folder holding one cannot be deleted. Only the configuration lifts a protection (the ones always applied cannot be lifted): the interface never does. The agent, the terminal and the Finder can still change these files. | |
| 60 | +A protected file shows 🔒 instead of ✏️ and 🗑 and opens read only; it can be neither renamed nor moved, and a folder holding one can be neither deleted nor moved. When one of several selected entries is protected, nothing is deleted. Only the configuration lifts a protection (the ones always applied cannot be lifted): the interface never does. The agent, the terminal and the Finder can still change these files. | |
| 57 | 61 | |
| 58 | 62 | ## Run commands in the agent's folder |
| 59 | 63 | |
| @@ -39,10 +39,14 @@ When an agent writes a document and gives a link to it in its answer, click the | |||
| 39 | 39 | ||
| 40 | The link must lead to a file of the agent's folder: a path relative to the folder (`notes/plan.md`), an absolute path inside it (as the agent or this computer sees it), or a `file://` address of such a path. A link to a site opens the browser; any other link shows why the file cannot be shown, and nothing outside the folder is read. To get links that open, tell the agent in its `AGENTS.md`, e.g. "When you write a file, give a Markdown link to it, relative to your folder". | 40 | The link must lead to a file of the agent's folder: a path relative to the folder (`notes/plan.md`), an absolute path inside it (as the agent or this computer sees it), or a `file://` address of such a path. A link to a site opens the browser; any other link shows why the file cannot be shown, and nothing outside the folder is read. To get links that open, tell the agent in its `AGENTS.md`, e.g. "When you write a file, give a Markdown link to it, relative to your folder". |
| 41 | 41 | ||
| 42 | -## Create or delete a file | 42 | +## Create, rename, move or delete files |
| 43 | 43 | ||
| 44 | -- **Create**: select a folder (or a file in it), click **+ New file**, type a name, Enter. The file opens, empty. | 44 | +- **Create**: select a folder (or a file in it), click **+ New file** (or **+ New folder**), type a name, Enter. A new file opens, empty. |
| 45 | -- **Delete**: hover the entry and click **🗑** (or **Delete** under the editor), then confirm. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so. | 45 | +- **Select several entries**: ⌘-click (Ctrl-click on Windows and Linux) adds an entry to the selection or takes it out; ⇧-click selects every row up to it; ⌘A (Ctrl+A) selects every row shown. The actions below then apply to the whole selection. |
| 46 | +- **Rename**: hover the entry and click **✏️**, double-click it, or select it and press **F2**. Type the new name, Enter (Escape cancels). An open file follows its new name, even with unsaved changes. | ||
| 47 | +- **Move**: drag entries onto a folder (or onto a file, to go next to it; below the rows for the top of the folder). Without the mouse, right-click → **Move to…** and type the folder (empty for the top). A folder never goes inside itself, and nothing replaces an entry that already has the name. | ||
| 48 | +- **Right-click** an entry for a menu with all these actions, and **Show where it is**. | ||
| 49 | +- **Delete**: hover the entry and click **🗑** (or **Delete** under the editor, or press **Delete** — ⌘⌫ on a Mac — in the tree), then confirm; with several entries selected, one confirmation covers them all. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so. | ||
| 46 | 50 | ||
| 47 | ## Protect files | 51 | ## Protect files |
| 48 | 52 | ||
| @@ -53,7 +57,7 @@ Some files must not be changed or deleted by mistake. Without writing anything, | |||
| 53 | protect: [notes/plan.md, "prompts/**"] | 57 | protect: [notes/plan.md, "prompts/**"] |
| 54 | ``` | 58 | ``` |
| 55 | 59 | ||
| 56 | -A protected file shows 🔒 instead of 🗑 and opens read only; a folder holding one cannot be deleted. Only the configuration lifts a protection (the ones always applied cannot be lifted): the interface never does. The agent, the terminal and the Finder can still change these files. | 60 | +A protected file shows 🔒 instead of ✏️ and 🗑 and opens read only; it can be neither renamed nor moved, and a folder holding one can be neither deleted nor moved. When one of several selected entries is protected, nothing is deleted. Only the configuration lifts a protection (the ones always applied cannot be lifted): the interface never does. The agent, the terminal and the Finder can still change these files. |
| 57 | 61 | ||
| 58 | ## Run commands in the agent's folder | 62 | ## Run commands in the agent's folder |
| 59 | 63 | ||
modified
docs/en/reference/agents-and-events.md +5 -1 | @@ -178,12 +178,16 @@ A file opened for editing has `path, content, version`; `version` identifies the | ||
| 178 | 178 | |
| 179 | 179 | | Method | Effect | |
| 180 | 180 | | --- | --- | |
| 181 | -| `Info(agent)` | `{location, problem}`: where the folder is (`local · /path`, `container name · /path`), or why it cannot be shown. | | |
| 181 | +| `Info(agent)` | `{location, problem, revealable}`: where the folder is (`local · /path`, `container name · /path`), or why it cannot be shown; `revealable` when the folder is on this computer (issue #74). | | |
| 182 | 182 | | `List(agent, dir)` | The entries of `dir` (`""` is the folder), folders first, then by name. | |
| 183 | 183 | | `Read(agent, path)` | A text file of at most 1 MB; a binary or larger file is an error. | |
| 184 | 184 | | `Save(agent, path, content, version)` | Writes the file if it still has `version`; otherwise `{conflict: true}` and nothing is written. An empty `version` overwrites. The file is written next to its place and moved over it. | |
| 185 | 185 | | `Create(agent, dir, name)` | Creates an empty file; refused if the name exists or contains `/`. | |
| 186 | 186 | | `Remove(agent, path)` | Deletes a file or a folder with its content (see the table above). | |
| 187 | +| `RemoveAll(agent, paths)` | Deletes several files and folders (a path inside another one of the list is skipped); nothing is deleted when one of them is protected or holds a protected file. Issue #70. | | |
| 188 | +| `Rename(agent, from, to)` | Renames or moves a file or a folder to the path `to` (its folders are created); returns the new path. Refused when `to` exists, leaves the folder, is inside `from`, or when `from` or `to` is protected. Issue #70. | | |
| 189 | +| `Move(agent, paths, dir)` | Moves files and folders into `dir` (`""` is the top), keeping their names; returns their new paths. Stops at the first that cannot move. Issue #70. | | |
| 190 | +| `CreateFolder(agent, dir, name)` | Creates an empty folder; refused if the name exists or contains `/`. Issue #70. | | |
| 187 | 191 | | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). | |
| 188 | 192 | | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. | |
| 189 | 193 | | `Image(agent, path)` | An image of the folder (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 MB at most) as a `data:` URL, for the preview. Any other file is an error. | |
| @@ -178,12 +178,16 @@ A file opened for editing has `path, content, version`; `version` identifies the | |||
| 178 | 178 | ||
| 179 | | Method | Effect | | 179 | | Method | Effect | |
| 180 | | --- | --- | | 180 | | --- | --- | |
| 181 | -| `Info(agent)` | `{location, problem}`: where the folder is (`local · /path`, `container name · /path`), or why it cannot be shown. | | 181 | +| `Info(agent)` | `{location, problem, revealable}`: where the folder is (`local · /path`, `container name · /path`), or why it cannot be shown; `revealable` when the folder is on this computer (issue #74). | |
| 182 | | `List(agent, dir)` | The entries of `dir` (`""` is the folder), folders first, then by name. | | 182 | | `List(agent, dir)` | The entries of `dir` (`""` is the folder), folders first, then by name. | |
| 183 | | `Read(agent, path)` | A text file of at most 1 MB; a binary or larger file is an error. | | 183 | | `Read(agent, path)` | A text file of at most 1 MB; a binary or larger file is an error. | |
| 184 | | `Save(agent, path, content, version)` | Writes the file if it still has `version`; otherwise `{conflict: true}` and nothing is written. An empty `version` overwrites. The file is written next to its place and moved over it. | | 184 | | `Save(agent, path, content, version)` | Writes the file if it still has `version`; otherwise `{conflict: true}` and nothing is written. An empty `version` overwrites. The file is written next to its place and moved over it. | |
| 185 | | `Create(agent, dir, name)` | Creates an empty file; refused if the name exists or contains `/`. | | 185 | | `Create(agent, dir, name)` | Creates an empty file; refused if the name exists or contains `/`. | |
| 186 | | `Remove(agent, path)` | Deletes a file or a folder with its content (see the table above). | | 186 | | `Remove(agent, path)` | Deletes a file or a folder with its content (see the table above). | |
| 187 | +| `RemoveAll(agent, paths)` | Deletes several files and folders (a path inside another one of the list is skipped); nothing is deleted when one of them is protected or holds a protected file. Issue #70. | | ||
| 188 | +| `Rename(agent, from, to)` | Renames or moves a file or a folder to the path `to` (its folders are created); returns the new path. Refused when `to` exists, leaves the folder, is inside `from`, or when `from` or `to` is protected. Issue #70. | | ||
| 189 | +| `Move(agent, paths, dir)` | Moves files and folders into `dir` (`""` is the top), keeping their names; returns their new paths. Stops at the first that cannot move. Issue #70. | | ||
| 190 | +| `CreateFolder(agent, dir, name)` | Creates an empty folder; refused if the name exists or contains `/`. Issue #70. | | ||
| 187 | | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). | | 191 | | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). | |
| 188 | | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. | | 192 | | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. | |
| 189 | | `Image(agent, path)` | An image of the folder (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 MB at most) as a `data:` URL, for the preview. Any other file is an error. | | 193 | | `Image(agent, path)` | An image of the folder (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 MB at most) as a `data:` URL, for the preview. Any other file is an error. | |
modified
docs/fr/how-to/fichiers-et-terminal-d-un-agent.md +8 -4 | @@ -39,10 +39,14 @@ Quand un agent écrit un document et donne un lien vers lui dans sa réponse, cl | ||
| 39 | 39 | |
| 40 | 40 | Le lien doit mener à un fichier du dossier de l'agent : un chemin relatif au dossier (`notes/plan.md`), un chemin absolu à l'intérieur (tel que l'agent ou cet ordinateur le voit), ou une adresse `file://` d'un tel chemin. Un lien vers un site ouvre le navigateur ; tout autre lien explique pourquoi le fichier ne peut pas être affiché, et rien n'est lu hors du dossier. Pour obtenir des liens qui s'ouvrent, dites-le à l'agent dans son `AGENTS.md`, par exemple « Quand tu écris un fichier, donne un lien Markdown vers lui, relatif à ton dossier ». |
| 41 | 41 | |
| 42 | -## Créer ou supprimer un fichier | |
| 42 | +## Créer, renommer, déplacer ou supprimer des fichiers | |
| 43 | 43 | |
| 44 | -- **Créer** : sélectionnez un dossier (ou un fichier qu'il contient), cliquez sur **+ New file**, tapez un nom, Entrée. Le fichier s'ouvre, vide. | |
| 45 | -- **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur), puis confirmez. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit. | |
| 44 | +- **Créer** : sélectionnez un dossier (ou un fichier qu'il contient), cliquez sur **+ New file** (ou **+ New folder**), tapez un nom, Entrée. Un nouveau fichier s'ouvre, vide. | |
| 45 | +- **Sélectionner plusieurs entrées** : ⌘-clic (Ctrl-clic sous Windows et Linux) ajoute une entrée à la sélection ou l'en retire ; ⇧-clic sélectionne toutes les lignes jusqu'à elle ; ⌘A (Ctrl+A) sélectionne toutes les lignes affichées. Les actions ci-dessous s'appliquent alors à toute la sélection. | |
| 46 | +- **Renommer** : survolez l'entrée et cliquez sur **✏️**, double-cliquez dessus, ou sélectionnez-la et appuyez sur **F2**. Tapez le nouveau nom, Entrée (Échap annule). Un fichier ouvert suit son nouveau nom, même avec des modifications non enregistrées. | |
| 47 | +- **Déplacer** : glissez les entrées sur un dossier (ou sur un fichier, pour aller à côté ; sous les lignes pour la racine du dossier). Sans la souris : clic droit → **Move to…** et tapez le dossier (vide pour la racine). Un dossier ne va jamais dans lui-même, et rien ne remplace une entrée qui porte déjà ce nom. | |
| 48 | +- **Clic droit** sur une entrée : un menu avec toutes ces actions, et **Afficher l'emplacement**. | |
| 49 | +- **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur, ou appuyez sur **Suppr** — ⌘⌫ sur Mac — dans l'arbre), puis confirmez ; avec plusieurs entrées sélectionnées, une seule confirmation suffit. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit. | |
| 46 | 50 | |
| 47 | 51 | ## Protéger des fichiers |
| 48 | 52 | |
| @@ -53,7 +57,7 @@ Certains fichiers ne doivent pas être modifiés ou supprimés par erreur. Sans | ||
| 53 | 57 | protect: [notes/plan.md, "prompts/**"] |
| 54 | 58 | ``` |
| 55 | 59 | |
| 56 | -Un fichier protégé affiche 🔒 au lieu de 🗑 et s'ouvre en lecture seule ; un dossier qui en contient un ne peut pas être supprimé. Seule la configuration lève une protection (celles toujours appliquées ne se lèvent pas) : l'interface jamais. L'agent, le terminal et le Finder peuvent toujours modifier ces fichiers. | |
| 60 | +Un fichier protégé affiche 🔒 au lieu de ✏️ et 🗑 et s'ouvre en lecture seule ; il ne peut être ni renommé ni déplacé, et un dossier qui en contient un ne peut être ni supprimé ni déplacé. Si l'une des entrées sélectionnées est protégée, rien n'est supprimé. Seule la configuration lève une protection (celles toujours appliquées ne se lèvent pas) : l'interface jamais. L'agent, le terminal et le Finder peuvent toujours modifier ces fichiers. | |
| 57 | 61 | |
| 58 | 62 | ## Lancer des commandes dans le dossier de l'agent |
| 59 | 63 | |
| @@ -39,10 +39,14 @@ Quand un agent écrit un document et donne un lien vers lui dans sa réponse, cl | |||
| 39 | 39 | ||
| 40 | Le lien doit mener à un fichier du dossier de l'agent : un chemin relatif au dossier (`notes/plan.md`), un chemin absolu à l'intérieur (tel que l'agent ou cet ordinateur le voit), ou une adresse `file://` d'un tel chemin. Un lien vers un site ouvre le navigateur ; tout autre lien explique pourquoi le fichier ne peut pas être affiché, et rien n'est lu hors du dossier. Pour obtenir des liens qui s'ouvrent, dites-le à l'agent dans son `AGENTS.md`, par exemple « Quand tu écris un fichier, donne un lien Markdown vers lui, relatif à ton dossier ». | 40 | Le lien doit mener à un fichier du dossier de l'agent : un chemin relatif au dossier (`notes/plan.md`), un chemin absolu à l'intérieur (tel que l'agent ou cet ordinateur le voit), ou une adresse `file://` d'un tel chemin. Un lien vers un site ouvre le navigateur ; tout autre lien explique pourquoi le fichier ne peut pas être affiché, et rien n'est lu hors du dossier. Pour obtenir des liens qui s'ouvrent, dites-le à l'agent dans son `AGENTS.md`, par exemple « Quand tu écris un fichier, donne un lien Markdown vers lui, relatif à ton dossier ». |
| 41 | 41 | ||
| 42 | -## Créer ou supprimer un fichier | 42 | +## Créer, renommer, déplacer ou supprimer des fichiers |
| 43 | 43 | ||
| 44 | -- **Créer** : sélectionnez un dossier (ou un fichier qu'il contient), cliquez sur **+ New file**, tapez un nom, Entrée. Le fichier s'ouvre, vide. | 44 | +- **Créer** : sélectionnez un dossier (ou un fichier qu'il contient), cliquez sur **+ New file** (ou **+ New folder**), tapez un nom, Entrée. Un nouveau fichier s'ouvre, vide. |
| 45 | -- **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur), puis confirmez. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit. | 45 | +- **Sélectionner plusieurs entrées** : ⌘-clic (Ctrl-clic sous Windows et Linux) ajoute une entrée à la sélection ou l'en retire ; ⇧-clic sélectionne toutes les lignes jusqu'à elle ; ⌘A (Ctrl+A) sélectionne toutes les lignes affichées. Les actions ci-dessous s'appliquent alors à toute la sélection. |
| 46 | +- **Renommer** : survolez l'entrée et cliquez sur **✏️**, double-cliquez dessus, ou sélectionnez-la et appuyez sur **F2**. Tapez le nouveau nom, Entrée (Échap annule). Un fichier ouvert suit son nouveau nom, même avec des modifications non enregistrées. | ||
| 47 | +- **Déplacer** : glissez les entrées sur un dossier (ou sur un fichier, pour aller à côté ; sous les lignes pour la racine du dossier). Sans la souris : clic droit → **Move to…** et tapez le dossier (vide pour la racine). Un dossier ne va jamais dans lui-même, et rien ne remplace une entrée qui porte déjà ce nom. | ||
| 48 | +- **Clic droit** sur une entrée : un menu avec toutes ces actions, et **Afficher l'emplacement**. | ||
| 49 | +- **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur, ou appuyez sur **Suppr** — ⌘⌫ sur Mac — dans l'arbre), puis confirmez ; avec plusieurs entrées sélectionnées, une seule confirmation suffit. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit. | ||
| 46 | 50 | ||
| 47 | ## Protéger des fichiers | 51 | ## Protéger des fichiers |
| 48 | 52 | ||
| @@ -53,7 +57,7 @@ Certains fichiers ne doivent pas être modifiés ou supprimés par erreur. Sans | |||
| 53 | protect: [notes/plan.md, "prompts/**"] | 57 | protect: [notes/plan.md, "prompts/**"] |
| 54 | ``` | 58 | ``` |
| 55 | 59 | ||
| 56 | -Un fichier protégé affiche 🔒 au lieu de 🗑 et s'ouvre en lecture seule ; un dossier qui en contient un ne peut pas être supprimé. Seule la configuration lève une protection (celles toujours appliquées ne se lèvent pas) : l'interface jamais. L'agent, le terminal et le Finder peuvent toujours modifier ces fichiers. | 60 | +Un fichier protégé affiche 🔒 au lieu de ✏️ et 🗑 et s'ouvre en lecture seule ; il ne peut être ni renommé ni déplacé, et un dossier qui en contient un ne peut être ni supprimé ni déplacé. Si l'une des entrées sélectionnées est protégée, rien n'est supprimé. Seule la configuration lève une protection (celles toujours appliquées ne se lèvent pas) : l'interface jamais. L'agent, le terminal et le Finder peuvent toujours modifier ces fichiers. |
| 57 | 61 | ||
| 58 | ## Lancer des commandes dans le dossier de l'agent | 62 | ## Lancer des commandes dans le dossier de l'agent |
| 59 | 63 | ||
modified
docs/fr/reference/agents-et-evenements.md +5 -1 | @@ -178,12 +178,16 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident | ||
| 178 | 178 | |
| 179 | 179 | | Méthode | Effet | |
| 180 | 180 | | --- | --- | |
| 181 | -| `Info(agent)` | `{location, problem}` : où est le dossier (`local · /chemin`, `container nom · /chemin`), ou pourquoi il ne peut pas être affiché. | | |
| 181 | +| `Info(agent)` | `{location, problem, revealable}` : où est le dossier (`local · /chemin`, `container nom · /chemin`), ou pourquoi il ne peut pas être affiché ; `revealable` si le dossier est sur cet ordinateur (issue #74). | | |
| 182 | 182 | | `List(agent, dir)` | Les entrées de `dir` (`""` est le dossier), dossiers d'abord, puis par nom. | |
| 183 | 183 | | `Read(agent, path)` | Un fichier texte de 1 Mo au plus ; un fichier binaire ou plus gros est une erreur. | |
| 184 | 184 | | `Save(agent, path, content, version)` | Écrit le fichier s'il a toujours `version` ; sinon `{conflict: true}` et rien n'est écrit. Une `version` vide écrase. Le fichier est écrit à côté puis déplacé à sa place. | |
| 185 | 185 | | `Create(agent, dir, name)` | Crée un fichier vide ; refusé si le nom existe ou contient `/`. | |
| 186 | 186 | | `Remove(agent, path)` | Supprime un fichier ou un dossier avec son contenu (voir le tableau ci-dessus). | |
| 187 | +| `RemoveAll(agent, paths)` | Supprime plusieurs fichiers et dossiers (un chemin à l'intérieur d'un autre de la liste est ignoré) ; rien n'est supprimé si l'un d'eux est protégé ou contient un fichier protégé. Issue #70. | | |
| 188 | +| `Rename(agent, from, to)` | Renomme ou déplace un fichier ou un dossier vers le chemin `to` (ses dossiers sont créés) ; renvoie le nouveau chemin. Refusé si `to` existe, sort du dossier, est dans `from`, ou si `from` ou `to` est protégé. Issue #70. | | |
| 189 | +| `Move(agent, paths, dir)` | Déplace des fichiers et dossiers dans `dir` (`""` est la racine), sans changer leur nom ; renvoie leurs nouveaux chemins. S'arrête au premier qui ne peut pas être déplacé. Issue #70. | | |
| 190 | +| `CreateFolder(agent, dir, name)` | Crée un dossier vide ; refusé si le nom existe ou contient `/`. Issue #70. | | |
| 187 | 191 | | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). | |
| 188 | 192 | | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. | |
| 189 | 193 | | `Image(agent, path)` | Une image du dossier (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 Mo au plus) sous forme d'URL `data:`, pour l'aperçu. Tout autre fichier est une erreur. | |
| @@ -178,12 +178,16 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident | |||
| 178 | 178 | ||
| 179 | | Méthode | Effet | | 179 | | Méthode | Effet | |
| 180 | | --- | --- | | 180 | | --- | --- | |
| 181 | -| `Info(agent)` | `{location, problem}` : où est le dossier (`local · /chemin`, `container nom · /chemin`), ou pourquoi il ne peut pas être affiché. | | 181 | +| `Info(agent)` | `{location, problem, revealable}` : où est le dossier (`local · /chemin`, `container nom · /chemin`), ou pourquoi il ne peut pas être affiché ; `revealable` si le dossier est sur cet ordinateur (issue #74). | |
| 182 | | `List(agent, dir)` | Les entrées de `dir` (`""` est le dossier), dossiers d'abord, puis par nom. | | 182 | | `List(agent, dir)` | Les entrées de `dir` (`""` est le dossier), dossiers d'abord, puis par nom. | |
| 183 | | `Read(agent, path)` | Un fichier texte de 1 Mo au plus ; un fichier binaire ou plus gros est une erreur. | | 183 | | `Read(agent, path)` | Un fichier texte de 1 Mo au plus ; un fichier binaire ou plus gros est une erreur. | |
| 184 | | `Save(agent, path, content, version)` | Écrit le fichier s'il a toujours `version` ; sinon `{conflict: true}` et rien n'est écrit. Une `version` vide écrase. Le fichier est écrit à côté puis déplacé à sa place. | | 184 | | `Save(agent, path, content, version)` | Écrit le fichier s'il a toujours `version` ; sinon `{conflict: true}` et rien n'est écrit. Une `version` vide écrase. Le fichier est écrit à côté puis déplacé à sa place. | |
| 185 | | `Create(agent, dir, name)` | Crée un fichier vide ; refusé si le nom existe ou contient `/`. | | 185 | | `Create(agent, dir, name)` | Crée un fichier vide ; refusé si le nom existe ou contient `/`. | |
| 186 | | `Remove(agent, path)` | Supprime un fichier ou un dossier avec son contenu (voir le tableau ci-dessus). | | 186 | | `Remove(agent, path)` | Supprime un fichier ou un dossier avec son contenu (voir le tableau ci-dessus). | |
| 187 | +| `RemoveAll(agent, paths)` | Supprime plusieurs fichiers et dossiers (un chemin à l'intérieur d'un autre de la liste est ignoré) ; rien n'est supprimé si l'un d'eux est protégé ou contient un fichier protégé. Issue #70. | | ||
| 188 | +| `Rename(agent, from, to)` | Renomme ou déplace un fichier ou un dossier vers le chemin `to` (ses dossiers sont créés) ; renvoie le nouveau chemin. Refusé si `to` existe, sort du dossier, est dans `from`, ou si `from` ou `to` est protégé. Issue #70. | | ||
| 189 | +| `Move(agent, paths, dir)` | Déplace des fichiers et dossiers dans `dir` (`""` est la racine), sans changer leur nom ; renvoie leurs nouveaux chemins. S'arrête au premier qui ne peut pas être déplacé. Issue #70. | | ||
| 190 | +| `CreateFolder(agent, dir, name)` | Crée un dossier vide ; refusé si le nom existe ou contient `/`. Issue #70. | | ||
| 187 | | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). | | 191 | | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). | |
| 188 | | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. | | 192 | | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. | |
| 189 | | `Image(agent, path)` | Une image du dossier (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 Mo au plus) sous forme d'URL `data:`, pour l'aperçu. Tout autre fichier est une erreur. | | 193 | | `Image(agent, path)` | Une image du dossier (`.png`, `.jpg`, `.gif`, `.webp`, `.svg`…, 5 Mo au plus) sous forme d'URL `data:`, pour l'aperçu. Tout autre fichier est une erreur. | |
modified
frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/workspaceservice.ts +34 -0 | @@ -49,6 +49,14 @@ export function Create(agent: string, dir: string, name: string): $CancellablePr | ||
| 49 | 49 | return $Call.ByID(1228380114, agent, dir, name); |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | +/** | |
| 53 | + * CreateFolder creates an empty folder called name in folder dir and | |
| 54 | + * returns its path (issue #70). | |
| 55 | + */ | |
| 56 | +export function CreateFolder(agent: string, dir: string, name: string): $CancellablePromise<string> { | |
| 57 | + return $Call.ByID(3711526042, agent, dir, name); | |
| 58 | +} | |
| 59 | + | |
| 52 | 60 | /** |
| 53 | 61 | * Image returns an image of the agent's folder as a data: URL, for the |
| 54 | 62 | * preview of the image itself or of a document that shows it. Shown in an |
| @@ -87,6 +95,15 @@ export function List(agent: string, dir: string): $CancellablePromise<workspace$ | ||
| 87 | 95 | return $Call.ByID(2507571650, agent, dir); |
| 88 | 96 | } |
| 89 | 97 | |
| 98 | +/** | |
| 99 | + * Move moves files and folders into folder dir ("" for the root), keeping | |
| 100 | + * their names (issue #70), and returns their new paths. It stops at the | |
| 101 | + * first one that cannot move: those before it have moved. | |
| 102 | + */ | |
| 103 | +export function Move(agent: string, files: string[] | null, dir: string): $CancellablePromise<string[] | null> { | |
| 104 | + return $Call.ByID(2757733347, agent, files, dir); | |
| 105 | +} | |
| 106 | + | |
| 90 | 107 | /** |
| 91 | 108 | * Read returns a text file of the agent; a protected one is read only. |
| 92 | 109 | */ |
| @@ -102,6 +119,23 @@ export function Remove(agent: string, file: string): $CancellablePromise<void> { | ||
| 102 | 119 | return $Call.ByID(2126785394, agent, file); |
| 103 | 120 | } |
| 104 | 121 | |
| 122 | +/** | |
| 123 | + * RemoveAll removes several files and folders at once (issue #70). Nothing | |
| 124 | + * is removed when one of them is protected, or holds a protected file. | |
| 125 | + */ | |
| 126 | +export function RemoveAll(agent: string, files: string[] | null): $CancellablePromise<void> { | |
| 127 | + return $Call.ByID(858143145, agent, files); | |
| 128 | +} | |
| 129 | + | |
| 130 | +/** | |
| 131 | + * Rename renames a file or a folder, or moves it when to is in another | |
| 132 | + * folder (issue #70); it returns the new path. A protected file, a folder | |
| 133 | + * that holds one, or a protected new path is refused. | |
| 134 | + */ | |
| 135 | +export function Rename(agent: string, $from: string, to: string): $CancellablePromise<string> { | |
| 136 | + return $Call.ByID(4252569200, agent, $from, to); | |
| 137 | +} | |
| 138 | + | |
| 105 | 139 | /** |
| 106 | 140 | * Reveal shows a file of agent's folder in the Finder (macOS), the Explorer |
| 107 | 141 | * (Windows) or the file manager (Linux). Only for a folder on this |
| @@ -49,6 +49,14 @@ export function Create(agent: string, dir: string, name: string): $CancellablePr | |||
| 49 | return $Call.ByID(1228380114, agent, dir, name); | 49 | return $Call.ByID(1228380114, agent, dir, name); |
| 50 | } | 50 | } |
| 51 | 51 | ||
| 52 | +/** | ||
| 53 | + * CreateFolder creates an empty folder called name in folder dir and | ||
| 54 | + * returns its path (issue #70). | ||
| 55 | + */ | ||
| 56 | +export function CreateFolder(agent: string, dir: string, name: string): $CancellablePromise<string> { | ||
| 57 | + return $Call.ByID(3711526042, agent, dir, name); | ||
| 58 | +} | ||
| 59 | + | ||
| 52 | /** | 60 | /** |
| 53 | * Image returns an image of the agent's folder as a data: URL, for the | 61 | * Image returns an image of the agent's folder as a data: URL, for the |
| 54 | * preview of the image itself or of a document that shows it. Shown in an | 62 | * preview of the image itself or of a document that shows it. Shown in an |
| @@ -87,6 +95,15 @@ export function List(agent: string, dir: string): $CancellablePromise<workspace$ | |||
| 87 | return $Call.ByID(2507571650, agent, dir); | 95 | return $Call.ByID(2507571650, agent, dir); |
| 88 | } | 96 | } |
| 89 | 97 | ||
| 98 | +/** | ||
| 99 | + * Move moves files and folders into folder dir ("" for the root), keeping | ||
| 100 | + * their names (issue #70), and returns their new paths. It stops at the | ||
| 101 | + * first one that cannot move: those before it have moved. | ||
| 102 | + */ | ||
| 103 | +export function Move(agent: string, files: string[] | null, dir: string): $CancellablePromise<string[] | null> { | ||
| 104 | + return $Call.ByID(2757733347, agent, files, dir); | ||
| 105 | +} | ||
| 106 | + | ||
| 90 | /** | 107 | /** |
| 91 | * Read returns a text file of the agent; a protected one is read only. | 108 | * Read returns a text file of the agent; a protected one is read only. |
| 92 | */ | 109 | */ |
| @@ -102,6 +119,23 @@ export function Remove(agent: string, file: string): $CancellablePromise<void> { | |||
| 102 | return $Call.ByID(2126785394, agent, file); | 119 | return $Call.ByID(2126785394, agent, file); |
| 103 | } | 120 | } |
| 104 | 121 | ||
| 122 | +/** | ||
| 123 | + * RemoveAll removes several files and folders at once (issue #70). Nothing | ||
| 124 | + * is removed when one of them is protected, or holds a protected file. | ||
| 125 | + */ | ||
| 126 | +export function RemoveAll(agent: string, files: string[] | null): $CancellablePromise<void> { | ||
| 127 | + return $Call.ByID(858143145, agent, files); | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/** | ||
| 131 | + * Rename renames a file or a folder, or moves it when to is in another | ||
| 132 | + * folder (issue #70); it returns the new path. A protected file, a folder | ||
| 133 | + * that holds one, or a protected new path is refused. | ||
| 134 | + */ | ||
| 135 | +export function Rename(agent: string, $from: string, to: string): $CancellablePromise<string> { | ||
| 136 | + return $Call.ByID(4252569200, agent, $from, to); | ||
| 137 | +} | ||
| 138 | + | ||
| 105 | /** | 139 | /** |
| 106 | * Reveal shows a file of agent's folder in the Finder (macOS), the Explorer | 140 | * Reveal shows a file of agent's folder in the Finder (macOS), the Explorer |
| 107 | * (Windows) or the file manager (Linux). Only for a folder on this | 141 | * (Windows) or the file manager (Linux). Only for a folder on this |
modified
frontend/src/lib/agent/FilesTab.svelte +289 -33 | @@ -2,7 +2,9 @@ | ||
| 2 | 2 | <script lang="ts"> |
| 3 | 3 | // The files of an agent (issues #29 and #30): a tree loaded folder by |
| 4 | 4 | // folder and kept up to date while the agent works, and an editor that |
| 5 | - // notices when the agent changes the file being edited. | |
| 5 | + // notices when the agent changes the file being edited. Entries can be | |
| 6 | + // selected together, renamed, moved (drag and drop, or Move to…) and | |
| 7 | + // deleted, from the buttons, the keyboard or a context menu (issue #70). | |
| 6 | 8 | import { onMount } from 'svelte' |
| 7 | 9 | import { WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app' |
| 8 | 10 | import type { Entry, File } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/workspace' |
| @@ -12,6 +14,7 @@ | ||
| 12 | 14 | import FileEditor from './FileEditor.svelte' |
| 13 | 15 | import FilePreview from './FilePreview.svelte' |
| 14 | 16 | import { previewKind } from '../preview' |
| 17 | + import { canDrop, isUnder, movedPath, nameOf, parentOf, select } from '../fileSelection' | |
| 15 | 18 | |
| 16 | 19 | let { |
| 17 | 20 | agent, |
| @@ -28,15 +31,25 @@ | ||
| 28 | 31 | let listings: Record<string, Entry[]> = $state({}) |
| 29 | 32 | let open: Record<string, boolean> = $state({ '': true }) |
| 30 | 33 | let showHidden = $state(false) |
| 34 | + // The entry clicked last (anchor of a ⇧ range), and the selected entries. | |
| 31 | 35 | let selected = $state('') |
| 36 | + let selection = $state<string[]>([]) | |
| 32 | 37 | let file = $state<File | null>(null) |
| 33 | 38 | let draft = $state('') |
| 34 | 39 | let conflict = $state(false) |
| 35 | 40 | let message = $state('') |
| 36 | 41 | let error = $state('') |
| 37 | - let creating = $state(false) | |
| 42 | + let creating = $state<'' | 'file' | 'folder'>('') | |
| 38 | 43 | let newName = $state('') |
| 39 | - let confirming = $state('') | |
| 44 | + // The entries waiting for the confirmation of their deletion. | |
| 45 | + let confirming = $state<string[]>([]) | |
| 46 | + let renaming = $state('') | |
| 47 | + let renameValue = $state('') | |
| 48 | + let moving = $state<string[]>([]) | |
| 49 | + let moveTarget = $state('') | |
| 50 | + let menu = $state<{ x: number; y: number; path: string } | null>(null) | |
| 51 | + let dragging: string[] = [] | |
| 52 | + let dropTarget = $state<string | null>(null) | |
| 40 | 53 | let editor: FileEditor | undefined = $state() |
| 41 | 54 | // Issue #46: a document with a preview opens on it; an image has nothing else. |
| 42 | 55 | let mode = $state<'preview' | 'edit'>('edit') |
| @@ -48,9 +61,13 @@ | ||
| 48 | 61 | if (!selected) return '' |
| 49 | 62 | const entry = Object.values(listings).flat().find((candidate) => candidate.path === selected) |
| 50 | 63 | if (entry?.dir) return entry.path |
| 51 | - return selected.includes('/') ? selected.slice(0, selected.lastIndexOf('/')) : '' | |
| 64 | + return parentOf(selected) | |
| 52 | 65 | }) |
| 53 | 66 | |
| 67 | + function entryAt(path: string): Entry | undefined { | |
| 68 | + return Object.values(listings).flat().find((candidate) => candidate.path === path) | |
| 69 | + } | |
| 70 | + | |
| 54 | 71 | async function attempt(action: () => Promise<void>) { |
| 55 | 72 | error = '' |
| 56 | 73 | try { |
| @@ -96,8 +113,22 @@ | ||
| 96 | 113 | } |
| 97 | 114 | } |
| 98 | 115 | |
| 116 | + // A click on a row: ⌘/Ctrl adds it to the selection or takes it out, ⇧ | |
| 117 | + // selects up to it; a plain click selects it alone and opens it. | |
| 118 | + function click(event: MouseEvent, entry: Entry) { | |
| 119 | + menu = null | |
| 120 | + const toggleKey = event.metaKey || event.ctrlKey | |
| 121 | + if (toggleKey || event.shiftKey) { | |
| 122 | + selection = select(rows.map((row) => row.entry.path), selection, selected, entry.path, { toggle: toggleKey, range: event.shiftKey }) | |
| 123 | + if (!event.shiftKey) selected = entry.path | |
| 124 | + return | |
| 125 | + } | |
| 126 | + void toggle(entry) | |
| 127 | + } | |
| 128 | + | |
| 99 | 129 | async function toggle(entry: Entry) { |
| 100 | 130 | selected = entry.path |
| 131 | + selection = [entry.path] | |
| 101 | 132 | if (!entry.dir) return openFile(entry.path) |
| 102 | 133 | open[entry.path] = !open[entry.path] |
| 103 | 134 | if (open[entry.path] && !listings[entry.path]) await attempt(() => load(entry.path)) |
| @@ -147,29 +178,173 @@ | ||
| 147 | 178 | async function create() { |
| 148 | 179 | if (!validFileName(newName)) return |
| 149 | 180 | const folder = targetFolder |
| 181 | + const name = newName.trim() | |
| 150 | 182 | await attempt(async () => { |
| 151 | - const created = await WorkspaceService.Create(agent, folder, newName.trim()) | |
| 152 | - creating = false | |
| 153 | - newName = '' | |
| 154 | - open[folder] = true | |
| 155 | - await load(folder) | |
| 156 | - if (created) { | |
| 157 | - selected = created.path | |
| 158 | - await openFile(created.path) | |
| 183 | + if (creating === 'folder') { | |
| 184 | + const created = await WorkspaceService.CreateFolder(agent, folder, name) | |
| 185 | + open[folder] = true | |
| 186 | + open[created] = true | |
| 187 | + await load(folder) | |
| 188 | + selected = created | |
| 189 | + selection = [created] | |
| 190 | + } else { | |
| 191 | + const created = await WorkspaceService.Create(agent, folder, name) | |
| 192 | + open[folder] = true | |
| 193 | + await load(folder) | |
| 194 | + if (created) { | |
| 195 | + selected = created.path | |
| 196 | + selection = [created.path] | |
| 197 | + await openFile(created.path) | |
| 198 | + } | |
| 159 | 199 | } |
| 200 | + creating = '' | |
| 201 | + newName = '' | |
| 160 | 202 | }) |
| 161 | 203 | } |
| 162 | 204 | |
| 163 | - async function remove(path: string) { | |
| 164 | - confirming = '' | |
| 205 | + // Asks to confirm the deletion of paths: the selection when the entry is | |
| 206 | + // part of it, the entry alone otherwise. | |
| 207 | + function askRemove(path: string) { | |
| 208 | + menu = null | |
| 209 | + confirming = selection.includes(path) ? [...selection] : [path] | |
| 210 | + } | |
| 211 | + | |
| 212 | + async function remove(paths: string[]) { | |
| 213 | + confirming = [] | |
| 165 | 214 | await attempt(async () => { |
| 166 | - await WorkspaceService.Remove(agent, path) | |
| 167 | - if (file && (file.path === path || file.path.startsWith(path + '/'))) file = null | |
| 215 | + if (paths.length === 1) await WorkspaceService.Remove(agent, paths[0]) | |
| 216 | + else await WorkspaceService.RemoveAll(agent, paths) | |
| 217 | + if (file && isUnder(file.path, paths)) file = null | |
| 218 | + selection = [] | |
| 168 | 219 | selected = '' |
| 169 | 220 | await refresh() |
| 170 | 221 | }) |
| 171 | 222 | } |
| 172 | 223 | |
| 224 | + // The tree remembers open folders by path: those under from now are under to. | |
| 225 | + function follow(from: string, to: string) { | |
| 226 | + for (const state of [open, listings] as Record<string, unknown>[]) { | |
| 227 | + for (const key of Object.keys(state)) { | |
| 228 | + if (isUnder(key, [from])) { | |
| 229 | + state[movedPath(key, from, to)] = state[key] | |
| 230 | + delete state[key] | |
| 231 | + } | |
| 232 | + } | |
| 233 | + } | |
| 234 | + // The open file keeps what is being typed: only its path changes. | |
| 235 | + if (file && isUnder(file.path, [from])) file = { ...file, path: movedPath(file.path, from, to) } | |
| 236 | + selection = selection.map((path) => movedPath(path, from, to)) | |
| 237 | + if (selected) selected = movedPath(selected, from, to) | |
| 238 | + } | |
| 239 | + | |
| 240 | + function startRename(path: string) { | |
| 241 | + menu = null | |
| 242 | + renaming = path | |
| 243 | + renameValue = nameOf(path) | |
| 244 | + } | |
| 245 | + | |
| 246 | + async function rename() { | |
| 247 | + const from = renaming | |
| 248 | + const name = renameValue.trim() | |
| 249 | + renaming = '' | |
| 250 | + if (!from || name === nameOf(from) || !validFileName(name)) return | |
| 251 | + const parent = parentOf(from) | |
| 252 | + await attempt(async () => { | |
| 253 | + const to = await WorkspaceService.Rename(agent, from, parent ? `${parent}/${name}` : name) | |
| 254 | + follow(from, to) | |
| 255 | + await refresh() | |
| 256 | + }) | |
| 257 | + } | |
| 258 | + | |
| 259 | + // Moves paths into folder ("" is the root), after a drop or Move to…. | |
| 260 | + async function moveInto(paths: string[], folder: string) { | |
| 261 | + moving = [] | |
| 262 | + if (!canDrop(paths, folder)) return | |
| 263 | + await attempt(async () => { | |
| 264 | + try { | |
| 265 | + const moved = (await WorkspaceService.Move(agent, paths, folder)) ?? [] | |
| 266 | + paths.forEach((from, index) => moved[index] && follow(from, moved[index])) | |
| 267 | + } finally { | |
| 268 | + open[folder] = true | |
| 269 | + if (!listings[folder]) await load(folder).catch(() => {}) | |
| 270 | + await refresh() | |
| 271 | + } | |
| 272 | + }) | |
| 273 | + } | |
| 274 | + | |
| 275 | + function askMove(path: string) { | |
| 276 | + menu = null | |
| 277 | + moving = selection.includes(path) ? [...selection] : [path] | |
| 278 | + moveTarget = parentOf(path) | |
| 279 | + } | |
| 280 | + | |
| 281 | + // Drag and drop: the dragged entry, with the rest of the selection when | |
| 282 | + // it is part of it, goes into the folder dropped on (or the folder of the | |
| 283 | + // file dropped on, or the root below the rows). | |
| 284 | + function dragStart(event: DragEvent, entry: Entry) { | |
| 285 | + dragging = selection.includes(entry.path) ? [...selection] : [entry.path] | |
| 286 | + event.dataTransfer?.setData('text/plain', dragging.join('\n')) | |
| 287 | + if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move' | |
| 288 | + } | |
| 289 | + | |
| 290 | + function dragOver(event: DragEvent, folder: string) { | |
| 291 | + if (!dragging.length || !canDrop(dragging, folder)) return | |
| 292 | + event.preventDefault() | |
| 293 | + event.stopPropagation() | |
| 294 | + dropTarget = folder | |
| 295 | + } | |
| 296 | + | |
| 297 | + function drop(event: DragEvent, folder: string) { | |
| 298 | + event.preventDefault() | |
| 299 | + event.stopPropagation() | |
| 300 | + const paths = dragging | |
| 301 | + dragging = [] | |
| 302 | + dropTarget = null | |
| 303 | + void moveInto(paths, folder) | |
| 304 | + } | |
| 305 | + | |
| 306 | + function dragEnd() { | |
| 307 | + dragging = [] | |
| 308 | + dropTarget = null | |
| 309 | + } | |
| 310 | + | |
| 311 | + function openMenu(event: MouseEvent, entry: Entry) { | |
| 312 | + event.preventDefault() | |
| 313 | + if (!selection.includes(entry.path)) { | |
| 314 | + selection = [entry.path] | |
| 315 | + selected = entry.path | |
| 316 | + } | |
| 317 | + menu = { x: event.clientX, y: event.clientY, path: entry.path } | |
| 318 | + } | |
| 319 | + | |
| 320 | + // Shortcuts of the tree: F2 renames, Delete (⌘⌫ on a Mac) deletes, ⌘A | |
| 321 | + // selects every row shown, Escape closes the menu or empties the selection. | |
| 322 | + function treeKey(event: KeyboardEvent) { | |
| 323 | + if ((event.target as HTMLElement).tagName === 'INPUT') return | |
| 324 | + const mod = event.metaKey || event.ctrlKey | |
| 325 | + if (event.key === 'F2' && selection.length === 1 && !entryAt(selection[0])?.protected) { | |
| 326 | + event.preventDefault() | |
| 327 | + startRename(selection[0]) | |
| 328 | + } else if ((event.key === 'Delete' || (event.key === 'Backspace' && mod)) && selection.length) { | |
| 329 | + event.preventDefault() | |
| 330 | + askRemove(selection[0]) | |
| 331 | + } else if (mod && event.key.toLowerCase() === 'a') { | |
| 332 | + event.preventDefault() | |
| 333 | + selection = rows.map((row) => row.entry.path) | |
| 334 | + } else if (event.key === 'Escape') { | |
| 335 | + if (menu) menu = null | |
| 336 | + else selection = [] | |
| 337 | + } | |
| 338 | + } | |
| 339 | + | |
| 340 | + function closeMenu(event: MouseEvent) { | |
| 341 | + if (menu && !(event.target as HTMLElement).closest('.menu')) menu = null | |
| 342 | + } | |
| 343 | + | |
| 344 | + function blocked(paths: string[]): boolean { | |
| 345 | + return paths.some((path) => entryAt(path)?.protected) | |
| 346 | + } | |
| 347 | + | |
| 173 | 348 | // Shows a file or a folder in the Finder, the Explorer or the file manager. |
| 174 | 349 | function reveal(path: string) { |
| 175 | 350 | void attempt(() => WorkspaceService.Reveal(agent, path)) |
| @@ -213,6 +388,7 @@ | ||
| 213 | 388 | if (!listings[dir]) await load(dir) |
| 214 | 389 | } |
| 215 | 390 | selected = wanted |
| 391 | + selection = [wanted] | |
| 216 | 392 | await openFile(wanted) |
| 217 | 393 | }) |
| 218 | 394 | }) |
| @@ -229,47 +405,116 @@ | ||
| 229 | 405 | }) |
| 230 | 406 | </script> |
| 231 | 407 | |
| 408 | +<svelte:window onclick={closeMenu} /> | |
| 409 | + | |
| 232 | 410 | <div class="files"> |
| 233 | - <aside class="tree"> | |
| 234 | - <ul> | |
| 411 | + <!-- svelte-ignore a11y_no_noninteractive_element_interactions --> | |
| 412 | + <aside class="tree" class:drop={dropTarget === ''} onkeydown={treeKey} ondragover={(event) => dragOver(event, '')} ondrop={(event) => drop(event, '')} ondragleave={() => (dropTarget = null)} aria-label={t('workspace.tree')}> | |
| 413 | + {#if confirming.length > 1} | |
| 414 | + <div class="confirm" role="alert"> | |
| 415 | + <span>{inContainer ? t('workspace.deleteManyForGood', { count: confirming.length }) : t('workspace.deleteManyConfirm', { count: confirming.length })}</span> | |
| 416 | + <button class="danger" onclick={() => remove(confirming)}>{t('workspace.delete')}</button> | |
| 417 | + <button onclick={() => (confirming = [])}>{t('workspace.cancel')}</button> | |
| 418 | + </div> | |
| 419 | + {/if} | |
| 420 | + {#if moving.length} | |
| 421 | + <form class="create" onsubmit={(event) => { event.preventDefault(); void moveInto(moving, moveTarget.trim().replace(/^\/+|\/+$/g, '')) }}> | |
| 422 | + <label for="move-target">{moving.length === 1 ? t('workspace.moveOne', { name: nameOf(moving[0]) }) : t('workspace.moveMany', { count: moving.length })}</label> | |
| 423 | + <input id="move-target" use:focus bind:value={moveTarget} placeholder={t('workspace.moveTarget')} onkeydown={(event) => event.key === 'Escape' && (moving = [])} /> | |
| 424 | + <button class="primary" disabled={!canDrop(moving, moveTarget.trim().replace(/^\/+|\/+$/g, ''))}>{t('workspace.move')}</button> | |
| 425 | + <button type="button" onclick={() => (moving = [])}>{t('workspace.cancel')}</button> | |
| 426 | + </form> | |
| 427 | + {/if} | |
| 428 | + <ul aria-multiselectable="true" role="tree"> | |
| 235 | 429 | {#each rows as { entry, depth } (entry.path)} |
| 236 | - <li class:selected={selected === entry.path} style:padding-left="{8 + depth * 14}px"> | |
| 237 | - <button class="row" onclick={() => toggle(entry)} title={entry.path}> | |
| 238 | - <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | |
| 239 | - {entry.name} | |
| 240 | - </button> | |
| 430 | + <li | |
| 431 | + role="treeitem" | |
| 432 | + aria-selected={selection.includes(entry.path)} | |
| 433 | + class:selected={selection.includes(entry.path)} | |
| 434 | + class:drop={dropTarget === entry.path} | |
| 435 | + style:padding-left="{8 + depth * 14}px" | |
| 436 | + draggable={renaming !== entry.path} | |
| 437 | + ondragstart={(event) => dragStart(event, entry)} | |
| 438 | + ondragend={dragEnd} | |
| 439 | + ondragover={(event) => dragOver(event, entry.dir ? entry.path : parentOf(entry.path))} | |
| 440 | + ondrop={(event) => drop(event, entry.dir ? entry.path : parentOf(entry.path))} | |
| 441 | + oncontextmenu={(event) => openMenu(event, entry)} | |
| 442 | + > | |
| 443 | + {#if renaming === entry.path} | |
| 444 | + <form class="rename" onsubmit={(event) => { event.preventDefault(); void rename() }}> | |
| 445 | + <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | |
| 446 | + <input use:focus bind:value={renameValue} aria-label={t('workspace.renameEntry', { name: entry.name })} onblur={() => void rename()} onkeydown={(event) => { if (event.key === 'Escape') { event.stopPropagation(); renaming = '' } }} /> | |
| 447 | + </form> | |
| 448 | + {:else} | |
| 449 | + <button class="row" onclick={(event) => click(event, entry)} ondblclick={(event) => !entry.protected && !event.metaKey && !event.ctrlKey && !event.shiftKey && startRename(entry.path)} title={entry.path}> | |
| 450 | + <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | |
| 451 | + {entry.name} | |
| 452 | + </button> | |
| 453 | + {/if} | |
| 241 | 454 | {#if revealable} |
| 242 | 455 | <button class="action" onclick={() => reveal(entry.path)} aria-label={t('workspace.revealEntry', { name: entry.name })} title={t('linked.reveal')}>📂</button> |
| 243 | 456 | {/if} |
| 244 | 457 | {#if entry.protected} |
| 245 | 458 | <span class="lock" title={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')} aria-label={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')}>🔒</span> |
| 246 | 459 | {:else} |
| 247 | - <button class="action" onclick={() => (confirming = entry.path)} aria-label={t('workspace.deleteFile', { name: entry.name })} title={t('workspace.deleteFile', { name: entry.name })}>🗑</button> | |
| 460 | + <button class="action" onclick={() => startRename(entry.path)} aria-label={t('workspace.renameEntry', { name: entry.name })} title={t('workspace.renameEntry', { name: entry.name })}>✏️</button> | |
| 461 | + <button class="action" onclick={() => askRemove(entry.path)} aria-label={t('workspace.deleteFile', { name: entry.name })} title={t('workspace.deleteFile', { name: entry.name })}>🗑</button> | |
| 248 | 462 | {/if} |
| 249 | 463 | </li> |
| 250 | - {#if confirming === entry.path} | |
| 464 | + {#if confirming.length === 1 && confirming[0] === entry.path} | |
| 251 | 465 | <li class="confirm"> |
| 252 | 466 | <span role="alert">{inContainer ? t('workspace.deleteForGood', { name: entry.name }) : t('workspace.deleteConfirm', { name: entry.name })}</span> |
| 253 | - <button class="danger" onclick={() => remove(entry.path)}>{t('workspace.delete')}</button> | |
| 254 | - <button onclick={() => (confirming = '')}>{t('workspace.cancel')}</button> | |
| 467 | + <button class="danger" onclick={() => remove(confirming)}>{t('workspace.delete')}</button> | |
| 468 | + <button onclick={() => (confirming = [])}>{t('workspace.cancel')}</button> | |
| 255 | 469 | </li> |
| 256 | 470 | {/if} |
| 257 | 471 | {:else} |
| 258 | 472 | <li class="empty">{t('workspace.empty')}</li> |
| 259 | 473 | {/each} |
| 260 | 474 | </ul> |
| 475 | + {#if selection.length > 1} | |
| 476 | + <p class="count">{t('workspace.selected', { count: selection.length })}</p> | |
| 477 | + {/if} | |
| 261 | 478 | {#if creating} |
| 262 | 479 | <form class="create" onsubmit={(event) => { event.preventDefault(); void create() }}> |
| 263 | - <label for="new-file">{t('workspace.newFileIn', { folder: targetFolder || '/' })}</label> | |
| 264 | - <input id="new-file" use:focus bind:value={newName} placeholder={t('workspace.fileName')} onkeydown={(event) => event.key === 'Escape' && (creating = false)} /> | |
| 480 | + <label for="new-file">{creating === 'folder' ? t('workspace.newFolderIn', { folder: targetFolder || '/' }) : t('workspace.newFileIn', { folder: targetFolder || '/' })}</label> | |
| 481 | + <input id="new-file" use:focus bind:value={newName} placeholder={creating === 'folder' ? t('workspace.folderName') : t('workspace.fileName')} onkeydown={(event) => event.key === 'Escape' && (creating = '')} /> | |
| 265 | 482 | <button class="primary" disabled={!validFileName(newName)}>{t('workspace.create')}</button> |
| 266 | 483 | </form> |
| 267 | 484 | {:else} |
| 268 | - <button class="link" onclick={() => (creating = true)}>{t('workspace.newFile')}</button> | |
| 485 | + <div class="links"> | |
| 486 | + <button class="link" onclick={() => (creating = 'file')}>{t('workspace.newFile')}</button> | |
| 487 | + <button class="link" onclick={() => (creating = 'folder')}>{t('workspace.newFolder')}</button> | |
| 488 | + </div> | |
| 269 | 489 | {/if} |
| 270 | 490 | <label class="hidden"><input type="checkbox" bind:checked={showHidden} /> {t('workspace.showHidden')}</label> |
| 271 | 491 | </aside> |
| 272 | 492 | |
| 493 | + {#if menu} | |
| 494 | + {@const many = selection.length > 1 && selection.includes(menu.path)} | |
| 495 | + {@const targets = many ? selection : [menu.path]} | |
| 496 | + {@const entry = entryAt(menu.path)} | |
| 497 | + <div class="menu" role="menu" tabindex="-1" style:left="{menu.x}px" style:top="{menu.y}px" onkeydown={(event) => event.key === 'Escape' && (menu = null)}> | |
| 498 | + {#if !many && entry && !entry.dir} | |
| 499 | + <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; selected = path; void openFile(path) }}>{t('workspace.menu.open')}</button> | |
| 500 | + {/if} | |
| 501 | + {#if !many && entry && !entry.protected} | |
| 502 | + <button role="menuitem" onclick={() => startRename(menu!.path)}>{t('workspace.menu.rename')}</button> | |
| 503 | + {/if} | |
| 504 | + {#if !blocked(targets)} | |
| 505 | + <button role="menuitem" onclick={() => askMove(menu!.path)}>{many ? t('workspace.menu.moveMany', { count: targets.length }) : t('workspace.menu.move')}</button> | |
| 506 | + {/if} | |
| 507 | + {#if !many && revealable} | |
| 508 | + <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; reveal(path) }}>📂 {t('linked.reveal')}</button> | |
| 509 | + {/if} | |
| 510 | + <button role="menuitem" onclick={() => { selected = menu!.path; menu = null; creating = 'file' }}>{t('workspace.newFile')}</button> | |
| 511 | + <button role="menuitem" onclick={() => { selected = menu!.path; menu = null; creating = 'folder' }}>{t('workspace.newFolder')}</button> | |
| 512 | + {#if !blocked(targets)} | |
| 513 | + <button role="menuitem" class="danger-text" onclick={() => askRemove(menu!.path)}>{many ? t('workspace.menu.deleteMany', { count: targets.length }) : t('workspace.delete')}</button> | |
| 514 | + {/if} | |
| 515 | + </div> | |
| 516 | + {/if} | |
| 517 | + | |
| 273 | 518 | <section class="editor"> |
| 274 | 519 | {#if error}<p class="error" role="alert">{t('workspace.cannotOpen', { error })}</p>{/if} |
| 275 | 520 | {#if file} |
| @@ -308,14 +553,14 @@ | ||
| 308 | 553 | {#if file.readOnly} |
| 309 | 554 | <span class="readonly-hint">{t('workspace.protected')}</span> |
| 310 | 555 | {:else} |
| 311 | - <button class="danger-outline" onclick={() => file && (confirming = file.path)}>{t('workspace.delete')}</button> | |
| 556 | + <button class="danger-outline" onclick={() => file && (confirming = [file.path])}>{t('workspace.delete')}</button> | |
| 312 | 557 | {/if} |
| 313 | 558 | </footer> |
| 314 | 559 | {:else if file.readOnly} |
| 315 | 560 | <footer><span class="readonly-hint">{t('workspace.protected')}</span></footer> |
| 316 | 561 | {:else} |
| 317 | 562 | <footer> |
| 318 | - <button class="danger-outline" onclick={() => file && (confirming = file.path)}>{t('workspace.delete')}</button> | |
| 563 | + <button class="danger-outline" onclick={() => file && (confirming = [file.path])}>{t('workspace.delete')}</button> | |
| 319 | 564 | <span class="spacer"></span> |
| 320 | 565 | <button disabled={!dirty} onclick={() => { if (file) { draft = file.content; editor?.setContent(file.content) } }}>{t('workspace.revert')}</button> |
| 321 | 566 | <button class="primary" disabled={!dirty} onclick={() => save()}>{t('workspace.save')}</button> |
| @@ -333,6 +578,16 @@ | ||
| 333 | 578 | ul { list-style: none; margin: 0; padding: 0; } |
| 334 | 579 | li { display: flex; align-items: center; border-radius: 4px; } |
| 335 | 580 | li:hover, li.selected { background: var(--panel-2); } |
| 581 | + li.selected { background: color-mix(in srgb, var(--accent) 14%, transparent); box-shadow: inset 2px 0 0 var(--accent); } | |
| 582 | + li.drop, .tree.drop { outline: 1px dashed var(--accent); outline-offset: -1px; } | |
| 583 | + .rename { flex: 1; min-width: 0; display: flex; gap: 6px; align-items: center; padding: 1px 4px; font-family: var(--mono); font-size: 12.5px; } | |
| 584 | + .rename input { flex: 1; min-width: 0; font: inherit; padding: 1px 4px; border: 1px solid var(--accent); border-radius: 3px; background: var(--bg); color: var(--text); } | |
| 585 | + .count { margin: 4px 10px 0; color: var(--muted); font-size: 12px; } | |
| 586 | + .links { display: flex; gap: 12px; } | |
| 587 | + .menu { position: fixed; z-index: 50; min-width: 180px; display: flex; flex-direction: column; padding: 4px; border: 1px solid var(--border); border-radius: 6px; background: var(--panel); box-shadow: 0 6px 20px rgb(0 0 0 / 0.25); } | |
| 588 | + .menu button { border: none; background: none; text-align: left; padding: 4px 10px; border-radius: 4px; font-size: 12.5px; } | |
| 589 | + .menu button:hover, .menu button:focus-visible { background: var(--panel-2); } | |
| 590 | + .danger-text { color: var(--danger); } | |
| 336 | 591 | .row { flex: 1; min-width: 0; display: flex; gap: 6px; text-align: left; border: none; background: none; padding: 3px 4px; font-family: var(--mono); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| 337 | 592 | .action { border: none; background: none; padding: 0 4px; font-size: 11px; opacity: 0; } |
| 338 | 593 | .reveal { border: none; background: none; padding: 0; font-size: 12px; color: var(--accent); } |
| @@ -342,9 +597,10 @@ | ||
| 342 | 597 | .modes button { border: none; border-radius: 0; padding: 2px 10px; font-size: 12px; background: none; } |
| 343 | 598 | .modes button.active { background: var(--accent); color: #fff; } |
| 344 | 599 | .readonly-hint { color: var(--muted); font-size: 12px; } |
| 345 | - li:hover .action, li:focus-within .action { opacity: 1; } | |
| 600 | + li:hover .action, li:has(:focus-visible) .action { opacity: 1; } | |
| 346 | 601 | .confirm { flex-wrap: wrap; gap: 6px; margin: 2px 8px 6px; padding: 6px 8px; border: 1px solid var(--danger); font-size: 12px; } |
| 347 | 602 | .confirm span { flex-basis: 100%; } |
| 603 | + div.confirm { display: flex; border-radius: 4px; } | |
| 348 | 604 | .empty, .pick { color: var(--muted); font-size: 12px; padding: 4px 10px; } |
| 349 | 605 | .pick { margin: auto; } |
| 350 | 606 | .link { align-self: flex-start; margin: 8px 8px 0; border: none; background: none; color: var(--accent); font-size: 12px; padding: 0; } |
| @@ -2,7 +2,9 @@ | |||
| 2 | <script lang="ts"> | 2 | <script lang="ts"> |
| 3 | // The files of an agent (issues #29 and #30): a tree loaded folder by | 3 | // The files of an agent (issues #29 and #30): a tree loaded folder by |
| 4 | // folder and kept up to date while the agent works, and an editor that | 4 | // folder and kept up to date while the agent works, and an editor that |
| 5 | - // notices when the agent changes the file being edited. | 5 | + // notices when the agent changes the file being edited. Entries can be |
| 6 | + // selected together, renamed, moved (drag and drop, or Move to…) and | ||
| 7 | + // deleted, from the buttons, the keyboard or a context menu (issue #70). | ||
| 6 | import { onMount } from 'svelte' | 8 | import { onMount } from 'svelte' |
| 7 | import { WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app' | 9 | import { WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app' |
| 8 | import type { Entry, File } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/workspace' | 10 | import type { Entry, File } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/workspace' |
| @@ -12,6 +14,7 @@ | |||
| 12 | import FileEditor from './FileEditor.svelte' | 14 | import FileEditor from './FileEditor.svelte' |
| 13 | import FilePreview from './FilePreview.svelte' | 15 | import FilePreview from './FilePreview.svelte' |
| 14 | import { previewKind } from '../preview' | 16 | import { previewKind } from '../preview' |
| 17 | + import { canDrop, isUnder, movedPath, nameOf, parentOf, select } from '../fileSelection' | ||
| 15 | 18 | ||
| 16 | let { | 19 | let { |
| 17 | agent, | 20 | agent, |
| @@ -28,15 +31,25 @@ | |||
| 28 | let listings: Record<string, Entry[]> = $state({}) | 31 | let listings: Record<string, Entry[]> = $state({}) |
| 29 | let open: Record<string, boolean> = $state({ '': true }) | 32 | let open: Record<string, boolean> = $state({ '': true }) |
| 30 | let showHidden = $state(false) | 33 | let showHidden = $state(false) |
| 34 | + // The entry clicked last (anchor of a ⇧ range), and the selected entries. | ||
| 31 | let selected = $state('') | 35 | let selected = $state('') |
| 36 | + let selection = $state<string[]>([]) | ||
| 32 | let file = $state<File | null>(null) | 37 | let file = $state<File | null>(null) |
| 33 | let draft = $state('') | 38 | let draft = $state('') |
| 34 | let conflict = $state(false) | 39 | let conflict = $state(false) |
| 35 | let message = $state('') | 40 | let message = $state('') |
| 36 | let error = $state('') | 41 | let error = $state('') |
| 37 | - let creating = $state(false) | 42 | + let creating = $state<'' | 'file' | 'folder'>('') |
| 38 | let newName = $state('') | 43 | let newName = $state('') |
| 39 | - let confirming = $state('') | 44 | + // The entries waiting for the confirmation of their deletion. |
| 45 | + let confirming = $state<string[]>([]) | ||
| 46 | + let renaming = $state('') | ||
| 47 | + let renameValue = $state('') | ||
| 48 | + let moving = $state<string[]>([]) | ||
| 49 | + let moveTarget = $state('') | ||
| 50 | + let menu = $state<{ x: number; y: number; path: string } | null>(null) | ||
| 51 | + let dragging: string[] = [] | ||
| 52 | + let dropTarget = $state<string | null>(null) | ||
| 40 | let editor: FileEditor | undefined = $state() | 53 | let editor: FileEditor | undefined = $state() |
| 41 | // Issue #46: a document with a preview opens on it; an image has nothing else. | 54 | // Issue #46: a document with a preview opens on it; an image has nothing else. |
| 42 | let mode = $state<'preview' | 'edit'>('edit') | 55 | let mode = $state<'preview' | 'edit'>('edit') |
| @@ -48,9 +61,13 @@ | |||
| 48 | if (!selected) return '' | 61 | if (!selected) return '' |
| 49 | const entry = Object.values(listings).flat().find((candidate) => candidate.path === selected) | 62 | const entry = Object.values(listings).flat().find((candidate) => candidate.path === selected) |
| 50 | if (entry?.dir) return entry.path | 63 | if (entry?.dir) return entry.path |
| 51 | - return selected.includes('/') ? selected.slice(0, selected.lastIndexOf('/')) : '' | 64 | + return parentOf(selected) |
| 52 | }) | 65 | }) |
| 53 | 66 | ||
| 67 | + function entryAt(path: string): Entry | undefined { | ||
| 68 | + return Object.values(listings).flat().find((candidate) => candidate.path === path) | ||
| 69 | + } | ||
| 70 | + | ||
| 54 | async function attempt(action: () => Promise<void>) { | 71 | async function attempt(action: () => Promise<void>) { |
| 55 | error = '' | 72 | error = '' |
| 56 | try { | 73 | try { |
| @@ -96,8 +113,22 @@ | |||
| 96 | } | 113 | } |
| 97 | } | 114 | } |
| 98 | 115 | ||
| 116 | + // A click on a row: ⌘/Ctrl adds it to the selection or takes it out, ⇧ | ||
| 117 | + // selects up to it; a plain click selects it alone and opens it. | ||
| 118 | + function click(event: MouseEvent, entry: Entry) { | ||
| 119 | + menu = null | ||
| 120 | + const toggleKey = event.metaKey || event.ctrlKey | ||
| 121 | + if (toggleKey || event.shiftKey) { | ||
| 122 | + selection = select(rows.map((row) => row.entry.path), selection, selected, entry.path, { toggle: toggleKey, range: event.shiftKey }) | ||
| 123 | + if (!event.shiftKey) selected = entry.path | ||
| 124 | + return | ||
| 125 | + } | ||
| 126 | + void toggle(entry) | ||
| 127 | + } | ||
| 128 | + | ||
| 99 | async function toggle(entry: Entry) { | 129 | async function toggle(entry: Entry) { |
| 100 | selected = entry.path | 130 | selected = entry.path |
| 131 | + selection = [entry.path] | ||
| 101 | if (!entry.dir) return openFile(entry.path) | 132 | if (!entry.dir) return openFile(entry.path) |
| 102 | open[entry.path] = !open[entry.path] | 133 | open[entry.path] = !open[entry.path] |
| 103 | if (open[entry.path] && !listings[entry.path]) await attempt(() => load(entry.path)) | 134 | if (open[entry.path] && !listings[entry.path]) await attempt(() => load(entry.path)) |
| @@ -147,29 +178,173 @@ | |||
| 147 | async function create() { | 178 | async function create() { |
| 148 | if (!validFileName(newName)) return | 179 | if (!validFileName(newName)) return |
| 149 | const folder = targetFolder | 180 | const folder = targetFolder |
| 181 | + const name = newName.trim() | ||
| 150 | await attempt(async () => { | 182 | await attempt(async () => { |
| 151 | - const created = await WorkspaceService.Create(agent, folder, newName.trim()) | 183 | + if (creating === 'folder') { |
| 152 | - creating = false | 184 | + const created = await WorkspaceService.CreateFolder(agent, folder, name) |
| 153 | - newName = '' | 185 | + open[folder] = true |
| 154 | - open[folder] = true | 186 | + open[created] = true |
| 155 | - await load(folder) | 187 | + await load(folder) |
| 156 | - if (created) { | 188 | + selected = created |
| 157 | - selected = created.path | 189 | + selection = [created] |
| 158 | - await openFile(created.path) | 190 | + } else { |
| 191 | + const created = await WorkspaceService.Create(agent, folder, name) | ||
| 192 | + open[folder] = true | ||
| 193 | + await load(folder) | ||
| 194 | + if (created) { | ||
| 195 | + selected = created.path | ||
| 196 | + selection = [created.path] | ||
| 197 | + await openFile(created.path) | ||
| 198 | + } | ||
| 159 | } | 199 | } |
| 200 | + creating = '' | ||
| 201 | + newName = '' | ||
| 160 | }) | 202 | }) |
| 161 | } | 203 | } |
| 162 | 204 | ||
| 163 | - async function remove(path: string) { | 205 | + // Asks to confirm the deletion of paths: the selection when the entry is |
| 164 | - confirming = '' | 206 | + // part of it, the entry alone otherwise. |
| 207 | + function askRemove(path: string) { | ||
| 208 | + menu = null | ||
| 209 | + confirming = selection.includes(path) ? [...selection] : [path] | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + async function remove(paths: string[]) { | ||
| 213 | + confirming = [] | ||
| 165 | await attempt(async () => { | 214 | await attempt(async () => { |
| 166 | - await WorkspaceService.Remove(agent, path) | 215 | + if (paths.length === 1) await WorkspaceService.Remove(agent, paths[0]) |
| 167 | - if (file && (file.path === path || file.path.startsWith(path + '/'))) file = null | 216 | + else await WorkspaceService.RemoveAll(agent, paths) |
| 217 | + if (file && isUnder(file.path, paths)) file = null | ||
| 218 | + selection = [] | ||
| 168 | selected = '' | 219 | selected = '' |
| 169 | await refresh() | 220 | await refresh() |
| 170 | }) | 221 | }) |
| 171 | } | 222 | } |
| 172 | 223 | ||
| 224 | + // The tree remembers open folders by path: those under from now are under to. | ||
| 225 | + function follow(from: string, to: string) { | ||
| 226 | + for (const state of [open, listings] as Record<string, unknown>[]) { | ||
| 227 | + for (const key of Object.keys(state)) { | ||
| 228 | + if (isUnder(key, [from])) { | ||
| 229 | + state[movedPath(key, from, to)] = state[key] | ||
| 230 | + delete state[key] | ||
| 231 | + } | ||
| 232 | + } | ||
| 233 | + } | ||
| 234 | + // The open file keeps what is being typed: only its path changes. | ||
| 235 | + if (file && isUnder(file.path, [from])) file = { ...file, path: movedPath(file.path, from, to) } | ||
| 236 | + selection = selection.map((path) => movedPath(path, from, to)) | ||
| 237 | + if (selected) selected = movedPath(selected, from, to) | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + function startRename(path: string) { | ||
| 241 | + menu = null | ||
| 242 | + renaming = path | ||
| 243 | + renameValue = nameOf(path) | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + async function rename() { | ||
| 247 | + const from = renaming | ||
| 248 | + const name = renameValue.trim() | ||
| 249 | + renaming = '' | ||
| 250 | + if (!from || name === nameOf(from) || !validFileName(name)) return | ||
| 251 | + const parent = parentOf(from) | ||
| 252 | + await attempt(async () => { | ||
| 253 | + const to = await WorkspaceService.Rename(agent, from, parent ? `${parent}/${name}` : name) | ||
| 254 | + follow(from, to) | ||
| 255 | + await refresh() | ||
| 256 | + }) | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + // Moves paths into folder ("" is the root), after a drop or Move to…. | ||
| 260 | + async function moveInto(paths: string[], folder: string) { | ||
| 261 | + moving = [] | ||
| 262 | + if (!canDrop(paths, folder)) return | ||
| 263 | + await attempt(async () => { | ||
| 264 | + try { | ||
| 265 | + const moved = (await WorkspaceService.Move(agent, paths, folder)) ?? [] | ||
| 266 | + paths.forEach((from, index) => moved[index] && follow(from, moved[index])) | ||
| 267 | + } finally { | ||
| 268 | + open[folder] = true | ||
| 269 | + if (!listings[folder]) await load(folder).catch(() => {}) | ||
| 270 | + await refresh() | ||
| 271 | + } | ||
| 272 | + }) | ||
| 273 | + } | ||
| 274 | + | ||
| 275 | + function askMove(path: string) { | ||
| 276 | + menu = null | ||
| 277 | + moving = selection.includes(path) ? [...selection] : [path] | ||
| 278 | + moveTarget = parentOf(path) | ||
| 279 | + } | ||
| 280 | + | ||
| 281 | + // Drag and drop: the dragged entry, with the rest of the selection when | ||
| 282 | + // it is part of it, goes into the folder dropped on (or the folder of the | ||
| 283 | + // file dropped on, or the root below the rows). | ||
| 284 | + function dragStart(event: DragEvent, entry: Entry) { | ||
| 285 | + dragging = selection.includes(entry.path) ? [...selection] : [entry.path] | ||
| 286 | + event.dataTransfer?.setData('text/plain', dragging.join('\n')) | ||
| 287 | + if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move' | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + function dragOver(event: DragEvent, folder: string) { | ||
| 291 | + if (!dragging.length || !canDrop(dragging, folder)) return | ||
| 292 | + event.preventDefault() | ||
| 293 | + event.stopPropagation() | ||
| 294 | + dropTarget = folder | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + function drop(event: DragEvent, folder: string) { | ||
| 298 | + event.preventDefault() | ||
| 299 | + event.stopPropagation() | ||
| 300 | + const paths = dragging | ||
| 301 | + dragging = [] | ||
| 302 | + dropTarget = null | ||
| 303 | + void moveInto(paths, folder) | ||
| 304 | + } | ||
| 305 | + | ||
| 306 | + function dragEnd() { | ||
| 307 | + dragging = [] | ||
| 308 | + dropTarget = null | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + function openMenu(event: MouseEvent, entry: Entry) { | ||
| 312 | + event.preventDefault() | ||
| 313 | + if (!selection.includes(entry.path)) { | ||
| 314 | + selection = [entry.path] | ||
| 315 | + selected = entry.path | ||
| 316 | + } | ||
| 317 | + menu = { x: event.clientX, y: event.clientY, path: entry.path } | ||
| 318 | + } | ||
| 319 | + | ||
| 320 | + // Shortcuts of the tree: F2 renames, Delete (⌘⌫ on a Mac) deletes, ⌘A | ||
| 321 | + // selects every row shown, Escape closes the menu or empties the selection. | ||
| 322 | + function treeKey(event: KeyboardEvent) { | ||
| 323 | + if ((event.target as HTMLElement).tagName === 'INPUT') return | ||
| 324 | + const mod = event.metaKey || event.ctrlKey | ||
| 325 | + if (event.key === 'F2' && selection.length === 1 && !entryAt(selection[0])?.protected) { | ||
| 326 | + event.preventDefault() | ||
| 327 | + startRename(selection[0]) | ||
| 328 | + } else if ((event.key === 'Delete' || (event.key === 'Backspace' && mod)) && selection.length) { | ||
| 329 | + event.preventDefault() | ||
| 330 | + askRemove(selection[0]) | ||
| 331 | + } else if (mod && event.key.toLowerCase() === 'a') { | ||
| 332 | + event.preventDefault() | ||
| 333 | + selection = rows.map((row) => row.entry.path) | ||
| 334 | + } else if (event.key === 'Escape') { | ||
| 335 | + if (menu) menu = null | ||
| 336 | + else selection = [] | ||
| 337 | + } | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + function closeMenu(event: MouseEvent) { | ||
| 341 | + if (menu && !(event.target as HTMLElement).closest('.menu')) menu = null | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + function blocked(paths: string[]): boolean { | ||
| 345 | + return paths.some((path) => entryAt(path)?.protected) | ||
| 346 | + } | ||
| 347 | + | ||
| 173 | // Shows a file or a folder in the Finder, the Explorer or the file manager. | 348 | // Shows a file or a folder in the Finder, the Explorer or the file manager. |
| 174 | function reveal(path: string) { | 349 | function reveal(path: string) { |
| 175 | void attempt(() => WorkspaceService.Reveal(agent, path)) | 350 | void attempt(() => WorkspaceService.Reveal(agent, path)) |
| @@ -213,6 +388,7 @@ | |||
| 213 | if (!listings[dir]) await load(dir) | 388 | if (!listings[dir]) await load(dir) |
| 214 | } | 389 | } |
| 215 | selected = wanted | 390 | selected = wanted |
| 391 | + selection = [wanted] | ||
| 216 | await openFile(wanted) | 392 | await openFile(wanted) |
| 217 | }) | 393 | }) |
| 218 | }) | 394 | }) |
| @@ -229,47 +405,116 @@ | |||
| 229 | }) | 405 | }) |
| 230 | </script> | 406 | </script> |
| 231 | 407 | ||
| 408 | +<svelte:window onclick={closeMenu} /> | ||
| 409 | + | ||
| 232 | <div class="files"> | 410 | <div class="files"> |
| 233 | - <aside class="tree"> | 411 | + <!-- svelte-ignore a11y_no_noninteractive_element_interactions --> |
| 234 | - <ul> | 412 | + <aside class="tree" class:drop={dropTarget === ''} onkeydown={treeKey} ondragover={(event) => dragOver(event, '')} ondrop={(event) => drop(event, '')} ondragleave={() => (dropTarget = null)} aria-label={t('workspace.tree')}> |
| 413 | + {#if confirming.length > 1} | ||
| 414 | + <div class="confirm" role="alert"> | ||
| 415 | + <span>{inContainer ? t('workspace.deleteManyForGood', { count: confirming.length }) : t('workspace.deleteManyConfirm', { count: confirming.length })}</span> | ||
| 416 | + <button class="danger" onclick={() => remove(confirming)}>{t('workspace.delete')}</button> | ||
| 417 | + <button onclick={() => (confirming = [])}>{t('workspace.cancel')}</button> | ||
| 418 | + </div> | ||
| 419 | + {/if} | ||
| 420 | + {#if moving.length} | ||
| 421 | + <form class="create" onsubmit={(event) => { event.preventDefault(); void moveInto(moving, moveTarget.trim().replace(/^\/+|\/+$/g, '')) }}> | ||
| 422 | + <label for="move-target">{moving.length === 1 ? t('workspace.moveOne', { name: nameOf(moving[0]) }) : t('workspace.moveMany', { count: moving.length })}</label> | ||
| 423 | + <input id="move-target" use:focus bind:value={moveTarget} placeholder={t('workspace.moveTarget')} onkeydown={(event) => event.key === 'Escape' && (moving = [])} /> | ||
| 424 | + <button class="primary" disabled={!canDrop(moving, moveTarget.trim().replace(/^\/+|\/+$/g, ''))}>{t('workspace.move')}</button> | ||
| 425 | + <button type="button" onclick={() => (moving = [])}>{t('workspace.cancel')}</button> | ||
| 426 | + </form> | ||
| 427 | + {/if} | ||
| 428 | + <ul aria-multiselectable="true" role="tree"> | ||
| 235 | {#each rows as { entry, depth } (entry.path)} | 429 | {#each rows as { entry, depth } (entry.path)} |
| 236 | - <li class:selected={selected === entry.path} style:padding-left="{8 + depth * 14}px"> | 430 | + <li |
| 237 | - <button class="row" onclick={() => toggle(entry)} title={entry.path}> | 431 | + role="treeitem" |
| 238 | - <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | 432 | + aria-selected={selection.includes(entry.path)} |
| 239 | - {entry.name} | 433 | + class:selected={selection.includes(entry.path)} |
| 240 | - </button> | 434 | + class:drop={dropTarget === entry.path} |
| 435 | + style:padding-left="{8 + depth * 14}px" | ||
| 436 | + draggable={renaming !== entry.path} | ||
| 437 | + ondragstart={(event) => dragStart(event, entry)} | ||
| 438 | + ondragend={dragEnd} | ||
| 439 | + ondragover={(event) => dragOver(event, entry.dir ? entry.path : parentOf(entry.path))} | ||
| 440 | + ondrop={(event) => drop(event, entry.dir ? entry.path : parentOf(entry.path))} | ||
| 441 | + oncontextmenu={(event) => openMenu(event, entry)} | ||
| 442 | + > | ||
| 443 | + {#if renaming === entry.path} | ||
| 444 | + <form class="rename" onsubmit={(event) => { event.preventDefault(); void rename() }}> | ||
| 445 | + <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | ||
| 446 | + <input use:focus bind:value={renameValue} aria-label={t('workspace.renameEntry', { name: entry.name })} onblur={() => void rename()} onkeydown={(event) => { if (event.key === 'Escape') { event.stopPropagation(); renaming = '' } }} /> | ||
| 447 | + </form> | ||
| 448 | + {:else} | ||
| 449 | + <button class="row" onclick={(event) => click(event, entry)} ondblclick={(event) => !entry.protected && !event.metaKey && !event.ctrlKey && !event.shiftKey && startRename(entry.path)} title={entry.path}> | ||
| 450 | + <span aria-hidden="true">{iconFor(entry.name, entry.dir, open[entry.path])}</span> | ||
| 451 | + {entry.name} | ||
| 452 | + </button> | ||
| 453 | + {/if} | ||
| 241 | {#if revealable} | 454 | {#if revealable} |
| 242 | <button class="action" onclick={() => reveal(entry.path)} aria-label={t('workspace.revealEntry', { name: entry.name })} title={t('linked.reveal')}>📂</button> | 455 | <button class="action" onclick={() => reveal(entry.path)} aria-label={t('workspace.revealEntry', { name: entry.name })} title={t('linked.reveal')}>📂</button> |
| 243 | {/if} | 456 | {/if} |
| 244 | {#if entry.protected} | 457 | {#if entry.protected} |
| 245 | <span class="lock" title={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')} aria-label={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')}>🔒</span> | 458 | <span class="lock" title={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')} aria-label={entry.dir ? t('workspace.protectedFolder') : t('workspace.protected')}>🔒</span> |
| 246 | {:else} | 459 | {:else} |
| 247 | - <button class="action" onclick={() => (confirming = entry.path)} aria-label={t('workspace.deleteFile', { name: entry.name })} title={t('workspace.deleteFile', { name: entry.name })}>🗑</button> | 460 | + <button class="action" onclick={() => startRename(entry.path)} aria-label={t('workspace.renameEntry', { name: entry.name })} title={t('workspace.renameEntry', { name: entry.name })}>✏️</button> |
| 461 | + <button class="action" onclick={() => askRemove(entry.path)} aria-label={t('workspace.deleteFile', { name: entry.name })} title={t('workspace.deleteFile', { name: entry.name })}>🗑</button> | ||
| 248 | {/if} | 462 | {/if} |
| 249 | </li> | 463 | </li> |
| 250 | - {#if confirming === entry.path} | 464 | + {#if confirming.length === 1 && confirming[0] === entry.path} |
| 251 | <li class="confirm"> | 465 | <li class="confirm"> |
| 252 | <span role="alert">{inContainer ? t('workspace.deleteForGood', { name: entry.name }) : t('workspace.deleteConfirm', { name: entry.name })}</span> | 466 | <span role="alert">{inContainer ? t('workspace.deleteForGood', { name: entry.name }) : t('workspace.deleteConfirm', { name: entry.name })}</span> |
| 253 | - <button class="danger" onclick={() => remove(entry.path)}>{t('workspace.delete')}</button> | 467 | + <button class="danger" onclick={() => remove(confirming)}>{t('workspace.delete')}</button> |
| 254 | - <button onclick={() => (confirming = '')}>{t('workspace.cancel')}</button> | 468 | + <button onclick={() => (confirming = [])}>{t('workspace.cancel')}</button> |
| 255 | </li> | 469 | </li> |
| 256 | {/if} | 470 | {/if} |
| 257 | {:else} | 471 | {:else} |
| 258 | <li class="empty">{t('workspace.empty')}</li> | 472 | <li class="empty">{t('workspace.empty')}</li> |
| 259 | {/each} | 473 | {/each} |
| 260 | </ul> | 474 | </ul> |
| 475 | + {#if selection.length > 1} | ||
| 476 | + <p class="count">{t('workspace.selected', { count: selection.length })}</p> | ||
| 477 | + {/if} | ||
| 261 | {#if creating} | 478 | {#if creating} |
| 262 | <form class="create" onsubmit={(event) => { event.preventDefault(); void create() }}> | 479 | <form class="create" onsubmit={(event) => { event.preventDefault(); void create() }}> |
| 263 | - <label for="new-file">{t('workspace.newFileIn', { folder: targetFolder || '/' })}</label> | 480 | + <label for="new-file">{creating === 'folder' ? t('workspace.newFolderIn', { folder: targetFolder || '/' }) : t('workspace.newFileIn', { folder: targetFolder || '/' })}</label> |
| 264 | - <input id="new-file" use:focus bind:value={newName} placeholder={t('workspace.fileName')} onkeydown={(event) => event.key === 'Escape' && (creating = false)} /> | 481 | + <input id="new-file" use:focus bind:value={newName} placeholder={creating === 'folder' ? t('workspace.folderName') : t('workspace.fileName')} onkeydown={(event) => event.key === 'Escape' && (creating = '')} /> |
| 265 | <button class="primary" disabled={!validFileName(newName)}>{t('workspace.create')}</button> | 482 | <button class="primary" disabled={!validFileName(newName)}>{t('workspace.create')}</button> |
| 266 | </form> | 483 | </form> |
| 267 | {:else} | 484 | {:else} |
| 268 | - <button class="link" onclick={() => (creating = true)}>{t('workspace.newFile')}</button> | 485 | + <div class="links"> |
| 486 | + <button class="link" onclick={() => (creating = 'file')}>{t('workspace.newFile')}</button> | ||
| 487 | + <button class="link" onclick={() => (creating = 'folder')}>{t('workspace.newFolder')}</button> | ||
| 488 | + </div> | ||
| 269 | {/if} | 489 | {/if} |
| 270 | <label class="hidden"><input type="checkbox" bind:checked={showHidden} /> {t('workspace.showHidden')}</label> | 490 | <label class="hidden"><input type="checkbox" bind:checked={showHidden} /> {t('workspace.showHidden')}</label> |
| 271 | </aside> | 491 | </aside> |
| 272 | 492 | ||
| 493 | + {#if menu} | ||
| 494 | + {@const many = selection.length > 1 && selection.includes(menu.path)} | ||
| 495 | + {@const targets = many ? selection : [menu.path]} | ||
| 496 | + {@const entry = entryAt(menu.path)} | ||
| 497 | + <div class="menu" role="menu" tabindex="-1" style:left="{menu.x}px" style:top="{menu.y}px" onkeydown={(event) => event.key === 'Escape' && (menu = null)}> | ||
| 498 | + {#if !many && entry && !entry.dir} | ||
| 499 | + <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; selected = path; void openFile(path) }}>{t('workspace.menu.open')}</button> | ||
| 500 | + {/if} | ||
| 501 | + {#if !many && entry && !entry.protected} | ||
| 502 | + <button role="menuitem" onclick={() => startRename(menu!.path)}>{t('workspace.menu.rename')}</button> | ||
| 503 | + {/if} | ||
| 504 | + {#if !blocked(targets)} | ||
| 505 | + <button role="menuitem" onclick={() => askMove(menu!.path)}>{many ? t('workspace.menu.moveMany', { count: targets.length }) : t('workspace.menu.move')}</button> | ||
| 506 | + {/if} | ||
| 507 | + {#if !many && revealable} | ||
| 508 | + <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; reveal(path) }}>📂 {t('linked.reveal')}</button> | ||
| 509 | + {/if} | ||
| 510 | + <button role="menuitem" onclick={() => { selected = menu!.path; menu = null; creating = 'file' }}>{t('workspace.newFile')}</button> | ||
| 511 | + <button role="menuitem" onclick={() => { selected = menu!.path; menu = null; creating = 'folder' }}>{t('workspace.newFolder')}</button> | ||
| 512 | + {#if !blocked(targets)} | ||
| 513 | + <button role="menuitem" class="danger-text" onclick={() => askRemove(menu!.path)}>{many ? t('workspace.menu.deleteMany', { count: targets.length }) : t('workspace.delete')}</button> | ||
| 514 | + {/if} | ||
| 515 | + </div> | ||
| 516 | + {/if} | ||
| 517 | + | ||
| 273 | <section class="editor"> | 518 | <section class="editor"> |
| 274 | {#if error}<p class="error" role="alert">{t('workspace.cannotOpen', { error })}</p>{/if} | 519 | {#if error}<p class="error" role="alert">{t('workspace.cannotOpen', { error })}</p>{/if} |
| 275 | {#if file} | 520 | {#if file} |
| @@ -308,14 +553,14 @@ | |||
| 308 | {#if file.readOnly} | 553 | {#if file.readOnly} |
| 309 | <span class="readonly-hint">{t('workspace.protected')}</span> | 554 | <span class="readonly-hint">{t('workspace.protected')}</span> |
| 310 | {:else} | 555 | {:else} |
| 311 | - <button class="danger-outline" onclick={() => file && (confirming = file.path)}>{t('workspace.delete')}</button> | 556 | + <button class="danger-outline" onclick={() => file && (confirming = [file.path])}>{t('workspace.delete')}</button> |
| 312 | {/if} | 557 | {/if} |
| 313 | </footer> | 558 | </footer> |
| 314 | {:else if file.readOnly} | 559 | {:else if file.readOnly} |
| 315 | <footer><span class="readonly-hint">{t('workspace.protected')}</span></footer> | 560 | <footer><span class="readonly-hint">{t('workspace.protected')}</span></footer> |
| 316 | {:else} | 561 | {:else} |
| 317 | <footer> | 562 | <footer> |
| 318 | - <button class="danger-outline" onclick={() => file && (confirming = file.path)}>{t('workspace.delete')}</button> | 563 | + <button class="danger-outline" onclick={() => file && (confirming = [file.path])}>{t('workspace.delete')}</button> |
| 319 | <span class="spacer"></span> | 564 | <span class="spacer"></span> |
| 320 | <button disabled={!dirty} onclick={() => { if (file) { draft = file.content; editor?.setContent(file.content) } }}>{t('workspace.revert')}</button> | 565 | <button disabled={!dirty} onclick={() => { if (file) { draft = file.content; editor?.setContent(file.content) } }}>{t('workspace.revert')}</button> |
| 321 | <button class="primary" disabled={!dirty} onclick={() => save()}>{t('workspace.save')}</button> | 566 | <button class="primary" disabled={!dirty} onclick={() => save()}>{t('workspace.save')}</button> |
| @@ -333,6 +578,16 @@ | |||
| 333 | ul { list-style: none; margin: 0; padding: 0; } | 578 | ul { list-style: none; margin: 0; padding: 0; } |
| 334 | li { display: flex; align-items: center; border-radius: 4px; } | 579 | li { display: flex; align-items: center; border-radius: 4px; } |
| 335 | li:hover, li.selected { background: var(--panel-2); } | 580 | li:hover, li.selected { background: var(--panel-2); } |
| 581 | + li.selected { background: color-mix(in srgb, var(--accent) 14%, transparent); box-shadow: inset 2px 0 0 var(--accent); } | ||
| 582 | + li.drop, .tree.drop { outline: 1px dashed var(--accent); outline-offset: -1px; } | ||
| 583 | + .rename { flex: 1; min-width: 0; display: flex; gap: 6px; align-items: center; padding: 1px 4px; font-family: var(--mono); font-size: 12.5px; } | ||
| 584 | + .rename input { flex: 1; min-width: 0; font: inherit; padding: 1px 4px; border: 1px solid var(--accent); border-radius: 3px; background: var(--bg); color: var(--text); } | ||
| 585 | + .count { margin: 4px 10px 0; color: var(--muted); font-size: 12px; } | ||
| 586 | + .links { display: flex; gap: 12px; } | ||
| 587 | + .menu { position: fixed; z-index: 50; min-width: 180px; display: flex; flex-direction: column; padding: 4px; border: 1px solid var(--border); border-radius: 6px; background: var(--panel); box-shadow: 0 6px 20px rgb(0 0 0 / 0.25); } | ||
| 588 | + .menu button { border: none; background: none; text-align: left; padding: 4px 10px; border-radius: 4px; font-size: 12.5px; } | ||
| 589 | + .menu button:hover, .menu button:focus-visible { background: var(--panel-2); } | ||
| 590 | + .danger-text { color: var(--danger); } | ||
| 336 | .row { flex: 1; min-width: 0; display: flex; gap: 6px; text-align: left; border: none; background: none; padding: 3px 4px; font-family: var(--mono); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } | 591 | .row { flex: 1; min-width: 0; display: flex; gap: 6px; text-align: left; border: none; background: none; padding: 3px 4px; font-family: var(--mono); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| 337 | .action { border: none; background: none; padding: 0 4px; font-size: 11px; opacity: 0; } | 592 | .action { border: none; background: none; padding: 0 4px; font-size: 11px; opacity: 0; } |
| 338 | .reveal { border: none; background: none; padding: 0; font-size: 12px; color: var(--accent); } | 593 | .reveal { border: none; background: none; padding: 0; font-size: 12px; color: var(--accent); } |
| @@ -342,9 +597,10 @@ | |||
| 342 | .modes button { border: none; border-radius: 0; padding: 2px 10px; font-size: 12px; background: none; } | 597 | .modes button { border: none; border-radius: 0; padding: 2px 10px; font-size: 12px; background: none; } |
| 343 | .modes button.active { background: var(--accent); color: #fff; } | 598 | .modes button.active { background: var(--accent); color: #fff; } |
| 344 | .readonly-hint { color: var(--muted); font-size: 12px; } | 599 | .readonly-hint { color: var(--muted); font-size: 12px; } |
| 345 | - li:hover .action, li:focus-within .action { opacity: 1; } | 600 | + li:hover .action, li:has(:focus-visible) .action { opacity: 1; } |
| 346 | .confirm { flex-wrap: wrap; gap: 6px; margin: 2px 8px 6px; padding: 6px 8px; border: 1px solid var(--danger); font-size: 12px; } | 601 | .confirm { flex-wrap: wrap; gap: 6px; margin: 2px 8px 6px; padding: 6px 8px; border: 1px solid var(--danger); font-size: 12px; } |
| 347 | .confirm span { flex-basis: 100%; } | 602 | .confirm span { flex-basis: 100%; } |
| 603 | + div.confirm { display: flex; border-radius: 4px; } | ||
| 348 | .empty, .pick { color: var(--muted); font-size: 12px; padding: 4px 10px; } | 604 | .empty, .pick { color: var(--muted); font-size: 12px; padding: 4px 10px; } |
| 349 | .pick { margin: auto; } | 605 | .pick { margin: auto; } |
| 350 | .link { align-self: flex-start; margin: 8px 8px 0; border: none; background: none; color: var(--accent); font-size: 12px; padding: 0; } | 606 | .link { align-self: flex-start; margin: 8px 8px 0; border: none; background: none; color: var(--accent); font-size: 12px; padding: 0; } |
added
frontend/src/lib/fileSelection.test.ts +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | |
| 2 | + | |
| 3 | +import { describe, expect, it } from 'vitest' | |
| 4 | +import { canDrop, isUnder, movedPath, nameOf, parentOf, select } from './fileSelection' | |
| 5 | + | |
| 6 | +const rows = ['notes', 'notes/a.md', 'notes/b.md', 'AGENTS.md'] | |
| 7 | + | |
| 8 | +describe('select (issue #70)', () => { | |
| 9 | + it('selects one entry with a plain click', () => { | |
| 10 | + expect(select(rows, ['notes', 'AGENTS.md'], 'notes', 'notes/a.md', {})).toEqual(['notes/a.md']) | |
| 11 | + }) | |
| 12 | + | |
| 13 | + it('adds or takes an entry with ⌘ or Ctrl', () => { | |
| 14 | + expect(select(rows, ['notes'], 'notes', 'AGENTS.md', { toggle: true })).toEqual(['notes', 'AGENTS.md']) | |
| 15 | + expect(select(rows, ['notes', 'AGENTS.md'], 'notes', 'notes', { toggle: true })).toEqual(['AGENTS.md']) | |
| 16 | + }) | |
| 17 | + | |
| 18 | + it('selects a range with ⇧, in either direction', () => { | |
| 19 | + expect(select(rows, ['notes/a.md'], 'notes/a.md', 'AGENTS.md', { range: true })).toEqual(['notes/a.md', 'notes/b.md', 'AGENTS.md']) | |
| 20 | + expect(select(rows, ['AGENTS.md'], 'AGENTS.md', 'notes/a.md', { range: true })).toEqual(['notes/a.md', 'notes/b.md', 'AGENTS.md']) | |
| 21 | + }) | |
| 22 | + | |
| 23 | + it('falls back to one entry when the anchor is not shown', () => { | |
| 24 | + expect(select(rows, [], 'gone.md', 'notes', { range: true })).toEqual(['notes']) | |
| 25 | + }) | |
| 26 | +}) | |
| 27 | + | |
| 28 | +describe('paths', () => { | |
| 29 | + it('splits a path', () => { | |
| 30 | + expect(parentOf('a/b/c.md')).toBe('a/b') | |
| 31 | + expect(parentOf('c.md')).toBe('') | |
| 32 | + expect(nameOf('a/b/c.md')).toBe('c.md') | |
| 33 | + }) | |
| 34 | + | |
| 35 | + it('follows a renamed or moved entry', () => { | |
| 36 | + expect(movedPath('notes', 'notes', 'journal')).toBe('journal') | |
| 37 | + expect(movedPath('notes/plan.md', 'notes', 'archive/notes')).toBe('archive/notes/plan.md') | |
| 38 | + expect(movedPath('notes-2/plan.md', 'notes', 'journal')).toBe('notes-2/plan.md') | |
| 39 | + }) | |
| 40 | + | |
| 41 | + it('tells where entries can be dropped', () => { | |
| 42 | + expect(canDrop(['AGENTS.md'], 'notes')).toBe(true) | |
| 43 | + expect(canDrop(['notes'], 'notes')).toBe(false) | |
| 44 | + expect(canDrop(['notes'], 'notes/old')).toBe(false) | |
| 45 | + expect(canDrop(['notes/a.md'], 'notes')).toBe(false) | |
| 46 | + expect(canDrop(['notes/a.md'], '')).toBe(true) | |
| 47 | + expect(canDrop([], 'notes')).toBe(false) | |
| 48 | + }) | |
| 49 | + | |
| 50 | + it('tells what goes away with removed entries', () => { | |
| 51 | + expect(isUnder('notes/a.md', ['notes'])).toBe(true) | |
| 52 | + expect(isUnder('notes', ['notes'])).toBe(true) | |
| 53 | + expect(isUnder('notes-2', ['notes'])).toBe(false) | |
| 54 | + }) | |
| 55 | +}) | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | ||
| 2 | + | ||
| 3 | +import { describe, expect, it } from 'vitest' | ||
| 4 | +import { canDrop, isUnder, movedPath, nameOf, parentOf, select } from './fileSelection' | ||
| 5 | + | ||
| 6 | +const rows = ['notes', 'notes/a.md', 'notes/b.md', 'AGENTS.md'] | ||
| 7 | + | ||
| 8 | +describe('select (issue #70)', () => { | ||
| 9 | + it('selects one entry with a plain click', () => { | ||
| 10 | + expect(select(rows, ['notes', 'AGENTS.md'], 'notes', 'notes/a.md', {})).toEqual(['notes/a.md']) | ||
| 11 | + }) | ||
| 12 | + | ||
| 13 | + it('adds or takes an entry with ⌘ or Ctrl', () => { | ||
| 14 | + expect(select(rows, ['notes'], 'notes', 'AGENTS.md', { toggle: true })).toEqual(['notes', 'AGENTS.md']) | ||
| 15 | + expect(select(rows, ['notes', 'AGENTS.md'], 'notes', 'notes', { toggle: true })).toEqual(['AGENTS.md']) | ||
| 16 | + }) | ||
| 17 | + | ||
| 18 | + it('selects a range with ⇧, in either direction', () => { | ||
| 19 | + expect(select(rows, ['notes/a.md'], 'notes/a.md', 'AGENTS.md', { range: true })).toEqual(['notes/a.md', 'notes/b.md', 'AGENTS.md']) | ||
| 20 | + expect(select(rows, ['AGENTS.md'], 'AGENTS.md', 'notes/a.md', { range: true })).toEqual(['notes/a.md', 'notes/b.md', 'AGENTS.md']) | ||
| 21 | + }) | ||
| 22 | + | ||
| 23 | + it('falls back to one entry when the anchor is not shown', () => { | ||
| 24 | + expect(select(rows, [], 'gone.md', 'notes', { range: true })).toEqual(['notes']) | ||
| 25 | + }) | ||
| 26 | +}) | ||
| 27 | + | ||
| 28 | +describe('paths', () => { | ||
| 29 | + it('splits a path', () => { | ||
| 30 | + expect(parentOf('a/b/c.md')).toBe('a/b') | ||
| 31 | + expect(parentOf('c.md')).toBe('') | ||
| 32 | + expect(nameOf('a/b/c.md')).toBe('c.md') | ||
| 33 | + }) | ||
| 34 | + | ||
| 35 | + it('follows a renamed or moved entry', () => { | ||
| 36 | + expect(movedPath('notes', 'notes', 'journal')).toBe('journal') | ||
| 37 | + expect(movedPath('notes/plan.md', 'notes', 'archive/notes')).toBe('archive/notes/plan.md') | ||
| 38 | + expect(movedPath('notes-2/plan.md', 'notes', 'journal')).toBe('notes-2/plan.md') | ||
| 39 | + }) | ||
| 40 | + | ||
| 41 | + it('tells where entries can be dropped', () => { | ||
| 42 | + expect(canDrop(['AGENTS.md'], 'notes')).toBe(true) | ||
| 43 | + expect(canDrop(['notes'], 'notes')).toBe(false) | ||
| 44 | + expect(canDrop(['notes'], 'notes/old')).toBe(false) | ||
| 45 | + expect(canDrop(['notes/a.md'], 'notes')).toBe(false) | ||
| 46 | + expect(canDrop(['notes/a.md'], '')).toBe(true) | ||
| 47 | + expect(canDrop([], 'notes')).toBe(false) | ||
| 48 | + }) | ||
| 49 | + | ||
| 50 | + it('tells what goes away with removed entries', () => { | ||
| 51 | + expect(isUnder('notes/a.md', ['notes'])).toBe(true) | ||
| 52 | + expect(isUnder('notes', ['notes'])).toBe(true) | ||
| 53 | + expect(isUnder('notes-2', ['notes'])).toBe(false) | ||
| 54 | + }) | ||
| 55 | +}) | ||
added
frontend/src/lib/fileSelection.ts +74 -0 | new file mode 100644 | ||
| @@ -0,0 +1,74 @@ | ||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | |
| 2 | + | |
| 3 | +// The selection of several entries in the workspace tree, and where the | |
| 4 | +// paths go when entries are renamed or moved (issue #70). Pure functions: | |
| 5 | +// the Files tab calls them. | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * The selection after a click on path: alone, added to or taken from the | |
| 9 | + * selection (⌘ or Ctrl), or every row from the anchor to it (⇧). | |
| 10 | + * | |
| 11 | + * @example | |
| 12 | + * select(['a', 'b', 'c'], ['a'], 'a', 'c', { range: true }) // ['a', 'b', 'c'] | |
| 13 | + */ | |
| 14 | +export function select( | |
| 15 | + rows: string[], | |
| 16 | + current: string[], | |
| 17 | + anchor: string, | |
| 18 | + path: string, | |
| 19 | + modifiers: { toggle?: boolean; range?: boolean }, | |
| 20 | +): string[] { | |
| 21 | + if (modifiers.range && anchor && rows.includes(anchor) && rows.includes(path)) { | |
| 22 | + const [from, to] = [rows.indexOf(anchor), rows.indexOf(path)].sort((a, b) => a - b) | |
| 23 | + return rows.slice(from, to + 1) | |
| 24 | + } | |
| 25 | + if (modifiers.toggle) { | |
| 26 | + return current.includes(path) ? current.filter((candidate) => candidate !== path) : [...current, path] | |
| 27 | + } | |
| 28 | + return [path] | |
| 29 | +} | |
| 30 | + | |
| 31 | +/** The folder of a path, "" for the root: "a/b/c.md" → "a/b". */ | |
| 32 | +export function parentOf(path: string): string { | |
| 33 | + return path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '' | |
| 34 | +} | |
| 35 | + | |
| 36 | +/** The last part of a path: "a/b/c.md" → "c.md". */ | |
| 37 | +export function nameOf(path: string): string { | |
| 38 | + return path.slice(path.lastIndexOf('/') + 1) | |
| 39 | +} | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * Where path is once from was renamed or moved to to: itself, or inside | |
| 43 | + * it; unchanged otherwise. | |
| 44 | + * | |
| 45 | + * @example | |
| 46 | + * movedPath('notes/plan.md', 'notes', 'archive/notes') // 'archive/notes/plan.md' | |
| 47 | + */ | |
| 48 | +export function movedPath(path: string, from: string, to: string): string { | |
| 49 | + if (path === from) return to | |
| 50 | + if (path.startsWith(from + '/')) return to + path.slice(from.length) | |
| 51 | + return path | |
| 52 | +} | |
| 53 | + | |
| 54 | +/** | |
| 55 | + * Whether entries can be dropped into folder: none of them is the folder, | |
| 56 | + * holds it, or is already directly in it. | |
| 57 | + * | |
| 58 | + * @example | |
| 59 | + * canDrop(['notes'], 'notes/old') // false: a folder never goes inside itself | |
| 60 | + */ | |
| 61 | +export function canDrop(paths: string[], folder: string): boolean { | |
| 62 | + if (paths.length === 0) return false | |
| 63 | + return paths.every( | |
| 64 | + (path) => path !== folder && !folder.startsWith(path + '/') && parentOf(path) !== folder, | |
| 65 | + ) | |
| 66 | +} | |
| 67 | + | |
| 68 | +/** | |
| 69 | + * Whether the entry at path disappears when paths are removed: it is one of | |
| 70 | + * them, or inside one. | |
| 71 | + */ | |
| 72 | +export function isUnder(path: string, paths: string[]): boolean { | |
| 73 | + return paths.some((removed) => path === removed || path.startsWith(removed + '/')) | |
| 74 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,74 @@ | |||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | ||
| 2 | + | ||
| 3 | +// The selection of several entries in the workspace tree, and where the | ||
| 4 | +// paths go when entries are renamed or moved (issue #70). Pure functions: | ||
| 5 | +// the Files tab calls them. | ||
| 6 | + | ||
| 7 | +/** | ||
| 8 | + * The selection after a click on path: alone, added to or taken from the | ||
| 9 | + * selection (⌘ or Ctrl), or every row from the anchor to it (⇧). | ||
| 10 | + * | ||
| 11 | + * @example | ||
| 12 | + * select(['a', 'b', 'c'], ['a'], 'a', 'c', { range: true }) // ['a', 'b', 'c'] | ||
| 13 | + */ | ||
| 14 | +export function select( | ||
| 15 | + rows: string[], | ||
| 16 | + current: string[], | ||
| 17 | + anchor: string, | ||
| 18 | + path: string, | ||
| 19 | + modifiers: { toggle?: boolean; range?: boolean }, | ||
| 20 | +): string[] { | ||
| 21 | + if (modifiers.range && anchor && rows.includes(anchor) && rows.includes(path)) { | ||
| 22 | + const [from, to] = [rows.indexOf(anchor), rows.indexOf(path)].sort((a, b) => a - b) | ||
| 23 | + return rows.slice(from, to + 1) | ||
| 24 | + } | ||
| 25 | + if (modifiers.toggle) { | ||
| 26 | + return current.includes(path) ? current.filter((candidate) => candidate !== path) : [...current, path] | ||
| 27 | + } | ||
| 28 | + return [path] | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/** The folder of a path, "" for the root: "a/b/c.md" → "a/b". */ | ||
| 32 | +export function parentOf(path: string): string { | ||
| 33 | + return path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '' | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/** The last part of a path: "a/b/c.md" → "c.md". */ | ||
| 37 | +export function nameOf(path: string): string { | ||
| 38 | + return path.slice(path.lastIndexOf('/') + 1) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/** | ||
| 42 | + * Where path is once from was renamed or moved to to: itself, or inside | ||
| 43 | + * it; unchanged otherwise. | ||
| 44 | + * | ||
| 45 | + * @example | ||
| 46 | + * movedPath('notes/plan.md', 'notes', 'archive/notes') // 'archive/notes/plan.md' | ||
| 47 | + */ | ||
| 48 | +export function movedPath(path: string, from: string, to: string): string { | ||
| 49 | + if (path === from) return to | ||
| 50 | + if (path.startsWith(from + '/')) return to + path.slice(from.length) | ||
| 51 | + return path | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/** | ||
| 55 | + * Whether entries can be dropped into folder: none of them is the folder, | ||
| 56 | + * holds it, or is already directly in it. | ||
| 57 | + * | ||
| 58 | + * @example | ||
| 59 | + * canDrop(['notes'], 'notes/old') // false: a folder never goes inside itself | ||
| 60 | + */ | ||
| 61 | +export function canDrop(paths: string[], folder: string): boolean { | ||
| 62 | + if (paths.length === 0) return false | ||
| 63 | + return paths.every( | ||
| 64 | + (path) => path !== folder && !folder.startsWith(path + '/') && parentOf(path) !== folder, | ||
| 65 | + ) | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/** | ||
| 69 | + * Whether the entry at path disappears when paths are removed: it is one of | ||
| 70 | + * them, or inside one. | ||
| 71 | + */ | ||
| 72 | +export function isUnder(path: string, paths: string[]): boolean { | ||
| 73 | + return paths.some((removed) => path === removed || path.startsWith(removed + '/')) | ||
| 74 | +} | ||
modified
frontend/src/lib/i18n/messages.ts +34 -0 | @@ -245,6 +245,23 @@ export const en = { | ||
| 245 | 245 | 'workspace.noChannel': 'in no channel', |
| 246 | 246 | 'workspace.showHidden': 'Show hidden files', |
| 247 | 247 | 'workspace.newFile': '+ New file', |
| 248 | + 'workspace.newFolder': '+ New folder', | |
| 249 | + 'workspace.newFolderIn': 'New folder in {folder}', | |
| 250 | + 'workspace.folderName': 'Folder name', | |
| 251 | + 'workspace.tree': 'Files of the agent', | |
| 252 | + 'workspace.renameEntry': 'Rename {name}', | |
| 253 | + 'workspace.selected': '{count} selected — ⌘/Ctrl-click or ⇧-click to change the selection', | |
| 254 | + 'workspace.deleteManyConfirm': 'Delete these {count} items? They go to the trash.', | |
| 255 | + 'workspace.deleteManyForGood': 'Delete these {count} items for good? There is no trash in a container or a sandbox.', | |
| 256 | + 'workspace.moveOne': 'Move {name} to the folder', | |
| 257 | + 'workspace.moveMany': 'Move these {count} items to the folder', | |
| 258 | + 'workspace.moveTarget': 'Folder (empty: the top)', | |
| 259 | + 'workspace.move': 'Move', | |
| 260 | + 'workspace.menu.open': 'Open', | |
| 261 | + 'workspace.menu.rename': 'Rename… (F2)', | |
| 262 | + 'workspace.menu.move': 'Move to…', | |
| 263 | + 'workspace.menu.moveMany': 'Move {count} items to…', | |
| 264 | + 'workspace.menu.deleteMany': 'Delete {count} items', | |
| 248 | 265 | 'workspace.newFileIn': 'New file in {folder}', |
| 249 | 266 | 'workspace.fileName': 'File name', |
| 250 | 267 | 'workspace.create': 'Create', |
| @@ -593,6 +610,23 @@ export const fr: Record<MessageKey, string> = { | ||
| 593 | 610 | 'workspace.noChannel': 'dans aucun channel', |
| 594 | 611 | 'workspace.showHidden': 'Afficher les fichiers cachés', |
| 595 | 612 | 'workspace.newFile': '+ Nouveau fichier', |
| 613 | + 'workspace.newFolder': '+ Nouveau dossier', | |
| 614 | + 'workspace.newFolderIn': 'Nouveau dossier dans {folder}', | |
| 615 | + 'workspace.folderName': 'Nom du dossier', | |
| 616 | + 'workspace.tree': "Fichiers de l'agent", | |
| 617 | + 'workspace.renameEntry': 'Renommer {name}', | |
| 618 | + 'workspace.selected': '{count} sélectionnés — ⌘/Ctrl-clic ou ⇧-clic pour changer la sélection', | |
| 619 | + 'workspace.deleteManyConfirm': 'Supprimer ces {count} éléments ? Ils partent à la corbeille.', | |
| 620 | + 'workspace.deleteManyForGood': "Supprimer définitivement ces {count} éléments ? Il n'y a pas de corbeille dans un conteneur ou une sandbox.", | |
| 621 | + 'workspace.moveOne': 'Déplacer {name} dans le dossier', | |
| 622 | + 'workspace.moveMany': 'Déplacer ces {count} éléments dans le dossier', | |
| 623 | + 'workspace.moveTarget': 'Dossier (vide : la racine)', | |
| 624 | + 'workspace.move': 'Déplacer', | |
| 625 | + 'workspace.menu.open': 'Ouvrir', | |
| 626 | + 'workspace.menu.rename': 'Renommer… (F2)', | |
| 627 | + 'workspace.menu.move': 'Déplacer vers…', | |
| 628 | + 'workspace.menu.moveMany': 'Déplacer {count} éléments vers…', | |
| 629 | + 'workspace.menu.deleteMany': 'Supprimer {count} éléments', | |
| 596 | 630 | 'workspace.newFileIn': 'Nouveau fichier dans {folder}', |
| 597 | 631 | 'workspace.fileName': 'Nom du fichier', |
| 598 | 632 | 'workspace.create': 'Créer', |
| @@ -245,6 +245,23 @@ export const en = { | |||
| 245 | 'workspace.noChannel': 'in no channel', | 245 | 'workspace.noChannel': 'in no channel', |
| 246 | 'workspace.showHidden': 'Show hidden files', | 246 | 'workspace.showHidden': 'Show hidden files', |
| 247 | 'workspace.newFile': '+ New file', | 247 | 'workspace.newFile': '+ New file', |
| 248 | + 'workspace.newFolder': '+ New folder', | ||
| 249 | + 'workspace.newFolderIn': 'New folder in {folder}', | ||
| 250 | + 'workspace.folderName': 'Folder name', | ||
| 251 | + 'workspace.tree': 'Files of the agent', | ||
| 252 | + 'workspace.renameEntry': 'Rename {name}', | ||
| 253 | + 'workspace.selected': '{count} selected — ⌘/Ctrl-click or ⇧-click to change the selection', | ||
| 254 | + 'workspace.deleteManyConfirm': 'Delete these {count} items? They go to the trash.', | ||
| 255 | + 'workspace.deleteManyForGood': 'Delete these {count} items for good? There is no trash in a container or a sandbox.', | ||
| 256 | + 'workspace.moveOne': 'Move {name} to the folder', | ||
| 257 | + 'workspace.moveMany': 'Move these {count} items to the folder', | ||
| 258 | + 'workspace.moveTarget': 'Folder (empty: the top)', | ||
| 259 | + 'workspace.move': 'Move', | ||
| 260 | + 'workspace.menu.open': 'Open', | ||
| 261 | + 'workspace.menu.rename': 'Rename… (F2)', | ||
| 262 | + 'workspace.menu.move': 'Move to…', | ||
| 263 | + 'workspace.menu.moveMany': 'Move {count} items to…', | ||
| 264 | + 'workspace.menu.deleteMany': 'Delete {count} items', | ||
| 248 | 'workspace.newFileIn': 'New file in {folder}', | 265 | 'workspace.newFileIn': 'New file in {folder}', |
| 249 | 'workspace.fileName': 'File name', | 266 | 'workspace.fileName': 'File name', |
| 250 | 'workspace.create': 'Create', | 267 | 'workspace.create': 'Create', |
| @@ -593,6 +610,23 @@ export const fr: Record<MessageKey, string> = { | |||
| 593 | 'workspace.noChannel': 'dans aucun channel', | 610 | 'workspace.noChannel': 'dans aucun channel', |
| 594 | 'workspace.showHidden': 'Afficher les fichiers cachés', | 611 | 'workspace.showHidden': 'Afficher les fichiers cachés', |
| 595 | 'workspace.newFile': '+ Nouveau fichier', | 612 | 'workspace.newFile': '+ Nouveau fichier', |
| 613 | + 'workspace.newFolder': '+ Nouveau dossier', | ||
| 614 | + 'workspace.newFolderIn': 'Nouveau dossier dans {folder}', | ||
| 615 | + 'workspace.folderName': 'Nom du dossier', | ||
| 616 | + 'workspace.tree': "Fichiers de l'agent", | ||
| 617 | + 'workspace.renameEntry': 'Renommer {name}', | ||
| 618 | + 'workspace.selected': '{count} sélectionnés — ⌘/Ctrl-clic ou ⇧-clic pour changer la sélection', | ||
| 619 | + 'workspace.deleteManyConfirm': 'Supprimer ces {count} éléments ? Ils partent à la corbeille.', | ||
| 620 | + 'workspace.deleteManyForGood': "Supprimer définitivement ces {count} éléments ? Il n'y a pas de corbeille dans un conteneur ou une sandbox.", | ||
| 621 | + 'workspace.moveOne': 'Déplacer {name} dans le dossier', | ||
| 622 | + 'workspace.moveMany': 'Déplacer ces {count} éléments dans le dossier', | ||
| 623 | + 'workspace.moveTarget': 'Dossier (vide : la racine)', | ||
| 624 | + 'workspace.move': 'Déplacer', | ||
| 625 | + 'workspace.menu.open': 'Ouvrir', | ||
| 626 | + 'workspace.menu.rename': 'Renommer… (F2)', | ||
| 627 | + 'workspace.menu.move': 'Déplacer vers…', | ||
| 628 | + 'workspace.menu.moveMany': 'Déplacer {count} éléments vers…', | ||
| 629 | + 'workspace.menu.deleteMany': 'Supprimer {count} éléments', | ||
| 596 | 'workspace.newFileIn': 'Nouveau fichier dans {folder}', | 630 | 'workspace.newFileIn': 'Nouveau fichier dans {folder}', |
| 597 | 'workspace.fileName': 'Nom du fichier', | 631 | 'workspace.fileName': 'Nom du fichier', |
| 598 | 'workspace.create': 'Créer', | 632 | 'workspace.create': 'Créer', |
modified
internal/app/app_test.go +34 -0 | @@ -394,6 +394,40 @@ func TestTheWorkspaceServiceEditsAnAgentsFiles(t *testing.T) { | ||
| 394 | 394 | } |
| 395 | 395 | } |
| 396 | 396 | |
| 397 | +func TestTheWorkspaceServiceRenamesMovesAndRemovesSeveralFiles(t *testing.T) { | |
| 398 | + core, folder, _ := workspaceCore(t) | |
| 399 | + service := &app.WorkspaceService{Core: core} | |
| 400 | + ctx := context.Background() | |
| 401 | + t.Setenv("HOME", t.TempDir()) | |
| 402 | + t.Setenv("XDG_DATA_HOME", t.TempDir()) | |
| 403 | + if renamed, err := service.Rename(ctx, "alice", "notes.md", "journal.md"); err != nil || renamed != "journal.md" { | |
| 404 | + t.Fatalf("rename: %q %v", renamed, err) | |
| 405 | + } | |
| 406 | + if created, err := service.CreateFolder(ctx, "alice", "", "archive"); err != nil || created != "archive" { | |
| 407 | + t.Fatalf("folder: %q %v", created, err) | |
| 408 | + } | |
| 409 | + if _, err := service.CreateFolder(ctx, "alice", "", "a/b"); err == nil { | |
| 410 | + t.Fatal("a folder name with / is refused") | |
| 411 | + } | |
| 412 | + write(t, filepath.Join(folder, "plan.md"), "plan") | |
| 413 | + moved, err := service.Move(ctx, "alice", []string{"journal.md", "plan.md"}, "archive") | |
| 414 | + if err != nil || strings.Join(moved, ",") != "archive/journal.md,archive/plan.md" { | |
| 415 | + t.Fatalf("move: %v %v", moved, err) | |
| 416 | + } | |
| 417 | + if moved, err := service.Move(ctx, "alice", []string{"archive/plan.md"}, "archive"); err != nil || moved[0] != "archive/plan.md" { | |
| 418 | + t.Fatalf("moving into its own folder changes nothing: %v %v", moved, err) | |
| 419 | + } | |
| 420 | + write(t, filepath.Join(folder, "draft.md"), "draft") | |
| 421 | + if err := service.RemoveAll(ctx, "alice", []string{"archive/journal.md", "archive", "draft.md"}); err != nil { | |
| 422 | + t.Fatal(err) | |
| 423 | + } | |
| 424 | + for _, gone := range []string{"archive", "draft.md"} { | |
| 425 | + if _, err := os.Stat(filepath.Join(folder, gone)); !os.IsNotExist(err) { | |
| 426 | + t.Fatalf("%s should be gone", gone) | |
| 427 | + } | |
| 428 | + } | |
| 429 | +} | |
| 430 | + | |
| 397 | 431 | func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) { |
| 398 | 432 | core, folder, recorder := workspaceCore(t) |
| 399 | 433 | service := &app.WorkspaceService{Core: core} |
| @@ -394,6 +394,40 @@ func TestTheWorkspaceServiceEditsAnAgentsFiles(t *testing.T) { | |||
| 394 | } | 394 | } |
| 395 | } | 395 | } |
| 396 | 396 | ||
| 397 | +func TestTheWorkspaceServiceRenamesMovesAndRemovesSeveralFiles(t *testing.T) { | ||
| 398 | + core, folder, _ := workspaceCore(t) | ||
| 399 | + service := &app.WorkspaceService{Core: core} | ||
| 400 | + ctx := context.Background() | ||
| 401 | + t.Setenv("HOME", t.TempDir()) | ||
| 402 | + t.Setenv("XDG_DATA_HOME", t.TempDir()) | ||
| 403 | + if renamed, err := service.Rename(ctx, "alice", "notes.md", "journal.md"); err != nil || renamed != "journal.md" { | ||
| 404 | + t.Fatalf("rename: %q %v", renamed, err) | ||
| 405 | + } | ||
| 406 | + if created, err := service.CreateFolder(ctx, "alice", "", "archive"); err != nil || created != "archive" { | ||
| 407 | + t.Fatalf("folder: %q %v", created, err) | ||
| 408 | + } | ||
| 409 | + if _, err := service.CreateFolder(ctx, "alice", "", "a/b"); err == nil { | ||
| 410 | + t.Fatal("a folder name with / is refused") | ||
| 411 | + } | ||
| 412 | + write(t, filepath.Join(folder, "plan.md"), "plan") | ||
| 413 | + moved, err := service.Move(ctx, "alice", []string{"journal.md", "plan.md"}, "archive") | ||
| 414 | + if err != nil || strings.Join(moved, ",") != "archive/journal.md,archive/plan.md" { | ||
| 415 | + t.Fatalf("move: %v %v", moved, err) | ||
| 416 | + } | ||
| 417 | + if moved, err := service.Move(ctx, "alice", []string{"archive/plan.md"}, "archive"); err != nil || moved[0] != "archive/plan.md" { | ||
| 418 | + t.Fatalf("moving into its own folder changes nothing: %v %v", moved, err) | ||
| 419 | + } | ||
| 420 | + write(t, filepath.Join(folder, "draft.md"), "draft") | ||
| 421 | + if err := service.RemoveAll(ctx, "alice", []string{"archive/journal.md", "archive", "draft.md"}); err != nil { | ||
| 422 | + t.Fatal(err) | ||
| 423 | + } | ||
| 424 | + for _, gone := range []string{"archive", "draft.md"} { | ||
| 425 | + if _, err := os.Stat(filepath.Join(folder, gone)); !os.IsNotExist(err) { | ||
| 426 | + t.Fatalf("%s should be gone", gone) | ||
| 427 | + } | ||
| 428 | + } | ||
| 429 | +} | ||
| 430 | + | ||
| 397 | func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) { | 431 | func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) { |
| 398 | core, folder, recorder := workspaceCore(t) | 432 | core, folder, recorder := workspaceCore(t) |
| 399 | service := &app.WorkspaceService{Core: core} | 433 | service := &app.WorkspaceService{Core: core} |
modified
internal/app/protect_test.go +24 -0 | @@ -81,3 +81,27 @@ func TestProtectedFilesAreMarkedReadOnlyAndKept(t *testing.T) { | ||
| 81 | 81 | t.Fatalf("the other files stay editable: %v", err) |
| 82 | 82 | } |
| 83 | 83 | } |
| 84 | + | |
| 85 | +func TestProtectedFilesCannotBeRenamedMovedNorRemovedTogether(t *testing.T) { | |
| 86 | + service, folder := protectedSetup(t) | |
| 87 | + ctx := context.Background() | |
| 88 | + t.Setenv("HOME", t.TempDir()) | |
| 89 | + t.Setenv("XDG_DATA_HOME", t.TempDir()) | |
| 90 | + for _, from := range []string{"AGENTS.md", "skills"} { | |
| 91 | + if _, err := service.Rename(ctx, "bob", from, "elsewhere"); !errors.Is(err, workspace.ErrProtected) { | |
| 92 | + t.Fatalf("renaming %s is refused: %v", from, err) | |
| 93 | + } | |
| 94 | + } | |
| 95 | + if _, err := service.Rename(ctx, "bob", "notes.md", "skills/notes.md"); !errors.Is(err, workspace.ErrProtected) { | |
| 96 | + t.Fatalf("a protected new path is refused: %v", err) | |
| 97 | + } | |
| 98 | + if _, err := service.Move(ctx, "bob", []string{"agent.yaml"}, "archive"); !errors.Is(err, workspace.ErrProtected) { | |
| 99 | + t.Fatalf("moving a protected file is refused: %v", err) | |
| 100 | + } | |
| 101 | + if err := service.RemoveAll(ctx, "bob", []string{"notes.md", "AGENTS.md"}); !errors.Is(err, workspace.ErrProtected) { | |
| 102 | + t.Fatalf("removing a protected file with others is refused: %v", err) | |
| 103 | + } | |
| 104 | + if _, err := os.Stat(filepath.Join(folder, "notes.md")); err != nil { | |
| 105 | + t.Fatal("nothing is removed when one of the files is protected") | |
| 106 | + } | |
| 107 | +} | |
| @@ -81,3 +81,27 @@ func TestProtectedFilesAreMarkedReadOnlyAndKept(t *testing.T) { | |||
| 81 | t.Fatalf("the other files stay editable: %v", err) | 81 | t.Fatalf("the other files stay editable: %v", err) |
| 82 | } | 82 | } |
| 83 | } | 83 | } |
| 84 | + | ||
| 85 | +func TestProtectedFilesCannotBeRenamedMovedNorRemovedTogether(t *testing.T) { | ||
| 86 | + service, folder := protectedSetup(t) | ||
| 87 | + ctx := context.Background() | ||
| 88 | + t.Setenv("HOME", t.TempDir()) | ||
| 89 | + t.Setenv("XDG_DATA_HOME", t.TempDir()) | ||
| 90 | + for _, from := range []string{"AGENTS.md", "skills"} { | ||
| 91 | + if _, err := service.Rename(ctx, "bob", from, "elsewhere"); !errors.Is(err, workspace.ErrProtected) { | ||
| 92 | + t.Fatalf("renaming %s is refused: %v", from, err) | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | + if _, err := service.Rename(ctx, "bob", "notes.md", "skills/notes.md"); !errors.Is(err, workspace.ErrProtected) { | ||
| 96 | + t.Fatalf("a protected new path is refused: %v", err) | ||
| 97 | + } | ||
| 98 | + if _, err := service.Move(ctx, "bob", []string{"agent.yaml"}, "archive"); !errors.Is(err, workspace.ErrProtected) { | ||
| 99 | + t.Fatalf("moving a protected file is refused: %v", err) | ||
| 100 | + } | ||
| 101 | + if err := service.RemoveAll(ctx, "bob", []string{"notes.md", "AGENTS.md"}); !errors.Is(err, workspace.ErrProtected) { | ||
| 102 | + t.Fatalf("removing a protected file with others is refused: %v", err) | ||
| 103 | + } | ||
| 104 | + if _, err := os.Stat(filepath.Join(folder, "notes.md")); err != nil { | ||
| 105 | + t.Fatal("nothing is removed when one of the files is protected") | ||
| 106 | + } | ||
| 107 | +} | ||
modified
internal/app/workspaces.go +91 -0 | @@ -169,6 +169,97 @@ func (s *WorkspaceService) Remove(ctx context.Context, agent, file string) error | ||
| 169 | 169 | return ws.Remove(ctx, file) |
| 170 | 170 | } |
| 171 | 171 | |
| 172 | +// RemoveAll removes several files and folders at once (issue #70). Nothing | |
| 173 | +// is removed when one of them is protected, or holds a protected file. | |
| 174 | +func (s *WorkspaceService) RemoveAll(ctx context.Context, agent string, files []string) error { | |
| 175 | + ws, err := s.Core.workspaceOf(agent) | |
| 176 | + if err != nil { | |
| 177 | + return err | |
| 178 | + } | |
| 179 | + outermost, err := workspace.Outermost(files) | |
| 180 | + if err != nil { | |
| 181 | + return err | |
| 182 | + } | |
| 183 | + protection := s.Core.protectionOf(agent) | |
| 184 | + for _, file := range outermost { | |
| 185 | + if protection.Blocks(file) { | |
| 186 | + return fmt.Errorf("%s: %w", file, workspace.ErrProtected) | |
| 187 | + } | |
| 188 | + } | |
| 189 | + for _, file := range outermost { | |
| 190 | + if err := ws.Remove(ctx, file); err != nil && !errors.Is(err, workspace.ErrNotFound) { | |
| 191 | + return fmt.Errorf("%s: %w", file, err) | |
| 192 | + } | |
| 193 | + } | |
| 194 | + return nil | |
| 195 | +} | |
| 196 | + | |
| 197 | +// Rename renames a file or a folder, or moves it when to is in another | |
| 198 | +// folder (issue #70); it returns the new path. A protected file, a folder | |
| 199 | +// that holds one, or a protected new path is refused. | |
| 200 | +func (s *WorkspaceService) Rename(ctx context.Context, agent, from, to string) (string, error) { | |
| 201 | + ws, err := s.Core.workspaceOf(agent) | |
| 202 | + if err != nil { | |
| 203 | + return "", err | |
| 204 | + } | |
| 205 | + target, err := workspace.Clean(to) | |
| 206 | + if err != nil { | |
| 207 | + return "", err | |
| 208 | + } | |
| 209 | + protection := s.Core.protectionOf(agent) | |
| 210 | + if protection.Blocks(from) || protection.Protects(target) { | |
| 211 | + return "", workspace.ErrProtected | |
| 212 | + } | |
| 213 | + return target, ws.Rename(ctx, from, target) | |
| 214 | +} | |
| 215 | + | |
| 216 | +// Move moves files and folders into folder dir ("" for the root), keeping | |
| 217 | +// their names (issue #70), and returns their new paths. It stops at the | |
| 218 | +// first one that cannot move: those before it have moved. | |
| 219 | +func (s *WorkspaceService) Move(ctx context.Context, agent string, files []string, dir string) ([]string, error) { | |
| 220 | + outermost, err := workspace.Outermost(files) | |
| 221 | + if err != nil { | |
| 222 | + return nil, err | |
| 223 | + } | |
| 224 | + folder, err := workspace.Clean(dir) | |
| 225 | + if err != nil { | |
| 226 | + return nil, err | |
| 227 | + } | |
| 228 | + moved := []string{} | |
| 229 | + for _, file := range outermost { | |
| 230 | + if parent := path.Dir(file); parent == folder || (parent == "." && folder == "") { | |
| 231 | + moved = append(moved, file) // already there | |
| 232 | + continue | |
| 233 | + } | |
| 234 | + target, err := s.Rename(ctx, agent, file, path.Join(folder, path.Base(file))) | |
| 235 | + if err != nil { | |
| 236 | + return moved, fmt.Errorf("%s: %w", file, err) | |
| 237 | + } | |
| 238 | + moved = append(moved, target) | |
| 239 | + } | |
| 240 | + return moved, nil | |
| 241 | +} | |
| 242 | + | |
| 243 | +// CreateFolder creates an empty folder called name in folder dir and | |
| 244 | +// returns its path (issue #70). | |
| 245 | +func (s *WorkspaceService) CreateFolder(ctx context.Context, agent, dir, name string) (string, error) { | |
| 246 | + ws, err := s.Core.workspaceOf(agent) | |
| 247 | + if err != nil { | |
| 248 | + return "", err | |
| 249 | + } | |
| 250 | + if name == "" || path.Base(name) != name || name == "." || name == ".." { | |
| 251 | + return "", errors.New("a folder name cannot be empty nor contain /") | |
| 252 | + } | |
| 253 | + folder, err := workspace.Clean(path.Join(dir, name)) | |
| 254 | + if err != nil { | |
| 255 | + return "", err | |
| 256 | + } | |
| 257 | + if s.Core.protectionOf(agent).Protects(folder) { | |
| 258 | + return "", workspace.ErrProtected | |
| 259 | + } | |
| 260 | + return folder, ws.MakeDir(ctx, folder) | |
| 261 | +} | |
| 262 | + | |
| 172 | 263 | // Watch follows the changes of the agent's folder, announced by |
| 173 | 264 | // workspace:changed events, until Unwatch or another Watch. |
| 174 | 265 | func (s *WorkspaceService) Watch(agent string) error { |
| @@ -169,6 +169,97 @@ func (s *WorkspaceService) Remove(ctx context.Context, agent, file string) error | |||
| 169 | return ws.Remove(ctx, file) | 169 | return ws.Remove(ctx, file) |
| 170 | } | 170 | } |
| 171 | 171 | ||
| 172 | +// RemoveAll removes several files and folders at once (issue #70). Nothing | ||
| 173 | +// is removed when one of them is protected, or holds a protected file. | ||
| 174 | +func (s *WorkspaceService) RemoveAll(ctx context.Context, agent string, files []string) error { | ||
| 175 | + ws, err := s.Core.workspaceOf(agent) | ||
| 176 | + if err != nil { | ||
| 177 | + return err | ||
| 178 | + } | ||
| 179 | + outermost, err := workspace.Outermost(files) | ||
| 180 | + if err != nil { | ||
| 181 | + return err | ||
| 182 | + } | ||
| 183 | + protection := s.Core.protectionOf(agent) | ||
| 184 | + for _, file := range outermost { | ||
| 185 | + if protection.Blocks(file) { | ||
| 186 | + return fmt.Errorf("%s: %w", file, workspace.ErrProtected) | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + for _, file := range outermost { | ||
| 190 | + if err := ws.Remove(ctx, file); err != nil && !errors.Is(err, workspace.ErrNotFound) { | ||
| 191 | + return fmt.Errorf("%s: %w", file, err) | ||
| 192 | + } | ||
| 193 | + } | ||
| 194 | + return nil | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +// Rename renames a file or a folder, or moves it when to is in another | ||
| 198 | +// folder (issue #70); it returns the new path. A protected file, a folder | ||
| 199 | +// that holds one, or a protected new path is refused. | ||
| 200 | +func (s *WorkspaceService) Rename(ctx context.Context, agent, from, to string) (string, error) { | ||
| 201 | + ws, err := s.Core.workspaceOf(agent) | ||
| 202 | + if err != nil { | ||
| 203 | + return "", err | ||
| 204 | + } | ||
| 205 | + target, err := workspace.Clean(to) | ||
| 206 | + if err != nil { | ||
| 207 | + return "", err | ||
| 208 | + } | ||
| 209 | + protection := s.Core.protectionOf(agent) | ||
| 210 | + if protection.Blocks(from) || protection.Protects(target) { | ||
| 211 | + return "", workspace.ErrProtected | ||
| 212 | + } | ||
| 213 | + return target, ws.Rename(ctx, from, target) | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +// Move moves files and folders into folder dir ("" for the root), keeping | ||
| 217 | +// their names (issue #70), and returns their new paths. It stops at the | ||
| 218 | +// first one that cannot move: those before it have moved. | ||
| 219 | +func (s *WorkspaceService) Move(ctx context.Context, agent string, files []string, dir string) ([]string, error) { | ||
| 220 | + outermost, err := workspace.Outermost(files) | ||
| 221 | + if err != nil { | ||
| 222 | + return nil, err | ||
| 223 | + } | ||
| 224 | + folder, err := workspace.Clean(dir) | ||
| 225 | + if err != nil { | ||
| 226 | + return nil, err | ||
| 227 | + } | ||
| 228 | + moved := []string{} | ||
| 229 | + for _, file := range outermost { | ||
| 230 | + if parent := path.Dir(file); parent == folder || (parent == "." && folder == "") { | ||
| 231 | + moved = append(moved, file) // already there | ||
| 232 | + continue | ||
| 233 | + } | ||
| 234 | + target, err := s.Rename(ctx, agent, file, path.Join(folder, path.Base(file))) | ||
| 235 | + if err != nil { | ||
| 236 | + return moved, fmt.Errorf("%s: %w", file, err) | ||
| 237 | + } | ||
| 238 | + moved = append(moved, target) | ||
| 239 | + } | ||
| 240 | + return moved, nil | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +// CreateFolder creates an empty folder called name in folder dir and | ||
| 244 | +// returns its path (issue #70). | ||
| 245 | +func (s *WorkspaceService) CreateFolder(ctx context.Context, agent, dir, name string) (string, error) { | ||
| 246 | + ws, err := s.Core.workspaceOf(agent) | ||
| 247 | + if err != nil { | ||
| 248 | + return "", err | ||
| 249 | + } | ||
| 250 | + if name == "" || path.Base(name) != name || name == "." || name == ".." { | ||
| 251 | + return "", errors.New("a folder name cannot be empty nor contain /") | ||
| 252 | + } | ||
| 253 | + folder, err := workspace.Clean(path.Join(dir, name)) | ||
| 254 | + if err != nil { | ||
| 255 | + return "", err | ||
| 256 | + } | ||
| 257 | + if s.Core.protectionOf(agent).Protects(folder) { | ||
| 258 | + return "", workspace.ErrProtected | ||
| 259 | + } | ||
| 260 | + return folder, ws.MakeDir(ctx, folder) | ||
| 261 | +} | ||
| 262 | + | ||
| 172 | // Watch follows the changes of the agent's folder, announced by | 263 | // Watch follows the changes of the agent's folder, announced by |
| 173 | // workspace:changed events, until Unwatch or another Watch. | 264 | // workspace:changed events, until Unwatch or another Watch. |
| 174 | func (s *WorkspaceService) Watch(agent string) error { | 265 | func (s *WorkspaceService) Watch(agent string) error { |
modified
internal/workspace/container.go +33 -0 | @@ -241,6 +241,39 @@ func (c *Remote) Remove(ctx context.Context, p string) error { | ||
| 241 | 241 | return err |
| 242 | 242 | } |
| 243 | 243 | |
| 244 | +// Rename implements Workspace. | |
| 245 | +func (c *Remote) Rename(ctx context.Context, from, to string) error { | |
| 246 | + source, fromRel, err := c.resolve(from) | |
| 247 | + if err != nil { | |
| 248 | + return err | |
| 249 | + } | |
| 250 | + target, toRel, err := c.resolve(to) | |
| 251 | + if err != nil { | |
| 252 | + return err | |
| 253 | + } | |
| 254 | + if err := checkRename(fromRel, toRel); err != nil { | |
| 255 | + return err | |
| 256 | + } | |
| 257 | + const script = `test -e "$1" || test -L "$1" || exit 3 | |
| 258 | +if test -e "$2" || test -L "$2"; then exit 5; fi | |
| 259 | +mkdir -p "$(dirname "$2")" && mv -- "$1" "$2"` | |
| 260 | + _, err = c.run(ctx, script, source, nil, target) | |
| 261 | + return err | |
| 262 | +} | |
| 263 | + | |
| 264 | +// MakeDir implements Workspace. | |
| 265 | +func (c *Remote) MakeDir(ctx context.Context, p string) error { | |
| 266 | + abs, rel, err := c.resolve(p) | |
| 267 | + if err != nil { | |
| 268 | + return err | |
| 269 | + } | |
| 270 | + if rel == "" { | |
| 271 | + return ErrExists | |
| 272 | + } | |
| 273 | + _, err = c.run(ctx, `if test -e "$1" || test -L "$1"; then exit 5; fi; mkdir -p "$1"`, abs, nil) | |
| 274 | + return err | |
| 275 | +} | |
| 276 | + | |
| 244 | 277 | // Changes implements Workspace by comparing, every two seconds, the dates |
| 245 | 278 | // and sizes of the files: a container or a sandbox offers no notifications |
| 246 | 279 | // to the outside. |
| @@ -241,6 +241,39 @@ func (c *Remote) Remove(ctx context.Context, p string) error { | |||
| 241 | return err | 241 | return err |
| 242 | } | 242 | } |
| 243 | 243 | ||
| 244 | +// Rename implements Workspace. | ||
| 245 | +func (c *Remote) Rename(ctx context.Context, from, to string) error { | ||
| 246 | + source, fromRel, err := c.resolve(from) | ||
| 247 | + if err != nil { | ||
| 248 | + return err | ||
| 249 | + } | ||
| 250 | + target, toRel, err := c.resolve(to) | ||
| 251 | + if err != nil { | ||
| 252 | + return err | ||
| 253 | + } | ||
| 254 | + if err := checkRename(fromRel, toRel); err != nil { | ||
| 255 | + return err | ||
| 256 | + } | ||
| 257 | + const script = `test -e "$1" || test -L "$1" || exit 3 | ||
| 258 | +if test -e "$2" || test -L "$2"; then exit 5; fi | ||
| 259 | +mkdir -p "$(dirname "$2")" && mv -- "$1" "$2"` | ||
| 260 | + _, err = c.run(ctx, script, source, nil, target) | ||
| 261 | + return err | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +// MakeDir implements Workspace. | ||
| 265 | +func (c *Remote) MakeDir(ctx context.Context, p string) error { | ||
| 266 | + abs, rel, err := c.resolve(p) | ||
| 267 | + if err != nil { | ||
| 268 | + return err | ||
| 269 | + } | ||
| 270 | + if rel == "" { | ||
| 271 | + return ErrExists | ||
| 272 | + } | ||
| 273 | + _, err = c.run(ctx, `if test -e "$1" || test -L "$1"; then exit 5; fi; mkdir -p "$1"`, abs, nil) | ||
| 274 | + return err | ||
| 275 | +} | ||
| 276 | + | ||
| 244 | // Changes implements Workspace by comparing, every two seconds, the dates | 277 | // Changes implements Workspace by comparing, every two seconds, the dates |
| 245 | // and sizes of the files: a container or a sandbox offers no notifications | 278 | // and sizes of the files: a container or a sandbox offers no notifications |
| 246 | // to the outside. | 279 | // to the outside. |
modified
internal/workspace/contract_test.go +69 -0 | @@ -128,6 +128,8 @@ func contract(t *testing.T, open opener) { | ||
| 128 | 128 | {"reads any file as bytes", checkReadsAnyFileAsBytes}, |
| 129 | 129 | {"imports a file under a free name", checkImportsAFileUnderAFreeName}, |
| 130 | 130 | {"removes a file and a folder", checkRemovesAFileAndAFolder}, |
| 131 | + {"renames and moves files and folders", checkRenamesAndMovesFilesAndFolders}, | |
| 132 | + {"creates a folder", checkCreatesAFolder}, | |
| 131 | 133 | {"signals changes", checkSignalsChanges}, |
| 132 | 134 | {"opens a shell in the folder", checkOpensAShellInTheFolder}, |
| 133 | 135 | {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt}, |
| @@ -282,6 +284,60 @@ func checkRemovesAFileAndAFolder(t *testing.T, open opener) { | ||
| 282 | 284 | } |
| 283 | 285 | } |
| 284 | 286 | |
| 287 | +func checkRenamesAndMovesFilesAndFolders(t *testing.T, open opener) { | |
| 288 | + ctx := context.Background() | |
| 289 | + ws := startWorkspace(t, open) | |
| 290 | + if err := ws.Rename(ctx, "AGENTS.md", "notes/STYLE.md"); err != nil { | |
| 291 | + t.Fatal(err) | |
| 292 | + } | |
| 293 | + if file, err := ws.Read(ctx, "notes/STYLE.md"); err != nil || file.Content != "# Style\n" { | |
| 294 | + t.Fatalf("moved file: %+v %v", file, err) | |
| 295 | + } | |
| 296 | + if _, err := ws.Read(ctx, "AGENTS.md"); !errors.Is(err, workspace.ErrNotFound) { | |
| 297 | + t.Fatalf("the old name is gone, got %v", err) | |
| 298 | + } | |
| 299 | + // A folder moves with its content, into a folder created on the way. | |
| 300 | + if err := ws.Rename(ctx, "skills", "archive/2026/skills"); err != nil { | |
| 301 | + t.Fatal(err) | |
| 302 | + } | |
| 303 | + if file, err := ws.Read(ctx, "archive/2026/skills/idioms/SKILL.md"); err != nil || file.Content != "idioms" { | |
| 304 | + t.Fatalf("moved folder: %+v %v", file, err) | |
| 305 | + } | |
| 306 | + if err := ws.Rename(ctx, "notes/STYLE.md", "archive"); !errors.Is(err, workspace.ErrExists) { | |
| 307 | + t.Fatalf("never over an existing entry, got %v", err) | |
| 308 | + } | |
| 309 | + if err := ws.Rename(ctx, "missing.md", "found.md"); !errors.Is(err, workspace.ErrNotFound) { | |
| 310 | + t.Fatalf("want ErrNotFound, got %v", err) | |
| 311 | + } | |
| 312 | + if err := ws.Rename(ctx, "archive", "archive/inside"); err == nil { | |
| 313 | + t.Fatal("a folder cannot go inside itself") | |
| 314 | + } | |
| 315 | + if err := ws.Rename(ctx, "notes", "../notes"); !errors.Is(err, workspace.ErrOutside) { | |
| 316 | + t.Fatalf("want ErrOutside, got %v", err) | |
| 317 | + } | |
| 318 | + if err := ws.Rename(ctx, "", "elsewhere"); !errors.Is(err, workspace.ErrOutside) { | |
| 319 | + t.Fatalf("never the whole folder, got %v", err) | |
| 320 | + } | |
| 321 | +} | |
| 322 | + | |
| 323 | +func checkCreatesAFolder(t *testing.T, open opener) { | |
| 324 | + ctx := context.Background() | |
| 325 | + ws := startWorkspace(t, open) | |
| 326 | + if err := ws.MakeDir(ctx, "drafts/2026"); err != nil { | |
| 327 | + t.Fatal(err) | |
| 328 | + } | |
| 329 | + entries, err := ws.List(ctx, "drafts") | |
| 330 | + if err != nil || len(entries) != 1 || !entries[0].Dir || entries[0].Path != "drafts/2026" { | |
| 331 | + t.Fatalf("got %+v %v", entries, err) | |
| 332 | + } | |
| 333 | + if err := ws.MakeDir(ctx, "notes"); !errors.Is(err, workspace.ErrExists) { | |
| 334 | + t.Fatalf("want ErrExists, got %v", err) | |
| 335 | + } | |
| 336 | + if err := ws.MakeDir(ctx, "AGENTS.md"); !errors.Is(err, workspace.ErrExists) { | |
| 337 | + t.Fatalf("want ErrExists for a file, got %v", err) | |
| 338 | + } | |
| 339 | +} | |
| 340 | + | |
| 285 | 341 | func checkSignalsChanges(t *testing.T, open opener) { |
| 286 | 342 | ctx := context.Background() |
| 287 | 343 | ws := startWorkspace(t, open) |
| @@ -449,6 +505,19 @@ func TestCleanKeepsPathsInsideTheFolder(t *testing.T) { | ||
| 449 | 505 | } |
| 450 | 506 | } |
| 451 | 507 | |
| 508 | +func TestOutermostKeepsWhatIsNotInsideAnotherPath(t *testing.T) { | |
| 509 | + got, err := workspace.Outermost([]string{"notes/a.md", "notes", "b.md", "./b.md", "notes-2/c.md"}) | |
| 510 | + if err != nil || strings.Join(got, ",") != "notes,b.md,notes-2/c.md" { | |
| 511 | + t.Fatalf("got %v %v", got, err) | |
| 512 | + } | |
| 513 | + if got, _ := workspace.Outermost([]string{"a", "", "b"}); len(got) != 1 || got[0] != "" { | |
| 514 | + t.Fatalf("the root holds everything: %v", got) | |
| 515 | + } | |
| 516 | + if _, err := workspace.Outermost([]string{"a", "../b"}); !errors.Is(err, workspace.ErrOutside) { | |
| 517 | + t.Fatalf("want ErrOutside, got %v", err) | |
| 518 | + } | |
| 519 | +} | |
| 520 | + | |
| 452 | 521 | func ExampleClean() { |
| 453 | 522 | cleaned, _ := workspace.Clean("skills/../AGENTS.md") |
| 454 | 523 | _, err := workspace.Clean("../secrets") |
| @@ -128,6 +128,8 @@ func contract(t *testing.T, open opener) { | |||
| 128 | {"reads any file as bytes", checkReadsAnyFileAsBytes}, | 128 | {"reads any file as bytes", checkReadsAnyFileAsBytes}, |
| 129 | {"imports a file under a free name", checkImportsAFileUnderAFreeName}, | 129 | {"imports a file under a free name", checkImportsAFileUnderAFreeName}, |
| 130 | {"removes a file and a folder", checkRemovesAFileAndAFolder}, | 130 | {"removes a file and a folder", checkRemovesAFileAndAFolder}, |
| 131 | + {"renames and moves files and folders", checkRenamesAndMovesFilesAndFolders}, | ||
| 132 | + {"creates a folder", checkCreatesAFolder}, | ||
| 131 | {"signals changes", checkSignalsChanges}, | 133 | {"signals changes", checkSignalsChanges}, |
| 132 | {"opens a shell in the folder", checkOpensAShellInTheFolder}, | 134 | {"opens a shell in the folder", checkOpensAShellInTheFolder}, |
| 133 | {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt}, | 135 | {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt}, |
| @@ -282,6 +284,60 @@ func checkRemovesAFileAndAFolder(t *testing.T, open opener) { | |||
| 282 | } | 284 | } |
| 283 | } | 285 | } |
| 284 | 286 | ||
| 287 | +func checkRenamesAndMovesFilesAndFolders(t *testing.T, open opener) { | ||
| 288 | + ctx := context.Background() | ||
| 289 | + ws := startWorkspace(t, open) | ||
| 290 | + if err := ws.Rename(ctx, "AGENTS.md", "notes/STYLE.md"); err != nil { | ||
| 291 | + t.Fatal(err) | ||
| 292 | + } | ||
| 293 | + if file, err := ws.Read(ctx, "notes/STYLE.md"); err != nil || file.Content != "# Style\n" { | ||
| 294 | + t.Fatalf("moved file: %+v %v", file, err) | ||
| 295 | + } | ||
| 296 | + if _, err := ws.Read(ctx, "AGENTS.md"); !errors.Is(err, workspace.ErrNotFound) { | ||
| 297 | + t.Fatalf("the old name is gone, got %v", err) | ||
| 298 | + } | ||
| 299 | + // A folder moves with its content, into a folder created on the way. | ||
| 300 | + if err := ws.Rename(ctx, "skills", "archive/2026/skills"); err != nil { | ||
| 301 | + t.Fatal(err) | ||
| 302 | + } | ||
| 303 | + if file, err := ws.Read(ctx, "archive/2026/skills/idioms/SKILL.md"); err != nil || file.Content != "idioms" { | ||
| 304 | + t.Fatalf("moved folder: %+v %v", file, err) | ||
| 305 | + } | ||
| 306 | + if err := ws.Rename(ctx, "notes/STYLE.md", "archive"); !errors.Is(err, workspace.ErrExists) { | ||
| 307 | + t.Fatalf("never over an existing entry, got %v", err) | ||
| 308 | + } | ||
| 309 | + if err := ws.Rename(ctx, "missing.md", "found.md"); !errors.Is(err, workspace.ErrNotFound) { | ||
| 310 | + t.Fatalf("want ErrNotFound, got %v", err) | ||
| 311 | + } | ||
| 312 | + if err := ws.Rename(ctx, "archive", "archive/inside"); err == nil { | ||
| 313 | + t.Fatal("a folder cannot go inside itself") | ||
| 314 | + } | ||
| 315 | + if err := ws.Rename(ctx, "notes", "../notes"); !errors.Is(err, workspace.ErrOutside) { | ||
| 316 | + t.Fatalf("want ErrOutside, got %v", err) | ||
| 317 | + } | ||
| 318 | + if err := ws.Rename(ctx, "", "elsewhere"); !errors.Is(err, workspace.ErrOutside) { | ||
| 319 | + t.Fatalf("never the whole folder, got %v", err) | ||
| 320 | + } | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +func checkCreatesAFolder(t *testing.T, open opener) { | ||
| 324 | + ctx := context.Background() | ||
| 325 | + ws := startWorkspace(t, open) | ||
| 326 | + if err := ws.MakeDir(ctx, "drafts/2026"); err != nil { | ||
| 327 | + t.Fatal(err) | ||
| 328 | + } | ||
| 329 | + entries, err := ws.List(ctx, "drafts") | ||
| 330 | + if err != nil || len(entries) != 1 || !entries[0].Dir || entries[0].Path != "drafts/2026" { | ||
| 331 | + t.Fatalf("got %+v %v", entries, err) | ||
| 332 | + } | ||
| 333 | + if err := ws.MakeDir(ctx, "notes"); !errors.Is(err, workspace.ErrExists) { | ||
| 334 | + t.Fatalf("want ErrExists, got %v", err) | ||
| 335 | + } | ||
| 336 | + if err := ws.MakeDir(ctx, "AGENTS.md"); !errors.Is(err, workspace.ErrExists) { | ||
| 337 | + t.Fatalf("want ErrExists for a file, got %v", err) | ||
| 338 | + } | ||
| 339 | +} | ||
| 340 | + | ||
| 285 | func checkSignalsChanges(t *testing.T, open opener) { | 341 | func checkSignalsChanges(t *testing.T, open opener) { |
| 286 | ctx := context.Background() | 342 | ctx := context.Background() |
| 287 | ws := startWorkspace(t, open) | 343 | ws := startWorkspace(t, open) |
| @@ -449,6 +505,19 @@ func TestCleanKeepsPathsInsideTheFolder(t *testing.T) { | |||
| 449 | } | 505 | } |
| 450 | } | 506 | } |
| 451 | 507 | ||
| 508 | +func TestOutermostKeepsWhatIsNotInsideAnotherPath(t *testing.T) { | ||
| 509 | + got, err := workspace.Outermost([]string{"notes/a.md", "notes", "b.md", "./b.md", "notes-2/c.md"}) | ||
| 510 | + if err != nil || strings.Join(got, ",") != "notes,b.md,notes-2/c.md" { | ||
| 511 | + t.Fatalf("got %v %v", got, err) | ||
| 512 | + } | ||
| 513 | + if got, _ := workspace.Outermost([]string{"a", "", "b"}); len(got) != 1 || got[0] != "" { | ||
| 514 | + t.Fatalf("the root holds everything: %v", got) | ||
| 515 | + } | ||
| 516 | + if _, err := workspace.Outermost([]string{"a", "../b"}); !errors.Is(err, workspace.ErrOutside) { | ||
| 517 | + t.Fatalf("want ErrOutside, got %v", err) | ||
| 518 | + } | ||
| 519 | +} | ||
| 520 | + | ||
| 452 | func ExampleClean() { | 521 | func ExampleClean() { |
| 453 | cleaned, _ := workspace.Clean("skills/../AGENTS.md") | 522 | cleaned, _ := workspace.Clean("skills/../AGENTS.md") |
| 454 | _, err := workspace.Clean("../secrets") | 523 | _, err := workspace.Clean("../secrets") |
modified
internal/workspace/local.go +43 -0 | @@ -224,6 +224,49 @@ func (l *Local) Remove(_ context.Context, p string) error { | ||
| 224 | 224 | return moveToTrash(abs) |
| 225 | 225 | } |
| 226 | 226 | |
| 227 | +// Rename implements Workspace. | |
| 228 | +func (l *Local) Rename(_ context.Context, from, to string) error { | |
| 229 | + source, fromRel, err := l.resolve(from) | |
| 230 | + if err != nil { | |
| 231 | + return err | |
| 232 | + } | |
| 233 | + target, toRel, err := l.resolve(to) | |
| 234 | + if err != nil { | |
| 235 | + return err | |
| 236 | + } | |
| 237 | + if err := checkRename(fromRel, toRel); err != nil { | |
| 238 | + return err | |
| 239 | + } | |
| 240 | + info, err := os.Lstat(source) | |
| 241 | + if err != nil { | |
| 242 | + return notFound(err) | |
| 243 | + } | |
| 244 | + // SameFile: only the case of the name changes (notes.md → Notes.md) on | |
| 245 | + // a case-insensitive disk, where the target "exists", being the source. | |
| 246 | + if existing, err := os.Lstat(target); err == nil && !os.SameFile(info, existing) { | |
| 247 | + return ErrExists | |
| 248 | + } | |
| 249 | + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { | |
| 250 | + return err | |
| 251 | + } | |
| 252 | + return os.Rename(source, target) | |
| 253 | +} | |
| 254 | + | |
| 255 | +// MakeDir implements Workspace. | |
| 256 | +func (l *Local) MakeDir(_ context.Context, p string) error { | |
| 257 | + abs, rel, err := l.resolve(p) | |
| 258 | + if err != nil { | |
| 259 | + return err | |
| 260 | + } | |
| 261 | + if rel == "" { | |
| 262 | + return ErrExists | |
| 263 | + } | |
| 264 | + if _, err := os.Lstat(abs); err == nil { | |
| 265 | + return ErrExists | |
| 266 | + } | |
| 267 | + return os.MkdirAll(abs, 0o755) | |
| 268 | +} | |
| 269 | + | |
| 227 | 270 | // Changes implements Workspace with file system notifications. Folders |
| 228 | 271 | // that hold many files nobody edits by hand are not watched. |
| 229 | 272 | func (l *Local) Changes(ctx context.Context) (<-chan struct{}, error) { |
| @@ -224,6 +224,49 @@ func (l *Local) Remove(_ context.Context, p string) error { | |||
| 224 | return moveToTrash(abs) | 224 | return moveToTrash(abs) |
| 225 | } | 225 | } |
| 226 | 226 | ||
| 227 | +// Rename implements Workspace. | ||
| 228 | +func (l *Local) Rename(_ context.Context, from, to string) error { | ||
| 229 | + source, fromRel, err := l.resolve(from) | ||
| 230 | + if err != nil { | ||
| 231 | + return err | ||
| 232 | + } | ||
| 233 | + target, toRel, err := l.resolve(to) | ||
| 234 | + if err != nil { | ||
| 235 | + return err | ||
| 236 | + } | ||
| 237 | + if err := checkRename(fromRel, toRel); err != nil { | ||
| 238 | + return err | ||
| 239 | + } | ||
| 240 | + info, err := os.Lstat(source) | ||
| 241 | + if err != nil { | ||
| 242 | + return notFound(err) | ||
| 243 | + } | ||
| 244 | + // SameFile: only the case of the name changes (notes.md → Notes.md) on | ||
| 245 | + // a case-insensitive disk, where the target "exists", being the source. | ||
| 246 | + if existing, err := os.Lstat(target); err == nil && !os.SameFile(info, existing) { | ||
| 247 | + return ErrExists | ||
| 248 | + } | ||
| 249 | + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { | ||
| 250 | + return err | ||
| 251 | + } | ||
| 252 | + return os.Rename(source, target) | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +// MakeDir implements Workspace. | ||
| 256 | +func (l *Local) MakeDir(_ context.Context, p string) error { | ||
| 257 | + abs, rel, err := l.resolve(p) | ||
| 258 | + if err != nil { | ||
| 259 | + return err | ||
| 260 | + } | ||
| 261 | + if rel == "" { | ||
| 262 | + return ErrExists | ||
| 263 | + } | ||
| 264 | + if _, err := os.Lstat(abs); err == nil { | ||
| 265 | + return ErrExists | ||
| 266 | + } | ||
| 267 | + return os.MkdirAll(abs, 0o755) | ||
| 268 | +} | ||
| 269 | + | ||
| 227 | // Changes implements Workspace with file system notifications. Folders | 270 | // Changes implements Workspace with file system notifications. Folders |
| 228 | // that hold many files nobody edits by hand are not watched. | 271 | // that hold many files nobody edits by hand are not watched. |
| 229 | func (l *Local) Changes(ctx context.Context) (<-chan struct{}, error) { | 272 | func (l *Local) Changes(ctx context.Context) (<-chan struct{}, error) { |
modified
internal/workspace/workspace.go +53 -0 | @@ -106,6 +106,13 @@ type Workspace interface { | ||
| 106 | 106 | // Remove removes a file or a folder with its content. A local workspace |
| 107 | 107 | // puts it in the system trash. |
| 108 | 108 | Remove(ctx context.Context, path string) error |
| 109 | + // Rename renames or moves a file or a folder to path to (its folders are | |
| 110 | + // created if needed); ErrExists when something already has that path | |
| 111 | + // (issue #70). | |
| 112 | + Rename(ctx context.Context, from, to string) error | |
| 113 | + // MakeDir creates a folder, and its parents if needed; ErrExists when | |
| 114 | + // something already has that path (issue #70). | |
| 115 | + MakeDir(ctx context.Context, path string) error | |
| 109 | 116 | // Changes signals, at most every half second, that something changed in |
| 110 | 117 | // the folder, until ctx ends. |
| 111 | 118 | Changes(ctx context.Context) (<-chan struct{}, error) |
| @@ -161,6 +168,52 @@ func freeName(name string, taken func(string) bool) string { | ||
| 161 | 168 | return candidate |
| 162 | 169 | } |
| 163 | 170 | |
| 171 | +// checkRename checks the paths of a renaming, already cleaned: neither is | |
| 172 | +// the root, and a folder never goes inside itself. | |
| 173 | +// | |
| 174 | +// checkRename("notes", "notes/old") // error | |
| 175 | +func checkRename(from, to string) error { | |
| 176 | + if from == "" || to == "" { | |
| 177 | + return ErrOutside | |
| 178 | + } | |
| 179 | + if to == from || strings.HasPrefix(to, from+"/") { | |
| 180 | + return fmt.Errorf("%s cannot be moved into itself", from) | |
| 181 | + } | |
| 182 | + return nil | |
| 183 | +} | |
| 184 | + | |
| 185 | +// Outermost cleans paths and keeps those that are not inside another one | |
| 186 | +// of the list, in their order, without duplicates: removing or moving a | |
| 187 | +// folder takes what it holds along (issue #70). | |
| 188 | +// | |
| 189 | +// Outermost([]string{"notes/a.md", "notes", "b.md"}) // ["notes", "b.md"], nil | |
| 190 | +func Outermost(paths []string) ([]string, error) { | |
| 191 | + cleaned := make([]string, 0, len(paths)) | |
| 192 | + for _, p := range paths { | |
| 193 | + clean, err := Clean(p) | |
| 194 | + if err != nil { | |
| 195 | + return nil, err | |
| 196 | + } | |
| 197 | + cleaned = append(cleaned, clean) | |
| 198 | + } | |
| 199 | + result := []string{} | |
| 200 | + for index, candidate := range cleaned { | |
| 201 | + kept := true | |
| 202 | + for other, container := range cleaned { | |
| 203 | + inside := container != candidate && (container == "" || strings.HasPrefix(candidate, container+"/")) | |
| 204 | + duplicate := container == candidate && other < index | |
| 205 | + if inside || duplicate { | |
| 206 | + kept = false | |
| 207 | + break | |
| 208 | + } | |
| 209 | + } | |
| 210 | + if kept { | |
| 211 | + result = append(result, candidate) | |
| 212 | + } | |
| 213 | + } | |
| 214 | + return result, nil | |
| 215 | +} | |
| 216 | + | |
| 164 | 217 | // checkImport checks the name and the size of an imported file. |
| 165 | 218 | func checkImport(name string, data []byte) error { |
| 166 | 219 | if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") { |
| @@ -106,6 +106,13 @@ type Workspace interface { | |||
| 106 | // Remove removes a file or a folder with its content. A local workspace | 106 | // Remove removes a file or a folder with its content. A local workspace |
| 107 | // puts it in the system trash. | 107 | // puts it in the system trash. |
| 108 | Remove(ctx context.Context, path string) error | 108 | Remove(ctx context.Context, path string) error |
| 109 | + // Rename renames or moves a file or a folder to path to (its folders are | ||
| 110 | + // created if needed); ErrExists when something already has that path | ||
| 111 | + // (issue #70). | ||
| 112 | + Rename(ctx context.Context, from, to string) error | ||
| 113 | + // MakeDir creates a folder, and its parents if needed; ErrExists when | ||
| 114 | + // something already has that path (issue #70). | ||
| 115 | + MakeDir(ctx context.Context, path string) error | ||
| 109 | // Changes signals, at most every half second, that something changed in | 116 | // Changes signals, at most every half second, that something changed in |
| 110 | // the folder, until ctx ends. | 117 | // the folder, until ctx ends. |
| 111 | Changes(ctx context.Context) (<-chan struct{}, error) | 118 | Changes(ctx context.Context) (<-chan struct{}, error) |
| @@ -161,6 +168,52 @@ func freeName(name string, taken func(string) bool) string { | |||
| 161 | return candidate | 168 | return candidate |
| 162 | } | 169 | } |
| 163 | 170 | ||
| 171 | +// checkRename checks the paths of a renaming, already cleaned: neither is | ||
| 172 | +// the root, and a folder never goes inside itself. | ||
| 173 | +// | ||
| 174 | +// checkRename("notes", "notes/old") // error | ||
| 175 | +func checkRename(from, to string) error { | ||
| 176 | + if from == "" || to == "" { | ||
| 177 | + return ErrOutside | ||
| 178 | + } | ||
| 179 | + if to == from || strings.HasPrefix(to, from+"/") { | ||
| 180 | + return fmt.Errorf("%s cannot be moved into itself", from) | ||
| 181 | + } | ||
| 182 | + return nil | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +// Outermost cleans paths and keeps those that are not inside another one | ||
| 186 | +// of the list, in their order, without duplicates: removing or moving a | ||
| 187 | +// folder takes what it holds along (issue #70). | ||
| 188 | +// | ||
| 189 | +// Outermost([]string{"notes/a.md", "notes", "b.md"}) // ["notes", "b.md"], nil | ||
| 190 | +func Outermost(paths []string) ([]string, error) { | ||
| 191 | + cleaned := make([]string, 0, len(paths)) | ||
| 192 | + for _, p := range paths { | ||
| 193 | + clean, err := Clean(p) | ||
| 194 | + if err != nil { | ||
| 195 | + return nil, err | ||
| 196 | + } | ||
| 197 | + cleaned = append(cleaned, clean) | ||
| 198 | + } | ||
| 199 | + result := []string{} | ||
| 200 | + for index, candidate := range cleaned { | ||
| 201 | + kept := true | ||
| 202 | + for other, container := range cleaned { | ||
| 203 | + inside := container != candidate && (container == "" || strings.HasPrefix(candidate, container+"/")) | ||
| 204 | + duplicate := container == candidate && other < index | ||
| 205 | + if inside || duplicate { | ||
| 206 | + kept = false | ||
| 207 | + break | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + if kept { | ||
| 211 | + result = append(result, candidate) | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + return result, nil | ||
| 215 | +} | ||
| 216 | + | ||
| 164 | // checkImport checks the name and the size of an imported file. | 217 | // checkImport checks the name and the size of an imported file. |
| 165 | func checkImport(name string, data []byte) error { | 218 | func checkImport(name string, data []byte) error { |
| 166 | if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") { | 219 | if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") { |