namespace UndoTree; internal static class UndoTreeDiff { public static IReadOnlyList Between(IUndoRedoHistory source, IReadOnlyList currentSteps, IReadOnlyList targetSteps) { var current = Collect(source, currentSteps); var target = Collect(source, targetSteps); var infos = new List(); foreach (var key in target.Keys.Concat(current.Keys.Where(key => !target.Changes.ContainsKey(key)))) { current.Changes.TryGetValue(key, out var leaving); target.Changes.TryGetValue(key, out var arriving); var shared = (leaving ?? arriving)!; var before = leaving is null ? shared.Before : leaving.After; var after = arriving is null ? shared.Before : arriving.After; if (Equals(before, after)) continue; infos.Add(shared.View.Describe() with { Detail = $"{UndoRedoCommandView.TextOf(before)} → {UndoRedoCommandView.TextOf(after)}" }); } foreach (var list in target.Lists.Keys.Concat(current.Lists.Keys.Where(list => !target.Lists.ContainsKey(list)))) { target.Lists.TryGetValue(list, out var arriving); current.Lists.TryGetValue(list, out var leaving); var added = (arriving?.Added ?? 0) + (leaving?.Removed ?? 0); var removed = (arriving?.Removed ?? 0) + (leaving?.Added ?? 0); if (added > 0 || removed > 0) infos.Add(new UndoTreeCommandInfo(CommandKind.ListItems, list, string.Empty, UndoRedoCommandView.ListChangeOf(added, removed), string.Empty, null)); } var opaque = current.Opaque + target.Opaque; if (opaque > 0) infos.Add(new UndoTreeCommandInfo(CommandKind.Action, null, string.Empty, string.Format(Texts.DiffOpaque, opaque), string.Empty, null)); return infos; } static Side Collect(IUndoRedoHistory source, IReadOnlyList steps) { var side = new Side(); foreach (var step in steps) { foreach (var command in source.CommandsOf(step.Handle!)) { var view = UndoRedoCommandView.Read(command); if (view.Key is { } key) { if (side.Changes.TryGetValue(key, out var change)) { side.Changes[key] = change with { After = view.NewValue }; } else { side.Keys.Add(key); side.Changes[key] = new Change(view, view.OldValue, view.NewValue); } } else if (view.Kind == CommandKind.ListItems && view.Target is { } list) { var counts = side.Lists.TryGetValue(list, out var existing) ? existing : new ListCounts(0, 0); side.Lists[list] = new ListCounts(counts.Added + view.Added, counts.Removed + view.Removed); } else { side.Opaque++; } } } return side; } sealed class Side { public List Keys { get; } = []; public Dictionary Changes { get; } = []; public Dictionary Lists { get; } = new(ReferenceEqualityComparer.Instance); public int Opaque { get; set; } } sealed record Change(UndoRedoCommandView View, object? Before, object? After); sealed record ListCounts(int Added, int Removed); }