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
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public static IServiceCollection AddRazorConsoleServices(this IServiceCollection
services.TryAddSingleton<TerminalMonitor>();

// Register translation middlewares in order of priority
// Overlay catcher
services.AddSingleton<ITranslationMiddleware, Rendering.Translation.Translators.AbsolutePositionMiddleware>();

// Text nodes and basic elements first
services.AddSingleton<ITranslationMiddleware, Rendering.Translation.Translators.TextNodeTranslator>();
services.AddSingleton<ITranslationMiddleware, Rendering.Translation.Translators.TextElementTranslator>();
Expand Down
198 changes: 198 additions & 0 deletions src/RazorConsole.Core/Renderables/OverlayRenderable.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// Copyright (c) RazorConsole. All rights reserved.

using System.Buffers;
using RazorConsole.Core.Rendering;
using Spectre.Console;
using Spectre.Console.Rendering;

namespace RazorConsole.Core.Renderables;

public sealed class OverlayRenderable(IRenderable background, IEnumerable<OverlayItem> overlays) : IRenderable
{
private readonly List<OverlayItem> _sortedOverlays = overlays.OrderBy(o => o.ZIndex).ToList();
private readonly Dictionary<int, List<OverlayPosition>> _overlayMapCache = new();

public Measurement Measure(RenderOptions options, int maxWidth) => background.Measure(options, maxWidth);

public IEnumerable<Segment> Render(RenderOptions options, int maxWidth)
{
var bgSegments = background.Render(options, maxWidth);
var canvas = Segment.SplitLines(bgSegments);

_overlayMapCache.Clear();

foreach (var overlay in _sortedOverlays)
{
var (widthToRender, finalLeft) = overlay switch
{
// CSS-like stretching
{ Left: { } l, Right: { } r } => (maxWidth - l - r, l),
{ Right: { } r } => CalculateRightPosition(overlay, r, options, maxWidth),
_ => (maxWidth - (overlay.Left ?? 0), overlay.Left ?? 0)
};

(int Width, int Left) CalculateRightPosition(OverlayItem item, int r, RenderOptions opt, int maxW)
Comment thread
TeseySTD marked this conversation as resolved.
{
var constraint = Math.Max(0, maxW - r);
var width = item.Renderable.Measure(opt, constraint).Max;
return (width, maxW - r - width);
}

var lines = Segment.SplitLines(
overlay.Renderable.Render(options, Math.Max(0, widthToRender))
);

int finalTop = overlay.Top ?? (overlay.Bottom.HasValue
? Math.Max(0, canvas.Count - overlay.Bottom.Value - lines.Count)
: 0);

for (int i = 0; i < lines.Count; i++)
{
int targetY = finalTop + i;
if (targetY < 0)
{
continue;
}

if (!_overlayMapCache.TryGetValue(targetY, out var positions))
{
positions = new List<OverlayPosition>(4);
_overlayMapCache[targetY] = positions;
}

positions.Add(new OverlayPosition(lines[i], finalLeft));
}
}

var cellPool = ArrayPool<Cell>.Shared;
Cell[]? lineBuffer = null;

try
{
lineBuffer = cellPool.Rent(maxWidth);

foreach (var (y, overlayPositions) in _overlayMapCache)
{
// If overlay is over the canvas
while (canvas.Count <= y)
{
canvas.Add(new SegmentLine());
}

// Clean up array
Array.Fill(lineBuffer, new Cell(' ', Style.Plain), 0, maxWidth);

int backgroundWidth = ToBuffer(canvas[y], lineBuffer, maxWidth);
int actualWidth = backgroundWidth;

foreach (var overlayPos in overlayPositions)
{
int endX = MergeToBuffer(overlayPos.Line, lineBuffer, overlayPos.Left, maxWidth);
if (endX > actualWidth)
{
actualWidth = endX;
}
}

canvas[y] = FromBuffer(lineBuffer, actualWidth);
}
}
finally
{
if (lineBuffer != null)
{
cellPool.Return(lineBuffer);
}
}

for (int i = 0; i < canvas.Count; i++)
{
foreach (var segment in canvas[i])
{
yield return segment;
}

if (i < canvas.Count - 1)
{
yield return Segment.LineBreak;
}
}
}

private static int ToBuffer(IReadOnlyList<Segment> segments, Cell[] buffer, int maxWidth)
{
int cursor = 0;
foreach (var segment in segments)
{
var text = segment.Text;
var style = segment.Style;
for (int i = 0; i < text.Length && cursor < maxWidth; i++)
{
buffer[cursor++] = new Cell(text[i], style);
}
}

return cursor;
}

private static int MergeToBuffer(IReadOnlyList<Segment> overlaySegments, Cell[] buffer, int left, int maxWidth)
{
int cursor = left;
foreach (var segment in overlaySegments)
{
var text = segment.Text;
var style = segment.Style;
for (int i = 0; i < text.Length && cursor < maxWidth; i++)
{
if (cursor >= 0)
{
buffer[cursor] = new Cell(text[i], style);
}

cursor++;
}
}

return cursor;
}

private static SegmentLine FromBuffer(Cell[] buffer, int length)
{
if (length <= 0)
{
return new SegmentLine();
}

var result = new SegmentLine();
var currentStyle = buffer[0].Style;
int start = 0;

for (int i = 1; i < length; i++)
{
if (!buffer[i].Style.Equals(currentStyle))
{
result.Add(new Segment(CreateStringFromBuffer(buffer, start, i - start), currentStyle));
currentStyle = buffer[i].Style;
start = i;
}
}

result.Add(new Segment(CreateStringFromBuffer(buffer, start, length - start), currentStyle));
return result;
}

private static string CreateStringFromBuffer(Cell[] buffer, int start, int count)
{
return string.Create(count, (buffer, start), static (span, state) =>
{
for (int i = 0; i < span.Length; i++)
{
span[i] = state.buffer[state.start + i].Char;
}
});
}

private record struct Cell(char Char, Style Style);

private record struct OverlayPosition(SegmentLine Line, int Left);
}
17 changes: 12 additions & 5 deletions src/RazorConsole.Core/Rendering/ConsoleRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.Extensions.Logging;
using RazorConsole.Core.Extensions;
using RazorConsole.Core.Renderables;
using RazorConsole.Core.Rendering.ComponentMarkup;
using RazorConsole.Core.Vdom;
using Spectre.Console.Rendering;
Expand Down Expand Up @@ -485,23 +486,29 @@ private RenderSnapshot CreateSnapshot()
return RenderSnapshot.Empty;
}

