Keel v0.5.1 中文 GitHub

Diff

Live example: a real Keel application compiled to WebAssembly. Interact with it here. The initial download is about 10 MB.Open full screen
Example sourceGo · Copyable

This is the complete source for the gallery example above.examples/components/diff.go

Reuse the component construction and Render methods in a scaffolded project. The example’s registerSection and shared helpers are provided by the component gallery.

package main

import (
	"fmt"
	"github.com/dyike/keel/ui/core"
	"github.com/dyike/keel/ui/el"
	"github.com/dyike/keel/ui/kit"
	"strings"
)

func init() {
	registerSection("diff", "data", func() core.Widget {
		enableHighlight()
		context := strings.Repeat("// unchanged context\n", 16)
		initial := kit.DiffValue{Before: "package main\n\nfunc greeting() string {\n\treturn \"Hello\"\n}\n\n" + context + "// old note\n", After: "package main\n\nfunc greeting() string {\n\treturn \"Hello, Keel\"\n}\n\n" + context + "// reviewed note\n"}
		patch := kit.Diff(initial.Before, initial.After).Patch("main.go", "main.go")
		d := kit.Diff(initial.Before, initial.After).Language("go").Name(demoText("Review changes", "审阅更改"))
		lineStatus := demoText("Click a line number to locate its source.", "点击行号查看对应源位置。")
		d.OnLineNumberPress(func(line kit.DiffLine) {
			side := demoText("After", "更改后")
			if line.Side == kit.DiffSideBefore {
				side = demoText("Before", "更改前")
			}
			lineStatus = fmt.Sprintf("%s · %d", side, line.Line+1)
		})
		d.HunkActions(func(h kit.DiffHunk) []kit.DiffAction {
			return []kit.DiffAction{
				{Label: demoText("Inspect region", "查看区域"), OnSelect: func(current kit.DiffHunk) {
					lineStatus = fmt.Sprintf("%s %d · -%d,%d +%d,%d", demoText("Region", "区域"), current.Index+1, current.BeforeStart+1, current.BeforeEnd-current.BeforeStart, current.AfterStart+1, current.AfterEnd-current.AfterStart)
				}},
				{Label: demoText("Restore region", "还原区域"), Disabled: h.PatchOnly, OnSelect: func(current kit.DiffHunk) { d.RevertAt(current.Index) }},
			}
		})
		modes := kit.Select(demoText("Presentation", "展示方式"), "Auto", "Unified", "Split").OnChange(func(s string) {
			switch s {
			case "Unified":
				d.Mode(kit.DiffModeUnified)
			case "Split":
				d.Mode(kit.DiffModeSplit)
			default:
				d.Mode(kit.DiffModeAuto)
			}
		})
		modes.SetValue("Auto")
		return el.Root(el.ViewFunc(func(cx *el.Context) el.Element {
			return el.Div().ScrollY().P(16).Gap(12).Child(modes.Render(cx), el.Text(lineStatus), kit.Button(demoText("Inspect patch", "查看补丁"), func() { _ = d.SetPatch(patch) }).Render(cx), kit.Button(demoText("Reset comparison", "重置比较"), func() { d.SetValue(initial) }).Render(cx), d.Render(cx))
		}))
	})
}

Compare two texts, navigate changed regions, accept or revert each change, and export a unified patch. The view uses read-only CodeEditors for selection, copy and virtualized text rendering.

review := kit.Diff(before, after).Name("Review changes").Height(360).
    OnChange(func(value kit.DiffValue) { /* save value.Before / value.After */ })
patch := review.Patch("file.go", "file.go")

Value() returns DiffValue{Before, After}. SetValue replaces the texts silently. Changes() reports changed regions; Current() is zero-based, or -1 when equal. SetCurrent(index) reveals a valid region without notifying. Keep() accepts the proposed region into Before; Revert() restores that region from Before into After. Both return whether they acted and notify OnChange once. SetDisabled prevents review actions; programmatic text and current-region assignments remain available. Ancestor disabling also disables controls.

Mode(DiffModeAuto) uses a unified patch below a text-scaled 720dp viewport width, with original Before/After editors side by side above that. DiffModeUnified and DiffModeSplit force a presentation. Height(dp) sets each editor's viewport height. The container can be placed in an outer vertical scroll view. Mode changes retain the text and current region. Split panes synchronize vertical scrolling through line mappings: unchanged lines match exactly, replacement interiors interpolate, and deleted regions map to the opposite boundary. Change navigation reveals corresponding source positions in both. Horizontal scrolling remains independent. A unified view displays three context lines around changes; equal input displays the original text.

