Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions UndoRedo.Test/CompositeCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,78 @@
Assert.IsEmpty(values);
Assert.IsLessThan(1000L, stopwatch.ElapsedMilliseconds, "Undo should be fast");
}

[TestMethod]
public void CompositeCommand_SinglePassSequence_KeepsEveryCommandAndItsMetadata()
{
// Arrange
List<string> values = [];

// Act
CompositeCommand composite = new("Single pass", SinglePass(values));
composite.Execute();

// Assert
Assert.HasCount(2, composite.Commands);
CollectionAssert.AreEqual(new List<string> { "A", "B" }, values);

Check warning on line 285 in UndoRedo.Test/CompositeCommandTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.AreSequenceEqual' instead of 'CollectionAssert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_UndoRedo&issues=AaDkmcT6MBdIn6dpt3C-&open=AaDkmcT6MBdIn6dpt3C-&pullRequest=110
CollectionAssert.AreEqual(new List<string> { "item-A", "item-B" }, composite.Metadata.AffectedItems.ToList());

Check warning on line 286 in UndoRedo.Test/CompositeCommandTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.AreSequenceEqual' instead of 'CollectionAssert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_UndoRedo&issues=AaDkmcT6MBdIn6dpt3C_&open=AaDkmcT6MBdIn6dpt3C_&pullRequest=110
Assert.AreEqual(5, composite.Metadata.Size);
}

[TestMethod]
public void CompositeCommand_LazyFactory_RunsOncePerCommand()
{
// Arrange
int created = 0;
IEnumerable<ICommand> commands = Enumerable.Range(0, 3).Select(i =>
{
created++;
return (ICommand)new DelegateCommand($"Command {i}", () => { }, () => { }, affectedItems: [$"item-{i}"], size: 1);
});

// Act
CompositeCommand composite = new("Lazy", commands);

// Assert
Assert.AreEqual(3, created);
Assert.HasCount(3, composite.Metadata.AffectedItems);
Assert.AreEqual(3, composite.Metadata.Size);
}

[TestMethod]
public void CompositeCommand_NullElement_ThrowsArgumentException()
{
// Arrange
ICommand[] commands = [new DelegateCommand("Ok", () => { }, () => { }), null!];

// Act & Assert
Assert.ThrowsExactly<ArgumentException>(() => new CompositeCommand("Null element", commands));
}

private static SinglePassSequence SinglePass(List<string> values) => new(
[
new DelegateCommand("Add A", () => values.Add("A"), () => values.RemoveAt(values.Count - 1), affectedItems: ["item-A"], size: 2),
new DelegateCommand("Add B", () => values.Add("B"), () => values.RemoveAt(values.Count - 1), affectedItems: ["item-B"], size: 3),
]);

/// <summary>
/// A sequence that yields its items only on the first enumeration, like a stream or a database cursor.
/// </summary>
private sealed class SinglePassSequence(IEnumerable<ICommand> items) : IEnumerable<ICommand>
{
private bool enumerated;

public IEnumerator<ICommand> GetEnumerator()
{
if (enumerated)
{
return Enumerable.Empty<ICommand>().GetEnumerator();
}

enumerated = true;
return items.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
}
39 changes: 23 additions & 16 deletions UndoRedo/CompositeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,21 @@ public sealed class CompositeCommand : BaseCommand
/// <param name="commands">Commands to execute as a group</param>
/// <param name="navigationContext">Optional navigation context</param>
public CompositeCommand(string description, IEnumerable<ICommand> commands, string? navigationContext = null)
: this(description, Materialize(commands), navigationContext)
{
}

// Takes the one materialized list, so the caller's sequence is enumerated exactly once and the
// metadata is computed from the same commands that Execute and Undo run.
private CompositeCommand(string description, List<ICommand> commands, string? navigationContext)
: base(
ChangeType.Composite,
GetAffectedItems(commands),
[.. commands.SelectMany(c => c.Metadata.AffectedItems).Distinct()],
navigationContext,
GetTotalSize(commands))
commands.Sum(c => c.Metadata.Size))
{
Description = description;
_commands = [.. commands];

if (_commands.Count == 0)
{
throw new ArgumentException("Composite command must contain at least one command", nameof(commands));
}
_commands = commands;
}

/// <inheritdoc />
Expand Down Expand Up @@ -114,15 +116,20 @@ public override void Undo()
/// <inheritdoc />
public override ICommand MergeWith(ICommand other) => throw new NotSupportedException("Composite commands cannot be merged");

private static IReadOnlyList<string> GetAffectedItems(IEnumerable<ICommand> commands)
private static List<ICommand> Materialize(IEnumerable<ICommand> commands)
{
List<ICommand> commandList = [.. commands];
return [.. commandList.SelectMany(c => c.Metadata.AffectedItems).Distinct()];
}
List<ICommand> commandList = [.. Ensure.NotNull(commands)];

private static int GetTotalSize(IEnumerable<ICommand> commands)
{
List<ICommand> commandList = [.. commands];
return commandList.Sum(c => c.Metadata.Size);
if (commandList.Count == 0)
{
throw new ArgumentException("Composite command must contain at least one command", nameof(commands));
}

if (commandList.Contains(null!))
{
throw new ArgumentException("Composite command cannot contain a null command", nameof(commands));
}

return commandList;
}
}
Loading