var vnode = CreateRenderableRoot(componentNode);
if (vnode is null)
var rootNode = CreateRenderableRoot(componentNode);
if (rootNode is null)
{
return RenderSnapshot.Empty;
}

_translationContext.CollectedOverlays.Clear();
_translationContext.AnimatedRenderables.Clear();
var renderable = _translationContext.Translate(vnode);
return new RenderSnapshot(vnode, renderable, _translationContext.AnimatedRenderables);

var mainRenderable = _translationContext.Translate(rootNode);

IRenderable finalRenderable = _translationContext.CollectedOverlays.Count > 0
? new OverlayRenderable(mainRenderable, _translationContext.CollectedOverlays)
: mainRenderable;

return new RenderSnapshot(rootNode, finalRenderable, _translationContext.AnimatedRenderables);
}
catch (Exception ex)
{
_logger.LogErrorCreatingRenderSnapshot(ex);
return RenderSnapshot.Empty;
}
}

private VNode? CreateRenderableRoot(VNode node)
{
var visitedComponents = new HashSet<int>();
Expand Down
14 changes: 14 additions & 0 deletions src/RazorConsole.Core/Rendering/OverlayItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) RazorConsole. All rights reserved.

using Spectre.Console.Rendering;

namespace RazorConsole.Core.Rendering;

