// Rows of chips that fill the width and then wrap: the capture dock's chips,// a mood's emotions, a meeting's speakers, a choice's options.importSwiftUI/// Rows of chips that fill the width and then wrap.////// The one thing `HStack` cannot do, and the reason the chip strip needed a/// `Layout` of its own: a strip that scrolls instead puts a link on the/// capture where the writer cannot see it.////// The maths is stated rather than trusted: `rows(widths:limit:spacing:)` is a/// pure function over the widths and `DockShellTests` walks it, because a/// layout that can only be checked by looking at it is a layout nobody can/// safely change.publicstructChipWrap: Layout {/// The gap between chips, and between rows — `gap-2` is both.let spacing: CGFloatpublicinit(spacing: CGFloat) {self.spacing = spacing }/// Which chip starts which row, for a set of widths and a width to fill.////// A chip WIDER than the whole strip still takes a row of its own rather/// than being dropped: a chip nobody can see is the exact failure the wrap/// exists to prevent, and one that overhangs is at least visibly wrong.staticfunc rows(widths: [CGFloat], limit: CGFloat, spacing: CGFloat) -> [[Int]] {var rows: [[Int]] = []var row: [Int] = []var used: CGFloat = 0for (index, width) in widths.enumerated() {let advance = row.isEmpty ? width : width + spacingif !row.isEmpty, used + advance > limit { rows.append(row) row = [index] used = width } else { row.append(index) used += advance } }if !row.isEmpty { rows.append(row) }return rows }publicfunc sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {let limit = proposal.width ?? .infinitylet sizes = subviews.map { $0.sizeThatFits(.unspecified) }let laid = ChipWrap.rows(widths: sizes.map(\.width), limit: limit, spacing: spacing)var widest: CGFloat = 0var stacked: CGFloat = 0for row in laid {var used: CGFloat = 0var tallest: CGFloat = 0for index in row { used += sizes[index].width tallest = max(tallest, sizes[index].height) } used += spacing * CGFloat(row.count - 1) widest = max(widest, used) stacked += tallest } stacked += spacing * CGFloat(max(0, laid.count - 1))return CGSize(width: min(widest, limit), height: stacked) }publicfunc placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout () ) {let sizes = subviews.map { $0.sizeThatFits(.unspecified) }let laid = ChipWrap.rows( widths: sizes.map(\.width), limit: bounds.width, spacing: spacing )var y = bounds.minYfor row in laid {var x = bounds.minXlet rowHeight = row.map { sizes[$0].height }.max() ?? 0for index in row { subviews[index].place( at: CGPoint(x: x, y: y), anchor: .topLeading, proposal: ProposedViewSize(sizes[index]) ) x += sizes[index].width + spacing } y += rowHeight + spacing } }}