From 7a2af964b23c2ffcfdf30feaef17042d8ddd2a6a Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 10 Nov 2026 10:04:24 +0100 Subject: [PATCH] docs(toolkit): FileTree over a repository, SetRepository, PostUI, in seven languages SetRepository with vcs.Detect and the git driver, the marks and folder rule, RefreshStatus, and PostUI with RefreshStatusAsync (Status must not run on the UI goroutine), with an example that compiles against toolkit v0.364.0, vcs v0.1.0 and vcs/git v0.1.0. Co-Authored-By: Claude Sonnet 5.5 --- content/de/rendering/toolkit.md | 72 ++++++++++++++++++++++++++++++ content/en/rendering/toolkit.md | 71 +++++++++++++++++++++++++++++ content/es/rendering/toolkit.md | 72 ++++++++++++++++++++++++++++++ content/fr/rendering/toolkit.md | 72 ++++++++++++++++++++++++++++++ content/ja/rendering/toolkit.md | 45 +++++++++++++++++++ content/ko/rendering/toolkit.md | 45 +++++++++++++++++++ content/zh-cn/rendering/toolkit.md | 45 +++++++++++++++++++ 7 files changed, 422 insertions(+) diff --git a/content/de/rendering/toolkit.md b/content/de/rendering/toolkit.md index e107299e..c97475a0 100644 --- a/content/de/rendering/toolkit.md +++ b/content/de/rendering/toolkit.md @@ -174,6 +174,78 @@ gelöschten Bereichs wird *darum herum* gelöscht und überlebt. Platzierung ist eine Schätzung; ein Zeichen, das vor einem Augenblick auf jemandes Bildschirm stand, ist keine. +### FileTree über einem versionierten Arbeitsverzeichnis {#filetree-vcs} + +Seit v0.363.0 füllt `FileTree.SetRepository(vcs.Repository)` die Marken `M`, `A`, +`D`, `?` und `!` aus einem [`vcs`](https://github.com/go-widgets/vcs)-Repository: +der Host muss nicht jeden `Status` von Hand setzen. Das Toolkit importiert nur +`vcs` (nur die Standardbibliothek), nie einen Treiber: den registriert der Host. +Der Git-Treiber ist das separate Modul `vcs/git` (go-git, nie das Programm `git`); +`vcs.Detect(dir)` steigt bis zum nächsten Repository auf. + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +Von den Zuständen des Repositorys zu den Marken: + +- `Modified`, `Added`, `Deleted`, `Untracked` und `Conflicted` entsprechen dem + gleichnamigen `FileStatus`. `Renamed` wird zu `FileAdded` am neuen Pfad. + `Ignored` hat keine Marke: `FileIgnored` würde nichts zeichnen. +- **Ein Ordner ist `FileModified`, sobald etwas darunter eine Marke trägt, und + `FileConflicted`, sobald etwas darunter im Konflikt ist** (der Konflikt gewinnt). + Das ist die Regel, die der Absatz davor nicht raten will; ein angehängtes + Repository ist die Zustimmung. Ein Ordner, den das Repository selbst meldet (ein + Submodul), behält seinen Zustand, außer darunter liegt ein Konflikt. Ein vom Host + gesetzter `Status` an einem Eintrag gewinnt gegen den des Repositorys. +- Eine gelöschte Datei wird nur markiert, wenn der Host sie noch auflistet: der + Baum erfindet keine Zeilen. +- `Marks()` ist ein `Observable` aller Marken, Ordner eingeschlossen, für eine + Legende oder ein Abzeichen „3 Änderungen“; `StatusError()` ist der Fehler der + letzten Aktualisierung, die dann die vorherigen Marken behält. + +Der Baum wendet Anlegen, Umbenennen, Löschen, Verschieben und Import nie selbst +an: das tut der Host und setzt `Entries`, und dieses `Set` aktualisiert die +Marken. `RefreshStatus(ctx)` fragt jetzt und kehrt zurück, wenn die Marken +angewendet sind. + +**Warum `PostUI`** (v0.364.0). `Repository.Status` kann bei einem großen Repository +Sekunden dauern (go-git baut den ganzen Status im Speicher auf und nimmt keinen +Kontext), darf also nicht auf der UI-Goroutine laufen; im Browser würde es die +Ereignisschleife der Seite blockieren. Mit `PostUI` führt jede vom Baum gestartete +Aktualisierung (`SetRepository`, eine Änderung von `Entries`, +`RefreshStatusAsync`) `Status` auf einer eigenen Goroutine aus und gibt das +Ergebnis als Closure zurück, **die der Host auf seiner UI-Goroutine ausführt**, +wie bei `collabui.CollabText`. Eine neuere Aktualisierung bricht die laufende ab +und macht ihre verspätete Antwort wirkungslos. Ohne `PostUI` ist alles +synchron, was für einen Test oder einen kleinen Baum richtig ist. + ## Binärgröße: ein Programm linkt, was es benutzt {#binary-size} Das Toolkit ist ein großes Paket, und für den Linker ist das in Ordnung: Die diff --git a/content/en/rendering/toolkit.md b/content/en/rendering/toolkit.md index 20e73b76..562d1aff 100644 --- a/content/en/rendering/toolkit.md +++ b/content/en/rendering/toolkit.md @@ -276,3 +276,74 @@ A folder's status is not derived from its children: "a folder holding a modified file" is a policy rather than a fact, and git says nothing about folders at all. An explicit `Dir` entry carries its own status — a submodule, a directory a merge left conflicted — while an implied parent has none. + +#### Filling the marks from a repository + +Since v0.363.0, `SetRepository(vcs.Repository)` fills the marks from a +[`vcs`](https://github.com/go-widgets/vcs) repository, so a host does not set +each `Status` by hand. The toolkit imports only `vcs` (standard library only), +never a driver: the host registers one. The git driver is the separate module +`vcs/git` (go-git, never the `git` binary); `vcs.Detect(dir)` walks up to the +nearest repository once a driver is imported. + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +How the repository's states become marks: + +- `Modified`, `Added`, `Deleted`, `Untracked` and `Conflicted` map to the + `FileStatus` of the same name. `Renamed` is `FileAdded` at the new path. + `Ignored` has no mark, because `FileIgnored` would draw as nothing. +- **A folder is `FileModified` when anything under it has a mark, and + `FileConflicted` when anything under it is conflicted** (conflicts win). This + is the policy the paragraph above declines to guess; attaching a repository is + the opt-in. A folder the repository reports itself (a submodule) keeps its + state, unless a conflict lies beneath it. A `Status` a host set on an entry + wins over the repository's. +- A deleted file is marked only if the host still lists it: the tree invents no + rows. +- `Marks()` is an `Observable` of every mark, folders included, for a legend or a + "3 changes" badge; `StatusError()` is the last refresh's error. A failed + refresh keeps the previous marks. + +The tree never applies a create, rename, delete, move or import: the host does, +and sets `Entries`, and that `Set` refreshes the marks. `RefreshStatus(ctx)` +asks now and returns when the marks are applied. + +**Why `PostUI`** (v0.364.0)**.** `Repository.Status` can take seconds on a large repository +(go-git builds the whole status in memory and takes no context), so it must not +run on the UI goroutine, and in a browser it would block the page's event loop. +Set `PostUI` and every refresh the tree starts (`SetRepository`, a change of +`Entries`, `RefreshStatusAsync`) runs `Status` on a goroutine of its own and +hands the result back as a closure that **the host runs on its UI goroutine** — +the same contract as `collabui.CollabText`. A newer refresh cancels the one in +flight and makes its late answer a no-op, so a slow answer never overwrites a +newer one. Without `PostUI` every refresh is synchronous, which is right for a +test or a small tree. diff --git a/content/es/rendering/toolkit.md b/content/es/rendering/toolkit.md index d87b0261..6b10b9a1 100644 --- a/content/es/rendering/toolkit.md +++ b/content/es/rendering/toolkit.md @@ -170,6 +170,78 @@ la persona podía ver y no los que no podía: la inserción de un par dentro del rango borrado se borra *alrededor* y sobrevive. La colocación es una conjetura; un carácter que hace un instante estaba en la pantalla de alguien no lo es. +### FileTree sobre un árbol de trabajo versionado {#filetree-vcs} + +Desde v0.363.0, `FileTree.SetRepository(vcs.Repository)` rellena las marcas `M`, +`A`, `D`, `?` y `!` desde un repositorio de [`vcs`](https://github.com/go-widgets/vcs): +el anfitrión ya no fija cada `Status` a mano. El toolkit importa solo `vcs` +(solo la biblioteca estándar), nunca un controlador: el anfitrión registra uno. +El controlador de git es el módulo aparte `vcs/git` (go-git, nunca el binario +`git`); `vcs.Detect(dir)` sube hasta el repositorio más cercano. + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +De los estados del repositorio a las marcas: + +- `Modified`, `Added`, `Deleted`, `Untracked` y `Conflicted` se corresponden con + el `FileStatus` del mismo nombre. `Renamed` pasa a `FileAdded` en la nueva ruta. + `Ignored` no tiene marca: `FileIgnored` no dibujaría nada. +- **Una carpeta es `FileModified` cuando algo debajo tiene marca, y + `FileConflicted` cuando algo debajo está en conflicto** (el conflicto gana). + Es la política que el párrafo anterior se niega a adivinar; adjuntar un + repositorio es aceptarla. Una carpeta que el propio repositorio informa (un + submódulo) conserva su estado, salvo que haya un conflicto debajo. Un `Status` + fijado por el anfitrión en una entrada gana al del repositorio. +- Un archivo borrado solo se marca si el anfitrión aún lo lista: el árbol no + inventa filas. +- `Marks()` es un `Observable` de todas las marcas, carpetas incluidas, para una + leyenda o una insignia de «3 cambios»; `StatusError()` es el error de la última + actualización, que conserva entonces las marcas anteriores. + +El árbol nunca aplica una creación, un cambio de nombre, un borrado, un traslado +o una importación: lo hace el anfitrión y fija `Entries`, y ese `Set` actualiza +las marcas. `RefreshStatus(ctx)` pregunta ahora y vuelve cuando las marcas están +aplicadas. + +**Por qué `PostUI`** (v0.364.0). `Repository.Status` puede tardar segundos en un +repositorio grande (go-git construye todo el estado en memoria y no admite +contexto), así que no debe ejecutarse en la goroutine de la interfaz; en un +navegador bloquearía el bucle de eventos de la página. Con `PostUI`, cada +actualización que inicia el árbol (`SetRepository`, un cambio de `Entries`, +`RefreshStatusAsync`) ejecuta `Status` en una goroutine propia y devuelve el +resultado como un cierre **que el anfitrión ejecuta en su goroutine de interfaz**, +igual que `collabui.CollabText`. Una actualización más nueva cancela la que está +en curso y deja sin efecto su respuesta tardía. Sin `PostUI` todo es síncrono, lo +cual vale para una prueba o un árbol pequeño. + ## Tamaño del binario: un programa enlaza lo que usa {#binary-size} El toolkit es un paquete grande, y para el enlazador eso no es un problema: la diff --git a/content/fr/rendering/toolkit.md b/content/fr/rendering/toolkit.md index 096bd9b3..606cc27d 100644 --- a/content/fr/rendering/toolkit.md +++ b/content/fr/rendering/toolkit.md @@ -171,6 +171,78 @@ l'insertion d'un pair à l'intérieur de la plage supprimée est supprimée *aut et survit. Le placement est une estimation ; un caractère qui était sur l'écran de quelqu'un il y a un instant n'en est pas une. +### FileTree sur une arborescence versionnée {#filetree-vcs} + +Depuis v0.363.0, `FileTree.SetRepository(vcs.Repository)` remplit les marques +`M`, `A`, `D`, `?` et `!` à partir d'un dépôt [`vcs`](https://github.com/go-widgets/vcs) : +l'hôte n'a plus à fixer chaque `Status` à la main. Le toolkit n'importe que `vcs` +(bibliothèque standard seule), jamais un pilote : c'est l'hôte qui en enregistre un. +Le pilote git est le module séparé `vcs/git` (go-git, jamais le binaire `git`) ; +`vcs.Detect(dir)` remonte jusqu'au dépôt le plus proche. + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +Des états du dépôt aux marques : + +- `Modified`, `Added`, `Deleted`, `Untracked` et `Conflicted` correspondent au + `FileStatus` du même nom. `Renamed` devient `FileAdded` au nouveau chemin. + `Ignored` n'a pas de marque : `FileIgnored` ne dessinerait rien. +- **Un dossier est `FileModified` dès que quelque chose dessous porte une marque, et + `FileConflicted` dès que quelque chose dessous est en conflit** (le conflit + l'emporte). C'est la politique que le paragraphe précédent refuse de deviner ; + attacher un dépôt vaut adhésion. Un dossier que le dépôt signale lui-même (un + sous-module) garde son état, sauf conflit en dessous. Un `Status` fixé par l'hôte + sur une entrée l'emporte sur celui du dépôt. +- Un fichier supprimé n'est marqué que si l'hôte le liste encore : l'arbre + n'invente aucune ligne. +- `Marks()` est un `Observable` de toutes les marques, dossiers compris, pour une + légende ou un badge « 3 modifications » ; `StatusError()` est l'erreur du dernier + rafraîchissement, qui conserve alors les marques précédentes. + +L'arbre n'applique jamais une création, un renommage, une suppression, un +déplacement ou un import : l'hôte le fait et fixe `Entries`, et ce `Set` +rafraîchit les marques. `RefreshStatus(ctx)` interroge maintenant et rend la main +quand les marques sont appliquées. + +**Pourquoi `PostUI`** (v0.364.0). `Repository.Status` peut durer des secondes sur +un grand dépôt (go-git construit tout l'état en mémoire et ne prend aucun +contexte) : il ne doit pas s'exécuter sur la goroutine d'interface, et dans un +navigateur il bloquerait la boucle d'événements de la page. Avec `PostUI`, chaque +rafraîchissement lancé par l'arbre (`SetRepository`, un changement de `Entries`, +`RefreshStatusAsync`) exécute `Status` sur une goroutine à part et rend le résultat +sous forme de fermeture **que l'hôte exécute sur sa goroutine d'interface**, comme +`collabui.CollabText`. Un rafraîchissement plus récent annule celui en cours et +rend sa réponse tardive sans effet. Sans `PostUI`, tout est synchrone, ce qui +convient à un test ou à un petit arbre. + ## Taille du binaire : un programme lie ce qu'il utilise {#binary-size} La boîte à outils est un grand paquet, et l'éditeur de liens s'en accommode : diff --git a/content/ja/rendering/toolkit.md b/content/ja/rendering/toolkit.md index 21bb93b2..be145a12 100644 --- a/content/ja/rendering/toolkit.md +++ b/content/ja/rendering/toolkit.md @@ -147,6 +147,51 @@ Gibbs(SIGMOD '89)の包含変換であり、Jupiter(Nichols ほか、UIST あるピアの挿入はその*まわり*が削除され、生き残ります。位置は推測ですが、ついさっき 誰かの画面にあった文字は推測ではありません。 +### バージョン管理された作業ツリー上の FileTree {#filetree-vcs} + +v0.363.0 以降、`FileTree.SetRepository(vcs.Repository)` は [`vcs`](https://github.com/go-widgets/vcs) のリポジトリから `M`、`A`、`D`、`?`、`!` のマークを埋めます。ホストが各 `Status` を手で設定する必要はありません。ツールキットが import するのは `vcs`(標準ライブラリのみ)だけで、ドライバは決して import しません。ドライバはホストが登録します。git ドライバは別モジュールの `vcs/git`(go-git を使い、`git` バイナリは呼びません)で、`vcs.Detect(dir)` は最も近いリポジトリまで親ディレクトリをたどります。 + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +リポジトリの状態からマークへの対応: + +- `Modified`、`Added`、`Deleted`、`Untracked`、`Conflicted` は同名の `FileStatus` に対応します。`Renamed` は新しいパスの `FileAdded` になります。`Ignored` にマークはありません(`FileIgnored` は何も描画しないため)。 +- **フォルダは、配下のどれかにマークがあれば `FileModified`、配下のどれかが競合していれば `FileConflicted` です**(競合が優先)。直前の段落が推測を避けているのがこの方針で、リポジトリを接続することがその承諾にあたります。リポジトリ自身が報告するフォルダ(サブモジュール)は、配下に競合がない限りその状態を保ちます。ホストがエントリに設定した `Status` は、リポジトリのものより優先されます。 +- 削除されたファイルは、ホストがまだ一覧に含めている場合にだけマークされます。ツリーが行を作り出すことはありません。 +- `Marks()` はフォルダを含むすべてのマークの `Observable` で、凡例や「3 件の変更」バッジに使えます。`StatusError()` は直近の更新のエラーで、その場合は以前のマークが保たれます。 + +ツリーは作成、名前変更、削除、移動、インポートを自分では適用しません。ホストが適用して `Entries` を設定し、その `Set` がマークを更新します。`RefreshStatus(ctx)` はその場で問い合わせ、マークが適用されてから戻ります。 + +**`PostUI` が必要な理由**(v0.364.0)。`Repository.Status` は大きなリポジトリでは数秒かかることがあり(go-git は状態全体をメモリに構築し、コンテキストを受け取りません)、UI の goroutine で実行してはなりません。ブラウザではページのイベントループを止めてしまいます。`PostUI` を設定すると、ツリーが開始するすべての更新(`SetRepository`、`Entries` の変更、`RefreshStatusAsync`)は専用の goroutine で `Status` を実行し、結果を **ホストが UI の goroutine で実行する** クロージャとして返します。`collabui.CollabText` と同じ約束です。新しい更新は進行中のものをキャンセルし、遅れて届いた応答は何も起こしません。`PostUI` がなければすべて同期で、テストや小さなツリーには適しています。 + ## バイナリサイズ:プログラムは使うものだけをリンクする {#binary-size} ツールキットは 1 つの大きなパッケージですが、リンカにとっては問題ありません。Go のデッドコード除去は、 diff --git a/content/ko/rendering/toolkit.md b/content/ko/rendering/toolkit.md index 13d43950..91a1dce1 100644 --- a/content/ko/rendering/toolkit.md +++ b/content/ko/rendering/toolkit.md @@ -159,6 +159,51 @@ toolkit.UseOpenTypeText() // Atkinson Hyperlegible, bundled; js/wasm-safe 피어의 삽입은 그 *주위*가 삭제되어 살아남습니다. 위치는 추측이지만, 조금 전까지 누군가의 화면에 있던 문자는 추측이 아닙니다. +### 버전 관리되는 작업 트리 위의 FileTree {#filetree-vcs} + +v0.363.0부터 `FileTree.SetRepository(vcs.Repository)`가 [`vcs`](https://github.com/go-widgets/vcs) 저장소에서 `M`, `A`, `D`, `?`, `!` 표시를 채웁니다. 호스트가 각 `Status`를 직접 설정할 필요가 없습니다. 툴킷은 `vcs`(표준 라이브러리만 사용)만 import하고 드라이버는 절대 import하지 않으며, 드라이버는 호스트가 등록합니다. git 드라이버는 별도 모듈인 `vcs/git`(go-git 사용, `git` 바이너리는 실행하지 않음)이고, `vcs.Detect(dir)`는 가장 가까운 저장소까지 상위 디렉터리를 거슬러 올라갑니다. + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +저장소 상태가 표시가 되는 방식: + +- `Modified`, `Added`, `Deleted`, `Untracked`, `Conflicted`는 이름이 같은 `FileStatus`에 대응합니다. `Renamed`는 새 경로의 `FileAdded`가 됩니다. `Ignored`는 표시가 없습니다(`FileIgnored`는 아무것도 그리지 않기 때문입니다). +- **폴더는 그 아래 무언가에 표시가 있으면 `FileModified`, 그 아래 무언가가 충돌 상태이면 `FileConflicted`입니다**(충돌이 우선). 앞 문단이 추측하기를 거부한 바로 그 정책이며, 저장소를 연결하는 것이 그 정책을 받아들이는 것입니다. 저장소가 직접 보고하는 폴더(서브모듈)는 그 아래에 충돌이 없는 한 자기 상태를 유지합니다. 호스트가 항목에 설정한 `Status`는 저장소의 것보다 우선합니다. +- 삭제된 파일은 호스트가 여전히 목록에 넣을 때만 표시됩니다. 트리는 행을 만들어 내지 않습니다. +- `Marks()`는 폴더를 포함한 모든 표시의 `Observable`로, 범례나 "변경 3개" 배지에 쓸 수 있습니다. `StatusError()`는 마지막 갱신의 오류이며, 이때는 이전 표시가 유지됩니다. + +트리는 생성, 이름 변경, 삭제, 이동, 가져오기를 스스로 적용하지 않습니다. 호스트가 적용하고 `Entries`를 설정하면 그 `Set`이 표시를 갱신합니다. `RefreshStatus(ctx)`는 지금 묻고, 표시가 적용되면 돌아옵니다. + +**`PostUI`가 필요한 이유**(v0.364.0). `Repository.Status`는 큰 저장소에서 몇 초가 걸릴 수 있고(go-git은 상태 전체를 메모리에 만들며 컨텍스트를 받지 않습니다), UI goroutine에서 실행하면 안 됩니다. 브라우저에서는 페이지의 이벤트 루프를 막게 됩니다. `PostUI`를 설정하면 트리가 시작하는 모든 갱신(`SetRepository`, `Entries` 변경, `RefreshStatusAsync`)이 별도 goroutine에서 `Status`를 실행하고, 결과를 **호스트가 UI goroutine에서 실행하는** 클로저로 돌려줍니다. `collabui.CollabText`와 같은 약속입니다. 더 새로운 갱신은 진행 중인 것을 취소하고 늦게 도착한 응답은 아무 효과가 없습니다. `PostUI`가 없으면 모두 동기이며, 테스트나 작은 트리에는 알맞습니다. + ## 바이너리 크기: 프로그램은 사용하는 것만 링크합니다 {#binary-size} 툴킷은 하나의 큰 패키지이지만 링커에게는 문제가 되지 않습니다. Go의 데드 코드 제거는 diff --git a/content/zh-cn/rendering/toolkit.md b/content/zh-cn/rendering/toolkit.md index 8c262a06..93ec9f19 100644 --- a/content/zh-cn/rendering/toolkit.md +++ b/content/zh-cn/rendering/toolkit.md @@ -137,6 +137,51 @@ CRDT,这层绑定不往里添加任何合并逻辑。而一次编辑被应用 内容之中。删除取走这个人能看见的字符,不取走看不见的:落在删除范围内部的对端插入会被 *绕开*删除而存活下来。位置是一种猜测;而片刻之前还在某个人屏幕上的字符不是。 +### 受版本控制的工作树上的 FileTree {#filetree-vcs} + +自 v0.363.0 起,`FileTree.SetRepository(vcs.Repository)` 会从 [`vcs`](https://github.com/go-widgets/vcs) 仓库填充 `M`、`A`、`D`、`?`、`!` 标记,宿主不必再逐个手动设置 `Status`。工具包只导入 `vcs`(只用标准库),从不导入驱动:驱动由宿主注册。git 驱动是单独的模块 `vcs/git`(基于 go-git,从不调用 `git` 可执行文件),`vcs.Detect(dir)` 会向上查找最近的仓库。 + +```go +import ( + "context" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/vcs" + _ "github.com/go-widgets/vcs/git" // registers the "git" driver +) + +// newTree shows dir's files with their git state. post hands a closure to the +// host's UI goroutine. +func newTree(dir string, entries []toolkit.FileEntry, post func(func())) (*toolkit.FileTree, error) { + repo, err := vcs.Detect(dir) // walks up to the nearest repository + if err != nil { + return nil, err // vcs.ErrNoRepository when there is none + } + tree := toolkit.NewFileTree(entries) + tree.PostUI = post // Status runs off the UI goroutine + tree.SetRepository(repo) + tree.StatusError().Subscribe(func(err error) { /* show it */ }) + return tree, nil +} + +// After a change the tree was not told of, say a save: +func saved(tree *toolkit.FileTree) { tree.RefreshStatusAsync() } + +// A refresh you can wait for, on a worker or in a test: +func wait(tree *toolkit.FileTree) error { return tree.RefreshStatus(context.Background()) } +``` + +仓库状态如何变成标记: + +- `Modified`、`Added`、`Deleted`、`Untracked` 和 `Conflicted` 对应同名的 `FileStatus`。`Renamed` 在新路径上成为 `FileAdded`。`Ignored` 没有标记(`FileIgnored` 不会绘制任何东西)。 +- **只要文件夹下有任何条目带标记,它就是 `FileModified`;只要其下有任何条目处于冲突,它就是 `FileConflicted`**(冲突优先)。这正是上一段拒绝猜测的策略,接入仓库即表示接受。仓库自己报告的文件夹(子模块)保持其状态,除非其下有冲突。宿主在条目上设置的 `Status` 优先于仓库的。 +- 已删除的文件只有在宿主仍列出它时才会被标记:树不会凭空创建行。 +- `Marks()` 是所有标记(含文件夹)的 `Observable`,可用于图例或“3 处更改”徽标;`StatusError()` 是最近一次刷新的错误,此时保留之前的标记。 + +树从不自行执行新建、重命名、删除、移动或导入:由宿主执行并设置 `Entries`,这次 `Set` 会刷新标记。`RefreshStatus(ctx)` 立即查询,并在标记应用后返回。 + +**为什么需要 `PostUI`**(v0.364.0)。在大型仓库上,`Repository.Status` 可能耗时数秒(go-git 在内存中构建完整状态,且不接受 context),所以它不能在界面 goroutine 上运行;在浏览器中它会阻塞页面的事件循环。设置 `PostUI` 后,树发起的每次刷新(`SetRepository`、`Entries` 的变化、`RefreshStatusAsync`)都会在自己的 goroutine 上运行 `Status`,并把结果作为一个闭包交回,**由宿主在界面 goroutine 上执行**,约定与 `collabui.CollabText` 相同。更新的刷新会取消进行中的那次,使其迟到的答复不起作用。没有 `PostUI` 时一切同步,适合测试或小型的树。 + ## 二进制体积:程序只链接它用到的部分 {#binary-size} 工具包是一个很大的包,这对链接器来说没有问题:Go 的死代码消除只保留从 `main.main` **以及每个被导入包的初始化任务**