public record OverlayItem(
IRenderable Renderable,
int? Top,
int? Left,
int? Right,
int? Bottom,
int ZIndex
);
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,25 @@ public sealed class TranslationContext
/// </remarks>
public HashSet<IAnimatedConsoleRenderable> AnimatedRenderables { get; } = [];

/// <summary>
/// Gets a collection of overlays that require special rendering in <see cref="ConsoleRenderer"/>.
/// </summary>
/// <remarks>
/// <para>
/// Middleware components can add <see cref="OverlayItem"/> to this collection during translation.
/// These items are collected and used by the rendering system to render these overlays.
/// </para>
/// <para>
/// The collection is cleared before each translation pass and populated as nodes are translated.
/// After translation completes, the collection contains all overlay items discovered during
/// the translation process.
/// </para>
/// </remarks>
public List<OverlayItem> CollectedOverlays { get; } = [];

public int CumulativeTop { get; set; }
public int CumulativeLeft { get; set; }

/// <summary>
/// Initializes a new instance of the <see cref="TranslationContext"/> class with the specified middleware components.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) RazorConsole. All rights reserved.

using RazorConsole.Core.Abstractions.Rendering;
using RazorConsole.Core.Rendering.Translation.Contexts;
using RazorConsole.Core.Rendering.Vdom;
using RazorConsole.Core.Vdom;
using Spectre.Console;
using Spectre.Console.Rendering;

namespace RazorConsole.Core.Rendering.Translation.Translators;

public class AbsolutePositionMiddleware : ITranslationMiddleware
{
public IRenderable Translate(TranslationContext context, TranslationDelegate next, VNode node)
{
var position = VdomSpectreTranslator.GetAttribute(node, "position");

if (!string.Equals(position, "absolute", StringComparison.OrdinalIgnoreCase))
{
return next(node);
}

var top = int.TryParse(VdomSpectreTranslator.GetAttribute(node, "top"), out int topVal)
Comment thread
TeseySTD marked this conversation as resolved.
? topVal
: (int?)null;
var left = int.TryParse(VdomSpectreTranslator.GetAttribute(node, "left"), out int leftVal)
? leftVal
: (int?)null;
var bottom = int.TryParse(VdomSpectreTranslator.GetAttribute(node, "bottom"), out int bottomVal)
? bottomVal
: (int?)null;
var right = int.TryParse(VdomSpectreTranslator.GetAttribute(node, "right"), out int rightVal)
? rightVal
: (int?)null;
var zIndex = VdomSpectreTranslator.TryGetIntAttribute(node, "z-index", 0);

int? finalTop = top.HasValue ? top.Value + context.CumulativeTop : null;
int? finalLeft = left.HasValue ? left.Value + context.CumulativeLeft : null;

int previousTop = context.CumulativeTop;
int previousLeft = context.CumulativeLeft;

context.CumulativeTop = finalTop ?? previousTop;
context.CumulativeLeft = finalLeft ?? previousLeft;

var renderable = next(node);

context.CumulativeTop = previousTop;
context.CumulativeLeft = previousLeft;

context.CollectedOverlays.Add(new OverlayItem(
renderable,
finalTop,
finalLeft,
right,
bottom,
zIndex
));

return new Markup(string.Empty);
}
}
2 changes: 2 additions & 0 deletions src/RazorConsole.Gallery/Components/NavBar.razor
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
new("scrollable", "Scrollable"),
new("textbutton", "Text Button"),
new("textinput", "Text Input"),
new("zindex", "Z-Index"),
new("cli-info", "CLI Info")
];

Expand Down Expand Up @@ -86,4 +87,5 @@

await InvokeAsync(StateHasChanged).ConfigureAwait(false);
}

}
Loading
Loading