途中の操作をリバートできるようにする

このコミットが含まれているのは:
routersys committed 2026-11-01 07:17:02 +09:00
1 親 fbc9b239b0
コミット 6024422e82
6ファイル変更
+247 -52

検索条件に一致するファイルはありません

+111
ファイルの表示
@@ -29,6 +29,117 @@ public sealed class UndoTreeApplyTests
Assert.Empty(result.Conflicts);
}
[Fact]
public async Task RevertingAnOperationInTheMiddleKeepsTheLaterOnes()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
var a = history.Cursor;
Histories.Edit(manager, () => document.Parts[0].Value = 10);
Histories.Edit(manager, () => document.Y = 5);
var result = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true);
Assert.Equal("X=0 Y=5 Parts=[p1:10]", document.Snapshot());
Assert.Equal(1, result.Applied);
Assert.Empty(result.Conflicts);
Assert.Equal(4, history.Cursor.Depth);
}
[Fact]
public async Task ARevertIsRecordedAsANewEditThatCanBeUndone()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
var a = history.Cursor;
Histories.Edit(manager, () => document.Y = 5);
await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true);
await history.UndoAsync();
Assert.Equal("X=1 Y=5 Parts=[p1:0]", document.Snapshot());
}
[Fact]
public async Task RevertingAChangeThatALaterOperationChangedAgainIsAConflict()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
var a = history.Cursor;
Histories.Edit(manager, () => document.X = 2);
var skipped = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true);
Assert.Equal("X=2 Y=0 Parts=[p1:0]", document.Snapshot());
Assert.Equal(0, skipped.Applied);
Assert.Equal(ConflictKind.SameProperty, Assert.Single(skipped.Conflicts).Kind);
var overwritten = await history.ApplyAsync([a], ConflictPolicy.Apply, inverse: true);
Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot());
Assert.Equal(1, overwritten.Applied);
}
[Fact]
public async Task RevertingSeveralChangesOfOneOperationRestoresThemInReverseOrder()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => { document.X = 1; document.Y = 2; document.Parts[0].Value = 3; });
var a = history.Cursor;
var result = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true);
Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot());
Assert.Equal(3, result.Applied);
}
[Fact]
public async Task RevertingAListChangeRemovesTheAddedItem()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.Parts.Add(new Part("p2")));
var a = history.Cursor;
Histories.Edit(manager, () => document.X = 1);
await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true);
Assert.Equal("X=1 Y=0 Parts=[p1:0]", document.Snapshot());
}
[Fact]
public async Task AnOperationWithAnActionCannotBeReverted()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { }));
manager.Record();
var a = history.Cursor;
var failure = await Assert.ThrowsAsync<UndoTreeOperationException>(() => history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true));
Assert.Equal(Texts.RevertUnsupported, failure.Message);
}
[Fact]
public async Task OnlyAnOperationOnTheCurrentPathCanBeReverted()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
var a = history.Cursor;
await history.JumpAsync(history.Root);
var failure = await Assert.ThrowsAsync<UndoTreeOperationException>(() => history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true));
Assert.Equal(Texts.NothingToApply, failure.Message);
Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot());
}
[Fact]
public async Task ReplayedOperationsBecomeNewNodesBelowTheCursorAndTheSourceBranchStays()
{
+36
ファイルの表示
@@ -321,6 +321,42 @@ public sealed class UndoTreeViewModelTests
return (model, manager, document);
}
[Fact]
public void OnlyANodeOnThePathOrTheCurrentOneCanBeReverted()
{
var (model, _, _, a, b, d) = Forked();
Assert.False(model.RevertCommand.CanExecute(model.Items[0]));
Assert.True(model.RevertCommand.CanExecute(a));
Assert.True(model.RevertCommand.CanExecute(d));
Assert.False(model.RevertCommand.CanExecute(b));
}
[Fact]
public void RevertingFromTheMenuUndoesTheOperationAsANewEditAndReportsIt()
{
var (model, _, document, a, _, _) = Forked();
model.RevertCommand.Execute(a);
Assert.Equal("X=0 Y=7 Parts=[p1:0]", document.Snapshot());
Assert.Equal(string.Format(Texts.ApplyResult, 1, 0), model.ResultText);
}
[Fact]
public void AnOperationThatCannotBeRevertedIsReportedWithoutChangingAnything()
{
var (model, manager, document) = Open();
manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { }));
manager.Record();
var node = model.Items[^1];
model.RevertCommand.Execute(node);
Assert.Equal(Texts.RevertUnsupported, model.ResultText);
Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot());
}
[Fact]
public void ConsecutiveChangesToTheSameItemAreShownAsOneRowWithTheCount()
{
+3
ファイルの表示
@@ -38,6 +38,9 @@ SelectionOnly,,選択中のアイテムの履歴だけを表示,Show only the hi
StatusFiltered,,{0}件中{1}件を表示,Showing {1} of {0},共 {0} 项,显示 {1} 项,共 {0} 項,顯示 {1} 項,{0}개 중 {1}개 표시,Mostrando {1} de {0},عرض {1} من {0},Menampilkan {1} dari {0}
FoldRuns,,同じ項目の連続した変更をまとめる,Group consecutive changes to the same item,合并对同一项目的连续更改,合併對同一項目的連續變更,같은 항목의 연속된 변경을 묶기,Agrupar cambios consecutivos del mismo elemento,تجميع التغييرات المتتالية على العنصر نفسه,Kelompokkan perubahan berurutan pada item yang sama
FoldedRun,,{0}({1}回),{0} ({1} times),{0}({1} 次),{0}({1} 次),{0} ({1}회),{0} ({1} veces),{0} ({1} مرات),{0} ({1} kali)
Revert,,この操作をリバート,Revert this operation,revert 此操作,revert 此操作,이 작업 리버트,Revertir esta operación,عكس هذه العملية (revert),Revert operasi ini
RevertTip,,この操作の変更を、現在の状態に対する新しい編集として打ち消します。,Undoes the changes of this operation as a new edit on the current state.,将此操作的更改作为对当前状态的新编辑撤销。,將此操作的變更作為對目前狀態的新編輯復原。,이 작업의 변경 내용을 현재 상태에 대한 새 편집으로 되돌립니다.,Deshace los cambios de esta operación como una edición nueva sobre el estado actual.,يتراجع عن تغييرات هذه العملية كتعديل جديد على الحالة الحالية.,Membatalkan perubahan operasi ini sebagai suntingan baru pada keadaan saat ini.
RevertUnsupported,,この操作には、リバートできない処理が含まれています。,This operation contains steps that cannot be reverted.,此操作包含无法 revert 的处理。,此操作包含無法 revert 的處理。,이 작업에는 리버트할 수 없는 처리가 포함되어 있습니다.,Esta operación contiene pasos que no se pueden revertir.,تحتوي هذه العملية على خطوات لا يمكن عكسها.,Operasi ini berisi langkah yang tidak dapat di-revert.
ConflictDeadTarget,,{0} / {1}: 対象が存在しないためスキップしました,{0} / {1}: skipped because the target no longer exists,{0} / {1}:对象已不存在,已跳过,{0} / {1}:物件已不存在,已略過,{0} / {1}: 대상이 없어 건너뛰었습니다,{0} / {1}: omitido porque el objetivo ya no existe,{0} / {1}: تم التخطي لأن الهدف لم يعد موجودًا,{0} / {1}: dilewati karena target sudah tidak ada
ConflictSameSkipped,,{0} / {1}: 現在の位置で既に変更されているためスキップしました,{0} / {1}: skipped because it was already changed here,{0} / {1}:已在当前位置更改,已跳过,{0} / {1}:已在目前位置變更,已略過,{0} / {1}: 현재 위치에서 이미 변경되어 건너뛰었습니다,{0} / {1}: omitido porque ya se modificó aquí,{0} / {1}: تم التخطي لأنه تغيّر هنا بالفعل,{0} / {1}: dilewati karena sudah diubah di sini
ConflictSameApplied,,{0} / {1}: 現在の位置で既に変更されていたため、操作の値で上書きしました,"{0} / {1}: already changed here, overwritten with the value of the operation",{0} / {1}:已在当前位置更改,已用该操作的值覆盖,{0} / {1}:已在目前位置變更,已用該操作的值覆蓋,{0} / {1}: 현재 위치에서 이미 변경되어 작업의 값으로 덮어썼습니다,"{0} / {1}: ya se modificó aquí, sobrescrito con el valor de la operación",{0} / {1}: تغيّر هنا بالفعل وتمت الكتابة فوقه بقيمة العملية,"{0} / {1}: sudah diubah di sini, ditimpa dengan nilai operasi"
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
38 StatusFiltered {0}件中{1}件を表示 Showing {1} of {0} 共 {0} 项,显示 {1} 项 共 {0} 項,顯示 {1} 項 {0}개 중 {1}개 표시 Mostrando {1} de {0} عرض {1} من {0} Menampilkan {1} dari {0}
39 FoldRuns 同じ項目の連続した変更をまとめる Group consecutive changes to the same item 合并对同一项目的连续更改 合併對同一項目的連續變更 같은 항목의 연속된 변경을 묶기 Agrupar cambios consecutivos del mismo elemento تجميع التغييرات المتتالية على العنصر نفسه Kelompokkan perubahan berurutan pada item yang sama
40 FoldedRun {0}({1}回) {0} ({1} times) {0}({1} 次) {0}({1} 次) {0} ({1}회) {0} ({1} veces) {0} ({1} مرات) {0} ({1} kali)
41 Revert この操作をリバート Revert this operation revert 此操作 revert 此操作 이 작업 리버트 Revertir esta operación عكس هذه العملية (revert) Revert operasi ini
42 RevertTip この操作の変更を、現在の状態に対する新しい編集として打ち消します。 Undoes the changes of this operation as a new edit on the current state. 将此操作的更改作为对当前状态的新编辑撤销。 將此操作的變更作為對目前狀態的新編輯復原。 이 작업의 변경 내용을 현재 상태에 대한 새 편집으로 되돌립니다. Deshace los cambios de esta operación como una edición nueva sobre el estado actual. يتراجع عن تغييرات هذه العملية كتعديل جديد على الحالة الحالية. Membatalkan perubahan operasi ini sebagai suntingan baru pada keadaan saat ini.
43 RevertUnsupported この操作には、リバートできない処理が含まれています。 This operation contains steps that cannot be reverted. 此操作包含无法 revert 的处理。 此操作包含無法 revert 的處理。 이 작업에는 리버트할 수 없는 처리가 포함되어 있습니다. Esta operación contiene pasos que no se pueden revertir. تحتوي هذه العملية على خطوات لا يمكن عكسها. Operasi ini berisi langkah yang tidak dapat di-revert.
44 ConflictDeadTarget {0} / {1}: 対象が存在しないためスキップしました {0} / {1}: skipped because the target no longer exists {0} / {1}:对象已不存在,已跳过 {0} / {1}:物件已不存在,已略過 {0} / {1}: 대상이 없어 건너뛰었습니다 {0} / {1}: omitido porque el objetivo ya no existe {0} / {1}: تم التخطي لأن الهدف لم يعد موجودًا {0} / {1}: dilewati karena target sudah tidak ada
45 ConflictSameSkipped {0} / {1}: 現在の位置で既に変更されているためスキップしました {0} / {1}: skipped because it was already changed here {0} / {1}:已在当前位置更改,已跳过 {0} / {1}:已在目前位置變更,已略過 {0} / {1}: 현재 위치에서 이미 변경되어 건너뛰었습니다 {0} / {1}: omitido porque ya se modificó aquí {0} / {1}: تم التخطي لأنه تغيّر هنا بالفعل {0} / {1}: dilewati karena sudah diubah di sini
46 ConflictSameApplied {0} / {1}: 現在の位置で既に変更されていたため、操作の値で上書きしました {0} / {1}: already changed here, overwritten with the value of the operation {0} / {1}:已在当前位置更改,已用该操作的值覆盖 {0} / {1}:已在目前位置變更,已用該操作的值覆蓋 {0} / {1}: 현재 위치에서 이미 변경되어 작업의 값으로 덮어썼습니다 {0} / {1}: ya se modificó aquí, sobrescrito con el valor de la operación {0} / {1}: تغيّر هنا بالفعل وتمت الكتابة فوقه بقيمة العملية {0} / {1}: sudah diubah di sini, ditimpa dengan nilai operasi
+80 -50
ファイルの表示
@@ -156,7 +156,7 @@ internal class UndoTreeHistory : IDisposable
}
}
public async Task<UndoTreeApplyResult> ApplyAsync(IReadOnlyList<UndoTreeNodeViewModel> sources, ConflictPolicy policy)
public async Task<UndoTreeApplyResult> ApplyAsync(IReadOnlyList<UndoTreeNodeViewModel> sources, ConflictPolicy policy, bool inverse = false)
{
Reconcile();
if (source is null)
@@ -165,6 +165,12 @@ internal class UndoTreeHistory : IDisposable
if (!source.CanReplay)
throw new UndoTreeOperationException(Texts.BranchUnavailable);
if (inverse && sources.Any(node => !(node.IsOnPath || node.IsCurrent) || node.IsRoot))
throw new UndoTreeOperationException(Texts.NothingToApply);
if (inverse && sources.Any(node => node.Commands.Any(command => command.Kind is CommandKind.Action or CommandKind.Other)))
throw new UndoTreeOperationException(Texts.RevertUnsupported);
var touched = new HashSet<UndoTreeChangeKey>();
var applied = 0;
var conflicts = new List<UndoTreeConflict>();
@@ -182,7 +188,7 @@ internal class UndoTreeHistory : IDisposable
{
foreach (var node in sources)
{
var result = await ReplayAsync(source, node.Handle!, true, policy, touched);
var result = await ReplayAsync(source, node.Handle!, true, policy, touched, inverse);
applied += result.Applied;
conflicts.AddRange(result.Conflicts);
Merge(source.Undo, source.Redo);
@@ -300,12 +306,22 @@ internal class UndoTreeHistory : IDisposable
return commands.Count == 1 ? commands[0].Text : string.Format(Texts.OperationAndMore, commands[0].Text, commands.Count - 1);
}
static async Task ExecuteAsync(IUndoRedoCommandBase command)
static async Task ExecuteAsync(IUndoRedoCommandBase command, bool inverse)
{
if (command is IUndoRedoCommand synchronous)
synchronous.Redo();
{
if (inverse)
synchronous.Undo();
else
synchronous.Redo();
}
else if (command is IUndoRedoAsyncCommand asynchronous)
await asynchronous.RedoAsync();
{
if (inverse)
await asynchronous.UndoAsync();
else
await asynchronous.RedoAsync();
}
}
void Manager_HistoryChanged(object? sender, EventArgs e)
@@ -561,7 +577,7 @@ internal class UndoTreeHistory : IDisposable
foreach (var node in descent)
{
var result = await ReplayAsync(history, node.Handle!, false, ConflictPolicy.Skip, []);
var result = await ReplayAsync(history, node.Handle!, false, ConflictPolicy.Skip, [], false);
if (result.Handle is null)
throw new InvalidOperationException(Texts.NothingToApply);
@@ -571,9 +587,9 @@ internal class UndoTreeHistory : IDisposable
}
}
async Task<ReplayResult> ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet<UndoTreeChangeKey> touched)
async Task<ReplayResult> ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet<UndoTreeChangeKey> touched, bool inverse)
{
var commands = history.CommandsOf(handle);
var commands = inverse ? history.CommandsOf(handle).Reverse().ToArray() : history.CommandsOf(handle);
var before = history.Undo;
var applied = 0;
var conflicts = new List<UndoTreeConflict>();
@@ -583,7 +599,7 @@ internal class UndoTreeHistory : IDisposable
{
foreach (var command in commands.Where(command => command.IsAction == pass))
{
if (await ReplayCommandAsync(command, check, policy, touched, conflicts))
if (await ReplayCommandAsync(command, check, policy, touched, conflicts, inverse))
applied++;
}
}
@@ -598,71 +614,85 @@ internal class UndoTreeHistory : IDisposable
return new ReplayResult(recorded ? after[^1] : null, applied, conflicts);
}
async Task<bool> ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet<UndoTreeChangeKey> touched, List<UndoTreeConflict> conflicts)
async Task<bool> ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet<UndoTreeChangeKey> touched, List<UndoTreeConflict> conflicts, bool inverse)
{
if (command.IsAction)
{
await ExecuteAsync(command);
await ExecuteAsync(command, inverse);
manager.AddCommand(command);
return true;
}
if (!check)
{
await ExecuteAsync(command);
await ExecuteAsync(command, inverse);
return true;
}
var view = UndoRedoCommandView.Read(command);
var info = view.Describe();
if (view.Target is { } target && view.Kind is CommandKind.Property or CommandKind.Indexer && !UndoRedoCommandView.IsLive(target))
var verdict = Judge(view, touched, inverse);
var apply = policy == ConflictPolicy.Apply;
switch (verdict)
{
conflicts.Add(new UndoTreeConflict(ConflictKind.DeadTarget, info.TargetLabel, info.Member, false));
return false;
case Verdict.DeadTarget:
conflicts.Add(new UndoTreeConflict(ConflictKind.DeadTarget, info.TargetLabel, info.Member, false));
return false;
case Verdict.Merged:
conflicts.Add(new UndoTreeConflict(ConflictKind.CollectionMerged, info.TargetLabel, info.Member, true));
TryMergeList(view, inverse, out var property, out var merged);
property!.SetValue(view.Target, merged);
return true;
case Verdict.Unreadable:
case Verdict.SameProperty:
conflicts.Add(new UndoTreeConflict(verdict == Verdict.Unreadable ? ConflictKind.Unreadable : ConflictKind.SameProperty, info.TargetLabel, info.Member, apply));
if (apply)
await ExecuteAsync(command, inverse);
return apply;
default:
await ExecuteAsync(command, inverse);
return true;
}
if (view.Kind is CommandKind.Property or CommandKind.Indexer && !view.IsReadable)
{
var apply = policy == ConflictPolicy.Apply;
conflicts.Add(new UndoTreeConflict(ConflictKind.Unreadable, info.TargetLabel, info.Member, apply));
if (apply)
await ExecuteAsync(command);
return apply;
}
if (view.Kind == CommandKind.Property && TryMergeList(view))
{
conflicts.Add(new UndoTreeConflict(ConflictKind.CollectionMerged, info.TargetLabel, info.Member, true));
return true;
}
if (view.Key is { } key && touched.Contains(key))
{
var apply = policy == ConflictPolicy.Apply;
conflicts.Add(new UndoTreeConflict(ConflictKind.SameProperty, info.TargetLabel, info.Member, apply));
if (apply)
await ExecuteAsync(command);
return apply;
}
await ExecuteAsync(command);
return true;
}
static bool TryMergeList(UndoRedoCommandView view)
static Verdict Judge(UndoRedoCommandView view, HashSet<UndoTreeChangeKey> touched, bool inverse)
{
var property = view.Target!.GetType().GetProperty(view.Member, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (view.Kind is CommandKind.Property or CommandKind.Indexer)
{
if (view.Target is { } target && !UndoRedoCommandView.IsLive(target))
return Verdict.DeadTarget;
if (!view.IsReadable)
return Verdict.Unreadable;
}
if (view.Kind == CommandKind.Property && TryMergeList(view, inverse, out _, out _))
return Verdict.Merged;
return view.Key is { } key && touched.Contains(key) ? Verdict.SameProperty : Verdict.Run;
}
static bool TryMergeList(UndoRedoCommandView view, bool inverse, out PropertyInfo? property, out object? merged)
{
merged = null;
property = view.Target!.GetType().GetProperty(view.Member, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property is null || !property.CanRead || !property.CanWrite)
return false;
var current = property.GetValue(view.Target);
if (Equals(current, view.OldValue) || !UndoTreeListMerge.TryMerge(current, view.OldValue, view.NewValue, out var merged))
return false;
var from = inverse ? view.NewValue : view.OldValue;
var to = inverse ? view.OldValue : view.NewValue;
return !Equals(current, from) && UndoTreeListMerge.TryMerge(current, from, to, out merged);
}
property.SetValue(view.Target, merged);
return true;
enum Verdict
{
Run,
DeadTarget,
Unreadable,
Merged,
SameProperty,
}
sealed record ReplayResult(object? Handle, int Applied, IReadOnlyList<UndoTreeConflict> Conflicts);
+2
ファイルの表示
@@ -21,6 +21,8 @@
<Separator/>
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBox}, Path=DataContext.CherryPickCommand}" CommandParameter="{Binding}" Header="{x:Static local:Texts.CherryPick}" Icon="{DynamicResource {x:Static icons:IconKeys.SourceMerge}}"/>
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBox}, Path=DataContext.CherryPickRangeCommand}" CommandParameter="{Binding}" Header="{x:Static local:Texts.CherryPickRange}" Icon="{DynamicResource {x:Static icons:IconKeys.SourceFork}}"/>
<Separator/>
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBox}, Path=DataContext.RevertCommand}" CommandParameter="{Binding}" Header="{x:Static local:Texts.Revert}" ToolTip="{x:Static local:Texts.RevertTip}" Icon="{DynamicResource {x:Static icons:IconKeys.Undo}}"/>
</ContextMenu>
<Style x:Key="ToolBarButtonStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="3"/>
+15 -2
ファイルの表示
@@ -65,6 +65,8 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
public ActionCommand CherryPickRangeCommand { get; }
public ActionCommand RevertCommand { get; }
public ActionCommand ExpandAllCommand { get; }
public ActionCommand CollapseAllCommand { get; }
@@ -81,6 +83,7 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
RedoCommand,
CherryPickCommand,
CherryPickRangeCommand,
RevertCommand,
ExpandAllCommand,
CollapseAllCommand,
GoToCurrentCommand,
@@ -121,6 +124,13 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
if (NodeOf(parameter) is { } node)
_ = RunAsync(() => ApplyAsync([node, .. history!.PrimaryChain(node)]));
});
RevertCommand = new ActionCommand(
parameter => CanRevert(NodeOf(parameter)),
parameter =>
{
if (NodeOf(parameter) is { } node)
_ = RunAsync(() => ApplyAsync([node], inverse: true));
});
ExpandAllCommand = new ActionCommand(
_ => history is not null,
_ => SetAllExpanded(true));
@@ -225,6 +235,9 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
bool CanApply(UndoTreeNodeViewModel? node)
=> !isRunning && history is { CanReplay: true } && node is { IsRoot: false, IsCurrent: false, IsOnPath: false };
bool CanRevert(UndoTreeNodeViewModel? node)
=> !isRunning && history is { CanReplay: true } && node is { IsRoot: false } && (node.IsOnPath || node.IsCurrent);
void RaiseCommandExecutable()
{
foreach (var command in Commands)
@@ -270,9 +283,9 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
}
}
async Task ApplyAsync(IReadOnlyList<UndoTreeNodeViewModel> sources)
async Task ApplyAsync(IReadOnlyList<UndoTreeNodeViewModel> sources, bool inverse = false)
{
var result = await history!.ApplyAsync(sources, UndoTreeSettings.Default.ConflictPolicy);
var result = await history!.ApplyAsync(sources, UndoTreeSettings.Default.ConflictPolicy, inverse);
ResultText = Summarize(result);
}