Editor/LineHistory.cs
using System;
using System.Collections.Generic;
using Editor;
using Sandbox.Helpers;

namespace TerrainLines;

// Preview gestures use the scene undo stack, then collapse away on Apply or Cancel.
internal sealed class LineHistory
{
	private readonly UndoSystem _undo;
	private readonly HashSet<UndoSystem.Entry> _entries = [];

	internal LineHistory( SceneEditorSession session ) => _undo = session.UndoSystem;
	internal void Push( string name, Action undo, Action redo ) => _entries.Add( _undo.Insert( name, undo, redo ) );

	internal void Clear()
	{
		RemoveEntries( _undo.Back );
		RemoveEntries( _undo.Forward );
		_entries.Clear();
	}

	private void RemoveEntries( Stack<UndoSystem.Entry> stack )
	{
		var keep = new Stack<UndoSystem.Entry>();
		while ( stack.TryPop( out var entry ) )
			if ( !_entries.Contains( entry ) ) keep.Push( entry );
		while ( keep.TryPop( out var entry ) ) stack.Push( entry );
	}
}