using System; using System.Collections.Generic; using Spectre.Console.Rendering; namespace Spectre.Console { /// /// A renderable grid. /// public sealed class Grid : Renderable, IExpandable { private readonly Table _table; /// /// Gets the number of columns in the table. /// public int ColumnCount => _table.ColumnCount; /// /// Gets the number of rows in the table. /// public int RowCount => _table.RowCount; /// public bool Expand { get => _table.Expand; set => _table.Expand = value; } /// /// Initializes a new instance of the class. /// public Grid() { _table = new Table { BorderKind = BorderKind.None, ShowHeaders = false, IsGrid = true, PadRightCell = false, }; } /// protected override Measurement Measure(RenderContext context, int maxWidth) { return ((IRenderable)_table).Measure(context, maxWidth); } /// protected override IEnumerable Render(RenderContext context, int width) { return ((IRenderable)_table).Render(context, width); } /// /// Adds a column to the grid. /// /// The same instance so that multiple calls can be chained. public Grid AddColumn() { AddColumn(new GridColumn()); return this; } /// /// Adds a column to the grid. /// /// The column to add. /// The same instance so that multiple calls can be chained. public Grid AddColumn(GridColumn column) { if (column is null) { throw new ArgumentNullException(nameof(column)); } if (_table.RowCount > 0) { throw new InvalidOperationException("Cannot add new columns to grid with existing rows."); } // Only pad the most right cell if we've explicitly set a padding. _table.PadRightCell = column.HasExplicitPadding; _table.AddColumn(new TableColumn(string.Empty) { Width = column.Width, NoWrap = column.NoWrap, Padding = column.Padding, Alignment = column.Alignment, }); return this; } /// /// Adds a new row to the grid. /// /// The columns to add. /// The same instance so that multiple calls can be chained. public Grid AddRow(params IRenderable[] columns) { if (columns is null) { throw new ArgumentNullException(nameof(columns)); } if (columns.Length > _table.ColumnCount) { throw new InvalidOperationException("The number of row columns are greater than the number of grid columns."); } _table.AddRow(columns); return this; } } }