The toolbar wraps and uses 44dp controls. Tab focuses controls; Enter/Space activates buttons. Editors support their usual selection, copy, navigation and search shortcuts, but reject edits. The Copy button copies the complete patch; editor selection copies displayed text, including patch markers in unified mode. Semantic role is group; editors and controls expose localized names. No new automation role is introduced.

Line tokens preserve CRLF and final-newline differences. Unique-line anchors plus bounded LCS avoid unbounded quadratic work; large repeated regions can produce a coarse replacement instead of a minimal edit. Patch(oldName, newName) uses quoted a/ and b/ paths, three context lines and missing-final-newline markers. Equal inputs produce an empty patch. Names describe text files; renames, file modes and binary patches are not modeled.

Validation: go test ./ui/kit -run TestDiff, go test ./ui/window -run TestDiff, and go run ./examples/components -section diff. Tests include exact reconstruction and applying exported patches using Git when installed. Changed line pairs also highlight individual inserted/deleted grapheme clusters, preserving combining marks and emoji sequences. Pairing is positional within each changed region; completely inserted/deleted lines retain line highlighting. Intraline work shares a bounded budget across the comparison. Custom per-hunk actions are available through HunkActions; full visual and device parity with NSH DiffView remains unverified. The referenced gallery does not require an editable merge pane.

Stats() returns added/deleted source-line counts and the number of changed regions. These counts exclude unchanged context and update after review actions. Expanded(true) shows all unchanged lines in both text views; Expanded(false) restores three-line context. Both toolbars expose these actions. This only changes presentation, retaining the current change and leaving Patch() output and OnChange untouched. Split panes fold unchanged gaps using source-preserving editor folds, leaving three context lines and a source-line fold anchor. Expand restores all rows; navigation keeps changed regions visible. Selection and copy still use the complete original text. Language(name) forwards the syntax language to both source editors through the existing optional highlighting provider; unified patches retain diff decorations.

SetPatch(text) atomically enters inspection of one textual unified patch; errors leave the current view intact. Git diff/index and new/deleted-file mode headers are accepted, but multi-file and binary patches are rejected. Hunk counts, ordering, numeric overflow and newline markers are checked. Empty input is a valid empty patch. PatchInput() returns the original input plus a mode flag. In this mode Value() is an empty pair because omitted source text is unknown; Patch(...) returns the original input unchanged, ignoring the requested names. SetValue returns to text comparison. Keep/Revert are unavailable and do not notify. Expand does not invent missing context. Split inspection shows hunk headers and source line numbers inside the text, separately from the editor's display-row gutter; large gaps do not allocate blank lines. The Gallery's Inspect patch action exercises this mode.

OnLineNumberPress(func(DiffLine)) reports a zero-based original source line and DiffSideBefore or DiffSideAfter. Split folds retain source identity; unified context belongs to After, removed lines to Before and added lines to After. Imported patches report their original sparse source numbers rather than fragment display rows. File/hunk headers and missing-newline markers do not notify. Clicking a number still selects the line; fold-arrow clicks only fold. Disabled views and ancestors suppress pointer callbacks.

Hunk(index) returns (DiffHunk, bool): a snapshot with its zero-based index, half-open BeforeStart/BeforeEnd and AfterStart/AfterEnd source ranges, exact Before/After text, and PatchOnly. Empty ranges represent insertions/deletions. Text comparisons expose each changed region without context; patch inspection exposes each imported hunk with its known context, original sparse source ranges and final-newline semantics. Omitted text is never synthesized. Snapshots do not track later edits.

KeepAt(index) / RevertAt(index) act on a specific current region and notify once, without first changing the current selection. Invalid indices, disabled views and patch-only inspection return false without mutation. The existing current index is clamped if the number of regions shrinks. Indices can change after any text update: obtain a fresh snapshot before using a stored index. These APIs also supply the source identity used by embedded hunk actions.

HunkActions(func(DiffHunk) []DiffAction) inserts an action row immediately before each region, in the unified editor or the After pane. Matching blank space in Before preserves alignment. Each DiffAction has Label, Disabled and OnSelect func(DiffHunk); nil callbacks are disabled. Actions receive a fresh snapshot and may call KeepAt or RevertAt explicitly. Patch inspection supports application actions but still rejects review mutations. An obsolete row cannot act on a replacement comparison.

The factory runs when actions or comparison/presentation are rebuilt, not each frame; do not mutate the Diff from the factory. Returned slices are copied. Reapply HunkActions when externally computed labels or availability change. Return no actions to omit a region's row, or pass nil to remove all rows. Labels should be short. Rows reserve text-scaled space, use buttons at least 44dp high and scroll horizontally when narrow. They scroll vertically with the source; hidden folded rows do not render. Source copying, line numbers, caret/selection, and keyboard text navigation exclude controls. Action buttons support ordinary pointer and keyboard activation; ancestor disabling applies. Only visible control rows are laid out.