Files
Evgeny @ SimpleX Chat ed9e9fe95d mcp, ui: sessions open in the Flat layout, with the avatar on the name line (#8169)
* plan: mcp-flat-sessions

* plan: mcp-flat-sessions, the user's answers

* plan: mcp-flat-sessions, image widths and times per platform

* plan: mcp-flat-sessions, one flat media width and smaller avatars

* plan: mcp-flat-sessions, list breaks

* plan: mcp-flat-sessions, visible avatar gaps and the gap below the sender row

* plan: mcp-flat-sessions, equal gaps around the name

* plan: mcp-flat-sessions, restore the approved gaps

* mcp: open the groups of new sessions in the Flat layout

* ui: avatar on the name line and full-width messages in the flat layout

* ui: record the snapshot references of the flat layout

* ui: flat media beside the go-to button, text below tall name lines

* mcp: source of the session image, Main group check in the e2e test

* plan: mcp-flat-sessions, as implemented

* plans: flat sessions, the tests run on master

* android, desktop: keep the width limit of the media box in intrinsic measurement

* android, desktop: test the intrinsic height of media at an unbounded width

* ui: flat name rows close to their messages, cards at the text edge

* desktop: flat group snapshot references, the media scene

* plans: flat sessions, avatars and flat-layout defects

* desktop: avatar snapshot scenes with photos and placeholders

* ios: flat snapshot references, the deleted items scene

* desktop: avatar snapshot scenes of share, contact and user lists, calls, channel members

* android, desktop: avatars without inner padding, each in its former box

* ios: snapshot scenes of hidden integrity errors in Flat rows and bubbles

* desktop: avatar snapshot references, recorded before the inset removal

* android, desktop: snapshot scenes of hidden integrity errors in Flat rows and bubbles

* ios: hidden integrity errors take no space in the chat

* plans: flat sessions, the user's answers, avatar call sites as implemented, hidden rows

* ios: scenes of the time before deleted items, unread users, appearance

* ios: avatars in Flat rows pass the letters' edge by 2 pt

* ios: 6 pt from the avatar to the message below it in Flat rows

* ios: time on the last line of messages ending with empty lines in Flat

* ios: code cards as wide as the code, the time beside them, in Flat rows

* ios: delivery status only with the time in Flat rows

* ios: time shown on a message before a deleted or hidden item

* ios: no gap below a reactions row between one sender's messages in Flat

* ios: no early wrap of the last word before the time in Flat rows

* ios: name the condition that shows the time before deleted items

* ios: spec links to the moved lines of TerminalItemView

* ios: test of the delivery status without the time in Flat rows

* desktop: snapshot references after the inset removal, hidden integrity error scenes

* android, desktop: blur of blocked members' photos as on iOS

* ios: user picker scene with the chat running, as in the app

* android, desktop: snapshot scenes of the Flat defects and the chat banner

* ios: status without the time only for partial delivery and errors

* ios: snapshot references of the Flat avatar overshoot, gap and defect fixes

* ios: snapshot references without the empty line after a hidden time

* android, desktop: hidden integrity errors take no space; the time before deleted and hidden items

* android, desktop: chat banner 20 dp above its avatar and 10 dp below

* android, desktop: Flat avatars 2 dp past the letters, 6 dp above the text, four layout defects

* android, desktop: share list shows each chat's own avatar

* android, desktop: business, bot and agent placeholders as on iOS

* plans: flat sessions, the decisions as implemented on Android and desktop

* ios: scene of a hidden item between two messages of one sender

* ios: sender name 12 pt after the visible avatar in Flat rows

* ios: rows around hidden items grouped as if the hidden items were absent

* ios: full time in a deleted message bubble

* android, desktop: rows skip hidden items as neighbours; the time before deleted items in Flat rows only

* android, desktop: Flat sender names 12 dp after the avatar

* android, desktop: avatar placeholders from their own assets; unused icons removed

* plans: flat sessions, questions numbered as answered, neighbours of hidden rows, overshoot note

* ios: snapshot references of rows around hidden items and the name start

* android, desktop: hidden rows keep one date separator; marked deleted errors shown; rows rebuilt on the developer setting

* desktop: snapshot references of the Flat decisions, defects, banner and rows around hidden items

* spec, plans: Flat row layout, hidden rows and their neighbours, status with the time; avatar assets as implemented

* android, desktop: new, unread and read statuses only with the time in Flat rows, as on iOS

* desktop: snapshot references of the Flat defects scene with an unread message; plans: partial delivery wording

* mcp: session image with the Flat row geometry: avatar 2 pt past the letters, text 6 pt below it

* mcp: session image with a shorter answer, so the first row shows in full

* ios: user picker snapshot scenes at the height of the sheet

* plans: flat sessions, an avatar column with tighter paddings

* ios: snapshot references of the user picker at the height of the sheet

* plans: flat sessions, the avatar column with only the gap open

* ui: Flat avatar column, the avatar 2 into the padding, text 10 after it

Names, items, later rows of one sender, events and deleted cards sit in the message column; media widths are measured from it. Chats without avatars keep 12 on both sides. The session scene on both platforms; the README image redrawn with the column.

* ui: snapshot references of the Flat avatar column and the session scene

* ui: Flat cards and pills take their corners from the roundness setting

Deleted, marked deleted, moderated, blocked, error and decryption error cards and group invitations: 18 × roundness without a tail, as media, on iOS and Android/desktop. A scene of each platform at roundness 0.3.

* ui: Flat pill text on the text start, sender rows at master's pitch

Deleted, marked deleted, moderated, blocked and error pills start at the message column, so their text lines up with the messages, as on master; in chats without avatars they keep 12 from the screen edge. The name line of a sender row starts at the row gap, as on master; the avatar is centred on it and reaches into the gap above, on both platforms.

* android, desktop: avatars in a box drawn at exactly 5/6 of it, as master's padded placeholders

centeredIn scales its child to 5/6 of the box and centres it with fractional placement, so placeholder edges match master at the pixel at every font scale. Photos and the incognito icon take the same size, up to 1 px larger than master's rounded photo padding. The chat-link thumbnail of the chat list uses the same box, 44 sp.

* android, desktop: avatars in a box at whole pixels, photos fill the drawn box

centeredIn places its child at box/12 rounded down and sizes it to the box less twice that, so placeholders keep master's first and last ink pixel and stay sharp. Photos take their rounded square from the drawn box in pixels.

* ui: photo corners from the nominal size; iOS references of pills, corners and sender rows

The rounded square of a photo keeps its corner radius from the size argument. iOS references for the pill alignment, the corner radius from the roundness setting with a 0.3 scene, and sender rows at master's pitch.

* android, desktop: snapshot references of pills, corners, sender rows and avatars at whole pixels
2026-11-14 22:58:41 +00:00

1159 lines
48 KiB
Swift

//
// MsgContentView.swift
// SimpleX
//
// Created by Evgeny on 13/03/2022.
// Copyright © 2022 SimpleX Chat. All rights reserved.
//
// Spec: spec/client/chat-view.md
import SwiftUI
import SimpleXChat
let uiLinkColor = UIColor(red: 0, green: 0.533, blue: 1, alpha: 1)
private func typing(_ theme: AppTheme, _ descr: UIFontDescriptor, _ ws: [UIFont.Weight]) -> NSMutableAttributedString {
let res = NSMutableAttributedString()
for w in ws {
res.append(NSAttributedString(string: ".", attributes: [
.font: UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: w),
.kern: -2 as NSNumber,
.foregroundColor: UIColor(theme.colors.secondary)
]))
}
return res
}
// Spec: spec/client/chat-view.md#MsgContentView
struct MsgContentView: View {
@ObservedObject var chat: Chat
@Environment(\.showTimestamp) var showTimestamp: Bool
@Environment(\.containerBackground) var containerBackground: UIColor
@Environment(\.terminalLayout) private var terminal
@EnvironmentObject var theme: AppTheme
var text: String
var formattedText: [FormattedText]? = nil
var markdownBlocks: [MarkdownBlock]? = nil
var textStyle: UIFont.TextStyle
var sender: String? = nil
var meta: CIMeta? = nil
var mentions: [String: CIMention]? = nil
var userMemberId: String? = nil
var rightToLeft = false
var prefix: NSAttributedString? = nil
var stripLink: String? = nil
var blockLayout = false
var cardColor: Color? = nil
var encrypted: Bool? = nil
var signedFileVerified: Bool? = nil
var textColor: Color? = nil
var ruleMinWidth: CGFloat = 0
@State private var showSecrets: Set<Int> = []
@State private var typingIdx = 0
@State private var timer: Timer?
@State private var typingIndicators: [NSAttributedString] = []
@State private var noTyping = NSAttributedString(string: " ")
@State private var phase: CGFloat = 0
@AppStorage(DEFAULT_SHOW_SENT_VIA_RPOXY) private var showSentViaProxy = false
@AppStorage(DEFAULT_PRIVACY_SHOW_SIGNATURE) private var showSignature = true
@AppStorage(DEFAULT_PRIVACY_SHOW_FILE_ENCRYPTION) private var showFileEncryption = true
var body: some View {
let v = contentView()
if meta?.isLive == true {
v.onAppear {
let descr = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
noTyping = NSAttributedString(string: " ", attributes: [
.font: UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: .regular),
.kern: -2 as NSNumber,
.foregroundColor: UIColor(theme.colors.secondary)
])
switchTyping()
}
.onDisappear(perform: stopTyping)
.onChange(of: meta?.isLive, perform: switchTyping)
.onChange(of: meta?.recent, perform: switchTyping)
} else {
v
}
}
private func switchTyping(_: Bool? = nil) {
if let meta = meta, meta.isLive && meta.recent {
if typingIndicators.isEmpty {
let descr = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
typingIndicators = [
typing(theme, descr, [.black, .light, .light]),
typing(theme, descr, [.bold, .black, .light]),
typing(theme, descr, [.light, .bold, .black]),
typing(theme, descr, [.light, .light, .bold])
]
}
timer = timer ?? Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
typingIdx = typingIdx + 1
}
} else {
stopTyping()
}
}
private func stopTyping() {
timer?.invalidate()
timer = nil
typingIdx = 0
}
@ViewBuilder
private func contentView() -> some View {
let fts = if let stripLink { stripFormattedTextLink(formattedText, stripLink) } else { formattedText }
if blockLayout, let fts, !fts.isEmpty, let blocks = markdownBlocks, prefix == nil || !blockTextRanges(blocks).isEmpty {
MarkdownBlocksView(
formattedText: fts,
blocks: blocks,
text: text,
textStyle: textStyle,
cardColor: cardColor ?? theme.appColors.receivedQuote,
rightToLeft: rightToLeft,
blockText: { index, range, font, secretStart, last, textAlpha in blockTextView(fts, blocks, index, range, font, secretStart, last, textAlpha) },
metaLine: { metaLineView() },
marksLastBlock: terminal && meta?.isLive != true,
ruleWidthText: terminal ? meta.map { reserveSpaceForMeta($0) } : nil,
ruleMinWidth: ruleMinWidth,
chatHeadings: true
)
} else {
msgContentView()
}
}
private func blockTextView(_ fts: [FormattedText], _ blocks: [MarkdownBlock], _ index: Int, _ range: Range<Int>, _ font: UIFont, _ secretStart: Int, _ last: Bool, _ textAlpha: Double) -> some View {
let r = messageText(
text,
fts,
markdownBlocks: blocks,
textStyle: textStyle,
sender: index == 0 ? sender : nil,
mentions: mentions,
userMemberId: userMemberId,
showSecrets: showSecrets,
commands: chat.chatInfo.useCommands && chat.chatInfo.sndReady,
backgroundColor: containerBackground,
prefix: index == 0 ? prefix : nil,
range: range,
baseFont: font,
secretStart: secretStart,
textColor: UIColor(messageColor)
)
let s = r.string
let t: Text
if last, let mt = meta {
if mt.isLive {
s.append(typingIndicator(mt.recent))
}
t = Text(AttributedString(s)) + reserveSpaceForMeta(mt)
} else {
t = Text(AttributedString(s))
}
let bodyFont = UIFont.preferredFont(forTextStyle: textStyle)
let box = terminal ? terminalLineBox(font, messageColor.opacity(textAlpha), theme, capsOf: font.pointSize > bodyFont.pointSize ? bodyFont : nil) : nil
return msgTextView(r, t, box)
}
@ViewBuilder
private func metaLineView() -> some View {
if let mt = meta, !terminal || mt.isLive {
(mt.isLive ? Text(AttributedString(typingIndicator(mt.recent))) : Text(verbatim: "")) + reserveSpaceForMeta(mt, newLine: false)
}
}
@inline(__always)
private func msgContentView() -> some View {
let r = messageText(
text,
formattedText,
markdownBlocks: blockLayout ? nil : markdownBlocks,
textStyle: textStyle,
sender: sender,
mentions: mentions,
userMemberId: userMemberId,
showSecrets: showSecrets,
commands: chat.chatInfo.useCommands && chat.chatInfo.sndReady,
backgroundColor: containerBackground,
prefix: prefix,
stripLink: stripLink,
textColor: UIColor(messageColor)
)
let s = r.string
let t: Text
if let mt = meta {
if mt.isLive {
s.append(typingIndicator(mt.recent))
}
t = Text(AttributedString(s)) + reserveSpaceForMeta(mt)
} else {
t = Text(AttributedString(s))
}
let box = terminal ? terminalLineBox(UIFont.preferredFont(forTextStyle: textStyle), messageColor, theme) : nil
return msgTextView(r, t, box)
}
@ViewBuilder private func msgTextView(_ r: MsgTextResult, _ t: Text, _ box: TerminalLineBox?) -> some View {
let v = msgTextResultView(r, t, showSecrets: $showSecrets, sendCommand: { cmd in sendCommandMsg(chat, cmd) }, lineSpacing: box?.spacing ?? 0)
if let box {
v.modifier(box)
} else {
v
}
}
private var messageColor: Color {
textColor ?? messageTextColor(theme)
}
@inline(__always)
private func typingIndicator(_ recent: Bool) -> NSAttributedString {
recent && !typingIndicators.isEmpty
? typingIndicators[typingIdx % 4]
: noTyping
}
@inline(__always)
private func reserveSpaceForMeta(_ mt: CIMeta, newLine: Bool = true) -> Text {
if terminal {
let separator = rightToLeft && newLine ? textNewLine : Text(verbatim: (rightToLeft ? "\u{200F}" : "\u{200E}") + " ")
return separator + ciMetaText(mt, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: encrypted, colorMode: .transparent, showStatus: terminalShowsStatus(mt.itemStatus, showTimestamp: showTimestamp), showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, signedFileVerified: signedFileVerified, showSignature: showSignature, showFileEncryption: showFileEncryption, unbreakable: true)
}
return (rightToLeft && newLine ? textNewLine : Text(verbatim: " ")) + ciMetaText(mt, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, showSignature: showSignature)
}
}
private func withLineSpacing(_ s: NSAttributedString, _ lineSpacing: CGFloat) -> NSAttributedString {
if lineSpacing <= 0 { return s }
let spaced = NSMutableAttributedString(attributedString: s)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
spaced.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: spaced.length))
return spaced
}
func msgTextResultView(
_ r: MsgTextResult,
_ t: Text,
showSecrets: Binding<Set<Int>>? = nil,
sendCommand: ((String) -> Void)? = nil,
openModal: ((Format) -> Void)? = nil,
centered: Bool = false,
smallFont: Bool = false,
lineSpacing: CGFloat = 0
) -> some View {
t.if(r.hasSecrets, transform: hiddenSecretsView)
.if(r.handleTaps) { $0.overlay(handleTextTaps(r.string, showSecrets: showSecrets, sendCommand: sendCommand, openModal: openModal, centered: centered, smallFont: smallFont, lineSpacing: lineSpacing)) }
}
// smallFont parameter is used to pad height, otherwise CTFrameGetLines fails to see them as lines - it's needed if font is not .body
@inline(__always)
private func handleTextTaps(
_ s: NSAttributedString,
showSecrets: Binding<Set<Int>>? = nil,
sendCommand: ((String) -> Void)? = nil,
openModal: ((Format) -> Void)? = nil,
centered: Bool,
smallFont: Bool,
lineSpacing: CGFloat
) -> some View {
return GeometryReader { g in
Rectangle()
.fill(Color.clear)
.contentShape(Rectangle())
.simultaneousGesture(DragGesture(minimumDistance: 0).onEnded { event in
let t = event.translation
if t.width * t.width + t.height * t.height > 100 { return }
let framesetter = CTFramesetterCreateWithAttributedString(withLineSpacing(s, lineSpacing) as CFAttributedString)
let paddedSize = smallFont ? CGSize(width: g.size.width, height: g.size.height + 1.0) : g.size
let path = CGPath(rect: CGRect(origin: .zero, size: paddedSize), transform: nil)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, s.length), path, nil)
let point = CGPoint(x: event.location.x, y: g.size.height - event.location.y) // Flip y for UIKit
var index: CFIndex?
if let lines = CTFrameGetLines(frame) as? [CTLine] {
var origins = [CGPoint](repeating: .zero, count: lines.count)
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &origins)
var maxWidth: CGFloat = 0
if centered {
for line in lines {
let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds)
if bounds.width > maxWidth {
maxWidth = bounds.width
}
}
}
for i in 0 ..< lines.count {
let bounds = CTLineGetBoundsWithOptions(lines[i], .useOpticalBounds)
let offsetX = centered ? (maxWidth - bounds.width) / 2 : 0
if bounds.offsetBy(dx: origins[i].x + offsetX, dy: origins[i].y).contains(point) {
let relativePoint = centered ? CGPoint(x: point.x - origins[i].x - offsetX, y: point.y - origins[i].y) : point
index = CTLineGetStringIndexForPosition(lines[i], relativePoint)
break
}
}
}
if let index, let (uri, browser, simplex) = attributedStringLink(s, for: index) {
if browser {
openBrowserAlert(uri: uri)
} else if simplex, let url = URL(string: uri) {
// SimpleX links target this same app (simplex: scheme / simplex.chat universal link),
// so UIApplication.shared.open is dropped by iOS while the app is in the foreground.
// Route to the in-app connect flow instead (same sink onOpenURL feeds).
ChatModel.shared.appOpenUrl = url
} else if let url = URL(string: uri) {
UIApplication.shared.open(url)
} else {
showInvalidLinkAlert(uri)
}
}
})
}
func attributedStringLink(_ s: NSAttributedString, for index: CFIndex) -> (String, Bool, Bool)? {
var linkURL: String?
var browser: Bool = false
var simplex: Bool = false
s.enumerateAttributes(in: NSRange(location: 0, length: s.length)) { attrs, range, stop in
if index >= range.location && index < range.location + range.length {
if attrs[nameAttrKey] is SimplexNameInfo {
planAndConnect(s.attributedSubstring(from: range).string, theme: AppTheme.shared, dismiss: false)
} else if let url = attrs[linkAttrKey] as? String {
linkURL = url
browser = attrs[webLinkAttrKey] != nil
simplex = attrs[simplexLinkAttrKey] != nil
} else if let showSecrets, let i = attrs[secretAttrKey] as? Int {
if showSecrets.wrappedValue.contains(i) {
showSecrets.wrappedValue.remove(i)
} else {
showSecrets.wrappedValue.insert(i)
}
} else if let sendCommand, let cmd = attrs[commandAttrKey] as? String {
sendCommand(cmd)
} else if let openModal, let fmt = attrs[modalAttrKey] as? Format {
openModal(fmt)
}
stop.pointee = true
}
}
return if let linkURL { (linkURL, browser, simplex) } else { nil }
}
}
func hiddenSecretsView<V: View>(_ v: V) -> some View {
v.overlay(
GeometryReader { g in
let size = (g.size.width + g.size.height) / 1.4142
Image("vertical_logo")
.resizable(resizingMode: .tile)
.frame(width: size, height: size)
.rotationEffect(.degrees(45), anchor: .center)
.position(x: g.size.width / 2, y: g.size.height / 2)
.clipped()
.saturation(0.65)
.opacity(0.35)
}
.mask(v)
)
}
private let linkAttrKey = NSAttributedString.Key("chat.simplex.app.link")
private let webLinkAttrKey = NSAttributedString.Key("chat.simplex.app.webLink")
private let simplexLinkAttrKey = NSAttributedString.Key("chat.simplex.app.simplexLink")
private let secretAttrKey = NSAttributedString.Key("chat.simplex.app.secret")
private let commandAttrKey = NSAttributedString.Key("chat.simplex.app.command")
private let nameAttrKey = NSAttributedString.Key("chat.simplex.app.name")
private let modalAttrKey = NSAttributedString.Key("chat.simplex.app.modal")
typealias MsgTextResult = (string: NSMutableAttributedString, hasSecrets: Bool, handleTaps: Bool)
// Reusable profile bio/description header: renders the teaser and opens the full
// description in a sheet when the "Read more" (Format.modal) link is tapped.
struct ProfileDescriptionView: View {
@EnvironmentObject var theme: AppTheme
let shortDescr: String?
let description: String?
@State private var showSecrets: Set<Int> = []
@State private var modal: ModalText? = nil
var body: some View {
if let r = markdownProfileDescription(shortDescr: shortDescr, description: description, showSecrets: showSecrets, backgroundColor: theme.colors.background) {
msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets, openModal: openModal, centered: true, smallFont: true)
.multilineTextAlignment(.center)
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
.appSheet(item: $modal) { m in
FullProfileDescriptionView(description: m.text).environmentObject(theme)
}
}
}
private func openModal(_ format: Format) {
if case let .modal(_, text) = format { modal = ModalText(text: text) }
}
}
private struct ModalText: Identifiable {
let id = UUID()
let text: String
}
private struct FullProfileDescriptionView: View {
@EnvironmentObject var theme: AppTheme
let description: String
@State private var showSecrets: Set<Int> = []
var body: some View {
List {
Text("Description")
.font(.title)
.bold()
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.listRowBackground(Color.clear)
Section {
let parsed = parseSimpleXMarkdownText(description)
MarkdownView(
text: description, formattedText: parsed?.formattedText, markdownBlocks: parsed?.markdownBlocks,
backgroundColor: theme.colors.background, cardColor: theme.appColors.receivedQuote, showSecrets: $showSecrets
)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
}
}
.modifier(ThemedBackground(grouped: true))
}
}
@inline(__always)
func markdownText(
_ s: String,
textStyle: UIFont.TextStyle = .body,
sender: String? = nil,
preview: Bool = false,
mentions: [String: CIMention]? = nil,
userMemberId: String? = nil,
showSecrets: Set<Int>? = nil,
backgroundColor: Color
) -> MsgTextResult {
let parsed = parseSimpleXMarkdownText(s)
return messageText(
s,
parsed?.formattedText,
markdownBlocks: parsed?.markdownBlocks,
textStyle: textStyle,
sender: sender,
preview: preview,
mentions: mentions,
userMemberId: userMemberId,
showSecrets: showSecrets,
commands: false,
backgroundColor: UIColor(backgroundColor)
)
}
// Renders a profile bio/description: the bio, a short single-line description, or a
// truncated teaser followed by a "Read more" link that opens the full description (Format.modal).
func markdownProfileDescription(
shortDescr: String?,
description: String?,
showSecrets: Set<Int>? = nil,
backgroundColor: Color
) -> MsgTextResult? {
func trimmed(_ s: String?) -> String? {
guard let t = s?.trimmingCharacters(in: .whitespacesAndNewlines), !t.isEmpty else { return nil }
return t
}
let short = trimmed(shortDescr)
let descr = trimmed(description)
guard let descr else {
return short.map { markdownText($0, textStyle: .subheadline, showSecrets: showSecrets, backgroundColor: backgroundColor) }
}
let firstLine = String(descr.prefix(while: { $0 != "\n" }))
let truncated = firstLine.count > 100
let multiline = descr.count > firstLine.count
if short == nil && !truncated && !multiline {
return markdownText(descr, textStyle: .subheadline, showSecrets: showSecrets, backgroundColor: backgroundColor)
}
let teaser = short ?? (truncated ? String(firstLine.prefix(100)).trimmingCharacters(in: .whitespaces) + "…" : firstLine + "…")
let readMore = NSLocalizedString("Read more", comment: "profile description teaser")
var formatted = parseSimpleXMarkdown(teaser) ?? [FormattedText(text: teaser)]
formatted.append(FormattedText(text: " "))
formatted.append(FormattedText(text: readMore, format: .modal(modalName: Format.modalDescription, text: descr)))
return messageText(
"\(teaser) \(readMore)",
formatted,
textStyle: .subheadline,
sender: nil,
mentions: nil,
userMemberId: nil,
showSecrets: showSecrets,
backgroundColor: UIColor(backgroundColor)
)
}
func messageText(
_ text: String,
_ formattedText: [FormattedText]?,
markdownBlocks: [MarkdownBlock]? = nil,
textStyle: UIFont.TextStyle = .body,
sender: String?,
preview: Bool = false,
mentions: [String: CIMention]?,
userMemberId: String?,
showSecrets: Set<Int>?,
commands: Bool = false,
backgroundColor: UIColor,
prefix: NSAttributedString? = nil,
stripLink: String? = nil,
range: Range<Int>? = nil,
baseFont: UIFont? = nil,
secretStart: Int = 0,
textColor: UIColor = .label
) -> MsgTextResult {
let text = if let stripLink { stripTextLink(text, stripLink) } else { text }
let formattedText = if let stripLink { stripFormattedTextLink(formattedText, stripLink) } else { formattedText }
let res = NSMutableAttributedString()
let descr = baseFont?.fontDescriptor ?? UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
let font = baseFont ?? UIFont.preferredFont(forTextStyle: textStyle)
let plain: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: textColor
]
let secretColor = backgroundColor.withAlphaComponent(1)
var hasSecrets = false
var handleTaps = false
var secretIdx: Int = secretStart
if let sender {
if preview {
res.append(NSAttributedString(string: sender + ": ", attributes: plain))
} else {
var attrs = plain
attrs[.font] = UIFont(descriptor: descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.medium]]), size: descr.pointSize)
res.append(NSAttributedString(string: sender, attributes: attrs))
res.append(NSAttributedString(string: ": ", attributes: plain))
}
}
if let prefix {
res.append(prefix)
}
if let fts = formattedText, fts.count > 0 {
if let range {
let start = min(max(range.lowerBound, 0), fts.count)
appendSegments(fts[start..<max(start, min(range.upperBound, fts.count))], false)
} else if let markdownBlocks {
let headings = headingSegments(fts.count, markdownBlocks)
var i = 0
while i < fts.count {
var j = i + 1
while j < fts.count && headings[j] == headings[i] { j += 1 }
appendSegments(fts[i..<j], headings[i])
i = j
}
} else {
appendSegments(fts[...], false)
}
} else {
res.append(NSMutableAttributedString(string: text, attributes: plain))
}
return (string: res, hasSecrets: hasSecrets, handleTaps: handleTaps)
func segmentFonts(_ heading: Bool) -> (descr: UIFontDescriptor, font: UIFont) {
if !heading { return (descr, font) }
let d = descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]])
return (d, UIFont(descriptor: d, size: d.pointSize))
}
func appendSegments(_ fts: ArraySlice<FormattedText>, _ heading: Bool) {
let (descr, font) = segmentFonts(heading)
let plain: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: textColor
]
var link: [NSAttributedString.Key: Any]?
var bold: UIFont?
var italic: UIFont?
var snippet: UIFont?
var small: UIFont?
var mention: UIFont?
for ft in fts {
var t = ft.text
var attrs = plain
switch (ft.format) {
case let .bold(singleStar):
if singleStar {
italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize)
attrs[.font] = italic
} else {
bold = bold ?? UIFont(descriptor: descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]]), size: descr.pointSize)
attrs[.font] = bold
}
case .italic:
italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize)
attrs[.font] = italic
case .strikeThrough:
attrs[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
case .snippet:
snippet = snippet ?? UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: .regular)
attrs[.font] = snippet
case .secret:
if let showSecrets {
if !showSecrets.contains(secretIdx) {
attrs[.foregroundColor] = UIColor.clear
attrs[.backgroundColor] = secretColor
}
attrs[secretAttrKey] = secretIdx
secretIdx += 1
handleTaps = true
} else {
attrs[.foregroundColor] = UIColor.clear
attrs[.backgroundColor] = secretColor
}
hasSecrets = true
case .small:
small = small ?? UIFont.preferredFont(forTextStyle: .footnote)
attrs[.font] = small
attrs[.foregroundColor] = UIColor.secondaryLabel
case let .colored(color):
if let c = color.uiColor {
attrs[.foregroundColor] = UIColor(c)
}
case .uri:
attrs = linkAttrs()
if !preview {
let link = t.hasPrefix("http://") || t.hasPrefix("https://")
? t
: "https://" + t
attrs[linkAttrKey] = link
attrs[webLinkAttrKey] = true
handleTaps = true
}
t = displayedUri(t)
case let .hyperLink(text, uri):
attrs = linkAttrs()
if let text { t = text }
if !preview {
attrs[linkAttrKey] = uri
if !ft.isEmailLink { attrs[webLinkAttrKey] = true }
handleTaps = true
}
case let .simplexLink(text, linkType, simplexUri, smpHosts):
attrs = linkAttrs()
if !preview {
attrs[linkAttrKey] = simplexUri
attrs[simplexLinkAttrKey] = true
handleTaps = true
}
if let s = text ?? (privacySimplexLinkModeDefault.get() == .description ? linkType.description : nil) {
res.append(NSAttributedString(string: s + " ", attributes: attrs))
italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize)
attrs[.font] = italic
t = viaHost(smpHosts)
}
case let .command(cmdStr):
if !preview && commands {
snippet = snippet ?? UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: .regular)
attrs[.font] = snippet
t = "/" + cmdStr
attrs[.foregroundColor] = uiLinkColor
attrs[commandAttrKey] = t
handleTaps = true
}
case let .mention(memberName):
if let m = mentions?[memberName] {
mention = mention ?? UIFont(descriptor: descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.semibold]]), size: descr.pointSize)
attrs[.font] = mention
if let ref = m.memberRef {
let name: String = if let alias = ref.localAlias, alias != "" {
"\(alias) (\(ref.displayName))"
} else {
ref.displayName
}
if m.memberId == userMemberId {
attrs[.foregroundColor] = UIColor.tintColor
}
t = mentionText(name)
} else {
t = mentionText(memberName)
}
}
case let .simplexName(nameInfo):
attrs = linkAttrs()
if !preview {
attrs[nameAttrKey] = nameInfo
handleTaps = true
}
case .email:
attrs = linkAttrs()
if !preview {
attrs[linkAttrKey] = "mailto:" + ft.text
handleTaps = true
}
case .phone:
attrs = linkAttrs()
if !preview {
attrs[linkAttrKey] = "tel:" + t.replacingOccurrences(of: " ", with: "")
handleTaps = true
}
case let .modal(modalName, text):
attrs = linkAttrs()
if !preview {
attrs[modalAttrKey] = Format.modal(modalName: modalName, text: text)
handleTaps = true
}
case .escape: t = ""
case let .markup(token):
if range != nil { t = token.drawnText } else if markdownBlocks != nil { t = token.previewText }
case .unknown: ()
case .none: ()
}
res.append(NSAttributedString(string: t, attributes: attrs))
}
func linkAttrs() -> [NSAttributedString.Key: Any] {
link = link ?? [
.font: font,
.foregroundColor: uiLinkColor,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
return link!
}
}
}
let swipeExclusionSpace = "swipeExclusion"
private let maxGridCells = 1000
struct SwipeExclusionFrames: PreferenceKey {
static var defaultValue: [CGRect] = []
static func reduce(value: inout [CGRect], nextValue: () -> [CGRect]) {
value += nextValue()
}
}
struct MarkdownView: View {
@EnvironmentObject var theme: AppTheme
var text: String
var formattedText: [FormattedText]?
var markdownBlocks: [MarkdownBlock]?
var sender: String? = nil
var mentions: [String: CIMention]? = nil
var userMemberId: String? = nil
var backgroundColor: Color
var cardColor: Color
@Binding var showSecrets: Set<Int>
var body: some View {
if let fts = formattedText, !fts.isEmpty, let blocks = markdownBlocks {
MarkdownBlocksView(
formattedText: fts,
blocks: blocks,
text: text,
textStyle: .body,
cardColor: cardColor,
rightToLeft: isRightToLeft(text),
blockText: { index, range, font, secretStart, _, _ in
let r = messageText(
text, fts, markdownBlocks: blocks, sender: index == 0 ? sender : nil, mentions: mentions, userMemberId: userMemberId,
showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor), range: range, baseFont: font, secretStart: secretStart,
textColor: UIColor(messageTextColor(theme))
)
msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
},
metaLine: { EmptyView() }
)
} else {
let r = messageText(text, formattedText, sender: sender, mentions: mentions, userMemberId: userMemberId, showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor), textColor: UIColor(messageTextColor(theme)))
msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
}
}
}
private struct BlocksLayout {
let font: UIFont
let starts: [Int]
let secrets: [Int]
let trailingEmptyLines: Int
let lastIsText: Bool
init(_ fts: [FormattedText], _ blocks: [MarkdownBlock], _ textStyle: UIFont.TextStyle, text: String, terminal: Bool) {
font = UIFont.preferredFont(forTextStyle: textStyle)
starts = blocks.reduce(into: [0]) { $0.append($0[$0.count - 1] + $1.textRanges.count) }
secrets = fts.reduce(into: [0]) { $0.append($0[$0.count - 1] + ($1.isSecret ? 1 : 0)) }
trailingEmptyLines = terminal ? 0 : emptyLines(fts, blocks.last?.endIndex ?? 0, fts.count, between: text.unicodeScalars.last != "\n")
lastIsText = switch blocks.last {
case .paragraph, .heading, .quote, .list: trailingEmptyLines == 0
default: false
}
}
}
struct MarkdownBlocksView<BlockText: View, MetaLine: View>: View {
@AppStorage(DEFAULT_CHAT_ITEM_ROUNDNESS) private var roundness = defaultChatItemRoundness
@Environment(\.terminalLayout) private var terminal
var formattedText: [FormattedText]
var blocks: [MarkdownBlock]
var text: String
var textStyle: UIFont.TextStyle
var cardColor: Color
var rightToLeft: Bool
@ViewBuilder var blockText: (_ index: Int, _ range: Range<Int>, _ font: UIFont, _ secretStart: Int, _ last: Bool, _ textAlpha: Double) -> BlockText
@ViewBuilder var metaLine: () -> MetaLine
var marksLastBlock = false
var ruleWidthText: Text? = nil
var ruleMinWidth: CGFloat = 0
var chatHeadings = false
var body: some View {
let l = BlocksLayout(formattedText, blocks, textStyle, text: text, terminal: terminal)
VStack(alignment: .leading, spacing: 0) {
emptyLinesGap(leadingEmptyLines(formattedText, blocks), l, between: false)
ForEach(Array(blocks.enumerated()), id: \.offset) { k, block in
let emptyHeight = k > 0 ? emptyLinesHeight(emptyLines(formattedText, blocks[k - 1].endIndex, block.startIndex, between: true), l) : 0
if k > 0 && terminal && (blocks[k - 1].isCard || block.isCard) {
Color.clear.frame(width: 0, height: max(terminalParagraphGap, emptyHeight))
} else if k > 0 && terminal && blocks[k - 1].isHeading && !block.isHeading {
Color.clear.frame(width: 0, height: terminalHeadingBottomGap + emptyHeight)
} else if k > 0 && terminal && block.isHeading {
Color.clear.frame(width: 0, height: terminalLevelStep + emptyHeight)
} else if emptyHeight > 0 {
Color.clear.frame(width: 0, height: emptyHeight)
}
blockView(block, l.starts[k], l, last: k == blocks.count - 1 && l.trailingEmptyLines == 0)
}
emptyLinesGap(l.trailingEmptyLines, l)
if !l.lastIsText {
metaLine()
}
}
.multilineTextAlignment(.leading)
.environment(\.layoutDirection, rightToLeft ? .rightToLeft : .leftToRight)
}
private func text(_ index: Int, _ r: SegmentRange, _ font: UIFont, _ l: BlocksLayout, textAlpha: Double = 1) -> BlockText {
blockText(index, r.from..<max(r.from, r.to), font, l.secrets[min(max(r.from, 0), formattedText.count)], l.lastIsText && index == l.starts[l.starts.count - 1] - 1, textAlpha)
}
@ViewBuilder private func blockView(_ block: MarkdownBlock, _ start: Int, _ l: BlocksLayout, last: Bool) -> some View {
switch block {
case let .paragraph(content):
text(start, content, l.font, l)
case let .heading(level, content):
text(start, content, terminal || chatHeadings ? terminalHeadingFont(l.font, level) : headingFont(l.font, level), l)
case let .quote(content):
HStack(alignment: .top, spacing: 10) {
quoteBar()
text(start, content, l.font, l, textAlpha: 0.72).opacity(0.72)
}
.fixedSize(horizontal: false, vertical: true)
case let .list(items):
let entries = listEntries(items, 0)
ForEach(Array(entries.enumerated()), id: \.offset) { j, e in
if j > 0 {
emptyLinesGap(emptyLines(formattedText, entries[j - 1].entry.content.to, e.entry.content.from, between: true), l)
}
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(e.entry.number ?? "•").font(.system(size: l.font.pointSize))
text(start + j, e.entry.content, l.font, l)
}
.padding(.leading, 20 * CGFloat(e.level))
}
case let .codeBlock(_, content):
CodeBlockCard(color: cardColor, radius: 12 * roundness, copyText: codeText(content)) {
text(start, content, monospacedFont(l.font), l).fixedSize(horizontal: true, vertical: false)
}
.if(terminal) { cardMargins($0.alignmentGuide(.lastTextBaseline) { d in d[explicit: .lastTextBaseline] ?? d[.bottom] - 8 + monospacedFont(l.font).descender }, last) }
case let .table(columns, header, rows):
tableView(columns, [header] + rows, start, l)
.if(terminal) { cardMargins($0.alignmentGuide(.lastTextBaseline) { d in d[explicit: .lastTextBaseline] ?? d[.bottom] - 4 + l.font.descender }, last) }
case .rule:
if terminal {
cardMargins(terminalRule(), last)
} else {
Rectangle().fill(Color(uiColor: .secondaryLabel).opacity(0.35)).frame(height: 1).padding(.vertical, 6)
}
}
}
private func cardMargins(_ block: some View, _ last: Bool) -> some View {
block
.if(last && marksLastBlock) { $0.modifier(MessageLastBlock()) }
.padding(.bottom, last && !marksLastBlock ? terminalParagraphGap : 0)
}
@ViewBuilder private func terminalRule() -> some View {
let rule = Rectangle().fill(Color(uiColor: .secondaryLabel).opacity(0.35)).frame(height: 1)
if let ruleWidthText, blocks.allSatisfy({ if case .rule = $0 { true } else { false } }) {
ruleWidthText.fixedSize().hidden().frame(minWidth: ruleMinWidth, alignment: .leading).frame(height: 1).overlay(rule)
} else {
rule
}
}
@ViewBuilder private func tableView(_ columns: [TableAlign], _ tableRows: [[SegmentRange]], _ start: Int, _ l: BlocksLayout) -> some View {
let rowStarts = tableRows.reduce(into: [start]) { $0.append($0[$0.count - 1] + $1.count) }
let columnCount = max(columns.count, tableRows.map(\.count).max() ?? 0)
let lineColor = Color(uiColor: .secondaryLabel).opacity(0.35)
let radius = 12 * roundness
if #available(iOS 16, *) {
if columnCount * tableRows.count <= maxGridCells {
HScroll {
Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {
ForEach(Array(tableRows.enumerated()), id: \.offset) { r, row in
GridRow {
ForEach(0..<columnCount, id: \.self) { c in
Group {
if c < row.count {
text(rowStarts[r] + c, row[c], r == 0 ? boldFont(l.font) : l.font, l).fixedSize()
} else {
Text(verbatim: "")
}
}
.padding(.horizontal, 12)
.padding(.vertical, 4)
.frame(maxWidth: .infinity, alignment: cellAlignment(c < columns.count ? columns[c] : .none))
.background(r == 0 ? cardColor : r % 2 == 0 ? Color(uiColor: .secondaryLabel).opacity(0.1) : Color.clear)
.overlay(Rectangle().stroke(lineColor, lineWidth: 0.5))
}
}
}
}
.fixedSize()
.clipShape(RoundedRectangle(cornerRadius: radius))
.overlay(RoundedRectangle(cornerRadius: radius).stroke(lineColor, lineWidth: 1))
}
} else {
tableSourceCard(tableRows, l, radius)
}
} else {
tableSourceCard(tableRows, l, radius)
}
}
private func tableSourceCard(_ tableRows: [[SegmentRange]], _ l: BlocksLayout, _ radius: CGFloat) -> some View {
let source = tableSource(tableRows)
return CodeBlockCard(color: cardColor, radius: radius, copyText: source) {
Text(verbatim: source).font(.system(size: l.font.pointSize * 0.875, design: .monospaced)).fixedSize(horizontal: true, vertical: false)
}
}
@ViewBuilder private func emptyLinesGap(_ lines: Int, _ l: BlocksLayout, between: Bool = true) -> some View {
if lines > 0 {
Color.clear.frame(width: 0, height: emptyLinesHeight(lines, l, between: between))
}
}
private func emptyLinesHeight(_ lines: Int, _ l: BlocksLayout, between: Bool = true) -> CGFloat {
if terminal { return CGFloat(lines) * terminalParagraphGap }
let height = CGFloat(lines) * (l.font.lineHeight + l.font.leading)
return between && lines > 0 ? height + l.font.leading : height
}
private func codeText(_ r: SegmentRange) -> String {
let start = min(max(r.from, 0), formattedText.count)
return formattedText[start..<max(start, min(r.to, formattedText.count))].map {
switch $0.format {
case let .markup(token): token.drawnText
case .escape: ""
default: $0.text
}
}.joined()
}
private func tableSource(_ tableRows: [[SegmentRange]]) -> String {
let start = min(max((tableRows.first?.first?.from ?? 1) - 1, 0), formattedText.count)
let end = min((tableRows.last?.last?.to ?? 0) + 1, formattedText.count)
return formattedText[start..<max(start, end)].map(\.text).joined()
}
}
private extension MarkdownBlock {
var startIndex: Int {
if case let .rule(mark) = self { mark.from } else { textRanges.first?.range.from ?? 0 }
}
var endIndex: Int {
if case let .rule(mark) = self { mark.to } else { textRanges.last?.range.to ?? 0 }
}
}
private let maxEmptyLines = 100
private func emptyLines(_ fts: [FormattedText], _ from: Int, _ to: Int, between: Bool) -> Int {
let start = min(max(from, 0), fts.count)
let lineBreaks = fts[start..<max(start, min(to, fts.count))].reduce(0) { n, ft in
switch ft.format {
case .markup(.lineBreak): n + 1
case let .markup(.paragraphBreak(breaks)): n + breaks
default: n
}
}
return min(max(0, lineBreaks - (between ? 1 : 0)), maxEmptyLines)
}
func leadingEmptyLines(_ fts: [FormattedText], _ blocks: [MarkdownBlock]) -> Int {
emptyLines(fts, 0, blocks.first?.startIndex ?? 0, between: false)
}
let quoteBarWidth: CGFloat = 4
func quoteBar() -> some View {
RoundedRectangle(cornerRadius: 2).fill(Color(uiColor: .label).opacity(0.16)).frame(width: quoteBarWidth)
}
private func headingFont(_ font: UIFont, _ level: Int) -> UIFont {
let scale: CGFloat = switch level {
case 1: 1.5
case 2: 1.3
case 3: 1.15
default: 1
}
return UIFont(descriptor: boldFont(font).fontDescriptor, size: font.pointSize * scale)
}
private func terminalHeadingFont(_ font: UIFont, _ level: Int) -> UIFont {
UIFont(descriptor: boldFont(font).fontDescriptor, size: font.pointSize * pow(terminalHeadingRatio, CGFloat(max(0, 3 - level))))
}
private func boldFont(_ font: UIFont) -> UIFont {
UIFont(descriptor: font.fontDescriptor.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]]), size: font.pointSize)
}
private func monospacedFont(_ font: UIFont) -> UIFont {
UIFont.monospacedSystemFont(ofSize: font.pointSize * 0.875, weight: .regular)
}
private func cellAlignment(_ align: TableAlign) -> Alignment {
switch align {
case .right: .trailing
case .center: .center
default: .leading
}
}
private struct CodeBlockCard<Content: View>: View {
@EnvironmentObject var theme: AppTheme
@Environment(\.terminalLayout) private var terminal
var color: Color
var radius: CGFloat
var copyText: String
@ViewBuilder var content: () -> Content
@State private var showCopy = false
var body: some View {
HScroll {
content()
.padding(.horizontal, 12)
.padding(.vertical, 8)
}
.if(!terminal) { $0.frame(maxWidth: .infinity, alignment: .leading) }
.overlay(alignment: .topTrailing) {
if showCopy {
Button {
UIPasteboard.general.string = copyText
showCopy = false
} label: {
Image(systemName: "doc.on.doc")
.foregroundColor(theme.colors.primary)
.frame(width: 28, height: 28)
.background(color)
.clipShape(RoundedRectangle(cornerRadius: radius * 2 / 3))
}
.padding(4)
}
}
.background(color)
.clipShape(RoundedRectangle(cornerRadius: radius))
.onTapGesture { showCopy.toggle() }
}
}
private struct HScroll<Content: View>: View {
@ViewBuilder var content: () -> Content
var body: some View {
if #available(iOS 16, *) {
ViewThatFits(in: .horizontal) {
content()
scrollView()
}
} else {
scrollView()
}
}
private func scrollView() -> some View {
ScrollView(.horizontal, showsIndicators: false) {
content()
}
.background {
GeometryReader { g in
Color.clear.preference(key: SwipeExclusionFrames.self, value: [g.frame(in: .named(swipeExclusionSpace))])
}
}
}
}
@inline(__always)
private func mentionText(_ name: String) -> String {
name.contains(" @") ? "@'\(name)'" : "@\(name)"
}
func simplexLinkText(_ linkType: SimplexLinkType, _ smpHosts: [String]) -> String {
linkType.description + " " + viaHost(smpHosts)
}
func viaHost(_ smpHosts: [String]) -> String {
"(via \(smpHosts.first ?? "?"))"
}
func stripTextLink(_ text: String, _ link: String) -> String {
text == link
? ""
: text.hasSuffix("\n" + link)
? String(text.dropLast(link.count + 1))
: text
}
func stripFormattedTextLink(_ ft: [FormattedText]?, _ link: String) -> [FormattedText]? {
guard var ft, ft.last?.text == link else { return ft }
ft.removeLast()
if let i = ft.indices.last, case .markup = ft[i].format {
ft.removeLast()
} else if let i = ft.indices.last, ft[i].format == nil, ft[i].text.hasSuffix("\n") {
ft[i].text = String(ft[i].text.dropLast())
if ft[i].text.isEmpty { ft.removeLast() }
}
return ft.isEmpty ? nil : ft
}
struct MsgContentView_Previews: PreviewProvider {
static var previews: some View {
let chatItem = ChatItem.getSample(1, .directSnd, previewDate, "hello")
return MsgContentView(
chat: Chat.sampleData,
text: chatItem.text,
formattedText: chatItem.formattedText,
textStyle: .body,
sender: chatItem.memberDisplayName,
meta: chatItem.meta
)
.environmentObject(Chat.sampleData)
}
}