712 lines · 31.2 KB · SwiftRaw
// Cotton Chat's bubbles, as the core lays them: yours at the right in the// accent, theirs at the left on a neutral; a run from one sender with its// name over the first (in a group) and the tail and picture on the last;// the time and ticks small in the bubble's corner. Inside: the forwarded// mark, a reply's quote, photos and albums, a voice message's waveform, a// file, a link's card, the text; reactions under it. Day pills, the unread// divider and events stand centred between them.#if os(iOS)import SwiftUIimport UIKit/// What a tap inside a bubble asks of the thread.struct ChatBubbleTaps { var quote: (String) -> Void = { _ in } /// A picture or a video tapped, by its place among the bubble's parts (a grid's tiles may share an index). var media: (ChatBubble, Int) -> Void = { _, _ in } var link: (URL) -> Void = { _ in } var reaction: (ChatBubble, ChatReaction) -> Void = { _, _ in } var pinned: (String) -> Void = { _ in } var call: (ChatThreadCall) -> Void = { _ in } /// Join on a group's call going on (`chat.call { thread, join: true }`). var join: (ChatGroupCallLine) -> Void = { _ in } /// A file's chip: opened with the system (`chat.file`). var file: (ChatBubble, Int) -> Void = { _, _ in } /// A failed message of the person's own, tapped: try it again. var retry: (ChatBubble) -> Void = { _ in } /// A safety number's line, tapped: the safety number's screen. var safety: () -> Void = {} /// A voice message of theirs played a second here: `chat.act played`, its bubble answered. var voicePlayed: (String) -> Void = { _ in } /// A poll tapped: its Votes, who chose what. var poll: (ChatBubble) -> Void = { _ in } /// An option of a poll he can vote on, tapped (its place, 0 first): `chat.act vote`. var vote: (ChatBubble, Int) -> Void = { _, _ in }}/// A call's line in its thread: the core's words centred, missed in the/// danger ink, a tap calls back (`chat.call {call}`).struct ChatCallLine: View { let text: String let call: ChatThreadCall let tap: () -> Void @Environment(\.chatLook) private var look var body: some View { Button(action: tap) { HStack(spacing: 6) { Image(systemName: glyph).font(.system(size: 12 * look.scale, weight: .semibold)) Text(verbatim: text).font(look.font(13, .semibold)) Text(verbatim: call.time).font(look.font(12)).foregroundStyle(look.colours.pillText.opacity(0.7)) } .foregroundStyle(call.missed ? look.colours.danger : look.colours.pillText) .padding(.horizontal, 12) .padding(.vertical, 6) .background(Capsule().fill(look.colours.pill)) .frame(maxWidth: .infinity) } .buttonStyle(.plain) .accessibilityElement(children: .combine) .accessibilityHint(Text(verbatim: call.back)) .accessibilityIdentifier("chat-call-line") } private var glyph: String { if call.video { return "video.fill" } if call.missed { return "phone.down.fill" } return call.incoming ? "phone.arrow.down.left.fill" : "phone.arrow.up.right.fill" }}/// A group's call going on, on its line: the core's words centred, and Join beside them.struct ChatGroupCallJoinLine: View { let text: String let line: ChatGroupCallLine let join: () -> Void @Environment(\.chatLook) private var look var body: some View { ViewThatFits(in: .horizontal) { HStack(spacing: 10) { words; button } VStack(spacing: 8) { words; button } } .frame(maxWidth: .infinity) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-group-call-line") } private var words: some View { HStack(spacing: 6) { Image(systemName: line.video ? "video.fill" : "phone.fill").font(.system(size: 12 * look.scale, weight: .semibold)) .accessibilityHidden(true) Text(verbatim: text).font(look.font(13.5, .medium)).multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) } .foregroundStyle(look.colours.dim) } private var button: some View { Button(action: join) { Text(verbatim: line.join).font(look.font(14, .semibold)).foregroundStyle(look.colours.onAccent) .padding(.horizontal, 16).frame(minHeight: 36) .background(Capsule().fill(look.colours.accent)) .contentShape(Capsule()) } .buttonStyle(.plain) .accessibilityIdentifier("chat-group-call-join") }}/// One item of a thread, drawn.struct ChatItemView: View { let item: ChatThreadItem let group: Bool let flash: Bool let taps: ChatBubbleTaps @Environment(\.chatLook) private var look var body: some View { switch item { case .day(let label, _, _): ChatPill(text: label) .padding(.vertical, 8) .accessibilityAddTraits(.isHeader) case .unread(let label): Text(verbatim: label) .font(look.font(13, .semibold)) .foregroundStyle(look.colours.pillText) .frame(maxWidth: .infinity) .padding(.vertical, 6) .background(look.colours.pill) .padding(.vertical, 8) .accessibilityIdentifier("chat-unread-divider") case .event(_, let text, let call, let opens, let groupCall): if let groupCall { ChatGroupCallJoinLine(text: text, line: groupCall) { taps.join(groupCall) } .padding(.vertical, 6) } else if let call { ChatCallLine(text: text, call: call) { taps.call(call) } .padding(.vertical, 6) } else if opens == "safety" { Button(action: taps.safety) { ChatPill(text: text) } .buttonStyle(.plain) .accessibilityIdentifier("chat-safety-line") .padding(.vertical, 6) } else { ChatPill(text: text) .padding(.vertical, 6) } case .bubble(let bubble): ChatBubbleRow(bubble: bubble, group: group, flash: flash, taps: taps) } }}struct ChatPill: View { let text: String @Environment(\.chatLook) private var look var body: some View { Text(verbatim: text) .font(look.font(12.5, .semibold)) .foregroundStyle(look.colours.pillText) .multilineTextAlignment(.center) .padding(.horizontal, 10) .padding(.vertical, 4) .background(Capsule().fill(look.colours.pill)) .frame(maxWidth: .infinity) .padding(.horizontal, 40) }}/// A bubble in its row: its side, the picture column in a group, the name/// over the head of a run, the reactions under it.struct ChatBubbleRow: View { let bubble: ChatBubble let group: Bool var flash = false let taps: ChatBubbleTaps @Environment(\.chatLook) private var look @Environment(\.layoutDirection) private var direction private static let pictureSide: CGFloat = 30 var body: some View { HStack(alignment: .bottom, spacing: 6) { if bubble.mine { Spacer(minLength: 56) } if group && !bubble.mine { Group { if bubble.tail, let sender = bubble.sender { ChatAvatarView(avatar: sender.picture, side: Self.pictureSide) } else { Color.clear.frame(width: Self.pictureSide, height: 1) } } .padding(.bottom, bubble.reactions.isEmpty ? 0 : 20) } VStack(alignment: bubble.mine ? .trailing : .leading, spacing: 0) { ChatBubbleBody(bubble: bubble, group: group, taps: taps) .overlay { if flash { ChatBubbleShape(mine: bubble.mine, tail: bubble.tail, rtl: direction == .rightToLeft) .fill(look.colours.accent.opacity(0.25)) .allowsHitTesting(false) } } if !bubble.reactions.isEmpty { ChatReactionsView(bubble: bubble, taps: taps) .padding(.top, -6) .padding(.horizontal, 8) } } if !bubble.mine { Spacer(minLength: 56) } } .padding(.horizontal, 8) .padding(.top, bubble.head ? 6 : 1.5) .padding(.bottom, bubble.tail ? 2 : 0) .accessibilityElement(children: .combine) .accessibilityIdentifier("chat-bubble-\(bubble.message)") }}/// The bubble itself: its shape, ground and everything inside.struct ChatBubbleBody: View { let bubble: ChatBubble let group: Bool let taps: ChatBubbleTaps @Environment(\.chatLook) private var look @Environment(\.layoutDirection) private var direction private var ink: Color { bubble.mine ? look.colours.bubbleOutText : look.colours.bubbleInText } private var dim: Color { bubble.mine ? look.colours.bubbleOutDim : look.colours.bubbleInDim } private var ground: Color { bubble.mine ? look.colours.bubbleOut : look.colours.bubbleIn } private var mediaOnly: Bool { (bubble.kind == .photo || bubble.kind == .album || bubble.kind == .video) && (bubble.text ?? "").isEmpty && bubble.reply == nil && bubble.forwarded == nil } var body: some View { VStack(alignment: .leading, spacing: 4) { if group, bubble.face, !bubble.mine, let sender = bubble.sender { Text(verbatim: sender.name) .font(look.font(13.5, .semibold)) .foregroundStyle(look.colours.name(sender.tint)) .lineLimit(1) .padding(.horizontal, 12) .padding(.top, 7) .padding(.bottom, mediaOnly ? 4 : -2) } if let forwarded = bubble.forwarded { Label { Text(verbatim: forwarded) } icon: { Image(systemName: "arrowshape.turn.up.right.fill") } .font(look.font(12.5, .regular, italic: true)) .foregroundStyle(dim) .padding(.horizontal, 12) .padding(.top, 7) .padding(.bottom, -2) } if let quote = bubble.reply { ChatQuoteView(quote: quote, mine: bubble.mine) .onTapGesture { if let id = quote.message { taps.quote(id) } } .padding(.horizontal, 6) .padding(.top, 6) } content } .frame(minWidth: 64, alignment: .leading) .background(ChatBubbleShape(mine: bubble.mine, tail: bubble.tail, rtl: direction == .rightToLeft).fill(ground)) .clipShape(ChatBubbleShape(mine: bubble.mine, tail: bubble.tail, rtl: direction == .rightToLeft)) .contentShape(ChatBubbleShape(mine: bubble.mine, tail: bubble.tail, rtl: direction == .rightToLeft)) } @ViewBuilder private var content: some View { switch bubble.kind { case .photo, .video, .album: ChatAlbumView(bubble: bubble, taps: taps) .overlay(alignment: .bottomTrailing) { if (bubble.text ?? "").isEmpty { meta(onPicture: true).padding(8) } } if let text = bubble.text, !text.isEmpty { textWithMeta(text).padding(.top, 2) } case .voice, .audio: ChatVoiceView(bubble: bubble, ink: ink, dim: dim) .padding(.horizontal, 10) .padding(.top, 8) HStack { Spacer(); meta(onPicture: false) } .padding(.horizontal, 10) .padding(.bottom, 6) case .file: ChatFileView(bubble: bubble, ink: ink, dim: dim) .contentShape(Rectangle()) .onTapGesture { taps.file(bubble, bubble.media.first?.index ?? 0) } .accessibilityAddTraits(.isButton) .padding(.horizontal, 10) .padding(.top, 8) HStack { Spacer(); meta(onPicture: false) } .padding(.horizontal, 10) .padding(.bottom, 6) case .poll where bubble.poll != nil: if let poll = bubble.poll { ChatPollView(poll: poll, message: bubble.message, mine: bubble.mine, vote: poll.votable == true ? { taps.vote(bubble, $0) } : nil) { taps.poll(bubble) } .padding(.horizontal, 12) .padding(.top, 8) HStack { Spacer(); meta(onPicture: false) } .padding(.horizontal, 10) .padding(.bottom, 6) } case .deleted: HStack(spacing: 6) { Image(systemName: "nosign") textWithMeta(bubble.text ?? "", italic: true) } .foregroundStyle(dim) .padding(.leading, 12) default: if let link = bubble.link { ChatLinkView(link: link, mine: bubble.mine) .onTapGesture { if let url = URL(string: link.url) { taps.link(url) } } .padding(.horizontal, 6) .padding(.top, 6) } textWithMeta(bubble.text ?? "") } } /// The text with room left on its last line for the time and ticks, /// which stand in the bubble's corner. private func textWithMeta(_ text: String, italic: Bool = false) -> some View { ZStack(alignment: .bottomTrailing) { Text(ChatText.withRoom(ChatText.attributed(text), chars: metaWidthChars, font: look.font(11.5))) .font(look.font(16.5, .regular, italic: italic)) .foregroundStyle(ink) .fixedSize(horizontal: false, vertical: true) .tint(bubble.mine ? look.colours.bubbleOutText : look.colours.link) .environment(\.openURL, OpenURLAction { url in taps.link(url) return .handled }) meta(onPicture: false) } .padding(.horizontal, 12) .padding(.top, 7) .padding(.bottom, 6) } private var metaWidthChars: Int { bubble.time.count + (bubble.edited.map { $0.count + 1 } ?? 0) + (bubble.tick == nil ? 0 : 3) + (bubble.pinned ? 2 : 0) + 1 } private func meta(onPicture: Bool) -> some View { HStack(spacing: 3) { if bubble.pinned { Image(systemName: "pin.fill").font(.system(size: 9 * look.scale)).rotationEffect(.degrees(45)) } if let edited = bubble.edited { Text(verbatim: edited) } Text(verbatim: bubble.time).monospacedDigit() if let tick = bubble.tick { ChatTickView(tick: tick, ink: onPicture ? look.colours.bubbleOutText : (bubble.mine ? look.colours.tick : dim), readInk: onPicture ? look.colours.bubbleOutText : (bubble.mine ? look.colours.tickRead : look.colours.accent), size: 11) } } .font(look.font(11.5)) .foregroundStyle(onPicture ? look.colours.bubbleOutText : dim) .padding(.horizontal, onPicture ? 7 : 0) .padding(.vertical, onPicture ? 2 : 0) .background { if onPicture { Capsule().fill(look.colours.scrim) } } .offset(y: onPicture ? 0 : 1) }}/// The bubble's outline: rounded, with a small tail at the bottom on the/// sender's side when it is the last of its run.struct ChatBubbleShape: Shape { let mine: Bool let tail: Bool var rtl = false func path(in rect: CGRect) -> Path { let r: CGFloat = 18 let small: CGFloat = tail ? 5 : 18 let right = mine != rtl var p = Path() let tl = right ? r : (tail ? r : r) let tr = r let br = right ? small : r let bl = right ? r : small p.move(to: CGPoint(x: rect.minX + tl, y: rect.minY)) p.addLine(to: CGPoint(x: rect.maxX - tr, y: rect.minY)) p.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.minY), tangent2End: CGPoint(x: rect.maxX, y: rect.minY + tr), radius: tr) p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - br)) p.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.maxY), tangent2End: CGPoint(x: rect.maxX - br, y: rect.maxY), radius: br) p.addLine(to: CGPoint(x: rect.minX + bl, y: rect.maxY)) p.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.maxY), tangent2End: CGPoint(x: rect.minX, y: rect.maxY - bl), radius: bl) p.addLine(to: CGPoint(x: rect.minX, y: rect.minY + tl)) p.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.minY), tangent2End: CGPoint(x: rect.minX + tl, y: rect.minY), radius: tl) p.closeSubpath() if tail { // The tail: a small curl out of the bottom corner. var t = Path() if right { t.move(to: CGPoint(x: rect.maxX - 8, y: rect.maxY)) t.addQuadCurve(to: CGPoint(x: rect.maxX + 5, y: rect.maxY), control: CGPoint(x: rect.maxX - 1, y: rect.maxY)) t.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY - 12), control: CGPoint(x: rect.maxX, y: rect.maxY - 4)) } else { t.move(to: CGPoint(x: rect.minX + 8, y: rect.maxY)) t.addQuadCurve(to: CGPoint(x: rect.minX - 5, y: rect.maxY), control: CGPoint(x: rect.minX + 1, y: rect.maxY)) t.addQuadCurve(to: CGPoint(x: rect.minX, y: rect.maxY - 12), control: CGPoint(x: rect.minX, y: rect.maxY - 4)) } t.closeSubpath() p.addPath(t) } return p }}/// A reply's quote: a bar in the accent, who wrote it, the line.struct ChatQuoteView: View { let quote: ChatQuote let mine: Bool @Environment(\.chatLook) private var look var body: some View { let bar = mine ? look.colours.bubbleOutText : look.colours.quoteBar HStack(spacing: 8) { RoundedRectangle(cornerRadius: 1.5).fill(bar).frame(width: 3) VStack(alignment: .leading, spacing: 1) { Text(verbatim: quote.sender) .font(look.font(13.5, .semibold)) .foregroundStyle(bar) .lineLimit(1) HStack(spacing: 4) { if let mark = quote.mark { Image(systemName: ChatMarks.symbol(mark)) } Text(verbatim: quote.line).lineLimit(1) } .font(look.font(13.5)) .foregroundStyle(mine ? look.colours.bubbleOutDim : look.colours.bubbleInDim) } Spacer(minLength: 0) } .padding(.vertical, 5) .padding(.horizontal, 6) .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(bar.opacity(0.12))) .accessibilityElement(children: .combine) }}/// The reactions under a bubble, each a small capsule; yours outlined.struct ChatReactionsView: View { let bubble: ChatBubble let taps: ChatBubbleTaps @Environment(\.chatLook) private var look var body: some View { HStack(spacing: 4) { ForEach(bubble.reactions, id: \.emoji) { reaction in Button { taps.reaction(bubble, reaction) } label: { HStack(spacing: 3) { Text(verbatim: reaction.emoji).font(.system(size: 14 * look.scale)) if reaction.count > 1 { Text(verbatim: String(reaction.count)) .font(look.font(12, .semibold)) .foregroundStyle(look.colours.reactionText) } } .padding(.horizontal, 7) .padding(.vertical, 3) .background(Capsule().fill(look.colours.reaction)) .overlay(Capsule().strokeBorder(reaction.mine ? look.colours.accent : look.colours.rule, lineWidth: 1.2)) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: "\(reaction.emoji) \(reaction.count)")) } } }}/// Photos: one at its own shape, an album as a grid of up to four.struct ChatAlbumView: View { let bubble: ChatBubble let taps: ChatBubbleTaps static let width: CGFloat = 248 var body: some View { let parts = bubble.media if parts.count <= 1, let part = parts.first { let ratio = CGFloat((part.height ?? 3) / max(1, part.width ?? 4)) ChatPhotoTile(bubble: bubble, part: part) .frame(width: Self.width, height: min(330, max(150, Self.width * ratio))) .onTapGesture { taps.media(bubble, 0) } } else { let shown = Array(parts.prefix(4)) let side = (Self.width - 2) / 2 LazyVGrid(columns: [GridItem(.fixed(side), spacing: 2), GridItem(.fixed(side), spacing: 2)], spacing: 2) { ForEach(Array(shown.enumerated()), id: \.offset) { i, part in // The fourth tile carries the count of the rest, drawn by the tile so it never sits over the tile's own words. ChatPhotoTile(bubble: bubble, part: part, more: i == 3 ? max(0, parts.count - 4) : 0) .frame(width: side, height: side) .onTapGesture { taps.media(bubble, i) } } } .frame(width: Self.width) } }}private struct ChatMoreCover: View { let count: Int @Environment(\.chatLook) private var look var body: some View { ZStack { look.colours.scrim Text(verbatim: "+\(count)").font(look.font(24, .semibold)).foregroundStyle(look.colours.bubbleOutText) } }}/// One picture: its tiny preview (carried in the message) blurred on the/// first frame at the picture's true size, then the picture decoded off the/// main thread at its drawn size and faded in; one already decoded this/// sitting is drawn at once. One that cannot be had says so quietly/// (`ChatPictureTries`), never an empty box.struct ChatPhotoTile: View { let bubble: ChatBubble let part: ChatMediaPart /// The pictures past the album's fourth, counted over this tile ("+2"); 0 for none. var more: Int = 0 @Environment(\.chatBook) private var book @Environment(\.chatLook) private var look @State private var image: UIImage? /// Keyed by the message the part opens through: a grid to WhatsApp names each tile's own (FEEDBACK-4 B3). private var message: String { part.opens(in: bubble) } private var key: String { ChatPictureTries.key(message, part.index) } /// The picture as drawn: this tile's, or one decoded this sitting (a cell drawn again, the chat opened again). private var shown: UIImage? { image ?? ChatPictures.drawn(key, side: ChatAlbumView.width) } /// The core's word first (the store said it does not hold the file); the phone's own tries for what the core cannot know. private var gone: Bool { shown == nil && (part.gone == true || ChatPictureTries.shared.gone.contains(key)) } var body: some View { let shown = shown ZStack { look.colours.pill if let preview = part.preview.flatMap(ChatPreviewImages.image), shown == nil || image != nil { Image(uiImage: preview).resizable().scaledToFill().blur(radius: 12) } if let shown { Image(uiImage: shown).resizable().scaledToFill().transition(.opacity) } if more > 0 { // The count of the rest stands alone: over the picture, or over the tile's ground with no other words. ChatMoreCover(count: more) } else if gone { ChatPictureGone(words: part.kind == .video ? nil : ChatWords.line("thread.picture_gone")) } else if part.kind == .video { Image(systemName: "play.circle.fill") .font(.system(size: 44)) .foregroundStyle(look.colours.bubbleOutText) .shadow(color: .black.opacity(0.3), radius: 6) } } .clipped() .contentShape(Rectangle()) .accessibilityLabel(Text(verbatim: gone ? ChatWords.line("thread.picture_gone") : part.name ?? "")) .task(id: "\(key)|\(part.gone == true)") { // Drawn already: nothing to ask. The core already knows it is not there: nothing is asked until it says // otherwise. One on its way (the person's own, still going up, opens from the phone's own file) is asked until it comes. guard self.shown == nil, part.gone != true, let book, let url = await ChatPictureTries.shared.file(message: message, index: part.index, book: book) else { return } let loaded = await ChatPictures.shared.image(url, side: ChatAlbumView.width) if let loaded { ChatPictures.remember(key, side: ChatAlbumView.width, loaded) withAnimation(.easeOut(duration: 0.18)) { image = loaded } } else if part.kind != .video { // A video's file is not a picture: its tile keeps the play mark, never "not available". ChatPictureTries.shared.unopened(message: message, index: part.index) } } }}/// A picture that cannot be had: a quiet mark and, where there is room, its words.struct ChatPictureGone: View { let words: String? @Environment(\.chatLook) private var look var body: some View { VStack(spacing: 6) { Image(systemName: "photo").font(.system(size: 22 * min(look.scale, 1.3), weight: .regular)) if let words { Text(verbatim: words).font(look.font(13)).multilineTextAlignment(.center).lineLimit(2) } } .foregroundStyle(look.colours.dim) .padding(10) .accessibilityHidden(true) }}/// A file: its kind's mark, name and size.struct ChatFileView: View { let bubble: ChatBubble let ink: Color let dim: Color @Environment(\.chatLook) private var look var body: some View { let part = bubble.media.first HStack(spacing: 10) { Image(systemName: "doc.text.fill") .font(.system(size: 20)) .foregroundStyle(bubble.mine ? look.colours.bubbleOut : look.colours.onAccent) .frame(width: 42, height: 42) .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(bubble.mine ? look.colours.bubbleOutText : look.colours.accent)) VStack(alignment: .leading, spacing: 2) { Text(verbatim: part?.name ?? "").font(look.font(15, .semibold)).foregroundStyle(ink).lineLimit(2) Text(verbatim: part?.size ?? "").font(look.font(12.5)).foregroundStyle(dim) } } .frame(minWidth: 200, alignment: .leading) }}/// A link unfolded: its picture, site, title and description.struct ChatLinkView: View { let link: ChatLinkCard let mine: Bool @Environment(\.chatLook) private var look @Environment(\.chatBook) private var book @State private var image: UIImage? var body: some View { let bar = mine ? look.colours.bubbleOutText : look.colours.accent HStack(spacing: 8) { RoundedRectangle(cornerRadius: 1.5).fill(bar).frame(width: 3) VStack(alignment: .leading, spacing: 3) { if let image { Image(uiImage: image).resizable().scaledToFill() .frame(height: 120).frame(maxWidth: .infinity).clipped() .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) .accessibilityIdentifier("link-picture") } else if let thumb = link.thumb, ChatLinkThumb.image(thumb) == nil, book?.photosByKey ?? false { RecordPicture(avatarKey: thumb, edge: 260) .frame(height: 120).frame(maxWidth: .infinity).clipped() .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) } if let site = link.site { Text(verbatim: site).font(look.font(12.5, .semibold)).foregroundStyle(bar).lineLimit(1) } if let title = link.title { Text(verbatim: title).font(look.font(14.5, .semibold)) .foregroundStyle(mine ? look.colours.bubbleOutText : look.colours.bubbleInText).lineLimit(2) } if let description = link.description { Text(verbatim: description).font(look.font(13.5)) .foregroundStyle(mine ? look.colours.bubbleOutDim : look.colours.bubbleInDim).lineLimit(3) } } } .padding(.vertical, 4) .padding(.horizontal, 6) .frame(maxWidth: 260, alignment: .leading) .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(bar.opacity(0.10))) .task(id: link.thumb) { // The sender's phone made it: a small JPEG carried in the message (CONTRACT.md "Link previews"). if let made = ChatLinkThumb.image(link.thumb) { image = made return } guard let thumb = link.thumb, let book, !book.photosByKey, let url = await book.picture(media: thumb, message: nil, index: nil) else { return } image = await ChatPictures.shared.image(url, side: 260) } }}/// Text as a bubble writes it: links found and underlined, kept per string.@MainActorenum ChatText { private static var cache: [String: AttributedString] = [:] private static let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) static func attributed(_ text: String) -> AttributedString { if let hit = cache[text] { return hit } var out = AttributedString(text) if let detector, text.contains(".") { let ns = text as NSString for match in detector.matches(in: text, range: NSRange(location: 0, length: ns.length)) { guard let url = match.url, let range = Range(match.range, in: text), let lower = AttributedString.Index(range.lowerBound, within: out), let upper = AttributedString.Index(range.upperBound, within: out) else { continue } out[lower..<upper].link = url out[lower..<upper].underlineStyle = .single } } if cache.count > 4000 { cache.removeAll(keepingCapacity: true) } cache[text] = out return out } /// The text with room left after it for the time's small type. static func withRoom(_ text: AttributedString, chars: Int, font: Font) -> AttributedString { var room = AttributedString(room(for: chars)) room.font = font room.foregroundColor = Color.clear return text + room } /// Room at the end of the last line for `chars` characters of the /// time's small type (figure spaces, which never break). static func room(for chars: Int) -> String { "\u{2004}" + String(repeating: "\u{2007}", count: max(0, chars)) }}#endif