Editor/Tilemap/ManualTileHistory.cs

The ManualTileHistory class tracks and persists a list of recently used tile IDs for various tilesets within the editor. It uses project cookies to save and load this history across editor sessions.

using System;
using Editor;
using Saandy.Tilemapper;

namespace Saandy.Editor.Tilemapper;

/// <summary>Project-local editor history keyed by tile identity, preserved across editor sessions.</summary>
internal sealed class ManualTileHistory
{
	private readonly Dictionary<TilesetResource, List<Guid>> History = new();

	public IReadOnlyList<Guid> GetRecent( TilesetResource tileset )
	{
		if ( tileset == null ) { return Array.Empty<Guid>(); }
		if ( History.TryGetValue( tileset, out var tiles ) ) { return tiles; }
		var key = CookieKey( tileset );
		tiles = key == null ? new() : ProjectCookie.Get<List<Guid>>( key, null ) ?? new();
		History[tileset] = tiles;
		return tiles;
	}

	private static string CookieKey( TilesetResource tileset ) => string.IsNullOrWhiteSpace( tileset.ResourcePath )
		? null : $"Tilemapper.ManualRecent.{tileset.ResourcePath.Replace( '\\', '/' ).ToLowerInvariant()}";

	public void Record( TilesetResource tileset, ushort index )
	{
		if ( tileset?.BrushType != BrushType.Manual || index >= (tileset.Tiles?.Count ?? 0) ) { return; }
		var id = tileset.Tiles[index]?.Id ?? Guid.Empty;
		if ( id == Guid.Empty ) { return; }
		var tiles = (List<Guid>)GetRecent( tileset );
		if ( tiles.Count > 0 && tiles[0] == id ) { return; }
		tiles.Remove( id );
		tiles.Insert( 0, id );
		if ( tiles.Count > 10 ) { tiles.RemoveRange( 10, tiles.Count - 10 ); }
		var key = CookieKey( tileset );
		if ( key != null ) { ProjectCookie.Set( key, tiles ); }
	}
}