// A note as wide as its words: the layout every chat note is drawn with — a // message thread's and a conversation page's (`ConversationPage`). Moved out // of the message thread's screen so the page style can use it. import SwiftUI /// A note as wide as its words and no wider, up to the lane it is offered. /// /// A `Layout`, because a paper is greedy — it takes the width it is proposed — /// and a short reply drawn full width is a slab, which is the one shape a /// conversation must not be. Its first subview is the words themselves, hidden: /// asked for their width inside the lane they answer their LONGEST WRAPPED LINE, /// which a paper can never say. That, plus the paper's margins, is the note's /// width — so a two-line note is as wide as its longer line, not the lane. public struct HuggingWidth: Layout { let inset: CGFloat public init(inset: CGFloat) { self.inset = inset } public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { // Exactly two subviews: the words, then the note. guard subviews.dropFirst().count == 1 else { return .zero } let width = width(for: proposal, words: subviews[0]) return subviews[1].sizeThatFits(ProposedViewSize(width: width, height: nil)) } public func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout () ) { guard subviews.dropFirst().count == 1 else { return } let lane = max(0, bounds.width - (inset + inset)) subviews[0].place( at: CGPoint(x: bounds.minX + inset, y: bounds.minY + inset), anchor: .topLeading, proposal: ProposedViewSize(width: lane, height: nil) ) subviews[1].place( at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(width: bounds.width, height: bounds.height) ) } private func width(for proposal: ProposedViewSize, words: LayoutSubview) -> CGFloat { let margins = inset + inset + 1 guard let offered = proposal.width else { return ceil(words.sizeThatFits(.unspecified).width) + margins } let lane = max(0, offered - margins) let wrapped = ceil(words.sizeThatFits(ProposedViewSize(width: lane, height: nil)).width) return min(wrapped + margins, offered) } }