Skip to content

Commit

Permalink
HStack 2
Browse files Browse the repository at this point in the history
  • Loading branch information
danielctull committed Dec 24, 2024
1 parent d969cf6 commit f715337
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 47 deletions.
68 changes: 68 additions & 0 deletions Sources/TerminalUI/Layouts/HStack.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

struct HStack {
private let children: [any View]
@Mutable private var sizes: [Size] = []
}

extension HStack: Builtin, View {

func size(
for proposal: ProposedSize,
environment: EnvironmentValues
) -> Size {

let flexibility = children.map { child in
let min = ProposedSize(width: 0, height: proposal.height)
let max = ProposedSize(width: .max, height: proposal.height)
let smallest = child._size(for: min)
let largest = child._size(for: max)
return largest.width - smallest.width
}

var indices = children.indices
.sorted { flexibility[$0] < flexibility[$1] }

sizes = Array(repeating: .zero, count: children.count)
var remaining = proposal.width

while !indices.isEmpty {

let proposal = ProposedSize(
width: remaining / indices.count,
height: proposal.height)

let index = indices.removeFirst()

let child = children[index]
let size = child._size(for: proposal, environment: environment)
sizes[index] = size
remaining -= size.width
if remaining < 0 { remaining = 0 }
}

let width = sizes.map(\.width).reduce(0, +)
let height = sizes.map(\.height).reduce(0, +)
return Size(width: width, height: height)
}

func render(
in canvas: any Canvas,
size: Size,
environment: EnvironmentValues
) {
var x: Horizontal = 0
for (child, childSize) in zip(children, sizes) {
let canvas = canvas.translateBy(x: x, y: 0)
child._render(in: canvas, size: childSize, environment: environment)
x += childSize.width
}
}
}

extension Horizontal {
fileprivate static var max: Self { Self(Int.max) }
}

extension Size {
fileprivate static var zero: Size { Size(width: 0, height: 0) }
}
6 changes: 6 additions & 0 deletions Sources/TerminalUI/Primitives/Dimensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ extension Horizontal {
}
}

extension Horizontal {
static func / (lhs: Horizontal, rhs: Int) -> Horizontal {
Horizontal(lhs.value / rhs)
}
}

// MARK: - Vertical

/// A measurement of the vertical dimension.
Expand Down
47 changes: 0 additions & 47 deletions Sources/TerminalUI/Views/HStack.swift

This file was deleted.

0 comments on commit f715337

Please sign in to comment.