ファイル

46 行
1.7 KiB
C#

namespace UndoTree;
internal enum UndoTreeRestoreBlock
{
None,
NoProject,
NoAnchor,
NotReplayable,
}
internal sealed record UndoTreeRestorePlan(IReadOnlyList<UndoTreeNodeViewModel> Undo, IReadOnlyList<UndoTreeNodeViewModel> Redo, UndoTreeRestoreBlock Block, UndoTreeNodeViewModel? Offending)
{
public bool IsPossible => Block == UndoTreeRestoreBlock.None;
public static UndoTreeRestorePlan For(IReadOnlyList<UndoTreeNodeViewModel> archived, UndoTreeNodeViewModel target, string projectHash)
{
if (projectHash.Length == 0)
return Blocked(UndoTreeRestoreBlock.NoProject, null);
var anchors = archived.Where(node => node.ProjectHash == projectHash).ToArray();
if (anchors.Length == 0)
return Blocked(UndoTreeRestoreBlock.NoAnchor, null);
UndoTreeRestorePlan? best = null;
UndoTreeNodeViewModel? offending = null;
foreach (var anchor in anchors)
{
var ancestor = UndoTreeNodeViewModel.CommonAncestor(anchor, target);
var undo = anchor.StepsBelow(ancestor).Reverse().ToArray();
var redo = target.StepsBelow(ancestor);
if (undo.Concat(redo).FirstOrDefault(node => node.Steps is null) is { } stuck)
{
offending ??= stuck;
continue;
}
if (best is null || undo.Length + redo.Count < best.Undo.Count + best.Redo.Count)
best = new UndoTreeRestorePlan(undo, redo, UndoTreeRestoreBlock.None, null);
}
return best ?? Blocked(UndoTreeRestoreBlock.NotReplayable, offending);
}
static UndoTreeRestorePlan Blocked(UndoTreeRestoreBlock block, UndoTreeNodeViewModel? offending) => new([], [], block, offending);
}