diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift index f74f428aef..a71cdeb4dc 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift @@ -53,7 +53,7 @@ struct CIFileView: View { metaReserve.font(.caption) } } - .padding(.top, terminal ? terminalFileTopGap : 4) + .padding(.top, terminal ? 0 : 4) .padding(.bottom, terminal ? 0 : 6) .padding(.leading, 10) .padding(.trailing, 12) diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift index 30785accc4..a9e732af41 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift @@ -69,8 +69,8 @@ struct CIVoiceView: View { } } } - .padding(.top, terminal ? terminalGap(4) : 4) - .padding(.bottom, terminal ? terminalGap(6) : 8) + .padding(.top, terminal ? 0 : 4) + .padding(.bottom, terminal ? terminalCardBottomGap(chatItem) : 8) .padding(.leading, terminal ? chatItemTextPadding : 0) } diff --git a/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift index 96ba9b6134..c19b1c3a93 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift @@ -32,7 +32,7 @@ struct EmojiItemView: View { } else { emojiText(chatItem.content.text) .modifier(MessageLastLine()) - .padding(EdgeInsets(top: terminalEmojiTopGap, leading: chatItemTextPadding, bottom: terminalEmojiBottomGap, trailing: chatItemTextPadding)) + .padding(EdgeInsets(top: 0, leading: chatItemTextPadding, bottom: terminalCardBottomGap(chatItem), trailing: chatItemTextPadding)) } } } diff --git a/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift b/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift index b440b5c129..9f9ec9136d 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift @@ -55,10 +55,10 @@ struct FramedCIVoiceView: View { playbackSlider() } } - .padding(.top, terminal ? terminalGap(4) : 6) + .padding(.top, terminal ? terminalCardTopGap(chatItem) : 6) .padding(.leading, terminal ? chatItemTextPadding : 6) .padding(.trailing, terminal ? 0 : 12) - .padding(.bottom, terminal ? terminalGap(6) : chatItem.content.text.isEmpty ? 10 : 0) + .padding(.bottom, terminal ? 0 : chatItem.content.text.isEmpty ? 10 : 0) } private func playbackSlider() -> some View { diff --git a/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift index 64a0ee3b0e..752cefb743 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift @@ -39,7 +39,8 @@ struct FramedItemView: View { showMeta: chatItem.content.msgContent != nil, metaReserved: metaPlacement.reserved, overlayMeta: captionlessMedia ? AnyView(CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary, invertedMaterial: true)) : nil, - endButton: endButton + endButton: endButton, + lastBlockGap: terminalCardBottomGap(chatItem) ) { CIMetaView( chat: chat, @@ -141,7 +142,7 @@ struct FramedItemView: View { } .background { if !terminal { chatItemFrameColorMaybeImageOrVideo(chatItem, theme).modifier(ChatTailPadding()) } } .onPreferenceChange(DetermineWidth.Key.self) { msgWidth = $0 } - .padding(.bottom, terminal && metaPlacement.gapBelowBlock ? terminalBlockBottomGap : 0) + .padding(.bottom, terminal && metaPlacement.gapBelowBlock ? terminalCardBottomGap(chatItem) : 0) if let (title, text) = chatItem.meta.itemStatus.statusInfo ?? chatItem.meta.msgVerified?.sigMissingInfo { v.simultaneousGesture(TapGesture().onEnded { @@ -157,12 +158,16 @@ struct FramedItemView: View { } } + static func showsEmoji(_ ci: ChatItem) -> Bool { + ci.formattedText == nil && ci.file == nil && !ci.meta.isLive && isShortEmoji(ci.content.text) + } + @ViewBuilder private func framedMsgContentView() -> some View { - if chatItem.formattedText == nil && chatItem.file == nil && !chatItem.meta.isLive && isShortEmoji(chatItem.content.text) { + if Self.showsEmoji(chatItem) { if terminal { emojiText(chatItem.content.text) .modifier(MessageLastLine()) - .padding(EdgeInsets(top: terminalEmojiTopGap, leading: chatItemTextPadding, bottom: terminalEmojiBottomGap, trailing: chatItemTextPadding)) + .padding(EdgeInsets(top: terminalCardTopGap(chatItem), leading: chatItemTextPadding, bottom: terminalCardBottomGap(chatItem), trailing: chatItemTextPadding)) } else { VStack(spacing: 4) { emojiText(chatItem.content.text) @@ -190,7 +195,7 @@ struct FramedItemView: View { useWhiteMetaColor = false } } else { - ciMsgContentView(chatItem, terminalTop: terminalBlockBottomGap) + ciMsgContentView(chatItem) } case let .video(text, _, duration): CIVideoView(chatItem: chatItem, preview: preview, duration: duration, maxWidth: maxWidth, videoWidth: videoWidth, showFullscreenPlayer: $showFullscreenGallery) @@ -206,7 +211,7 @@ struct FramedItemView: View { useWhiteMetaColor = false } } else { - ciMsgContentView(chatItem, terminalTop: terminalBlockBottomGap) + ciMsgContentView(chatItem) } case let .voice(text, duration): FramedCIVoiceView(chat: chat, chatItem: chatItem, recordingFile: chatItem.file, duration: duration, allowMenu: $allowMenu) @@ -221,7 +226,7 @@ struct FramedItemView: View { case let .link(_, preview): CILinkView(linkPreview: preview, maxWidth: maxWidth) .if(terminal) { terminalBlock($0.frame(maxWidth: maxWidth).padding(.bottom, 8), chatItemFrameContextColor(chatItem, theme)) } - ciMsgContentView(chatItem, terminalTop: terminalBlockBottomGap) + ciMsgContentView(chatItem) case let .chat(text, chatLink, ownerSig): let hasText = text != chatLink.connLinkStr CIChatLinkHeader(chatItem: chatItem, chatLink: chatLink, ownerSig: ownerSig, hasText: hasText) @@ -231,7 +236,7 @@ struct FramedItemView: View { }) .if(terminal) { terminalBlock($0.frame(maxWidth: maxWidth).fixedSize(horizontal: true, vertical: false), chatItemFrameContextColor(chatItem, theme)) } if hasText { - ciMsgContentView(chatItem, stripLink: chatLink.connLinkStr, terminalTop: terminalBlockBottomGap) + ciMsgContentView(chatItem, stripLink: chatLink.connLinkStr) } case let .unknown(_, text: text): if chatItem.file == nil { @@ -396,8 +401,7 @@ struct FramedItemView: View { .fixedSize(horizontal: false, vertical: true) .padding(.leading, chatItemTextPadding) .overlay { if case .voice = chatItem.content.msgContent {} else { DetermineWidth() } } - .padding(.top, terminalBlockTopGap) - .padding(.bottom, terminalBlockBottomGap) + .padding(.top, chatItem.hasHeaderAboveQuote ? terminalParagraphGap : 0) } private func terminalBlock(_ block: some View, _ background: Color = .clear) -> some View { @@ -405,7 +409,7 @@ struct FramedItemView: View { .background(background) .clipShape(RoundedRectangle(cornerRadius: msgRectMaxRadius * roundness)) .padding(.leading, chatItemTextPadding) - .padding(.top, terminalBlockTopGap) + .padding(.top, terminalCardTopGap(chatItem)) } private func membership() -> GroupMember? { @@ -415,7 +419,7 @@ struct FramedItemView: View { } } - @ViewBuilder private func ciMsgContentView(_ ci: ChatItem, txtPrefix: NSAttributedString? = nil, stripLink: String? = nil, terminalTop: CGFloat = 0) -> some View { + @ViewBuilder private func ciMsgContentView(_ ci: ChatItem, txtPrefix: NSAttributedString? = nil, stripLink: String? = nil) -> some View { let text = ci.meta.isLive ? ci.content.msgContent?.text ?? ci.text : ci.text let rtl = isRightToLeft(text) let ft = text == "" ? [] : ci.formattedText @@ -440,7 +444,7 @@ struct FramedItemView: View { .environment(\.containerBackground, UIColor(terminal ? terminalBackgroundColor(theme) : chatItemFrameColor(ci, theme))) .multilineTextAlignment(rtl ? .trailing : .leading) .padding(.vertical, terminal ? 0 : 6) - .padding(.top, terminal ? terminalTop + terminalHeadingGap(ci) : 0) + .padding(.top, terminal ? terminalTextTopGap(ci) : 0) .padding(.horizontal, 12) .overlay(DetermineWidth()) .frame(minWidth: 0, alignment: .leading) @@ -455,6 +459,7 @@ struct FramedItemView: View { @ViewBuilder private func ciFileView(_ ci: ChatItem, _ text: String) -> some View { CIFileView(chat: chat, file: chatItem.file, meta: chatItem.meta) .overlay(DetermineWidth()) + .padding(.top, terminal ? terminalCardTopGap(ci) : 0) if text != "" || ci.meta.isLive { ciMsgContentView (chatItem) } @@ -492,7 +497,8 @@ struct FramedItemView: View { private var metaPlacement: (reserved: Bool, gapBelowBlock: Bool) { switch chatItem.content.msgContent { - case let .voice(text, _): (text != "", false) + case let .voice(text, _): (text != "", text == "") + case let .file(text), let .unknown(_, text): (true, chatItem.file != nil && text == "" && !chatItem.meta.isLive) case let .chat(text, chatLink, _): text != chatLink.connLinkStr ? (true, false) : (false, true) default: (!captionlessMedia, captionlessMedia) } diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift index a69150a985..b732f93cb7 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift @@ -111,11 +111,12 @@ struct MsgContentView: View { 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() }, + metaLine: { metaLineView(afterEmptyLines: $0) }, marksLastBlock: terminal && meta?.isLive != true, ruleWidthText: terminal ? meta.map { reserveSpaceForMeta($0) } : nil, ruleMinWidth: ruleMinWidth, @@ -160,9 +161,10 @@ struct MsgContentView: View { } @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) + private func metaLineView(afterEmptyLines: Bool) -> some View { + if let mt = meta, !terminal || mt.isLive || afterEmptyLines { + ((mt.isLive ? Text(AttributedString(typingIndicator(mt.recent))) : Text(verbatim: "")) + reserveSpaceForMeta(mt, newLine: false)) + .if(terminal && afterEmptyLines) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: textStyle), messageColor, theme)) } } } @@ -593,7 +595,7 @@ func messageText( var attrs = plain switch (ft.format) { case let .bold(singleStar): - if singleStar && markdownBlocks != nil { + if singleStar { italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize) attrs[.font] = italic } else { @@ -762,6 +764,7 @@ struct MarkdownView: View { MarkdownBlocksView( formattedText: fts, blocks: blocks, + text: text, textStyle: .body, cardColor: cardColor, rightToLeft: isRightToLeft(text), @@ -773,7 +776,7 @@ struct MarkdownView: View { ) msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets) }, - metaLine: { EmptyView() } + metaLine: { _ in EmptyView() } ) } else { let r = messageText(text, formattedText, sender: sender, mentions: mentions, userMemberId: userMemberId, showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor), textColor: UIColor(messageTextColor(theme))) @@ -786,14 +789,16 @@ 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) { + init(_ fts: [FormattedText], _ blocks: [MarkdownBlock], _ textStyle: UIFont.TextStyle, text: String) { 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 = emptyLines(fts, blocks.last?.endIndex ?? 0, fts.count, between: text.unicodeScalars.last != "\n") lastIsText = switch blocks.last { - case .paragraph, .heading, .quote, .list: true + case .paragraph, .heading, .quote, .list: trailingEmptyLines == 0 default: false } } @@ -804,29 +809,37 @@ struct MarkdownBlocksView: View { @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, _ font: UIFont, _ secretStart: Int, _ last: Bool, _ textAlpha: Double) -> BlockText - @ViewBuilder var metaLine: () -> MetaLine + @ViewBuilder var metaLine: (_ afterEmptyLines: Bool) -> 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) + let l = BlocksLayout(formattedText, blocks, textStyle, text: text) VStack(alignment: .leading, spacing: 0) { + emptyLinesGap(leadingEmptyLines(formattedText, blocks), l) ForEach(Array(blocks.enumerated()), id: \.offset) { k, block in - if k > 0 && terminal && blocks[k - 1].isHeading && !block.isHeading { - Color.clear.frame(height: terminalHeadingBottomGap) - } else if k > 0 && (paragraphBreak(blocks[k - 1].endIndex, block.startIndex) || terminal && block.isHeading) { - Color.clear.frame(height: terminal ? terminalLevelStep : l.font.lineHeight / 2) + 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(height: max(terminalParagraphGap, emptyHeight)) + } else if k > 0 && terminal && blocks[k - 1].isHeading && !block.isHeading { + Color.clear.frame(height: terminalHeadingBottomGap + emptyHeight) + } else if k > 0 && terminal && block.isHeading { + Color.clear.frame(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) + blockView(block, l.starts[k], l, last: k == blocks.count - 1 && l.trailingEmptyLines == 0) } + emptyLinesGap(l.trailingEmptyLines, l) if !l.lastIsText { - metaLine() + metaLine(l.trailingEmptyLines > 0) } } .multilineTextAlignment(.leading) @@ -850,7 +863,11 @@ struct MarkdownBlocksView: View { } .fixedSize(horizontal: false, vertical: true) case let .list(items): - ForEach(Array(listEntries(items, 0).enumerated()), id: \.offset) { j, e in + 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) @@ -877,8 +894,7 @@ struct MarkdownBlocksView: View { private func cardMargins(_ block: some View, _ last: Bool) -> some View { block .if(last && marksLastBlock) { $0.modifier(MessageLastBlock()) } - .padding(.top, terminalBlockTopGap) - .padding(.bottom, last && marksLastBlock ? 0 : terminalBlockBottomGap) + .padding(.bottom, last && !marksLastBlock ? terminalParagraphGap : 0) } @ViewBuilder private func terminalRule() -> some View { @@ -937,13 +953,16 @@ struct MarkdownBlocksView: View { } } - private func paragraphBreak(_ from: Int, _ to: Int) -> Bool { - let start = min(max(from, 0), formattedText.count) - return formattedText[start.. some View { + if lines > 0 { + Color.clear.frame(width: 0, height: emptyLinesHeight(lines, l)) } } + private func emptyLinesHeight(_ lines: Int, _ l: BlocksLayout) -> CGFloat { + CGFloat(lines) * (terminal ? terminalParagraphGap : l.font.lineHeight) + } + private func codeText(_ r: SegmentRange) -> String { let start = min(max(r.from, 0), formattedText.count) return formattedText[start.. Int { + let start = min(max(from, 0), fts.count) + let lineBreaks = fts[start.. Int { + emptyLines(fts, 0, blocks.first?.startIndex ?? 0, between: false) +} + let quoteBarWidth: CGFloat = 4 func quoteBar() -> some View { diff --git a/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift index d305293630..f8ff86e3d3 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift @@ -13,25 +13,18 @@ extension EnvironmentValues { } let chatItemTextPadding: CGFloat = 12 -var terminalBlockTopGap: CGFloat { terminalGap(5.75) } -var terminalBlockBottomGap: CGFloat { terminalGap(5) } +var terminalParagraphGap: CGFloat { terminalGap(terminalGapBodySize * terminalLineHeightRatio / 3) } var terminalLevelStep: CGFloat { terminalGap(4.75) } var terminalHeadingBottomGap: CGFloat { terminalLevelStep / 2 } -var terminalSenderTopGap: CGFloat { terminalGap(6.5) } -private var terminalSenderBottomGap: CGFloat { terminalGap(5.5) } var terminalHeaderTopGap: CGFloat { terminalGap(2.5) } var terminalHeaderBottomGap: CGFloat { terminalGap(1.5) } -var terminalEventTopGap: CGFloat { terminalGap(8.25) } -var terminalEventBottomGap: CGFloat { terminalGap(1.5) } -var terminalFileTopGap: CGFloat { terminalGap(2) } -var terminalEmojiTopGap: CGFloat { terminalGap(4.25) } -var terminalEmojiBottomGap: CGFloat { terminalGap(1.5) } var terminalMetaGap: CGFloat { terminalGap(6) } var terminalNameSize: CGFloat { bodyScaled(13.5 * 17 / 16) } let terminalHeadingRatio: CGFloat = 1.25 private let terminalLineHeightRatio: CGFloat = 22 / 16 private let terminalLineHeightContrastSlope: CGFloat = 0.1515 private let terminalGapBodySize: CGFloat = 16 +private let terminalNameRepeatInterval: TimeInterval = 7.5 * 60 func terminalGap(_ size: CGFloat) -> CGFloat { size * UIFont.preferredFont(forTextStyle: .body).pointSize / terminalGapBodySize @@ -125,7 +118,7 @@ private func composited(_ color: UIColor, over background: UIColor) -> UIColor { func terminalItemShowsSender(_ item: ChatItem, _ older: ChatItem?) -> Bool { guard item.content.hasTerminalSender else { return false } guard let older else { return true } - return !older.content.hasTerminalSender || !sameSender(item, older) + return !older.content.hasTerminalSender || !sameSender(item, older) || item.meta.itemTs.timeIntervalSince(older.meta.itemTs) >= terminalNameRepeatInterval } private func sameSender(_ item: ChatItem, _ older: ChatItem) -> Bool { @@ -136,13 +129,58 @@ private func sameSender(_ item: ChatItem, _ older: ChatItem) -> Bool { func terminalRowGap(_ item: ChatItem, _ older: ChatItem?, separated: Bool, largeGap: Bool, hasSenderRow: Bool) -> CGFloat { guard let older, !separated else { return 0 } - return largeGap || hasSenderRow || !item.content.hasTerminalSender || !older.content.hasTerminalSender || (item.textAtItemTop && item.startsWithHeading) - ? terminalLevelStep + return largeGap || hasSenderRow || !item.isOneLine || !older.isOneLine || !older.reactions.isEmpty + ? terminalParagraphGap : 0 } -func terminalHeadingGap(_ item: ChatItem) -> CGFloat { - !item.textAtItemTop && item.startsWithHeading ? terminalLevelStep : 0 +func terminalItemStartsWithCard(_ item: ChatItem, revealed: Bool) -> Bool { + if item.meta.itemDeleted != nil && (!revealed || item.isDeletedContent) { return true } + if item.quotedItem != nil { return !item.hasHeaderAboveQuote } + if item.hasQuoteOrHeader { return false } + guard let mc = item.content.msgContent else { + switch item.content { + case .sndCall, .rcvCall: return false + default: return true + } + } + return terminalMediaCard(item) || item.markdownBlocks?.first?.isCard == true || mc.isText && isShortEmoji(mc.text) || FramedItemView.showsEmoji(item) +} + +func terminalCardTopGap(_ item: ChatItem) -> CGFloat { + item.hasQuoteOrHeader ? terminalParagraphGap : 0 +} + +func terminalCardBottomGap(_ item: ChatItem) -> CGFloat { + item.reactions.isEmpty ? 0 : terminalParagraphGap +} + +func terminalTextTopGap(_ item: ChatItem) -> CGFloat { + if item.textAtItemTop { + 0 + } else if item.quotedItem != nil || terminalMediaCard(item) || item.markdownBlocks?.first?.isCard == true { + startsWithEmptyLine(item) ? 0 : terminalParagraphGap + } else if item.startsWithHeading { + terminalLevelStep + } else { + 0 + } +} + +private func startsWithEmptyLine(_ item: ChatItem) -> Bool { + if let fts = item.formattedText, let blocks = item.markdownBlocks { + leadingEmptyLines(fts, blocks) > 0 + } else { + item.content.text.first?.isNewline == true && !item.isReport + } +} + +private func terminalMediaCard(_ item: ChatItem) -> Bool { + switch item.content.msgContent { + case .link, .image, .video, .voice, .file, .chat: true + case .unknown: item.file != nil + case .text, .report, nil: false + } } private enum MessageLastLineRight: AlignmentID { @@ -182,6 +220,7 @@ struct ItemWithMeta: View { var metaReserved = false var overlayMeta: AnyView? = nil var endButton: AnyView? = nil + var lastBlockGap: CGFloat = 0 @ViewBuilder var meta: () -> Meta @ViewBuilder var content: (_ inlineMeta: Meta?) -> Content @@ -195,7 +234,7 @@ struct ItemWithMeta: View { @ViewBuilder private var terminalBody: some View { if #available(iOS 16, *) { - TerminalMetaLayout(metaReserved: metaReserved, hasOverlay: overlayMeta != nil, hasEndButton: endButton != nil) { + TerminalMetaLayout(metaReserved: metaReserved, hasOverlay: overlayMeta != nil, hasEndButton: endButton != nil, lastBlockGap: lastBlockGap) { ZStack(alignment: .topLeading) { content(nil) } @@ -235,6 +274,7 @@ private struct TerminalMetaLayout: Layout { var metaReserved: Bool var hasOverlay: Bool var hasEndButton: Bool + var lastBlockGap: CGFloat private struct Placement { var size: CGSize @@ -286,7 +326,7 @@ private struct TerminalMetaLayout: Layout { ? content.height + gap : textBaseline.map { $0 - metaBaseline } ?? content.height - gap - meta.height ) - let blockGap = content[explicit: MessageLastBlock.bottom].map { abs($0 - content.height) < 0.5 } == true ? terminalBlockBottomGap : 0 + let blockGap = content[explicit: MessageLastBlock.bottom].map { abs($0 - content.height) < 0.5 } == true ? lastBlockGap : 0 let overlayFrame: CGRect? = if let overlay, content.width + meta.width > rowWidth { CGRect(x: content.width - overlay.width, y: max(0, content.height - gap - overlay.height), width: overlay.width, height: overlay.height) } else { @@ -331,9 +371,7 @@ struct ChatEventWithMeta: View { } } -var terminalEventPadding: EdgeInsets { - EdgeInsets(top: terminalEventTopGap, leading: chatItemTextPadding, bottom: terminalEventBottomGap, trailing: chatItemTextPadding) -} +let terminalEventPadding = EdgeInsets(top: 0, leading: chatItemTextPadding, bottom: 0, trailing: chatItemTextPadding) struct ChatItemSender { var name: Text @@ -348,7 +386,7 @@ struct TerminalChatItemRow: View { var sender: ChatItemSender? var gutter: CGFloat var topGap: CGFloat - var senderTopGap: CGFloat = terminalSenderTopGap + var contentStartsWithCard: Bool @ViewBuilder var content: () -> Content var body: some View { @@ -363,28 +401,27 @@ struct TerminalChatItemRow: View { if let sender { senderNameAndRole(sender) .padding(.leading, chatItemTextPadding) - .padding(.bottom, terminalSenderBottomGap) + .padding(.bottom, contentStartsWithCard ? terminalParagraphGap : 0) } content() } } - .padding(.top, topGap + (sender == nil ? 0 : senderTopGap)) + .padding(.top, topGap) } private func senderNameAndRole(_ sender: ChatItemSender) -> some View { - let size = terminalNameSize - return HStack(alignment: .firstTextBaseline, spacing: 0) { - NameWithBadge(sender.name.font(.system(size: size)).foregroundColor(sender.own ? theme.colors.primary : theme.colors.secondary), sender.badge, .footnote) + HStack(alignment: .firstTextBaseline, spacing: 0) { + NameWithBadge(sender.name.font(.body.weight(.semibold)).foregroundColor(sender.own ? theme.colors.primary : theme.colors.secondary), sender.badge) .lineLimit(1) if let role = sender.role { Text(role) - .font(.system(size: size, weight: .medium)) + .font(.body.weight(.medium)) .foregroundColor(theme.colors.secondary) .lineLimit(1) .padding(.leading, 15) .layoutPriority(1) } } - .modifier(terminalLineBox(UIFont.systemFont(ofSize: size), nil, theme)) + .modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .body), nil, theme)) } } diff --git a/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift b/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift index 7a610cebff..02ea691887 100644 --- a/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift +++ b/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift @@ -282,7 +282,7 @@ struct ListItem: Hashable { // using meta.hashValue instead of parts takes much more time so better to use partial meta here func genHash(_ prevRevealed: Bool, _ nextRevealed: Bool) -> String { - "\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextRevealed)" + "\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextItem?.reactions.isEmpty ?? true) \(nextItem?.isOneLine ?? false) \(nextRevealed)" } } diff --git a/apps/ios/Shared/Views/Chat/ChatView.swift b/apps/ios/Shared/Views/Chat/ChatView.swift index b4cc5acb04..a35b57e33a 100644 --- a/apps/ios/Shared/Views/Chat/ChatView.swift +++ b/apps/ios/Shared/Views/Chat/ChatView.swift @@ -2166,7 +2166,8 @@ struct ChatView: View { TerminalChatItemRow( sender: showSender ? chatItemSender(ci, range) : nil, gutter: gutter, - topGap: topGap + topGap: topGap, + contentStartsWithCard: terminalItemStartsWithCard(ci, revealed: revealed) ) { chatItemWithMenu(ci, range, min(maxWidth, listWidth - leading - gutter - 2 * chatItemTextPadding), itemSeparation) } @@ -2253,7 +2254,7 @@ struct ChatView: View { .foregroundColor(.secondary) .opacity(min(1, -swipeOffset / 30)) .offset(x: swipeOffset + 40) - VStack(alignment: alignment.horizontal, spacing: 3) { + VStack(alignment: alignment.horizontal, spacing: terminal ? 0 : 3) { HStack { if alignEnd { goToItemButton(true) @@ -2280,7 +2281,7 @@ struct ChatView: View { if ci.content.msgContent != nil && (ci.meta.itemDeleted == nil || revealed) && ci.reactions.count > 0 { chatItemReactions(ci) .padding(.leading, terminal ? chatItemTextPadding - 6 : 0) - .padding(.bottom, 4) + .padding(.bottom, terminal ? 0 : 4) } } .coordinateSpace(name: swipeExclusionSpace) diff --git a/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift b/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift index dd61bddad3..477dd31093 100644 --- a/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift +++ b/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift @@ -393,10 +393,10 @@ struct ChatThemePreview: View { .opacity(terminal ? 0 : 1) .accessibilityHidden(terminal) VStack(spacing: 0) { - TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "alice"), own: false), gutter: 0, topGap: terminalRowGap(alice, nil, separated: false, largeGap: true, hasSenderRow: true), senderTopGap: 0) { + TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "alice"), own: false), gutter: 0, topGap: terminalRowGap(alice, nil, separated: false, largeGap: true, hasSenderRow: true), contentStartsWithCard: terminalItemStartsWithCard(alice, revealed: true)) { ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: alice, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)) } - TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "bob"), own: true), gutter: 0, topGap: terminalRowGap(bob, alice, separated: false, largeGap: true, hasSenderRow: true)) { + TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "bob"), own: true), gutter: 0, topGap: terminalRowGap(bob, alice, separated: false, largeGap: true, hasSenderRow: true), contentStartsWithCard: terminalItemStartsWithCard(bob, revealed: true)) { ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: bob, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)) } } diff --git a/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-dark-large.png b/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-dark-large.png index 993a991674..80e5e9d738 100644 Binary files a/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-dark-large.png and b/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-light-large.png b/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-light-large.png index 47320f9cd7..444d21de0e 100644 Binary files a/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-light-large.png and b/apps/ios/SimpleX Snapshots/References/ClassicOverviewDirect-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-accessibility-medium.png index 89396def56..c07e9484f2 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-extra-extra-extra-large.png index 37341aaf65..4afea6042d 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-large.png index 77979bb5b8..0824e4963e 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-accessibility-medium.png index d83a8e2065..db203a2cd5 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-extra-extra-extra-large.png index 2b5cff2bdd..30fe017b8c 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-large.png index bfd14772b1..14483755aa 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalAvatars-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalMedia-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalMedia-dark-large.png index 081cc78a7f..e3183dc890 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalMedia-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalMedia-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalMedia-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalMedia-light-large.png index 8923342079..f128a8ed9e 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalMedia-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalMedia-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-accessibility-medium.png index 8a25677c37..89d29058ce 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-extra-extra-extra-large.png index df3faaed20..3ec1e9ad58 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-large.png index 760f2455db..8f28746bdd 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-accessibility-medium.png index 417e0bd111..adcd3c9fbf 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-extra-extra-extra-large.png index 339153a82c..eb57380f86 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-large.png index 841b1116d1..31d64a824f 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalNames-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalNames-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-dark-large.png index 7af9328996..c520d95210 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-light-large.png index 0cdbe015a6..505fc05cbc 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewChannel-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-dark-large.png index 5b3676e5bb..6e5d4818f4 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-light-large.png index 1afbe1bee3..a4ed97a815 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewDirect-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-dark-large.png index 6033f996b2..d56a88cfe7 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-light-large.png index 3902b4c50c..0e005f5c1a 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalOverviewGroup-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-accessibility-medium.png index bacb74027f..23284c5a5b 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-extra-extra-extra-large.png index 590b37c648..0762dd64cb 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-large.png index a54551f56d..17671ebc6b 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-accessibility-medium.png index a2df39f183..6de4ced9ea 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-extra-extra-extra-large.png index 21f4233f54..c8bc9f351d 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-large.png index 0ae8957367..232ed88f5e 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalQuoteThumbnail-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-accessibility-medium.png index 835daeb62a..2a044de254 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-extra-extra-extra-large.png index 0912c3f0e4..4393879234 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-large.png index 362ed36b70..f2d6692373 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-accessibility-medium.png index 48be4456d1..ac88fc4c67 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-accessibility-medium.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-extra-extra-extra-large.png index a17e3f1ade..78ee84d799 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-extra-extra-extra-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-large.png index ab85ccd88f..4b5c9c08e8 100644 Binary files a/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-large.png and b/apps/ios/SimpleX Snapshots/References/TerminalRuleOnly-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-accessibility-medium.png new file mode 100644 index 0000000000..d42188c3fa Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-extra-extra-extra-large.png new file mode 100644 index 0000000000..741f5d8d7e Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-large.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-large.png new file mode 100644 index 0000000000..475c1212ed Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-accessibility-medium.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-accessibility-medium.png new file mode 100644 index 0000000000..e033864131 Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-accessibility-medium.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-extra-extra-extra-large.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-extra-extra-extra-large.png new file mode 100644 index 0000000000..0f801c6375 Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-extra-extra-extra-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-large.png b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-large.png new file mode 100644 index 0000000000..bfcb1321c5 Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/TerminalSpacing-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/SnapshotTests.swift b/apps/ios/SimpleX Snapshots/SnapshotTests.swift index db91c961ce..140c05d05a 100644 --- a/apps/ios/SimpleX Snapshots/SnapshotTests.swift +++ b/apps/ios/SimpleX Snapshots/SnapshotTests.swift @@ -137,6 +137,29 @@ final class SnapshotTests: XCTestCase { window.isHidden = true window.rootViewController = nil } + + @MainActor + func testTerminalSpacing() { + let items = SnapshotFixtures().spacingItems() + let p = terminalParagraphGap + let rows = zip(items.dropFirst(), items).map { item, older in + let sender = terminalItemShowsSender(item, older) + let largeGap = !item.chatDir.sameDirection(older.chatDir) || item.meta.itemTs.timeIntervalSince(older.meta.itemTs) > 60 + return (sender: sender, gap: terminalRowGap(item, older, separated: false, largeGap: largeGap, hasSenderRow: sender), card: terminalItemStartsWithCard(item, revealed: true)) + } + XCTAssertEqual(items.map(\.isOneLine), [false, true, true, true, true, true, true, false, true, true, false, true, false, false]) + XCTAssertEqual(rows.map { $0.sender }, [true, true, false, false, true, false, true, false, true, true, true, false, true]) + XCTAssertEqual(rows.map { $0.gap }, [p, p, 0, p, p, 0, p, p, p, p, p, p, p]) + XCTAssertEqual(rows.map { $0.card }, [false, false, false, false, false, false, false, false, false, true, true, true, false]) + XCTAssertEqual(items.suffix(2).map(terminalTextTopGap), [p, 0]) + let edges = SnapshotFixtures().spacingEdgeItems() + XCTAssertEqual(edges.map { terminalItemStartsWithCard($0, revealed: true) }, [true, false, true, true]) + XCTAssertEqual(edges.suffix(3).map(terminalTextTopGap), [0, 0, 0]) + var unreacted = items[3] + unreacted.reactions = [] + let rowHash = { (older: ChatItem) in ListItem(item: items[4], prevItem: items[5], nextItem: older, unreadBefore: 0).genHash(false, false) } + XCTAssertNotEqual(rowHash(items[3]), rowHash(unreacted)) + } } private func layoutCheckDir(_ env: [String: String]) -> URL { @@ -211,6 +234,7 @@ private func previewScenes() -> [SnapshotScene] { SnapshotScene(ClassicOverviewChannel_Previews.self), SnapshotScene(ClassicOverviewDirect_Previews.self), SnapshotScene(ClassicOverviewGroup_Previews.self), + SnapshotScene(ClassicParagraphs_Previews.self, allSizes: true), SnapshotScene(ComposeVoiceView_Previews.self), SnapshotScene(ConnectDesktopView_Previews.self, device: true), SnapshotScene(ContactConnectionInfo_Previews.self), @@ -294,6 +318,7 @@ private func previewScenes() -> [SnapshotScene] { SnapshotScene(TerminalOverviewGroup_Previews.self), SnapshotScene(TerminalQuoteThumbnail_Previews.self, allSizes: true), SnapshotScene(TerminalRuleOnly_Previews.self, allSizes: true), + SnapshotScene(TerminalSpacing_Previews.self, allSizes: true), SnapshotScene(UserAddressLearnMore_Previews.self), SnapshotScene(UserAddressView_Previews.self), SnapshotScene(UserPicker_Previews.self), @@ -410,6 +435,12 @@ struct TerminalRuleOnly_Previews: PreviewProvider { } } +struct TerminalSpacing_Previews: PreviewProvider { + static var previews: some View { + SnapshotFixtures().spacing() + } +} + struct TerminalAvatars_Previews: PreviewProvider { static var previews: some View { SnapshotFixtures().avatars(terminal: true) @@ -458,6 +489,12 @@ struct ClassicOverviewChannel_Previews: PreviewProvider { } } +struct ClassicParagraphs_Previews: PreviewProvider { + static var previews: some View { + SnapshotFixtures().paragraphs() + } +} + private struct ChatRows: View { @EnvironmentObject var theme: AppTheme let chat: Chat @@ -626,6 +663,77 @@ private final class SnapshotFixtures { .quote(content: SegmentRange(from: 11, to: 12)) ] ), + "### Gaps\n\none empty line above\n\n\ntwo empty lines above\n\n### After one empty line\n- list entry\n\n- after one empty line\n\n": ParsedMarkdown( + formattedText: [ + FormattedText(text: "### ", format: .markup(token: .headingMark(level: 3))), + FormattedText(text: "Gaps"), + FormattedText(text: "\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 2))), + FormattedText(text: "one empty line above"), + FormattedText(text: "\n\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 3))), + FormattedText(text: "two empty lines above"), + FormattedText(text: "\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 2))), + FormattedText(text: "### ", format: .markup(token: .headingMark(level: 3))), + FormattedText(text: "After one empty line"), + FormattedText(text: "\n", format: .markup(token: .lineBreak)), + FormattedText(text: "- ", format: .markup(token: .listMark(number: nil))), + FormattedText(text: "list entry"), + FormattedText(text: "\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 2))), + FormattedText(text: "- ", format: .markup(token: .listMark(number: nil))), + FormattedText(text: "after one empty line"), + FormattedText(text: "\n", format: .markup(token: .lineBreak)) + ], + markdownBlocks: [ + .heading(level: 3, content: SegmentRange(from: 1, to: 2)), + .paragraph(content: SegmentRange(from: 3, to: 4)), + .paragraph(content: SegmentRange(from: 5, to: 6)), + .heading(level: 3, content: SegmentRange(from: 8, to: 9)), + .list(items: [ + ListEntry(number: nil, content: SegmentRange(from: 11, to: 12), items: []), + ListEntry(number: nil, content: SegmentRange(from: 14, to: 15), items: []) + ]) + ] + ), + "first part\n\nafter one empty line\n\n\nafter two empty lines": ParsedMarkdown( + formattedText: [ + FormattedText(text: "first part"), + FormattedText(text: "\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 2))), + FormattedText(text: "after one empty line"), + FormattedText(text: "\n\n\n", format: .markup(token: .paragraphBreak(lineBreaks: 3))), + FormattedText(text: "after two empty lines") + ], + markdownBlocks: [ + .paragraph(content: SegmentRange(from: 0, to: 1)), + .paragraph(content: SegmentRange(from: 2, to: 3)), + .paragraph(content: SegmentRange(from: 4, to: 5)) + ] + ), + "\nlinks to a scam site": ParsedMarkdown( + formattedText: [ + FormattedText(text: "\n", format: .markup(token: .paragraphBreak(lineBreaks: 1))), + FormattedText(text: "links to a scam site") + ], + markdownBlocks: [ + .paragraph(content: SegmentRange(from: 1, to: 2)) + ] + ), + "\nafter an empty line": ParsedMarkdown( + formattedText: [ + FormattedText(text: "\n", format: .markup(token: .paragraphBreak(lineBreaks: 1))), + FormattedText(text: "after an empty line") + ], + markdownBlocks: [ + .paragraph(content: SegmentRange(from: 1, to: 2)) + ] + ), + " \nafter a line of spaces": ParsedMarkdown( + formattedText: [ + FormattedText(text: " \n", format: .markup(token: .paragraphBreak(lineBreaks: 1))), + FormattedText(text: "after a line of spaces") + ], + markdownBlocks: [ + .paragraph(content: SegmentRange(from: 1, to: 2)) + ] + ), "Plan for today:\n1. review\n2. **release**": ParsedMarkdown( formattedText: [ FormattedText(text: "Plan for today:"), @@ -666,6 +774,21 @@ private final class SnapshotFixtures { ListEntry(number: nil, content: SegmentRange(from: 7, to: 8), items: []) ]) ] + ), + "run this one first:\n```\nnpm run publish\n```": ParsedMarkdown( + formattedText: [ + FormattedText(text: "run this one first:"), + FormattedText(text: "\n", format: .markup(token: .lineBreak)), + FormattedText(text: "```", format: .markup(token: .fenceMark(language: nil))), + FormattedText(text: "\n", format: .markup(token: .hardBreak)), + FormattedText(text: "npm run publish"), + FormattedText(text: "\n", format: .markup(token: .hardBreak)), + FormattedText(text: "```", format: .markup(token: .fenceMark(language: nil))) + ], + markdownBlocks: [ + .paragraph(content: SegmentRange(from: 0, to: 1)), + .codeBlock(language: nil, content: SegmentRange(from: 4, to: 5)) + ] ) ] @@ -816,12 +939,54 @@ private final class SnapshotFixtures { ], terminal: terminal) } + func spacingItems() -> [ChatItem] { + [ + event(.groupRcv(groupMember: carol), .rcvGroupEvent(rcvGroupEvent: .memberConnected), -130), + msg(.groupRcv(groupMember: alice), "Welcome, carol!", -120), + msg(.groupRcv(groupMember: carol), "Thanks! Glad to be here", -118), + msg(.groupRcv(groupMember: carol), "ok", -118 + 20.0 / 60, reactions: [reaction(.heart, 2)]), + msg(.groupRcv(groupMember: carol), "one question", -118 + 40.0 / 60), + msg(.groupRcv(groupMember: bob), "I pushed the release build, please check it on your phones", -105), + msg(.groupRcv(groupMember: bob), "done", -104.5), + msg(.groupRcv(groupMember: alice), "first part\n\nafter one empty line\n\n\nafter two empty lines", -90), + msg(.groupRcv(groupMember: alice), "and one more thing", -89.5), + msg(.groupRcv(groupMember: alice), "after a pause of eight minutes", -81.5), + msg(.groupRcv(groupMember: bob), "", -80, reactions: [reaction(.heart, 2)], content: .image(text: "", image: landscape), file: imageFile("view.jpg")), + msg(.groupSnd, "👍", -79), + msg(.groupSnd, "nice view", -78.5, quote: quote(.groupRcv(groupMember: bob), "", image: landscape)), + msg(.groupRcv(groupMember: carol), "run this one first:\n```\nnpm run publish\n```", -70, reactions: [reaction(.thumbsup, 1)]) + ] + } + + func spacing() -> some View { + chatRows(teamChat, spacingItems(), terminal: true) + } + + func paragraphs() -> some View { + let text = "first part\n\nafter one empty line\n\n\nafter two empty lines" + var oneText = msg(.directRcv, text, -9) + oneText.formattedText = nil + oneText.markdownBlocks = nil + return chatRows(direct, [msg(.directRcv, text, -10), oneText], terminal: false) + } + + func spacingEdgeItems() -> [ChatItem] { + let reported = quote(.groupRcv(groupMember: alice), "Welcome, carol!") + return [ + msg(.groupRcv(groupMember: bob), "👍", -10, content: .unknown(type: "sticker", text: "👍")), + msg(.groupSnd, "\nlinks to a scam site", -9, quote: reported, content: .report(text: "\nlinks to a scam site", reason: .spam)), + msg(.groupSnd, "\nafter an empty line", -8, quote: reported), + msg(.groupSnd, " \nafter a line of spaces", -7, quote: reported) + ] + } + func overviewDirect(terminal: Bool) -> ChatRows { chatRows(direct, [ event(.directRcv, .rcvChatFeature(feature: .voice, enabled: FeatureEnabled(forUser: true, forContact: true), param: nil), -120), msg(.directRcv, "Hi! Did you see the **new release**?", -60), msg(.directSnd, "Yes, *great* changes 🎉", -58, reactions: [reaction(.thumbsup, 1)]), msg(.directRcv, "# Release notes\n- terminal layout\n- `code` blocks\n\n> quoted line", -50), + msg(.directRcv, "### Gaps\n\none empty line above\n\n\ntwo empty lines above\n\n### After one empty line\n- list entry\n\n- after one empty line\n\n", -48), msg(.directSnd, "Thanks for the summary", -45, quote: quote(.directRcv, "Release notes")), msg(.directRcv, "", -40, content: .image(text: "", image: landscape), file: imageFile("photo.jpg")), msg(.directRcv, "", -35, content: .file(""), file: CIFile.getSample(fileId: id(), fileName: "report.pdf", fileSize: 245_760, filePath: nil, fileStatus: .rcvInvitation)), diff --git a/apps/ios/SimpleXChat/ChatTypes.swift b/apps/ios/SimpleXChat/ChatTypes.swift index cf4abebcb0..e43d1950d0 100644 --- a/apps/ios/SimpleXChat/ChatTypes.swift +++ b/apps/ios/SimpleXChat/ChatTypes.swift @@ -4203,19 +4203,31 @@ public struct ChatItem: Identifiable, Decodable, Hashable { } } + public var hasHeaderAboveQuote: Bool { + isReport || meta.itemDeleted != nil || meta.isLive + } + + public var hasQuoteOrHeader: Bool { + quotedItem != nil || meta.itemForwarded != nil || hasHeaderAboveQuote + } + public var textAtItemTop: Bool { let textContent = switch content.msgContent { case .text: true case .unknown: file == nil default: false } - return textContent && quotedItem == nil && meta.itemForwarded == nil && meta.itemDeleted == nil && !meta.isLive && !isReport + return textContent && !hasQuoteOrHeader } public var startsWithHeading: Bool { if case .heading = markdownBlocks?.first { true } else { false } } + public var isOneLine: Bool { + textAtItemTop && markdownBlocks == nil && !content.text.contains(where: \.isNewline) + } + public static func getSample (_ id: Int64, _ dir: CIDirection, _ ts: Date, _ text: String, _ status: CIStatus = .sndNew, quotedItem: CIQuote? = nil, file: CIFile? = nil, itemDeleted: CIDeleted? = nil, itemEdited: Bool = false, itemLive: Bool = false, deletable: Bool = true, editable: Bool = true) -> ChatItem { ChatItem( chatDir: dir, @@ -5911,6 +5923,13 @@ public enum MarkdownBlock: Decodable, Hashable { public var isHeading: Bool { if case .heading = self { true } else { false } } + + public var isCard: Bool { + switch self { + case .codeBlock, .table, .rule: true + case .paragraph, .heading, .quote, .list: false + } + } } public struct ListEntry: Decodable, Hashable { diff --git a/apps/ios/SimpleXChat/Notifications.swift b/apps/ios/SimpleXChat/Notifications.swift index be6245da7d..9eaf03306b 100644 --- a/apps/ios/SimpleXChat/Notifications.swift +++ b/apps/ios/SimpleXChat/Notifications.swift @@ -208,6 +208,9 @@ func hideSecrets(_ cItem: ChatItem, isChannel: Bool = false) -> String { default: res = res + ft.text } } + if case .report = cItem.content.msgContent { + return String.localizedStringWithFormat(NSLocalizedString("Report: %@", comment: "report in notification"), res) + } return res } else { let mc = cItem.content.msgContent diff --git a/apps/ios/product/views/chat.md b/apps/ios/product/views/chat.md index b62078fca0..0ca5c5ee00 100644 --- a/apps/ios/product/views/chat.md +++ b/apps/ios/product/views/chat.md @@ -120,7 +120,7 @@ For groups with member support enabled: ### Terminal Layout -A chat with the terminal layout shows messages as full-width rows without bubbles, starting at one edge for sent and received messages, with the sender's name above each group of messages and the time at the end of the last line. Groups and channels show the sender's avatar beside its name; other chats have no avatar column. The wallpaper is drawn as its colour without the image. +A chat with the terminal layout shows messages as full-width rows without bubbles, starting at one edge for sent and received messages, with the sender's name above each group of messages, again after a pause of 7.5 minutes, and the time at the end of the last line. Groups and channels show the sender's avatar beside its name; other chats have no avatar column. The wallpaper is drawn as its colour without the image. A chat uses the user's choice for that chat, otherwise the layout set by the group owner or by the address the contact came from, otherwise the user's choice for the profile and then the app setting, otherwise classic. The choice for a chat is made in its theme screen; the choices for the app and the profile are made in Settings › Appearance. diff --git a/apps/ios/spec/client/chat-view.md b/apps/ios/spec/client/chat-view.md index 38230ce93c..c9a35df974 100644 --- a/apps/ios/spec/client/chat-view.md +++ b/apps/ios/spec/client/chat-view.md @@ -190,7 +190,7 @@ Renders emoji-only messages (messages containing only emoji characters) in a lar **File**: [`Shared/Views/Chat/ChatItem/MsgContentView.swift`](../../Shared/Views/Chat/ChatItem/MsgContentView.swift) -Renders message text with SimpleX markdown formatting (bold, italic, code, links, mentions). Blocks of `markdownBlocks` (headings, lists, quotes, code blocks, tables, rules) are drawn as a column of views by `MarkdownBlocksView`; code blocks and tables scroll sideways. +Renders message text with SimpleX markdown formatting (bold, italic, code, links, mentions). Blocks of `markdownBlocks` (paragraphs, headings, lists, quotes, code blocks, tables, rules) are drawn as a column of views by `MarkdownBlocksView`; code blocks and tables scroll sideways. The core sends `markdownBlocks` for text with block syntax or an empty line, up to 2000 markup tokens. In bubbles, each empty line is one line of the font, in a gap of zero width: the bubble is as wide as its widest block. Text colour: `textColor`, else `messageTextColor(theme)`: `onSurface`, at 95% in dark themes. `FramedItemView` passes `onSurface` for quote text (terminal rows: 70%). `MarkdownView` (chat item info, group welcome message, profile description) draws its text in `messageTextColor(theme)`. @@ -352,17 +352,20 @@ unknown values skipped ### Rows -[`ChatItemWithMenu.terminalItemRow`](../../Shared/Views/Chat/ChatView.swift#L2149) wraps `chatItemWithMenu` in [`TerminalChatItemRow`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L346): +[`ChatItemWithMenu.terminalItemRow`](../../Shared/Views/Chat/ChatView.swift#L2149) wraps `chatItemWithMenu` in [`TerminalChatItemRow`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L384). Gaps follow the paragraph unit `terminalParagraphGap` (user, terminal spacing mockup): ``` -row padding top: topGap, plus terminalSenderTopGap with a sender row +row padding top: topGap gutter groups and channels: memberImageSize + chatItemTextPadding, with the sender avatar chatItemTextPadding from the start; other chats: none one 12pt padding (user, I26): screen edge to the text or the avatar, avatar to the text, time to the screen edge avatar memberImageSize: scaledMemberImageSize, 34pt × chat list profileImageSize ÷ 63 (dynamicSize at the text size, at most 75); classic rows too + top-aligned with the name classic group bubbles: maximum width less the avatar column, scaledMemberImageSize + 8pt classic sender name: memberImageSize + 10pt after the avatar's start, on the bubble edge (user, I23) -sender row name and badge at terminalNameSize, 13.5 × 17/16 pt (primary for own items, secondary otherwise); role label 15pt after the name - start padding chatItemTextPadding; terminalSenderBottomGap below +sender row name and badge in the body text style, semibold (primary for own items, secondary otherwise) + role label in the body text style, medium, secondary, 15pt after the name; line box of the body font + start padding chatItemTextPadding; below: terminalParagraphGap when the content starts with a card + (contentStartsWithCard: terminalItemStartsWithCard), otherwise 0 selection SelectedChatItem 8pt from the start; row moved by 28pt; selected row tint primary 10% media width classic maxWidth, at most listWidth less the selection offset, the gutter and two text edges: media end at the time's end padding bottom padding newest row: 8pt; above a date separator: terminalLevelStep; otherwise 0 @@ -370,15 +373,21 @@ bottom padding newest row: 8pt; above a date separator: terminalLevelStep; o | Function | Rule | |----------|------| -| [`terminalItemShowsSender(item, older)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L125) | Item with a sender (`hasTerminalSender`), and the older item is absent, has no sender or has another sender. Same sender: channel as sender on both items, or `CIDirection.sameDirection` when neither item has it | -| [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L137) | `terminalLevelStep` when the older item exists, the rows are not separated, and one holds: large gap, sender row, either item without a sender, text at the item top starting with a heading. Otherwise 0 | -| [`terminalHeadingGap(item)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L144) | `terminalLevelStep` above a heading that starts the text below a quote, header or block | -| [`terminalRowsSeparated(olderRow)`](../../Shared/Views/Chat/ChatView.swift#L2179) | The newest item of the older row is the chat banner, or its `getItemSeparation` has a date (against its newer item only for single and revealed rows) | -| [`chatItemSender(ci, range)`](../../Shared/Views/Chat/ChatView.swift#L2186) | Channel as sender: group name, role "channel", group image. Received direct: contact name and badge. Group member: `memberNames`, badge and role of a single member, member image (tap: member info). Own group items: membership name, badge, role, image. Other own items: user name and badge, or "Incognito" | +| [`terminalItemShowsSender(item, older)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L118) | Item with a sender (`hasTerminalSender`), and the older item is absent, has no sender, has another sender, or is `terminalNameRepeatInterval` (7.5 minutes) or more older. Same sender: channel as sender on both items, or `CIDirection.sameDirection` when neither item has it | +| [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L130) | `terminalParagraphGap` when the older item exists, the rows are not separated, and one holds: large gap (`getItemSeparation`: another sender, or more than 60 seconds apart), sender row, either item not one-line, the older item has reactions. Otherwise 0 | +| `ChatItem.isOneLine` | Text at the item top (`textAtItemTop`: text content without a quote or header, `hasQuoteOrHeader`), no block markdown, no line break in the text; a large emoji is one-line; reactions do not count. Items without a sender (events) are not one-line | +| [`terminalItemStartsWithCard(item, revealed)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L137) | The first element of the item is a card: a marked deleted item drawn as a card; a quote without a report, deleted or live header above it (`hasHeaderAboveQuote`). Without a quote or header: content other than a message, except calls (deleted, error and group invitation cards, invalid data); media (`terminalMediaCard`: image, video, voice, file, link preview, chat link); text starting with a code block, table or rule (`MarkdownBlock.isCard`); a large emoji (text content, or `FramedItemView.showsEmoji`) | +| [`terminalCardTopGap(item)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L150) | `terminalParagraphGap` above media, voice, file and emoji when a quote or header is above them (`hasQuoteOrHeader`), otherwise 0 | +| [`terminalCardBottomGap(item)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L154) | `terminalParagraphGap` below a card that ends the item when reactions follow, otherwise 0 | +| [`terminalTextTopGap(item)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L158) | Above the text of `FramedItemView`: 0 at the item top; `terminalParagraphGap` below a quote or media, or when the text starts with a code block, table or rule (0 when the text starts with empty lines, which are at least as high: `startsWithEmptyLine`; block markdown: `leadingEmptyLines`; other text: a line break at its start, except in reports, whose reason is drawn first); `terminalLevelStep` below a header when the text starts with a heading; otherwise 0 | +| [`terminalRowsSeparated(olderRow)`](../../Shared/Views/Chat/ChatView.swift#L2180) | The newest item of the older row is the chat banner, or its `getItemSeparation` has a date (against its newer item only for single and revealed rows) | +| [`chatItemSender(ci, range)`](../../Shared/Views/Chat/ChatView.swift#L2187) | Channel as sender: group name, role "channel", group image. Received direct: contact name and badge. Group member: `memberNames`, badge and role of a single member, member image (tap: member info). Own group items: membership name, badge, role, image. Other own items: user name and badge, or "Incognito" | | `CIContent.hasTerminalSender` | Sent messages, deleted and moderated items, calls and group invitations; received content with `showMemberName` | `ChatView` passes `olderRow`, the next merged item. `MergedItem.revealed`: true for `.single`, the flag of `.grouped`. +A visible cell is rebuilt when the hash of its merged item changes ([`ListItem.genHash`](../../Shared/Views/Chat/ChatItemsMerger.swift#L284)). The hash of a single item includes whether the older item (`nextItem`) has reactions and whether it is one-line, so the cell is rebuilt, and `terminalRowGap` computed again, when the first reaction is added to the older item, its last reaction is removed, or an edit adds or removes its line break or block markdown. The gap of a grouped row does not depend on the older item's reactions or lines: its newest item is a deleted item or an event (`mergeCategory`), which is not one-line. + ### Items `chatItemWithMenu`: @@ -388,7 +397,9 @@ alignment start for both directions (alignEnd = sent && !terminal); max clip ChatItemClipped skipped; its tail disabled in terminal rows go-to button search results and marked deleted items: after the item forwarded items: endButton of FramedItemView, placed by ItemWithMeta -reactions chatItemTextPadding − 6pt from the start +reactions chatItemTextPadding − 6pt from the start; no spacing above or below, as a line of text + (classic: 3pt above, 4pt below); below a card that ends the item: terminalCardBottomGap of the card + the next row: terminalParagraphGap above it (terminalRowGap) ``` Item views start at the text edge `chatItemTextPadding` (12pt): @@ -396,7 +407,8 @@ Item views start at the text edge `chatItemTextPadding` (12pt): ``` FramedItemView background, quote background and header backgrounds omitted headers: terminalHeaderTopGap above, terminalHeaderBottomGap below - quote: quoteBar(), text onSurface 70%, terminalBlockTopGap above, terminalBlockBottomGap below + quote: quoteBar(), text onSurface 70%; above: terminalParagraphGap below a report, deleted or live + header (hasHeaderAboveQuote), otherwise 0; below: none, the content below it has the gap quote sender: terminalNameSize (13.5 × 17/16 pt, Dynamic Type), no spacing above the text quote thumbnail: 12pt after the quote text; a quote without text and sender: 12pt after the bar (quotedMsgOrGap) quote thumbnail end padding: chatItemTextPadding, as the time's @@ -404,23 +416,35 @@ FramedItemView background, quote background and header backgrounds omitte link preview and chat link cards: quote colour, message corner clip (terminalBlock) link preview card: at most maxWidth wide media width limit for captionless media only (mediaLimit) - captionless media, chat link without text: terminalBlockBottomGap below (metaPlacement) -MsgContentView line box terminalLineBox; meta line for live messages only + media, voice, file and emoji: terminalCardTopGap above + captionless media, chat link without text, voice and file without text (metaPlacement.gapBelowBlock), + emoji: terminalCardBottomGap below + text: terminalTextTopGap above +MsgContentView line box terminalLineBox; meta line for live messages, and in the line box after empty lines at the text end text ends with the transparent copy of the meta (reserveSpaceForMeta) -MarkdownBlocksView paragraph break, heading after another block: terminalLevelStep + text without markdownBlocks (over 2000 markup tokens) keeps one full line per empty line +MarkdownBlocksView code block, table or rule next to another block (MarkdownBlock.isCard): terminalParagraphGap, + or the typed empty lines when they are higher + heading after another block: terminalLevelStep block other than a heading after a heading: terminalHeadingBottomGap + each empty line typed before or between blocks and list entries: terminalParagraphGap added + empty lines after the last block: line breaks of the tokens after it, less one when the text does not end + with a line break (the core removes one final line break); terminalParagraphGap each, then the meta line + at most maxEmptyLines (100) empty lines in one gap (emptyLines) heading size: body × 1.25^max(0, 3 − level), bold (terminalHeadingFont); classic chat items too (chatHeadings, user) item info, welcome message and profile description: body × 1.5, 1.3, 1.15 for levels 1–3 (headingFont) - code, tables and rules: terminalBlockTopGap above, terminalBlockBottomGap below (cardMargins) - last block of a message that is not live: no bottom margin, MessageLastBlock + code, tables and rules (cardMargins): last block of a live message: terminalParagraphGap below, + above the typing line; otherwise no margins + last block of a message that is not live, without empty lines after it: MessageLastBlock rules of a rule-only message: as wide as the copy of the meta, or the item less its text edges when a quote or header is wider (ruleMinWidth: msgWidth less 24pt; terminalQuote reports its full width) -emoji EmojiItemView and FramedItemView: terminalEmojiTopGap, terminalEmojiBottomGap, MessageLastLine -voice CIVoiceView: received layout for both directions, terminalGap(4) above, terminalGap(6) below - FramedCIVoiceView: terminalGap(4) above, terminalGap(6) below, player background +emoji EmojiItemView: 0 above, terminalCardBottomGap below; MessageLastLine + FramedItemView: terminalCardTopGap above, terminalCardBottomGap below; MessageLastLine +voice CIVoiceView: received layout for both directions, 0 above, terminalCardBottomGap below + FramedCIVoiceView: terminalCardTopGap above, 0 below, player background VoiceMessagePlayer circle in the quote colour (chatItemFrameContextColor); classic: the bubble colour -files CIFileView: terminalFileTopGap above, icon without top padding -events terminalEventPadding, line box, line limit removed +files CIFileView: 0 above, icon without top padding; FramedItemView: terminalCardTopGap above +events terminalEventPadding: chatItemTextPadding at the sides, 0 above and below; line box, line limit removed feature and preference icons without height; merged feature icons one event line high cards DeletedItemView, MarkedDeletedItemView, CIMsgError, CIRcvDecryptionError, CIGroupInvitationView: ChatItemClipped(tailVisible: false), time beside the card @@ -428,16 +452,16 @@ cards DeletedItemView, MarkedDeletedItemView, CIMsgError, CIRcvD ### Time and Status -[`ItemWithMeta(showMeta, metaReserved, overlayMeta, endButton, meta, content)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L178): +[`ItemWithMeta(showMeta, metaReserved, overlayMeta, endButton, lastBlockGap, meta, content)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L216): ``` classic content(meta()): the meta drawn inside the item, as before terminal content(nil); the meta in a box with 12pt end padding and the caption line box iOS 16 TerminalMetaLayout -iOS 15 HStack(alignment: .lastTextBaseline): content, end button, meta +iOS 15 HStack(alignment: .lastTextBaseline): content, end button, meta; lastBlockGap not applied ``` -[`TerminalMetaLayout`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L234): +[`TerminalMetaLayout`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L273): ``` content width row width less the wider of: the end button; the meta, without metaReserved and overlayMeta @@ -445,7 +469,8 @@ meta baseline on the last text baseline of the content meta below content reports MessageLastLine.right and its right edge plus the meta width exceeds the row: terminalMetaGap under the content no baseline meta ends terminalMetaGap above the content bottom -last block MessageLastBlock.bottom at the content bottom, meta beside it: terminalBlockBottomGap below the content +last block MessageLastBlock.bottom at the content bottom, meta beside it: lastBlockGap below the content + (FramedItemView: terminalCardBottomGap) overlayMeta content and meta wider than the row: white meta over the media corner, terminalMetaGap above its bottom end button row end, centred between the content top and the meta top (overlayMeta: on the content) row height at least the meta height @@ -453,7 +478,7 @@ row height at least the meta height `metaReserved`: content with its own reserve for the time: text with the copy, files, emoji, events. -[`ChatEventWithMeta(chatItem) { ts in }`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L311) passes the end of the event text, placed after the classic separator: classic `chatItem.timestampText`; terminal `metaCopyJoiner`, two no-break spaces and the transparent unbreakable time in regular weight. +[`ChatEventWithMeta(chatItem) { ts in }`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L351) passes the end of the event text, placed after the classic separator: classic `chatItem.timestampText`; terminal `metaCopyJoiner`, two no-break spaces and the transparent unbreakable time in regular weight. Meta copy, `ciMetaText(unbreakable: true)`: @@ -470,23 +495,17 @@ content file encryption and signature included (MsgContentView encryp Constants at the top of `TerminalItemView.swift`: the Kotlin values in sp at its 16sp body, converted by `terminalGap`, value × body point size ÷ 16 (17pt body by default; Dynamic Type included): ``` -terminalBlockTopGap 5.75 -terminalBlockBottomGap 5 +terminalParagraphGap 7.33 ⅓ of the line height at the 16sp body: 16 × 22/16 ÷ 3 terminalLevelStep 4.75 terminalHeadingBottomGap 2.375 -terminalSenderTopGap 6.5 -terminalSenderBottomGap 5.5 terminalHeaderTopGap 2.5 terminalHeaderBottomGap 1.5 -terminalEventTopGap 8.25 -terminalEventBottomGap 1.5 -terminalFileTopGap 2 -terminalEmojiTopGap 4.25 -terminalEmojiBottomGap 1.5 terminalMetaGap 6 ``` -[`terminalLineBox(font, color, theme, capsOf:)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L65), a `TerminalLineBox` view modifier: +`terminalNameRepeatInterval`: 7.5 minutes; after this pause the name is shown again (`terminalItemShowsSender`). + +[`terminalLineBox(font, color, theme, capsOf:)`](../../Shared/Views/Chat/ChatItem/TerminalItemView.swift#L58), a `TerminalLineBox` view modifier: ``` line height font size × 22/16 × f(w) @@ -507,7 +526,8 @@ taps handleTextTaps lays the text out with the same lineSpacing (w | Chat theme | `activeChatLayout(profileChatLayout(currentUser))` of the chat | ``` -ChatThemePreview two TerminalChatItemRow rows: "alice", then "bob" as own; both layouts in one ZStack, one height +ChatThemePreview two TerminalChatItemRow rows: "alice", then "bob" as own, with the gaps of terminalRowGap and + terminalItemStartsWithCard; both layouts in one ZStack, one height background wallpaper background colour, image omitted; preset tiles drawn as colours WallpaperPresetSelector custom image tile hidden WallpaperSetupView image scale type, scale slider and wallpaper tint hidden diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/platform/NtfManager.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/platform/NtfManager.kt index 290d93db71..a4ed1afa00 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/platform/NtfManager.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/platform/NtfManager.kt @@ -143,7 +143,7 @@ abstract class NtfManager { else -> ft.text } } - res + if (cItem.content.msgContent is MsgContent.MCReport) generalGetString(MR.strings.notification_group_report).format(res) else res } else { val mc = cItem.content.msgContent if (mc is MsgContent.MCReport) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt index f4a8f3f182..b8a014cac2 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt @@ -4032,6 +4032,12 @@ fun PreviewGroupChatLayout() = BubblePreview { } } +@Preview +@Composable +fun PreviewGroupChatLayoutTerminal() = CompositionLocalProvider(LocalTerminalLayout provides true) { + PreviewGroupChatLayout() +} + enum class ContentFilter( val contentTag: MsgContentTag, val label: StringResource, diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt index be565843c5..ef0399d806 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt @@ -11,7 +11,6 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import chat.simplex.common.model.ChatItem import chat.simplex.common.ui.theme.* -import chat.simplex.common.views.helpers.toDp @Composable fun CIEventView(text: AnnotatedString) { @@ -24,7 +23,7 @@ fun chatEventTextStyle(base: TextStyle = LocalTextStyle.current): TextStyle = @Composable fun chatEventPadding(): PaddingValues = - if (LocalTerminalLayout.current) PaddingValues(start = CHAT_ITEM_TEXT_PADDING, top = TERMINAL_EVENT_TOP_GAP.toDp(), end = CHAT_ITEM_TEXT_PADDING, bottom = TERMINAL_EVENT_BOTTOM_GAP.toDp()) + if (LocalTerminalLayout.current) PaddingValues(horizontal = CHAT_ITEM_TEXT_PADDING) else PaddingValues(horizontal = 6.dp, vertical = 6.dp) @Composable diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt index b455a57b70..1aac4a960a 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt @@ -39,6 +39,7 @@ fun CIFileView( showTimestamp: Boolean, showMenu: MutableState, smallView: Boolean = false, + terminalTop: Dp = 0.dp, receiveFile: (Long) -> Unit ) { val saveFileLauncher = rememberSaveFileLauncher(ciFile = file) @@ -211,7 +212,7 @@ fun CIFileView( .then( when { smallView -> Modifier - terminal -> Modifier.padding(top = TERMINAL_FILE_TOP_GAP.toDp(), start = 6.sp.toDp(), end = 12.sp.toDp()) + terminal -> Modifier.padding(top = terminalTop, start = 6.sp.toDp(), end = 12.sp.toDp()).messageCard() else -> Modifier.padding(top = 4.sp.toDp(), start = 6.sp.toDp(), end = 12.sp.toDp()).paddingFromBaseline(bottom = BUBBLE_TEXT_INSET) } ), diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIGroupInvitationView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIGroupInvitationView.kt index 8d20378159..8cb6910da8 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIGroupInvitationView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIGroupInvitationView.kt @@ -97,6 +97,7 @@ fun CIGroupInvitationView( ) { Box( Modifier + .messageCard() .width(IntrinsicSize.Min) .padding(start = 8.dp, end = 12.dp, top = 8.dp, bottom = 4.dp), contentAlignment = Alignment.BottomEnd diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIRcvDecryptionError.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIRcvDecryptionError.kt index d10aa3a407..0feba2032a 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIRcvDecryptionError.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIRcvDecryptionError.kt @@ -210,7 +210,7 @@ private fun DecryptionErrorCard(onClick: () -> Unit, inlineMeta: (@Composable () } } } else { - Surface(Modifier.clickable(onClick = onClick), shape = RoundedCornerShape(18.dp), color = receivedColor, contentColor = LocalContentColor.current) { + Surface(Modifier.clickable(onClick = onClick).messageCard(), shape = RoundedCornerShape(18.dp), color = receivedColor, contentColor = LocalContentColor.current) { Box(Modifier.padding(vertical = 6.dp, horizontal = 12.dp), contentAlignment = Alignment.BottomEnd) { content() } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIVoiceView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIVoiceView.kt index 3de61ab8ae..28abbbb53c 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIVoiceView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIVoiceView.kt @@ -48,7 +48,8 @@ fun CIVoiceView( val padding = when { smallView -> PaddingValues() classicWithText -> PaddingValues(top = 14.sp.toDp() * sizeMultiplier, bottom = 14.sp.toDp() * sizeMultiplier, start = 6.sp.toDp() * sizeMultiplier, end = 6.sp.toDp() * sizeMultiplier) - else -> PaddingValues(top = 4.sp.toDp() * sizeMultiplier, bottom = 6.sp.toDp() * sizeMultiplier, start = if (LocalTerminalLayout.current) CHAT_ITEM_TEXT_PADDING else 0.dp, end = 0.dp) + LocalTerminalLayout.current -> PaddingValues(start = CHAT_ITEM_TEXT_PADDING, top = terminalCardTop(ci).toDp()) + else -> PaddingValues(top = 4.sp.toDp() * sizeMultiplier, bottom = 6.sp.toDp() * sizeMultiplier) } Row( Modifier.padding(padding), @@ -212,7 +213,7 @@ private fun VoiceLayout( else -> { @Composable fun VoiceRow(inlineMeta: (@Composable () -> Unit)?) { - Column(horizontalAlignment = Alignment.Start) { + Column(Modifier.messageCard(), horizontalAlignment = Alignment.Start) { Row { VoiceMsgIndicator(file, audioPlaying.value, sent, false, progress, duration, brokenAudio, 1f, play, pause, longClick, receiveFile) Row(Modifier.weight(1f, false), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) { @@ -228,7 +229,7 @@ private fun VoiceLayout( } } } - if (hasText) VoiceRow(null) else ItemWithMeta(meta = { CIMetaView(ci, timedMessagesTTL, showViaProxy = showViaProxy, showTimestamp = showTimestamp) }) { VoiceRow(it) } + if (hasText) VoiceRow(null) else ItemWithMeta(meta = { CIMetaView(ci, timedMessagesTTL, showViaProxy = showViaProxy, showTimestamp = showTimestamp) }, gapBelowCard = terminalReactionsGap(ci).toDp()) { VoiceRow(it) } } } } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt index 916605917f..e39560a773 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt @@ -1559,6 +1559,44 @@ fun PreviewChatItemView( ) } +@Preview +@Composable +fun PreviewChatItemViewEmptyLines() = PreviewChatItemView( + ChatItem.getSampleData(1, CIDirection.DirectSnd(), previewDate, "### Gaps\n\none empty line above\n\n\ntwo empty lines above\n\n### After one empty line\n- list entry\n\n- after one empty line\n\n").copy( + formattedText = listOf( + FormattedText("### ", Format.Markup(BlockToken.HeadingMark(3))), + FormattedText("Gaps"), + FormattedText("\n\n", Format.Markup(BlockToken.ParagraphBreak(2))), + FormattedText("one empty line above"), + FormattedText("\n\n\n", Format.Markup(BlockToken.ParagraphBreak(3))), + FormattedText("two empty lines above"), + FormattedText("\n\n", Format.Markup(BlockToken.ParagraphBreak(2))), + FormattedText("### ", Format.Markup(BlockToken.HeadingMark(3))), + FormattedText("After one empty line"), + FormattedText("\n", Format.Markup(BlockToken.LineBreak())), + FormattedText("- ", Format.Markup(BlockToken.ListMark())), + FormattedText("list entry"), + FormattedText("\n\n", Format.Markup(BlockToken.ParagraphBreak(2))), + FormattedText("- ", Format.Markup(BlockToken.ListMark())), + FormattedText("after one empty line"), + FormattedText("\n", Format.Markup(BlockToken.LineBreak())) + ), + markdownBlocks = listOf( + MarkdownBlock.Heading(3, SegmentRange(1, 2)), + MarkdownBlock.Paragraph(SegmentRange(3, 4)), + MarkdownBlock.Paragraph(SegmentRange(5, 6)), + MarkdownBlock.Heading(3, SegmentRange(8, 9)), + MarkdownBlock.ItemList(listOf(ListEntry(content = SegmentRange(11, 12), items = listOf()), ListEntry(content = SegmentRange(14, 15), items = listOf()))) + ) + ) +) + +@Preview +@Composable +fun PreviewChatItemViewEmptyLinesTerminal() = CompositionLocalProvider(LocalTerminalLayout provides true) { + PreviewChatItemViewEmptyLines() +} + @Preview @Composable fun PreviewChatItemViewDeletedContent() = BubblePreview { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt index 261e4eb3b3..b1cbb69f02 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt @@ -44,7 +44,7 @@ fun ItemTextCard(ci: ChatItem, firstLineFontSize: TextUnit, inlineMeta: (@Compos } } } else { - Surface(modifier, shape = RoundedCornerShape(18.dp), color = color, contentColor = LocalContentColor.current) { + Surface(modifier.messageCard(), shape = RoundedCornerShape(18.dp), color = color, contentColor = LocalContentColor.current) { Row(Modifier.padding(horizontal = 12.dp, vertical = 6.dp)) { text() } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/EmojiItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/EmojiItemView.kt index 4b8633c4b3..82d3bb3946 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/EmojiItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/EmojiItemView.kt @@ -26,9 +26,9 @@ fun EmojiItemView(chatItem: ChatItem, timedMessagesTTL: Int?, showViaProxy: Bool val emojiText = chatItem.content.text.trim() val isSelected = setupEmojiSelection(LocalSelectionManager.current, LocalItemContext.current.selectionIndex, emojiText.length) - ItemWithMeta(meta = { CIMetaView(chatItem, timedMessagesTTL, showViaProxy = showViaProxy, showTimestamp = showTimestamp) }, metaReserved = true) { inlineMeta -> + ItemWithMeta(meta = { CIMetaView(chatItem, timedMessagesTTL, showViaProxy = showViaProxy, showTimestamp = showTimestamp) }, metaReserved = true, gapBelowCard = terminalReactionsGap(chatItem).toDp()) { inlineMeta -> Column( - if (LocalTerminalLayout.current) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = TERMINAL_EMOJI_TOP_GAP.toDp(), end = CHAT_ITEM_TEXT_PADDING, bottom = TERMINAL_EMOJI_BOTTOM_GAP.toDp()).messageLastLine() else Modifier.padding(vertical = 8.dp, horizontal = 12.dp), + if (LocalTerminalLayout.current) Modifier.padding(horizontal = CHAT_ITEM_TEXT_PADDING).messageCard().messageLastLine() else Modifier.padding(vertical = 8.dp, horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { if (isSelected) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt index 0123dabb3d..391c70c4c8 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt @@ -53,7 +53,8 @@ fun FramedItemView( val sent = ci.chatDir.sent val chatTTL = chatInfo.timedMessagesTTL val terminal = LocalTerminalLayout.current - val mediaModifier = if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = TERMINAL_BLOCK_TOP_GAP.toDp(), end = CHAT_ITEM_TEXT_PADDING).clipChatItem(ci, revealed = true) else Modifier + val cardTop = terminalCardTop(ci).toDp() + val mediaModifier = if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = cardTop, end = CHAT_ITEM_TEXT_PADDING).messageCard().clipChatItem(ci, revealed = true) else Modifier val quoteColor = if (sent) MaterialTheme.appColors.sentQuote else MaterialTheme.appColors.receivedQuote val cardModifier = mediaModifier.background(quoteColor) val thumbnailInset = if (terminal) Modifier.padding(end = CHAT_ITEM_TEXT_PADDING) else Modifier @@ -178,7 +179,7 @@ fun FramedItemView( val blurred = remember { mutableStateOf(appPreferences.privacyMediaBlurRadius.get() > 0) } Row( Modifier - .then(if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = TERMINAL_BLOCK_TOP_GAP.toDp(), bottom = TERMINAL_BLOCK_BOTTOM_GAP.toDp()).quoteBar(MaterialTheme.colors.onSurface) else Modifier.background(quoteColor)) + .then(if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = terminalQuoteTop(ci).toDp()).messageCard().quoteBar(MaterialTheme.colors.onSurface) else Modifier.background(quoteColor)) .fillMaxWidth() ) { when (qi.content) { @@ -236,9 +237,9 @@ fun FramedItemView( @Composable fun ciFileView(ci: ChatItem, text: String) { - CIFileView(ci.file, ci.meta, chatTTL, showViaProxy, showTimestamp, showMenu, false, receiveFile) + CIFileView(ci.file, ci.meta, chatTTL, showViaProxy, showTimestamp, showMenu, false, cardTop, receiveFile) if (text != "" || ci.meta.isLive) { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode = linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = 0.dp) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode = linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } @@ -248,16 +249,15 @@ fun FramedItemView( val sentColor = MaterialTheme.appColors.sentMessage val receivedColor = MaterialTheme.appColors.receivedMessage - val (metaReserved, gapBelowBlock) = when (val mc = ci.content.msgContent) { - is MsgContent.MCVoice -> (mc.text != "") to false - is MsgContent.MCChat -> (mc.text != mc.chatLink.connLinkStr).let { it to !it } - else -> !captionlessMedia to captionlessMedia + val metaReserved = when (val mc = ci.content.msgContent) { + is MsgContent.MCVoice -> mc.text != "" + is MsgContent.MCChat -> mc.text != mc.chatLink.connLinkStr + else -> !captionlessMedia } Box(Modifier .then( when { !terminal -> Modifier.clipChatItem(ci, tailVisible, revealed = true) - gapBelowBlock -> Modifier.padding(bottom = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) else -> Modifier } ) @@ -273,6 +273,7 @@ fun FramedItemView( meta = { CIMetaView(ci, chatTTL, metaColor, showViaProxy = showViaProxy, showTimestamp = showTimestamp) }, overlayMeta = if (captionlessMedia) { { Box(Modifier.padding(end = CHAT_ITEM_TEXT_PADDING)) { CIMetaView(ci, chatTTL, Color.White, showViaProxy = showViaProxy, showTimestamp = showTimestamp, lineHeightColor = messageTextColor()) } } } else null, metaReserved = metaReserved, + gapBelowCard = terminalReactionsGap(ci).toDp(), endButton = endButton ) { inlineMeta -> Box(contentAlignment = Alignment.BottomEnd) { @@ -379,7 +380,7 @@ fun FramedItemView( } } if (ci.file == null && ci.formattedText == null && !ci.meta.isLive && isShortEmoji(ci.content.text)) { - Box(if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = TERMINAL_EMOJI_TOP_GAP.toDp(), end = CHAT_ITEM_TEXT_PADDING, bottom = TERMINAL_EMOJI_BOTTOM_GAP.toDp()) else Modifier.padding(bubbleTextBoxPadding())) { + Box(if (terminal) Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, top = cardTop, end = CHAT_ITEM_TEXT_PADDING).messageCard() else Modifier.padding(bubbleTextBoxPadding())) { Column( if (terminal) Modifier.messageLastLine() else Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally @@ -404,7 +405,7 @@ fun FramedItemView( if (mc.text == "" && !ci.meta.isLive) { if (!terminal) metaColor = Color.White } else { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } is MsgContent.MCVideo -> { @@ -415,19 +416,19 @@ fun FramedItemView( if (mc.text == "" && !ci.meta.isLive) { if (!terminal) metaColor = Color.White } else { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } is MsgContent.MCVoice -> { CIVoiceView(mc.duration, ci.file, ci.meta.itemEdited, ci.chatDir.sent, hasText = true, ci, timedMessagesTTL = chatTTL, showViaProxy = showViaProxy, showTimestamp = showTimestamp, longClick = { onLinkLongClick("") }, receiveFile = receiveFile) if (mc.text != "") { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = 0.dp) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } is MsgContent.MCFile -> ciFileView(ci, mc.text) is MsgContent.MCUnknown -> if (ci.file == null) { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = 0.dp) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } else { ciFileView(ci, mc.text) } @@ -436,7 +437,7 @@ fun FramedItemView( ChatItemLinkView(mc.preview, showMenu, onLongClick = { showMenu.value = true }) } Box(if (terminal) Modifier else Modifier.widthIn(max = DEFAULT_MAX_IMAGE_WIDTH)) { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } is MsgContent.MCChat -> { @@ -452,7 +453,7 @@ fun FramedItemView( CIChatLinkHeader(chatLink = mc.chatLink, ownerSig = mc.ownerSig, hasText = hasText) } if (hasText) { - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, stripLink = mc.chatLink.connLinkStr, terminalTop = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, showViaProxy = showViaProxy, showTimestamp = showTimestamp, stripLink = mc.chatLink.connLinkStr) } } is MsgContent.MCReport -> { @@ -461,9 +462,9 @@ fun FramedItemView( append(itemPrefixText(ci)) } } - CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp, prefix = prefix, terminalTop = 0.dp) + CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp, prefix = prefix) } - else -> CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp, terminalTop = 0.dp) + else -> CIMarkdownText(chatsCtx, ci, chat, chatTTL, linkMode, uriHandler, onLinkLongClick, showViaProxy = showViaProxy, showTimestamp = showTimestamp) } } } @@ -496,8 +497,7 @@ fun CIMarkdownText( showViaProxy: Boolean, showTimestamp: Boolean, prefix: AnnotatedString? = null, - stripLink: String? = null, - terminalTop: Dp + stripLink: String? = null ) { val chatInfo = chat.chatInfo val text = if (ci.meta.isLive) ci.content.msgContent?.text ?: ci.text else ci.text @@ -508,7 +508,7 @@ fun CIMarkdownText( Box( Modifier .padding( - if (terminal) PaddingValues(start = CHAT_ITEM_TEXT_PADDING, top = terminalTop + terminalHeadingGap(ci).toDp(), end = CHAT_ITEM_TEXT_PADDING) + if (terminal) PaddingValues(start = CHAT_ITEM_TEXT_PADDING, top = terminalTextTop(ci).toDp(), end = CHAT_ITEM_TEXT_PADDING) else bubbleTextBoxPadding() ) ) { diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt index 29752968cd..a630429917 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt @@ -59,6 +59,7 @@ import kotlin.math.roundToInt fun MarkdownBlocks( formattedText: List, blocks: List, + trailingEmptyLines: Int, style: TextStyle, modifier: Modifier, cardColor: Color, @@ -73,25 +74,34 @@ fun MarkdownBlocks( val fontSize = style.fontSize.takeOrElse { 16.sp } val lineHeight = style.lineHeight.takeOrElse { 22.sp } val chatTypography = usesChatTypography() + val terminal = LocalTerminalLayout.current val starts = remember(blocks) { blocks.runningFold(0) { n, b -> n + b.textRanges.size } } val lastIsText = when (blocks.lastOrNull()) { - is MarkdownBlock.Paragraph, is MarkdownBlock.Heading, is MarkdownBlock.Quote, is MarkdownBlock.ItemList -> true + is MarkdownBlock.Paragraph, is MarkdownBlock.Heading, is MarkdownBlock.Quote, is MarkdownBlock.ItemList -> trailingEmptyLines == 0 else -> false } @Composable fun BlockText(index: Int, range: SegmentRange, style: TextStyle, modifier: Modifier = Modifier, softWrap: Boolean = true) { blockText(index, range, style, modifier, softWrap, lastIsText && index == starts.last() - 1) } + val emptyLineHeight = if (terminal) TERMINAL_PARAGRAPH_GAP.toDp() else with(LocalDensity.current) { (fontSize.toPx() * lineHeight.value / fontSize.value).toDp() } + fun emptyLinesHeight(from: Int, to: Int, between: Boolean): Dp = emptyLineHeight * emptyLines(formattedText, from, to, between) Column(modifier) { + Spacer(Modifier.height(emptyLineHeight * leadingEmptyLines(formattedText, blocks))) blocks.forEachIndexed { k, block -> - if (k > 0 && chatTypography && blocks[k - 1] is MarkdownBlock.Heading && block !is MarkdownBlock.Heading) { - Spacer(Modifier.height(TERMINAL_HEADING_BOTTOM_GAP.toDp())) - } else if (k > 0 && (paragraphBreak(formattedText, blocks[k - 1].end, block.start) || chatTypography && block is MarkdownBlock.Heading)) { - Spacer(Modifier.height(if (chatTypography) TERMINAL_LEVEL_STEP.toDp() else with(LocalDensity.current) { (lineHeight.toPx() / 2).toDp() })) + val emptyHeight = if (k > 0) emptyLinesHeight(blocks[k - 1].end, block.start, between = true) else 0.dp + if (k > 0 && terminal && (block.isCard || blocks[k - 1].isCard)) { + Spacer(Modifier.height(maxOf(TERMINAL_PARAGRAPH_GAP.toDp(), emptyHeight))) + } else if (k > 0 && chatTypography && blocks[k - 1] is MarkdownBlock.Heading && block !is MarkdownBlock.Heading) { + Spacer(Modifier.height(TERMINAL_HEADING_BOTTOM_GAP.toDp() + emptyHeight)) + } else if (k > 0 && chatTypography && block is MarkdownBlock.Heading) { + Spacer(Modifier.height(TERMINAL_LEVEL_STEP.toDp() + emptyHeight)) + } else if (emptyHeight > 0.dp) { + Spacer(Modifier.height(emptyHeight)) } val start = starts[k] val marksLastBlock = k == blocks.lastIndex && metaLine == null - val cardMargins = if (!chatTypography) Modifier else if (marksLastBlock) Modifier.padding(top = TERMINAL_BLOCK_TOP_GAP.toDp()).messageLastBlock() else Modifier.padding(top = TERMINAL_BLOCK_TOP_GAP.toDp(), bottom = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) + val cardMargins = if (!chatTypography) Modifier else if (terminal) Modifier.messageCard().then(if (marksLastBlock) Modifier.messageLastLine() else Modifier) else Modifier.padding(top = TERMINAL_BLOCK_TOP_GAP.toDp(), bottom = TERMINAL_BLOCK_BOTTOM_GAP.toDp()) when (block) { is MarkdownBlock.Paragraph -> BlockText(start, block.content, style) is MarkdownBlock.Heading -> { @@ -110,11 +120,15 @@ fun MarkdownBlocks( val quoteColor = textColor.copy(alpha = 0.7f) BlockText(start, block.content, style.copy(color = quoteColor).merge(chatTextStyle(fontSize, quoteColor))) } - is MarkdownBlock.ItemList -> listEntries(block.items, 0).forEachIndexed { j, (entry, level) -> - Row(Modifier.padding(start = 20.dp * level)) { - Text(entry.number ?: "•", Modifier.widthIn(min = 14.dp), style = style) - Spacer(Modifier.width(6.dp)) - BlockText(start + j, entry.content, style, Modifier.weight(1f, fill = false)) + is MarkdownBlock.ItemList -> { + val entries = listEntries(block.items, 0) + entries.forEachIndexed { j, (entry, level) -> + if (j > 0) Spacer(Modifier.height(emptyLinesHeight(entries[j - 1].first.content.to, entry.content.from, between = true))) + Row(Modifier.padding(start = 20.dp * level)) { + Text(entry.number ?: "•", Modifier.widthIn(min = 14.dp), style = style) + Spacer(Modifier.width(6.dp)) + BlockText(start + j, entry.content, style, Modifier.weight(1f, fill = false)) + } } } is MarkdownBlock.CodeBlock -> CodeBlockCard(cardShape, cardColor, roundness, codeText(formattedText, block.content), cardMargins) { m -> @@ -143,6 +157,7 @@ fun MarkdownBlocks( is MarkdownBlock.Rule -> Box((if (chatTypography) cardMargins.widthIn(min = ruleMinWidth) else Modifier.padding(vertical = 6.dp)).fillMaxWidth().height(1.dp).background(lineColor)) } } + Spacer(Modifier.height(emptyLineHeight * trailingEmptyLines)) if (!lastIsText) metaLine?.invoke() } } @@ -184,8 +199,27 @@ private val MarkdownBlock.end: Int get() = when (this) { else -> textRanges.lastOrNull()?.range?.to ?: 0 } -private fun paragraphBreak(fts: List, from: Int, to: Int): Boolean = - (from.coerceIn(0, fts.size) until to.coerceIn(0, fts.size)).any { (fts[it].format as? Format.Markup)?.token is BlockToken.ParagraphBreak } +val MarkdownBlock.isCard: Boolean get() = + this is MarkdownBlock.CodeBlock || this is MarkdownBlock.Table || this is MarkdownBlock.Rule + +const val MAX_EMPTY_LINES = 100 + +fun emptyLines(fts: List, from: Int, to: Int, between: Boolean): Int { + val lineBreaks = (from.coerceIn(0, fts.size) until to.coerceIn(0, fts.size)).sumOf { + when (val token = (fts[it].format as? Format.Markup)?.token) { + is BlockToken.LineBreak -> 1 + is BlockToken.ParagraphBreak -> token.lineBreaks + else -> 0 + } + } + return (lineBreaks - if (between) 1 else 0).coerceIn(0, MAX_EMPTY_LINES) +} + +fun leadingEmptyLines(fts: List, blocks: List): Int = + emptyLines(fts, 0, blocks.firstOrNull()?.start ?: 0, between = false) + +fun trailingEmptyLines(text: CharSequence, fts: List, blocks: List): Int = + emptyLines(fts, blocks.lastOrNull()?.end ?: 0, fts.size, between = !text.endsWith("\n")) private fun codeText(fts: List, r: SegmentRange): String = (r.from.coerceIn(0, fts.size) until r.to.coerceIn(0, fts.size)).joinToString("") { i -> diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt index 4fb7a72139..e9b484f2bb 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt @@ -64,16 +64,11 @@ val TERMINAL_BLOCK_TOP_GAP = 5.75.sp val TERMINAL_BLOCK_BOTTOM_GAP = 5.sp val TERMINAL_LEVEL_STEP = 4.75.sp val TERMINAL_HEADING_BOTTOM_GAP = TERMINAL_LEVEL_STEP / 2 -val TERMINAL_SENDER_TOP_GAP = 6.5.sp -private val TERMINAL_SENDER_BOTTOM_GAP = 5.5.sp +val TERMINAL_PARAGRAPH_GAP = 16.sp * CHAT_LINE_HEIGHT_RATIO / 3 val TERMINAL_HEADER_TOP_GAP = 2.5.sp val TERMINAL_HEADER_BOTTOM_GAP = 1.5.sp -val TERMINAL_EVENT_TOP_GAP = 8.25.sp -val TERMINAL_EVENT_BOTTOM_GAP = 1.5.sp -val TERMINAL_FILE_TOP_GAP = 2.sp -val TERMINAL_EMOJI_TOP_GAP = 4.25.sp -val TERMINAL_EMOJI_BOTTOM_GAP = 1.5.sp val TERMINAL_META_GAP = 6.sp +const val TERMINAL_NAME_REPEAT_SECONDS = 450 const val TERMINAL_HEADING_RATIO = 1.25f private const val CHAT_LINE_HEIGHT_RATIO = 22f / 16f private const val CHAT_LINE_HEIGHT_CONTRAST_SLOPE = 0.1515f @@ -122,7 +117,7 @@ private fun lightness(color: Color): Float { } fun terminalItemShowsSender(item: ChatItem, older: ChatItem?): Boolean = - item.content.hasTerminalSender && (older == null || !older.content.hasTerminalSender || !sameSender(item, older)) + item.content.hasTerminalSender && (older == null || !older.content.hasTerminalSender || !sameSender(item, older) || afterPause(item, older)) private fun sameSender(item: ChatItem, older: ChatItem): Boolean { val d = item.chatDir @@ -134,21 +129,54 @@ private fun sameSender(item: ChatItem, older: ChatItem): Boolean { } } +private fun afterPause(item: ChatItem, older: ChatItem): Boolean = + item.meta.itemTs.epochSeconds - older.meta.itemTs.epochSeconds >= TERMINAL_NAME_REPEAT_SECONDS + private val ChatItem.channelIsSender: Boolean get() = chatDir is CIDirection.ChannelRcv || (chatDir is CIDirection.GroupSnd && meta.showGroupAsSender) fun terminalRowGap(item: ChatItem, older: ChatItem?, separated: Boolean, largeGap: Boolean, hasSenderRow: Boolean): TextUnit = - if (older != null && !separated && (largeGap || hasSenderRow || !item.content.hasTerminalSender || !older.content.hasTerminalSender || item.textAtItemTop && item.startsWithHeading)) TERMINAL_LEVEL_STEP else 0.sp + if (older != null && !separated && (largeGap || hasSenderRow || !item.isOneLine || !older.isOneLine || older.reactions.isNotEmpty())) TERMINAL_PARAGRAPH_GAP else 0.sp -fun terminalHeadingGap(item: ChatItem): TextUnit = - if (!item.textAtItemTop && item.startsWithHeading) TERMINAL_LEVEL_STEP else 0.sp +fun terminalTextTop(item: ChatItem): TextUnit = when { + item.cardAboveText || item.hasQuoteOrHeader && item.startsWithCard -> if (item.startsWithEmptyLines) 0.sp else TERMINAL_PARAGRAPH_GAP + item.hasQuoteOrHeader && item.startsWithHeading -> TERMINAL_LEVEL_STEP + else -> 0.sp +} + +fun terminalCardTop(item: ChatItem): TextUnit = + if (item.hasQuoteOrHeader) TERMINAL_PARAGRAPH_GAP else 0.sp + +fun terminalQuoteTop(item: ChatItem): TextUnit = + if (item.isReport || item.meta.itemDeleted != null || item.meta.isLive) TERMINAL_PARAGRAPH_GAP else 0.sp + +fun terminalReactionsGap(item: ChatItem): TextUnit = + if (item.reactions.isNotEmpty()) TERMINAL_PARAGRAPH_GAP else 0.sp + +val ChatItem.isOneLine: Boolean get() = + textAtItemTop && markdownBlocks == null && '\n' !in content.text private val ChatItem.textAtItemTop: Boolean get() = - (content.msgContent is MsgContent.MCText || content.msgContent is MsgContent.MCUnknown && file == null) && !hasQuoteOrHeader + textOnly && !hasQuoteOrHeader + +private val ChatItem.cardAboveText: Boolean get() = + quotedItem != null || !textOnly + +private val ChatItem.textOnly: Boolean get() = + content.msgContent is MsgContent.MCText || content.msgContent is MsgContent.MCReport || content.msgContent is MsgContent.MCUnknown && file == null private val ChatItem.startsWithHeading: Boolean get() = markdownBlocks?.firstOrNull() is MarkdownBlock.Heading +private val ChatItem.startsWithCard: Boolean get() = + markdownBlocks?.firstOrNull()?.isCard == true + +private val ChatItem.startsWithEmptyLines: Boolean get() { + val fts = formattedText + val blocks = markdownBlocks + return if (fts != null && blocks != null) leadingEmptyLines(fts, blocks) > 0 else !isReport && (content.text.startsWith('\n') || content.text.startsWith("\r\n")) +} + val CIContent.hasTerminalSender: Boolean get() = when (this) { is CIContent.SndMsgContent, is CIContent.SndDeleted, @@ -196,16 +224,17 @@ fun Modifier.terminalStartOffset(offset: () -> Dp): Modifier = private val LastLineLeft = VerticalAlignmentLine(::min) private val LastLineRight = VerticalAlignmentLine(::max) -private val LastBlockBottom = HorizontalAlignmentLine(::max) +private val CardTop = HorizontalAlignmentLine(::min) +private val CardBottom = HorizontalAlignmentLine(::max) -fun Modifier.messageLastLine(): Modifier = lastLine { emptyMap() } +fun Modifier.messageLastLine(): Modifier = marked { mapOf(LastLineLeft to 0, LastLineRight to it.width) } -fun Modifier.messageLastBlock(): Modifier = lastLine { mapOf(LastBlockBottom to it.height) } +fun Modifier.messageCard(): Modifier = marked { mapOf(CardTop to 0, CardBottom to it.height) } -private fun Modifier.lastLine(extraAlignmentLines: (Placeable) -> Map): Modifier = +private fun Modifier.marked(alignmentLines: (Placeable) -> Map): Modifier = layout { measurable, constraints -> val placeable = measurable.measure(constraints) - layout(placeable.width, placeable.height, mapOf(LastLineLeft to 0, LastLineRight to placeable.width) + extraAlignmentLines(placeable)) { placeable.placeRelative(0, 0) } + layout(placeable.width, placeable.height, alignmentLines(placeable)) { placeable.placeRelative(0, 0) } } @Composable @@ -220,9 +249,9 @@ fun Modifier.inlineIcon(): Modifier = } @Composable -fun ItemWithMeta(meta: @Composable () -> Unit, overlayMeta: (@Composable () -> Unit)? = null, metaReserved: Boolean = false, endButton: (@Composable () -> Unit)? = null, content: @Composable (inlineMeta: (@Composable () -> Unit)?) -> Unit) { +fun ItemWithMeta(meta: @Composable () -> Unit, overlayMeta: (@Composable () -> Unit)? = null, metaReserved: Boolean = false, endButton: (@Composable () -> Unit)? = null, gapBelowCard: Dp = 0.dp, content: @Composable (inlineMeta: (@Composable () -> Unit)?) -> Unit) { if (LocalTerminalLayout.current) { - TerminalMetaLayout(metaReserved, hasOverlay = overlayMeta != null) { + TerminalMetaLayout(metaReserved, hasOverlay = overlayMeta != null, gapBelowCard) { content(null) listOfNotNull(meta, overlayMeta, endButton).forEach { m -> Box(Modifier.padding(end = 12.dp)) { @@ -236,7 +265,7 @@ fun ItemWithMeta(meta: @Composable () -> Unit, overlayMeta: (@Composable () -> U } @Composable -private fun TerminalMetaLayout(metaReserved: Boolean, hasOverlay: Boolean, contentWithMeta: @Composable () -> Unit) { +private fun TerminalMetaLayout(metaReserved: Boolean, hasOverlay: Boolean, gapBelowCard: Dp, contentWithMeta: @Composable () -> Unit) { Layout(contentWithMeta) { measurables, constraints -> val metaConstraints = constraints.copy(minWidth = 0, minHeight = 0) val meta = measurables[1].measure(metaConstraints) @@ -261,11 +290,11 @@ private fun TerminalMetaLayout(metaReserved: Boolean, hasOverlay: Boolean, conte overlay == null && textBaseline != AlignmentLine.Unspecified -> textBaseline - metaBaseline else -> content.height - gap - meta.height }.coerceAtLeast(0) - val blockGap = if (content[LastBlockBottom] == content.height) TERMINAL_BLOCK_BOTTOM_GAP.toPx().roundToInt() else 0 + val cardGap = if (content[CardBottom] == content.height) gapBelowCard.roundToPx() else 0 val placedOverlay = overlay?.takeIf { content.width + meta.width > width } val endButtonHeight = endButton?.height ?: 0 val endButtonTop = (((if (placedOverlay != null) content.height else metaTop) - endButtonHeight) / 2).coerceAtLeast(0) - layout(width, maxOf(content.height + blockGap, metaTop + meta.height, placedOverlay?.height ?: 0, endButtonTop + endButtonHeight)) { + layout(width, maxOf(content.height + cardGap, metaTop + meta.height, placedOverlay?.height ?: 0, endButtonTop + endButtonHeight)) { content.placeRelative(0, 0) if (placedOverlay != null) { placedOverlay.placeRelative(content.width - placedOverlay.width, (content.height - gap - placedOverlay.height).coerceAtLeast(0)) @@ -341,7 +370,8 @@ private fun SenderNameAndRole(sender: ChatItemSender, modifier: Modifier) { sender.name, sender.badge, Modifier.weight(1f, false), - fontSize = 13.5.sp, + fontSize = MaterialTheme.typography.body1.fontSize, + fontWeight = FontWeight.SemiBold, color = if (sender.own) MaterialTheme.colors.primary else MaterialTheme.colors.secondary, overflow = TextOverflow.Ellipsis, maxLines = 1 @@ -350,7 +380,7 @@ private fun SenderNameAndRole(sender: ChatItemSender, modifier: Modifier) { Text( sender.role, Modifier.padding(start = DEFAULT_PADDING_HALF * 1.5f), - fontSize = 13.5.sp, + fontSize = MaterialTheme.typography.body1.fontSize, fontWeight = FontWeight.Medium, color = MaterialTheme.colors.secondary, maxLines = 1 @@ -369,9 +399,9 @@ fun TerminalChatItemRow( gutter: Dp, topGap: Dp, modifier: Modifier = Modifier, - senderTopGap: Dp = TERMINAL_SENDER_TOP_GAP.toDp(), content: @Composable () -> Unit ) { + val cardGap = TERMINAL_PARAGRAPH_GAP.toDp() Layout( content = { Box { @@ -379,8 +409,8 @@ fun TerminalChatItemRow( } Box { if (sender != null) { - ProvideTextStyle(LocalTextStyle.current.merge(chatTextStyle(13.5.sp))) { - SenderNameAndRole(sender, Modifier.padding(start = CHAT_ITEM_TEXT_PADDING, bottom = TERMINAL_SENDER_BOTTOM_GAP.toDp())) + ProvideTextStyle(LocalTextStyle.current.merge(chatTextStyle(MaterialTheme.typography.body1.fontSize))) { + SenderNameAndRole(sender, Modifier.padding(start = CHAT_ITEM_TEXT_PADDING)) } } } @@ -389,7 +419,7 @@ fun TerminalChatItemRow( } }, modifier - .padding(top = topGap + if (sender != null) senderTopGap else 0.dp) + .padding(top = topGap) .fillMaxWidth() ) { measurables, constraints -> val messageStart = gutter.roundToPx() @@ -398,7 +428,7 @@ fun TerminalChatItemRow( val avatar = measurables[0].measure(looseConstraints) val name = measurables[1].measure(messageConstraints) val message = measurables[2].measure(messageConstraints) - val messageTop = name.height + val messageTop = name.height + if (sender != null && message[CardTop] == 0) cardGap.roundToPx() else 0 layout(constraints.maxWidth, max(messageTop + message.height, avatar.height)) { avatar.placeRelative(CHAT_ITEM_TEXT_PADDING.roundToPx(), 0) name.placeRelative(messageStart, 0) diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt index ca067b2956..74ba499002 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TextItemView.kt @@ -144,10 +144,11 @@ fun itemDisplay(ci: ChatItem, linkMode: SimplexLinkMode): ItemDisplay? { val blocks = ci.markdownBlocks ?: return ItemDisplay(fts.map(segment), listOf(0)) val parts = mutableListOf>() var offset = itemPrefixText(ci).length - val bases = blockTextRanges(blocks).mapIndexed { i, t -> + val ranges = blockTextRanges(blocks) + val bases = ranges.mapIndexed { i, t -> if (i > 0) { val separator = if (t.inRow) "\t" else "\n" - parts += separator to separator + parts += separator to separator.repeat(1 + emptyLines(fts, ranges[i - 1].range.to, t.range.from, between = true)) offset += 1 } val base = if (i == 0) 0 else offset @@ -215,12 +216,13 @@ fun MarkdownText ( if (blockLayout && formattedText != null && markdownBlocks != null && range == null) { val direction = LocalLayoutDirection.current val terminal = LocalTerminalLayout.current + val trailingEmptyLines = trailingEmptyLines(text, formattedText, markdownBlocks) val ruleMinWidth = if (terminal && metaCopy != null && markdownBlocks.isNotEmpty() && markdownBlocks.all { it is MarkdownBlock.Rule }) { with(LocalDensity.current) { rememberTextMeasurer().measure(metaCopy, style).size.width.toDp() } } else 0.dp CompositionLocalProvider(LocalLayoutDirection provides textLayoutDirection) { MarkdownBlocks( - formattedText, markdownBlocks, style, modifier, cardColor ?: MaterialTheme.appColors.receivedQuote, + formattedText, markdownBlocks, trailingEmptyLines, style, modifier, cardColor ?: MaterialTheme.appColors.receivedQuote, blockText = { index, r, blockStyle, blockModifier, blockSoftWrap, last -> MarkdownText( text, formattedText, markdownBlocks, sender = if (index == 0) sender else null, meta = if (last) meta else null, chatTTL = chatTTL, @@ -231,7 +233,7 @@ fun MarkdownText ( selection = selection, textIndex = index, range = r.from until r.to, softWrap = blockSoftWrap, parentDirection = direction ) }, - metaLine = if (terminal && meta?.isLive != true) null else { + metaLine = if (terminal && meta?.isLive != true && trailingEmptyLines == 0) null else { { MarkdownText( text, formattedText, markdownBlocks, meta = meta, chatTTL = chatTTL, encrypted = encrypted, signedFileVerified = signedFileVerified, toggleSecrets = toggleSecrets, style = style, @@ -331,7 +333,7 @@ fun MarkdownText ( if (heading) pushStyle(SpanStyle(fontWeight = FontWeight.Bold)) if (ft.format == null) append(ft.text) else when(ft.format) { - is Format.Bold -> withStyle(if (markdownBlocks != null && ft.format.singleStar) Format.Italic().style else ft.format.style) { append(ft.text) } + is Format.Bold -> withStyle(if (ft.format.singleStar) Format.Italic().style else ft.format.style) { append(ft.text) } is Format.Italic -> withStyle(ft.format.style) { append(ft.text) } is Format.StrikeThrough -> withStyle(ft.format.style) { append(ft.text) } is Format.Snippet -> withStyle(ft.format.style) { append(ft.text) } diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt index 3c473a04e7..940dfc0fc8 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt @@ -43,7 +43,6 @@ import chat.simplex.common.views.chat.item.ChatItemSender import chat.simplex.common.views.chat.item.LocalBubbleLayout import chat.simplex.common.views.chat.item.LocalTerminalLayout import chat.simplex.common.views.chat.item.PreviewChatItemView -import chat.simplex.common.views.chat.item.TERMINAL_SENDER_TOP_GAP import chat.simplex.common.views.chat.item.TerminalChatItemRow import chat.simplex.common.views.chat.item.terminalRowGap import chat.simplex.common.views.chat.item.msgTailWidthDp @@ -308,7 +307,7 @@ object AppearanceScope { @Composable fun TerminalPreviewRow(item: ChatItem, older: ChatItem?, sender: ChatItemSender) { - TerminalChatItemRow(sender, gutter = 0.dp, topGap = terminalRowGap(item, older, separated = false, largeGap = true, hasSenderRow = true).toDp(), senderTopGap = if (older == null) 0.dp else TERMINAL_SENDER_TOP_GAP.toDp()) { + TerminalChatItemRow(sender, gutter = 0.dp, topGap = terminalRowGap(item, older, separated = false, largeGap = true, hasSenderRow = true).toDp()) { PreviewChatItemView(item) } } diff --git a/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/MarkdownBlocksTest.kt b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/MarkdownBlocksTest.kt index ccf78ba276..cd1902a0e5 100644 --- a/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/MarkdownBlocksTest.kt +++ b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/MarkdownBlocksTest.kt @@ -1,8 +1,12 @@ package chat.simplex.app import chat.simplex.common.model.* +import chat.simplex.common.views.chat.item.MAX_EMPTY_LINES +import chat.simplex.common.views.chat.item.emptyLines import chat.simplex.common.views.chat.item.itemDisplay +import chat.simplex.common.views.chat.item.leadingEmptyLines import chat.simplex.common.views.chat.item.segmentDisplayText +import chat.simplex.common.views.chat.item.trailingEmptyLines import chat.simplex.common.views.helpers.ParsedFormattedText import kotlin.test.Test import kotlin.test.assertEquals @@ -22,6 +26,12 @@ class MarkdownBlocksTest { private val gaps = parsed("""{"formattedText":[{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":2}},"text":"\n\n"},{"text":"a"},{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":3}},"text":"\n\n\n"},{"format":{"type":"markup","token":{"type":"headingMark","level":1}},"text":"# "},{"text":"h"},{"format":{"type":"markup","token":{"type":"lineBreak"}},"text":"\n"}],"markdownBlocks":[{"type":"paragraph","content":{"from":1,"to":2}},{"type":"heading","level":1,"content":{"from":4,"to":5}}]}""") + private val looseList = parsed("""{"formattedText":[{"format":{"type":"markup","token":{"type":"listMark"}},"text":"- "},{"text":"a"},{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":2}},"text":"\n\n"},{"format":{"type":"markup","token":{"type":"listMark"}},"text":"- "},{"text":"b"},{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":3}},"text":"\n\n\n"},{"format":{"type":"markup","token":{"type":"listMark"}},"text":"- "},{"text":"c"}],"markdownBlocks":[{"type":"list","items":[{"content":{"from":1,"to":2},"items":[]},{"content":{"from":4,"to":5},"items":[]},{"content":{"from":7,"to":8},"items":[]}]}]}""") + + private val trailingSpaces = parsed("""{"formattedText":[{"format":{"type":"markup","token":{"type":"headingMark","level":1}},"text":"# "},{"text":"a"},{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":1}},"text":"\n "}],"markdownBlocks":[{"type":"heading","level":1,"content":{"from":1,"to":2}}]}""") + + private val emptyLineAndSpaces = parsed("""{"formattedText":[{"format":{"type":"markup","token":{"type":"headingMark","level":1}},"text":"# "},{"text":"a"},{"format":{"type":"markup","token":{"type":"paragraphBreak","lineBreaks":2}},"text":"\n\n "}],"markdownBlocks":[{"type":"heading","level":1,"content":{"from":1,"to":2}}]}""") + private val escapes = parsed("""{"formattedText":[{"text":"text "},{"format":{"type":"escape"},"text":"\\"},{"text":"*not"},{"format":{"type":"escape"},"text":"\\"},{"text":"*\nmore"}]}""") @Test @@ -82,6 +92,24 @@ class MarkdownBlocksTest { assertEquals(listOf(1 to 0, 7 to 1, 10 to 0), listEntries(list.items, 0).map { (entry, level) -> entry.content.from to level }) } + @Test + fun testEmptyLines() { + val gapTokens = gaps.formattedText!! + assertEquals(2, emptyLines(gapTokens, 0, 1, between = false)) + assertEquals(2, leadingEmptyLines(gapTokens, gaps.markdownBlocks!!)) + assertEquals(0, leadingEmptyLines(headingAndParagraph.formattedText!!, headingAndParagraph.markdownBlocks!!)) + assertEquals(2, emptyLines(gapTokens, 2, 4, between = true)) + assertEquals(0, emptyLines(headingAndParagraph.formattedText!!, 3, 4, between = true)) + assertEquals(0, emptyLines(nestedList.formattedText!!, 5, 7, between = true)) + assertEquals(MAX_EMPTY_LINES, emptyLines(listOf(FormattedText("\n".repeat(5000), Format.Markup(BlockToken.ParagraphBreak(5000)))), 0, 1, between = true)) + val entries = listEntries(assertIs(looseList.markdownBlocks!!.single()).items, 0).map { it.first.content } + assertEquals(listOf(1, 2), entries.zipWithNext { a, b -> emptyLines(looseList.formattedText!!, a.to, b.from, between = true) }) + assertEquals(1, trailingEmptyLines("\n\na\n\n\n# h\n\n", gapTokens, gaps.markdownBlocks!!)) + assertEquals(0, trailingEmptyLines("# a\n ", trailingSpaces.formattedText!!, trailingSpaces.markdownBlocks!!)) + assertEquals(1, trailingEmptyLines("# a\n\n ", emptyLineAndSpaces.formattedText!!, emptyLineAndSpaces.markdownBlocks!!)) + assertEquals(0, trailingEmptyLines("# Title *x*\nPara a\nb \nc\n", headingAndParagraph.formattedText!!, headingAndParagraph.markdownBlocks!!)) + } + @Test fun testHeadingSegments() { assertEquals(listOf(1, 2), headingSegments(9, headingAndParagraph.markdownBlocks!!).withIndex().filter { it.value }.map { it.index }) @@ -112,7 +140,11 @@ class MarkdownBlocksTest { val table = item.copy(formattedText = tableAligned.formattedText, markdownBlocks = tableAligned.markdownBlocks) val tableDisplay = itemDisplay(table, SimplexLinkMode.DESCRIPTION)!! assertEquals("a\tb\tc\td\nxxx\tyyy\tzzz", tableDisplay.parts.joinToString("") { it.first }) + assertEquals("a\tb\tc\td\nxxx\tyyy\tzzz", tableDisplay.parts.joinToString("") { it.second }) assertEquals(listOf(0, 2, 4, 6, 8, 12, 16), tableDisplay.bases) + val paragraphs = itemDisplay(item.copy(formattedText = gaps.formattedText, markdownBlocks = gaps.markdownBlocks), SimplexLinkMode.DESCRIPTION)!! + assertEquals(listOf("a" to "a", "\n" to "\n\n\n", "h" to "h"), paragraphs.parts) + assertEquals(listOf(0, 2), paragraphs.bases) val plain = item.copy(formattedText = escapes.formattedText, markdownBlocks = null) val plainDisplay = itemDisplay(plain, SimplexLinkMode.DESCRIPTION)!! assertEquals(listOf("text " to "text ", "" to "\\", "*not" to "*not", "" to "\\", "*\nmore" to "*\nmore"), plainDisplay.parts) diff --git a/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt index 91b7854dae..bd838e66a7 100644 --- a/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt +++ b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt @@ -6,9 +6,15 @@ import chat.simplex.common.views.chat.ListItem import chat.simplex.common.views.chat.MergedItem import chat.simplex.common.views.chat.terminalRowsSeparated import chat.simplex.common.views.chat.item.TERMINAL_LEVEL_STEP -import chat.simplex.common.views.chat.item.terminalHeadingGap +import chat.simplex.common.views.chat.item.TERMINAL_NAME_REPEAT_SECONDS +import chat.simplex.common.views.chat.item.TERMINAL_PARAGRAPH_GAP +import chat.simplex.common.views.chat.item.isOneLine +import chat.simplex.common.views.chat.item.terminalCardTop import chat.simplex.common.views.chat.item.terminalItemShowsSender +import chat.simplex.common.views.chat.item.terminalQuoteTop +import chat.simplex.common.views.chat.item.terminalReactionsGap import chat.simplex.common.views.chat.item.terminalRowGap +import chat.simplex.common.views.chat.item.terminalTextTop import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.datetime.Instant import kotlinx.datetime.LocalDate @@ -25,13 +31,13 @@ class TerminalItemViewTest { private val alice = GroupMember.sampleData.copy(groupMemberId = 1, memberId = "alice") private val bob = GroupMember.sampleData.copy(groupMemberId = 2, memberId = "bob") - private fun msgAt(id: Long, dir: CIDirection, ts: Instant) = - ChatItem.getSampleData(id, dir, ts).let { - if (dir.sent) it else it.copy(content = CIContent.RcvMsgContent(MsgContent.MCText("hello"))) + private fun msgAt(id: Long, dir: CIDirection, ts: Instant, text: String = "hello") = + ChatItem.getSampleData(id, dir, ts, text).let { + if (dir.sent) it else it.copy(content = CIContent.RcvMsgContent(MsgContent.MCText(text))) } - private fun msg(id: Long, dir: CIDirection, secondsAfterNoon: Long) = - msgAt(id, dir, Instant.fromEpochSeconds(noon.epochSeconds + secondsAfterNoon)) + private fun msg(id: Long, dir: CIDirection, secondsAfterNoon: Long, text: String = "hello") = + msgAt(id, dir, Instant.fromEpochSeconds(noon.epochSeconds + secondsAfterNoon), text) private fun integrityError(id: Long, secondsAfterNoon: Long) = msg(id, CIDirection.DirectRcv(), secondsAfterNoon).copy(content = CIContent.RcvIntegrityError(MsgErrorType.MsgSkipped(1, 2))) @@ -53,7 +59,15 @@ class TerminalItemViewTest { fun senderHiddenForSameSender() { assertFalse(terminalItemShowsSender(msg(2, CIDirection.DirectSnd(), 30), older = msg(1, CIDirection.DirectSnd(), 0))) assertFalse(terminalItemShowsSender(msg(2, CIDirection.GroupRcv(alice), 59), older = msg(1, CIDirection.GroupRcv(alice), 0))) - assertFalse(terminalItemShowsSender(msg(2, CIDirection.DirectRcv(), 3600), older = msg(1, CIDirection.DirectRcv(), 0))) + assertFalse(terminalItemShowsSender(msg(2, CIDirection.DirectRcv(), TERMINAL_NAME_REPEAT_SECONDS - 1L), older = msg(1, CIDirection.DirectRcv(), 0))) + assertFalse(terminalItemShowsSender(msg(2, CIDirection.DirectRcv(), 0), older = msg(1, CIDirection.DirectRcv(), TERMINAL_NAME_REPEAT_SECONDS.toLong()))) + } + + @Test + fun senderShownAgainAfterPause() { + assertTrue(terminalItemShowsSender(msg(2, CIDirection.DirectRcv(), TERMINAL_NAME_REPEAT_SECONDS.toLong()), older = msg(1, CIDirection.DirectRcv(), 0))) + assertTrue(terminalItemShowsSender(msg(2, CIDirection.GroupRcv(alice), 3600), older = msg(1, CIDirection.GroupRcv(alice), 0))) + assertFalse(terminalItemShowsSender(featureEvent(2, 3600), older = featureEvent(1, 0))) } @Test @@ -130,6 +144,10 @@ class TerminalItemViewTest { private fun forwarded(item: ChatItem) = item.copy(meta = item.meta.copy(itemForwarded = CIForwardedFrom.Unknown)) + private val file = CIFile(fileId = 1, fileName = "a.txt", fileSize = 1, fileStatus = CIFileStatus.SndComplete, fileProtocol = FileProtocol.XFTP) + + private val thumbsUp = listOf(CIReactionCount(MsgReaction.Emoji(MREmojiChar.ThumbsUp), userReacted = false, totalReacted = 1)) + private fun gap(item: ChatItem, older: ChatItem?, separated: Boolean = false, largeGap: Boolean = false, hasSenderRow: Boolean = false) = terminalRowGap(item, older, separated, largeGap, hasSenderRow) @@ -144,21 +162,55 @@ class TerminalItemViewTest { } @Test - fun rowGapZeroBetweenCloseMessages() { + fun rowGapZeroBetweenCloseOneLineMessages() { assertEquals(0.sp, gap(msg(2, CIDirection.DirectSnd(), 10), msg(1, CIDirection.DirectSnd(), 0))) + assertEquals(0.sp, gap(msg(2, CIDirection.DirectRcv(), 10, "👍"), msg(1, CIDirection.DirectRcv(), 0))) + } + + @Test + fun rowGapBetweenCloseMessagesUnlessBothAreOneLine() { + val older = msg(1, CIDirection.DirectSnd(), 0) + val twoLines = msg(2, CIDirection.DirectSnd(), 10, "line one\nline two") + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(twoLines, older)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(msg(3, CIDirection.DirectSnd(), 20), twoLines)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(quoted(msg(2, CIDirection.DirectSnd(), 10)), older)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(withBlocks(msg(2, CIDirection.DirectSnd(), 10), heading()), older)) + } + + @Test + fun rowGapBelowReactions() { + val older = msg(1, CIDirection.DirectSnd(), 0) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(msg(2, CIDirection.DirectSnd(), 10), older.copy(reactions = thumbsUp))) + assertEquals(0.sp, gap(msg(2, CIDirection.DirectSnd(), 10).copy(reactions = thumbsUp), older)) + } + + @Test + fun oneLineMessages() { + assertTrue(msg(1, CIDirection.DirectSnd(), 0).isOneLine) + assertTrue(msg(1, CIDirection.DirectRcv(), 0, "👍").isOneLine) + assertFalse(msg(1, CIDirection.DirectSnd(), 0, "hello\n").isOneLine) + assertTrue(msg(1, CIDirection.DirectSnd(), 0).copy(reactions = thumbsUp).isOneLine) + assertFalse(quoted(msg(1, CIDirection.DirectSnd(), 0)).isOneLine) + assertFalse(forwarded(msg(1, CIDirection.DirectSnd(), 0)).isOneLine) + assertFalse(withBlocks(msg(1, CIDirection.DirectSnd(), 0), heading()).isOneLine) + val base = msg(1, CIDirection.DirectSnd(), 0) + assertFalse(base.copy(content = CIContent.SndMsgContent(MsgContent.MCImage("hello", ""))).isOneLine) + assertFalse(base.copy(content = CIContent.SndMsgContent(MsgContent.MCUnknown(text = "hello", json = JsonPrimitive("unknown"))), file = file).isOneLine) + assertFalse(featureEvent(1, 0).isOneLine) } @Test fun rowGapAfterLargeGapOrAboveSenderRow() { val older = msg(1, CIDirection.DirectSnd(), 0) - assertEquals(TERMINAL_LEVEL_STEP, gap(msg(2, CIDirection.DirectSnd(), 70), older, largeGap = true)) - assertEquals(TERMINAL_LEVEL_STEP, gap(msg(2, CIDirection.DirectSnd(), 10), older, hasSenderRow = true)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(msg(2, CIDirection.DirectSnd(), 70), older, largeGap = true)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(msg(2, CIDirection.DirectSnd(), 10), older, hasSenderRow = true)) } @Test fun rowGapNextToEvent() { - assertEquals(TERMINAL_LEVEL_STEP, gap(featureEvent(2, 10), msg(1, CIDirection.DirectRcv(), 0))) - assertEquals(TERMINAL_LEVEL_STEP, gap(msg(2, CIDirection.DirectRcv(), 10), featureEvent(1, 0))) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(featureEvent(2, 10), msg(1, CIDirection.DirectRcv(), 0))) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(msg(2, CIDirection.DirectRcv(), 10), featureEvent(1, 0))) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(featureEvent(2, 10), featureEvent(1, 0))) } @Test @@ -184,51 +236,93 @@ class TerminalItemViewTest { @Test fun headingAtItemTopTakesRowGap() { val item = withBlocks(msg(2, CIDirection.DirectSnd(), 10), heading()) - assertEquals(TERMINAL_LEVEL_STEP, gap(item, msg(1, CIDirection.DirectSnd(), 0))) - assertEquals(0.sp, terminalHeadingGap(item)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(item, msg(1, CIDirection.DirectSnd(), 0))) + assertEquals(0.sp, terminalTextTop(item)) } @Test - fun headingBelowQuoteOrHeaderTakesHeadingGap() { - val older = msg(1, CIDirection.DirectSnd(), 0) - listOf(quoted(msg(2, CIDirection.DirectSnd(), 10)), forwarded(msg(2, CIDirection.DirectSnd(), 10))).forEach { - val item = withBlocks(it, heading()) - assertEquals(0.sp, gap(item, older)) - assertEquals(TERMINAL_LEVEL_STEP, terminalHeadingGap(item)) - } - } - - @Test - fun headingBelowDeletionLiveFileOrMediaTakesHeadingGap() { - val older = msg(1, CIDirection.DirectSnd(), 0) + fun headingBelowHeaderTakesHeadingGap() { val base = msg(2, CIDirection.DirectSnd(), 10) - val file = CIFile(fileId = 1, fileName = "a.txt", fileSize = 1, fileStatus = CIFileStatus.SndComplete, fileProtocol = FileProtocol.XFTP) listOf( + forwarded(base), base.copy(meta = base.meta.copy(itemDeleted = CIDeleted.Deleted(null))), - base.copy(meta = base.meta.copy(itemLive = true)), - base.copy(content = CIContent.SndMsgContent(MsgContent.MCUnknown(text = "# Notes", json = JsonPrimitive("unknown"))), file = file), - base.copy(content = CIContent.SndMsgContent(MsgContent.MCImage("# Caption", ""))) + base.copy(meta = base.meta.copy(itemLive = true)) ).forEach { - val item = withBlocks(it, heading()) - assertEquals(0.sp, gap(item, older)) - assertEquals(TERMINAL_LEVEL_STEP, terminalHeadingGap(item)) + assertEquals(TERMINAL_LEVEL_STEP, terminalTextTop(withBlocks(it, heading()))) + assertEquals(0.sp, terminalTextTop(it)) } } + @Test + fun textBelowCardTakesParagraphGap() { + val base = msg(2, CIDirection.DirectSnd(), 10) + listOf( + quoted(base), + base.copy(content = CIContent.SndMsgContent(MsgContent.MCUnknown(text = "# Notes", json = JsonPrimitive("unknown"))), file = file), + base.copy(content = CIContent.SndMsgContent(MsgContent.MCImage("# Caption", ""))), + forwarded(base).copy(content = CIContent.SndMsgContent(MsgContent.MCVoice("# Caption", 10))) + ).forEach { + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalTextTop(withBlocks(it, heading()))) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalTextTop(it)) + } + } + + @Test + fun emptyLinesBelowCardReplaceParagraphGap() { + val caption = msg(2, CIDirection.DirectSnd(), 10).copy( + content = CIContent.SndMsgContent(MsgContent.MCImage("\n\nCaption", "")), + formattedText = listOf(FormattedText("\n\n", Format.Markup(BlockToken.ParagraphBreak(2))), FormattedText("Caption")), + markdownBlocks = listOf(MarkdownBlock.Paragraph(SegmentRange(1, 2))) + ) + assertEquals(0.sp, terminalTextTop(caption)) + val oneBreak = caption.copy( + content = CIContent.SndMsgContent(MsgContent.MCImage("\nCaption", "")), + formattedText = listOf(FormattedText("\n", Format.Markup(BlockToken.ParagraphBreak(1))), FormattedText("Caption")) + ) + assertEquals(0.sp, terminalTextTop(oneBreak)) + val base = msg(2, CIDirection.DirectSnd(), 10) + assertEquals(0.sp, terminalTextTop(base.copy(content = CIContent.SndMsgContent(MsgContent.MCImage("\nCaption", ""))))) + assertEquals(0.sp, terminalTextTop(base.copy(content = CIContent.SndMsgContent(MsgContent.MCImage("\r\nCaption", ""))))) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalTextTop(quoted(base).copy(content = CIContent.SndMsgContent(MsgContent.MCReport("\nComment", ReportReason.Spam))))) + } + + @Test + fun cardStartingTextBelowHeaderTakesParagraphGap() { + val code = withBlocks(msg(2, CIDirection.DirectSnd(), 10), MarkdownBlock.CodeBlock(content = SegmentRange(0, 1))) + assertEquals(0.sp, terminalTextTop(code)) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalTextTop(forwarded(code))) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalTextTop(code.copy(meta = code.meta.copy(itemLive = true)))) + } + @Test fun headingInUnknownContentWithoutFileTakesRowGap() { val base = msg(2, CIDirection.DirectSnd(), 10) val item = withBlocks(base.copy(content = CIContent.SndMsgContent(MsgContent.MCUnknown(text = "# Notes", json = JsonPrimitive("unknown")))), heading()) - assertEquals(TERMINAL_LEVEL_STEP, gap(item, msg(1, CIDirection.DirectSnd(), 0))) - assertEquals(0.sp, terminalHeadingGap(item)) + assertEquals(TERMINAL_PARAGRAPH_GAP, gap(item, msg(1, CIDirection.DirectSnd(), 0))) + assertEquals(0.sp, terminalTextTop(item)) } @Test fun noHeadingGapsWithoutLeadingHeading() { - val older = msg(1, CIDirection.DirectSnd(), 0) val headingSecond = withBlocks(msg(2, CIDirection.DirectSnd(), 10), MarkdownBlock.Paragraph(SegmentRange(0, 1)), heading()) - assertEquals(0.sp, gap(headingSecond, older)) - assertEquals(0.sp, terminalHeadingGap(headingSecond)) - assertEquals(0.sp, terminalHeadingGap(quoted(msg(2, CIDirection.DirectSnd(), 10)))) + assertEquals(0.sp, terminalTextTop(headingSecond)) + assertEquals(0.sp, terminalTextTop(forwarded(headingSecond))) + } + + @Test + fun cardBelowQuoteOrHeaderTakesParagraphGap() { + val base = msg(2, CIDirection.DirectSnd(), 10) + assertEquals(0.sp, terminalCardTop(base)) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalCardTop(quoted(base))) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalCardTop(forwarded(base))) + assertEquals(0.sp, terminalQuoteTop(quoted(base))) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalQuoteTop(quoted(base).let { it.copy(meta = it.meta.copy(itemLive = true)) })) + } + + @Test + fun lastCardTakesParagraphGapAboveReactions() { + val base = msg(2, CIDirection.DirectSnd(), 10) + assertEquals(0.sp, terminalReactionsGap(base)) + assertEquals(TERMINAL_PARAGRAPH_GAP, terminalReactionsGap(base.copy(reactions = thumbsUp))) } } diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt index a3e20f2443..d9d29237bb 100644 --- a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt @@ -62,6 +62,7 @@ private val previewScenes = listOf( SnapshotScene("ChatInfoView.PreviewChatInfoLayout") { chat.simplex.common.views.chat.PreviewChatInfoLayout() }, SnapshotScene("ChatView.PreviewChatLayout") { PreviewChatLayout() }, SnapshotScene("ChatView.PreviewGroupChatLayout") { PreviewGroupChatLayout() }, + SnapshotScene("ChatView.PreviewGroupChatLayoutTerminal", chatItemFontScales) { PreviewGroupChatLayoutTerminal() }, SnapshotScene("ComposeFileView.PreviewComposeFileView") { PreviewComposeFileView() }, SnapshotScene("ComposeVoiceView.PreviewComposeAudioView") { PreviewComposeAudioView() }, SnapshotScene("ContextItemView.PreviewContextItemView") { PreviewContextItemView() }, @@ -85,6 +86,8 @@ private val previewScenes = listOf( SnapshotScene("CIMetaView.PreviewCIMetaViewEditedSent", chatItemFontScales) { SimpleXTheme { PreviewCIMetaViewEditedSent() } }, SnapshotScene("CIMetaView.PreviewCIMetaViewDeletedContent", chatItemFontScales) { SimpleXTheme { PreviewCIMetaViewDeletedContent() } }, SnapshotScene("ChatItemView.PreviewChatItemView", chatItemFontScales) { SimpleXTheme { PreviewChatItemView() } }, + SnapshotScene("ChatItemView.PreviewChatItemViewEmptyLines", chatItemFontScales) { SimpleXTheme { PreviewChatItemViewEmptyLines() } }, + SnapshotScene("ChatItemView.PreviewChatItemViewEmptyLinesTerminal", chatItemFontScales) { SimpleXTheme { PreviewChatItemViewEmptyLinesTerminal() } }, SnapshotScene("ChatItemView.PreviewChatItemViewDeletedContent", chatItemFontScales) { PreviewChatItemViewDeletedContent() }, SnapshotScene("DeletedItemView.PreviewDeletedItemView", chatItemFontScales) { PreviewDeletedItemView() }, SnapshotScene("IntegrityErrorItemView.IntegrityErrorItemViewPreview", chatItemFontScales) { IntegrityErrorItemViewPreview() }, diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalChatItemRowTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalChatItemRowTest.kt new file mode 100644 index 0000000000..0af912b3b8 --- /dev/null +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalChatItemRowTest.kt @@ -0,0 +1,54 @@ +package chat.simplex.app + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import chat.simplex.common.views.chat.item.* +import kotlin.test.Test +import kotlin.test.assertEquals + +class TerminalChatItemRowTest { + private val density = Density(1f) + private val cardGap = with(density) { TERMINAL_PARAGRAPH_GAP.roundToPx() } + private val alice = ChatItemSender("alice", null, null, own = false, image = null) + private val placed = mutableMapOf() + + private fun messageTop(sender: ChatItemSender?, message: @Composable (Modifier) -> Unit): Int { + renderScene { + CompositionLocalProvider(LocalTerminalLayout provides true) { + Box(Modifier.width(300.dp).record(placed, "row")) { + TerminalChatItemRow(sender, gutter = 0.dp, topGap = 0.dp) { message(Modifier.record(placed, "message")) } + } + } + } + return placed.getValue("message").relativeTo(placed.getValue("row")).y + } + + @Test + fun cardRightBelowNameTakesParagraphGap() { + val textTop = messageTop(alice) { Box(it.fixed(100, 22, 17)) } + assertEquals(textTop + cardGap, messageTop(alice) { Box(it.messageCard().fixed(100, 40, null)) }) + } + + @Test + fun cardBelowTextTakesNoGapUnderName() { + val textTop = messageTop(alice) { Box(it.fixed(100, 22, 17)) } + val cardSecond = messageTop(alice) { + Column(it) { + Box(Modifier.fixed(100, 22, 17)) + Box(Modifier.messageCard().fixed(100, 40, null)) + } + } + assertEquals(textTop, cardSecond) + } + + @Test + fun cardWithoutNameTakesNoGap() { + assertEquals(0, messageTop(null) { Box(it.messageCard().fixed(100, 40, null)) }) + } +} diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMarkdownGapsTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMarkdownGapsTest.kt new file mode 100644 index 0000000000..833ef16b91 --- /dev/null +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMarkdownGapsTest.kt @@ -0,0 +1,73 @@ +package chat.simplex.app + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.material.MaterialTheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import chat.simplex.common.model.* +import chat.simplex.common.views.chat.item.* +import kotlin.test.Test +import kotlin.test.assertEquals + +class TerminalMarkdownGapsTest { + private val density = Density(1f) + private val placed = mutableMapOf() + + private fun paragraphGaps(n: Int) = with(density) { (TERMINAL_PARAGRAPH_GAP.value * n).dp.roundToPx() } + + private fun lineBreaks(n: Int) = + if (n == 1) FormattedText("\n", Format.Markup(BlockToken.LineBreak())) else FormattedText("\n".repeat(n), Format.Markup(BlockToken.ParagraphBreak(n))) + + private fun height(terminal: Boolean, fts: List, blocks: List): Int { + renderScene { + CompositionLocalProvider(LocalTerminalLayout provides terminal, LocalBubbleLayout provides !terminal) { + Box(Modifier.width(300.dp).record(placed, "text")) { + MarkdownText( + fts.joinToString("") { it.text }, fts, blocks, toggleSecrets = false, + style = MaterialTheme.typography.body1.copy(lineHeight = 22.sp), linkMode = SimplexLinkMode.DESCRIPTION, blockLayout = true + ) + } + } + } + return placed.getValue("text").height + } + + private fun paragraphs(terminal: Boolean, emptyLines: Int) = height( + terminal, + listOf(FormattedText("a"), lineBreaks(emptyLines + 1), FormattedText("b")), + listOf(MarkdownBlock.Paragraph(SegmentRange(0, 1)), MarkdownBlock.Paragraph(SegmentRange(2, 3))) + ) + + private fun paragraphAndCode(emptyLines: Int) = height( + terminal = true, + listOf( + FormattedText("a"), lineBreaks(emptyLines + 1), FormattedText("```", Format.Markup(BlockToken.FenceMark())), + FormattedText("\n", Format.Markup(BlockToken.HardBreak())), FormattedText("code"), + FormattedText("\n", Format.Markup(BlockToken.HardBreak())), FormattedText("```", Format.Markup(BlockToken.FenceMark())) + ), + listOf(MarkdownBlock.Paragraph(SegmentRange(0, 1)), MarkdownBlock.CodeBlock(content = SegmentRange(4, 5))) + ) + + @Test + fun emptyLinesAreParagraphGapsInTerminalRows() { + val noEmptyLine = paragraphs(terminal = true, emptyLines = 0) + assertEquals(paragraphGaps(1), paragraphs(terminal = true, emptyLines = 1) - noEmptyLine) + assertEquals(paragraphGaps(2), paragraphs(terminal = true, emptyLines = 2) - noEmptyLine) + } + + @Test + fun emptyLinesAreFullLinesInBubbles() { + assertEquals(22, paragraphs(terminal = false, emptyLines = 1) - paragraphs(terminal = false, emptyLines = 0)) + } + + @Test + fun cardGapIsLargerOfParagraphGapAndEmptyLines() { + val oneGap = paragraphAndCode(emptyLines = 0) + assertEquals(oneGap, paragraphAndCode(emptyLines = 1)) + assertEquals(paragraphGaps(2) - paragraphGaps(1), paragraphAndCode(emptyLines = 2) - oneGap) + } +} diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt index b76d5abe39..d908a99e4f 100644 --- a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt @@ -27,7 +27,7 @@ class TerminalMetaLayoutTest { private val metaBaseline = 12 private val metaBoxWidth = metaWidth + 12 private val gap = with(density) { TERMINAL_META_GAP.roundToPx() } - private val blockGap = with(density) { TERMINAL_BLOCK_BOTTOM_GAP.roundToPx() } + private val cardGap = with(density) { TERMINAL_PARAGRAPH_GAP.roundToPx() } private val placed = mutableMapOf() private class Result(val row: Placed, val content: Placed, val meta: Placed?, val overlay: Placed?, val endButton: Placed?, val drawn: Set) @@ -37,6 +37,7 @@ class TerminalMetaLayoutTest { metaReserved: Boolean = true, overlay: Boolean = false, endButton: Boolean = false, + reactions: Boolean = false, content: @Composable (Modifier) -> Unit ): Result { val drawn = mutableSetOf() @@ -47,7 +48,8 @@ class TerminalMetaLayoutTest { meta = { Box(Modifier.record(placed, "meta").drawBehind { drawn += "meta" }.fixed(metaWidth, metaHeight, metaBaseline)) }, overlayMeta = if (overlay) { { Box(Modifier.record(placed, "overlay").drawBehind { drawn += "overlay" }.fixed(metaWidth, metaHeight, metaBaseline)) } } else null, metaReserved = metaReserved, - endButton = if (endButton) { { Box(Modifier.record(placed, "endButton").fixed(22, 22, null)) } } else null + endButton = if (endButton) { { Box(Modifier.record(placed, "endButton").fixed(22, 22, null)) } } else null, + gapBelowCard = if (reactions) cardGap.dp else 0.dp ) { content(Modifier.record(placed, "content")) } } } @@ -85,10 +87,23 @@ class TerminalMetaLayoutTest { } @Test - fun blockGapBelowLastBlockWithMetaBeside() { - val r = layOut { Box(it.messageLastBlock().fixed(100, 40, 30)) } - assertEquals(Placed(rowWidth - metaBoxWidth, 30 - metaBaseline, metaWidth, metaHeight), r.meta) - assertEquals(40 + blockGap, r.row.height) + fun gapBelowLastCardAboveReactions() { + val card = layOut { Box(it.messageCard().messageLastLine().fixed(100, 40, 30)) } + assertEquals(40, card.row.height) + val withReactions = layOut(reactions = true) { Box(it.messageCard().messageLastLine().fixed(100, 40, 30)) } + assertEquals(Placed(rowWidth - metaBoxWidth, 30 - metaBaseline, metaWidth, metaHeight), withReactions.meta) + assertEquals(40 + cardGap, withReactions.row.height) + } + + @Test + fun noGapBelowTextAfterCard() { + val r = layOut(reactions = true) { + Column(it) { + Box(Modifier.messageCard().fixed(100, 40, null)) + Box(Modifier.fixed(100, 22, 17)) + } + } + assertEquals(62, r.row.height) } @Test diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-100.png new file mode 100644 index 0000000000..61e5f6d3dd Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-140.png new file mode 100644 index 0000000000..1600b5d3ab Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-150.png new file mode 100644 index 0000000000..fe86c24bcb Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-dark-font-150.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-100.png new file mode 100644 index 0000000000..6e7d63707f Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-140.png new file mode 100644 index 0000000000..cb51aadd02 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-150.png new file mode 100644 index 0000000000..36669fe0f7 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLines-light-font-150.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-100.png new file mode 100644 index 0000000000..d033532486 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-140.png new file mode 100644 index 0000000000..045ff31a75 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-150.png new file mode 100644 index 0000000000..ec9f4b4bd1 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-dark-font-150.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-100.png new file mode 100644 index 0000000000..1364689c31 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-140.png new file mode 100644 index 0000000000..d44da8c41b Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-150.png new file mode 100644 index 0000000000..41bca11eed Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatItemView.PreviewChatItemViewEmptyLinesTerminal-light-font-150.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-100.png new file mode 100644 index 0000000000..dc4950b6de Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-140.png new file mode 100644 index 0000000000..3a5ea010ae Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-150.png new file mode 100644 index 0000000000..8a54dc173e Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-dark-font-150.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-100.png new file mode 100644 index 0000000000..35366f1ca5 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-140.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-140.png new file mode 100644 index 0000000000..60c6230dba Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-140.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-150.png b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-150.png new file mode 100644 index 0000000000..2c2ec030ee Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/ChatView.PreviewGroupChatLayoutTerminal-light-font-150.png differ diff --git a/apps/multiplatform/product/concepts.md b/apps/multiplatform/product/concepts.md index e7edf3e887..c08774ed53 100644 --- a/apps/multiplatform/product/concepts.md +++ b/apps/multiplatform/product/concepts.md @@ -50,7 +50,7 @@ This document provides a structured mapping between product-level concepts, thei | PC29 | User Address | [README.md](README.md) (Contacts, User Management) | [spec/api.md](../spec/api.md) | `common/.../views/usersettings/UserAddressView.kt`, `UserAddressLearnMore.kt` | `Controller.hs` (`APICreateMyAddress`) | | PC30 | Member Support Chat | [README.md](README.md) (Groups) | [spec/api.md](../spec/api.md) | `common/.../views/chat/group/MemberSupportView.kt`, `MemberSupportChatView.kt`, `MemberAdmission.kt` | `Messages.hs` (`GroupChatScope`), `Controller.hs` | | PC31 | Channels (Relays) | [views/group-info.md](views/group-info.md) | [spec/client/chat-view.md](../spec/client/chat-view.md), [spec/state.md](../spec/state.md) | `common/.../model/ChatModel.kt` (`RelayStatus` incl. `RsRejected`, `GroupRelay`, `GroupMemberRole.Relay`, `GroupMemberStatus.MemRejected`), `common/.../views/chat/group/ChannelRelaysView.kt`, `GroupMemberInfoView.kt` (rejected-status row), `common/.../views/newchat/AddChannelView.kt` (`RelayStatusIndicator` rejected branch), `common/.../views/chat/group/AddGroupRelayView.kt` | `Controller.hs` (`APIAddGroupRelays`, `APIAllowRelayGroup`, `XGrpRelayReject` CONF handler) | -| PC32 | Terminal Chat Layout | [views/chat.md](views/chat.md) (Terminal Layout) | [spec/client/chat-view.md](../spec/client/chat-view.md#TerminalLayout), [spec/state.md](../spec/state.md), [spec/services/theme.md](../spec/services/theme.md#ThemeModeOverrides) | `common/.../views/chat/item/TerminalItemView.kt`, `common/.../views/chat/ChatView.kt` (`LocalTerminalLayout` provider, terminal row branch), `common/.../views/chat/item/ChatItemView.kt` (`alignEnd`, `chatItemTailEnabled`), `FramedItemView.kt` (text edge, meta), `CIEventView.kt` (`chatEventPadding`, `chatEventTextStyle`, `ChatEventWithMeta`), `CIMetaView.kt` (`metaReserveCopy`), `MarkdownBlocks.kt` (terminal block gaps, `headingBox`), `TextItemView.kt` (copy of the meta), `common/.../model/ChatModel.kt` (`ChatLayoutMode`, `activeChatLayout`), `common/.../ui/theme/Theme.kt` (`ThemeModeOverrides.chatLayout`), `common/.../views/usersettings/Appearance.kt` (`ChatLayoutRow`, theme previews), `common/.../views/chat/ChatInfoView.kt` (`ChatLayoutSection`); tests: `common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaCopyTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/PriorityLayoutTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/ChatEventTextTest.kt` | `Types/UITheme.hs` (`ChatLayout`, `UIThemeEntityOverrides`), `Types.hs` (`GroupProfile`), `Controller.hs` (`SetGroupChatLayout`, `SetAddressSettings`) | +| PC32 | Terminal Chat Layout | [views/chat.md](views/chat.md) (Terminal Layout) | [spec/client/chat-view.md](../spec/client/chat-view.md#TerminalLayout), [spec/state.md](../spec/state.md), [spec/services/theme.md](../spec/services/theme.md#ThemeModeOverrides) | `common/.../views/chat/item/TerminalItemView.kt`, `common/.../views/chat/ChatView.kt` (`LocalTerminalLayout` provider, terminal row branch), `common/.../views/chat/item/ChatItemView.kt` (`alignEnd`, `chatItemTailEnabled`), `FramedItemView.kt` (text edge, meta), `CIEventView.kt` (`chatEventPadding`, `chatEventTextStyle`, `ChatEventWithMeta`), `CIMetaView.kt` (`metaReserveCopy`), `MarkdownBlocks.kt` (terminal block gaps, `headingBox`), `TextItemView.kt` (copy of the meta), `common/.../model/ChatModel.kt` (`ChatLayoutMode`, `activeChatLayout`), `common/.../ui/theme/Theme.kt` (`ThemeModeOverrides.chatLayout`), `common/.../views/usersettings/Appearance.kt` (`ChatLayoutRow`, theme previews), `common/.../views/chat/ChatInfoView.kt` (`ChatLayoutSection`); tests: `common/src/commonTest/kotlin/chat/simplex/app/TerminalItemViewTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaCopyTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalMetaLayoutTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalChatItemRowTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/TerminalMarkdownGapsTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/PriorityLayoutTest.kt`, `common/src/desktopTest/kotlin/chat/simplex/app/ChatEventTextTest.kt` | `Types/UITheme.hs` (`ChatLayout`, `UIThemeEntityOverrides`), `Types.hs` (`GroupProfile`), `Controller.hs` (`SetGroupChatLayout`, `SetAddressSettings`) | **Legend for abbreviated paths:** - `common/.../` expands to `common/src/commonMain/kotlin/chat/simplex/common/` diff --git a/apps/multiplatform/product/views/chat.md b/apps/multiplatform/product/views/chat.md index 49ed6b8eff..6f05879b9a 100644 --- a/apps/multiplatform/product/views/chat.md +++ b/apps/multiplatform/product/views/chat.md @@ -128,7 +128,7 @@ When `timedMessageAllowed` is true, compose bar includes a timer icon for settin ### Terminal Layout -On Android and desktop, a chat with the terminal layout shows messages as full-width rows without bubbles, starting at one edge for sent and received messages, with the sender's name above each group of messages and the time at the end of the last line. The wallpaper is drawn as its colour without the image. +On Android and desktop, a chat with the terminal layout shows messages as full-width rows without bubbles, starting at one edge for sent and received messages, with the sender's name above each group of messages, again after a pause of 7.5 minutes, and the time at the end of the last line. The wallpaper is drawn as its colour without the image. A chat uses the user's choice for that chat, otherwise the layout set by the group owner or by the address the contact came from, otherwise the user's choice for the profile and then the app setting, otherwise classic. diff --git a/apps/multiplatform/spec/client/chat-view.md b/apps/multiplatform/spec/client/chat-view.md index 11f15f1d54..8ba615fe8c 100644 --- a/apps/multiplatform/spec/client/chat-view.md +++ b/apps/multiplatform/spec/client/chat-view.md @@ -182,36 +182,36 @@ When `LocalTerminalLayout.current` is true, `ChatItemView` and the item views it - Items are start-aligned for both directions ([`alignEnd`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L125)). The item click has no indication; the row draws it (section 10). `GoToItemButton` is placed as described in section 10 ([L345](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L345), [L819](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L819)). Voice items use the arrangement of received items for both directions. - [`chatItemTailEnabled()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1222) returns false, so `shapeStyle` draws no tail. -- `FramedItemView` has a transparent background. Headers (report, moderated, blocked, deleted, live, forwarded) and the quote have no background and start at the text edge. The quote has the bar of Markdown quotes ([`Modifier.quoteBar`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt#L151)), its text in `onSurface` at 70%, 15sp. The bar and the padding, `TERMINAL_BLOCK_TOP_GAP` (5.75sp) above and `TERMINAL_BLOCK_BOTTOM_GAP` (5sp) below, span the whole quote row, including an image or video thumbnail; the thumbnail has the message corner clip of media (`thumbnailClip`, `clipChatItem`, rounded by the `chatItemRoundness` preference, square at 0) and stands 12dp after the quote text, or 12dp after the bar when the quote has no text and no sender (`QuotedMsgOrGap`, `QUOTE_BAR_GAP`); the file, voice and chat link icons of the quote have no top padding. Headers: `TERMINAL_HEADER_TOP_GAP` (2.5sp) above, `TERMINAL_HEADER_BOTTOM_GAP` (1.5sp) below; the header text uses `chatTextStyle` at its size in `secondary`, and the icon is centred on it and takes no height (`Modifier.inlineIcon()`). -- Images, videos, link previews and chat link cards start at the text edge, `TERMINAL_BLOCK_TOP_GAP` below the part above them, and keep the message corner clip ([`mediaModifier`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L56)). Link previews and chat links are cards in the quote colour ([`cardModifier`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L58)). The item itself is not clipped (`clipChatItem` of `FramedItemView` and `ChatItemView` is skipped), so headings and emoji are drawn whole. An image or video without caption, or a chat link card without text (`gapBelowBlock`, computed with `metaReserved`, which is passed to `ItemWithMeta`), has `TERMINAL_BLOCK_BOTTOM_GAP` below it, outside `ItemWithMeta`. Captions are selected by the classic conditions. +- `FramedItemView` has a transparent background. Headers (report, moderated, blocked, deleted, live, forwarded) and the quote have no background and start at the text edge. The quote has the bar of Markdown quotes ([`Modifier.quoteBar`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt#L166)), its text in `onSurface` at 70%, 15sp. The quote is a card (cards, below), [`terminalQuoteTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L150-L151) below the part above it: `TERMINAL_PARAGRAPH_GAP` below a report, deletion or live header, otherwise 0. The bar spans the whole quote row, including an image or video thumbnail; the thumbnail has the message corner clip of media (`thumbnailClip`, `clipChatItem`, rounded by the `chatItemRoundness` preference, square at 0) and stands 12dp after the quote text, or 12dp after the bar when the quote has no text and no sender (`QuotedMsgOrGap`, `QUOTE_BAR_GAP`); the file, voice and chat link icons of the quote have no top padding. Headers: `TERMINAL_HEADER_TOP_GAP` (2.5sp) above, `TERMINAL_HEADER_BOTTOM_GAP` (1.5sp) below; the header text uses `chatTextStyle` at its size in `secondary`, and the icon is centred on it and takes no height (`Modifier.inlineIcon()`). +- Images, videos, link previews and chat link cards are cards (below), start at the text edge, [`terminalCardTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L147-L148) below the part above them (`TERMINAL_PARAGRAPH_GAP` below a header or the quote, otherwise 0), and keep the message corner clip ([`mediaModifier`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L57)). Link previews and chat links are cards in the quote colour ([`cardModifier`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L59)). The item itself is not clipped (`clipChatItem` of `FramedItemView` and `ChatItemView` is skipped), so headings and emoji are drawn whole. Captions are selected by the classic conditions. - Captions (user, D30): the text below an image, video, link preview, chat link card, voice message or file is laid out as the text of a close follow-up message, the time on it only. `PriorityLayout` measures it in the full width of the item (`limitToPriorityWidth = false`; classic: the width of the media) and places the elements at the start edge in both directions (`placeRelative`), the caption of a link preview has no width limit (classic: `DEFAULT_MAX_IMAGE_WIDTH`), and a chat link card keeps its own width (`width(IntrinsicSize.Max)`). Its gap below the media is the gap from the same media without text to a close follow-up message. An image or video without caption keeps the classic limit (`limitToPriorityWidth = true`): a quote or header above it takes the width of the media, so the white time over the media stays on its bottom end corner. -- [`CIMarkdownText`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L487): top padding `terminalTop` (required): 0 below the sender row, a header, the quote, a voice message or a file, `TERMINAL_BLOCK_BOTTOM_GAP` below an image, video, link preview or chat link card; plus [`terminalHeadingGap(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L143-L144), `TERMINAL_LEVEL_STEP` when the text starts with a heading and is not at the top of the item (below a quote, a header or a block); no bottom padding. Its text style: `body1` in `messageTextColor()`, merged with `chatTextStyle` at the `body1` size. The default style of `MarkdownText` is classic and is used outside the rows (the compose context preview). -- Code block cards, table cards and rules of `MarkdownBlocks`: `TERMINAL_BLOCK_TOP_GAP` above, `TERMINAL_BLOCK_BOTTOM_GAP` below, except the last block of a message without a meta line (`marksLastBlock`; a live message has the meta line with the typing indicator, so its last block keeps the gap). That block has no bottom margin and is marked with `messageLastBlock()`: `TERMINAL_BLOCK_BOTTOM_GAP` is added below it when the time stays beside it, and the time moved under it is `TERMINAL_META_GAP` below its edge (section 10). In a message of rules only, the rules are at least as wide as the copy of the time (`ruleMinWidth` of `MarkdownBlocks`, measured by `MarkdownText`; user, D31), as in classic, where the meta line sets the width; the time stays beside them unless a wider quote or header widens the item so that the rule leaves no room for the time. -- Text blocks of [`MarkdownBlocks`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt#L59): a paragraph break, and a heading that does not start the text, add `TERMINAL_LEVEL_STEP` (4.75sp), also in bubbles (outside chats: half the line height, before a paragraph break only); above a heading that starts the text, the gap is added by `terminalRowGap` or `terminalHeadingGap`. A block after a heading, other than a heading, has `TERMINAL_HEADING_BOTTOM_GAP` (half of `TERMINAL_LEVEL_STEP`, 2.375sp) above it instead, so a heading is nearer to its own text than to the text above it. -- Text styles: [`chatTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L87-L94) sets the line height to font size × `CHAT_LINE_HEIGHT_RATIO` (22/16) × f(w) and `LineHeightStyle(Proportional, Trim.None)`, in terminal rows and in bubbles (`usesChatTypography()`: `LocalTerminalLayout` or `LocalBubbleLayout`); outside chats it returns `TextStyle.Default`. Every line takes the full line height, one-line texts included. The space added to a line is split in the ratio of the font's ascent to its descent. On desktop each run of a line is given its own line box; with this alignment, runs of different sizes (the 12sp time in the copy of the meta) are placed on one baseline in a line of the body line height. f(w) = 1 − `CHAT_LINE_HEIGHT_CONTRAST_SLOPE` (0.1515) × (1 − w); w: the L* contrast of the text colour against `MaterialTheme.colors.background`, divided by that of `messageTextColor()`, limited to 0…1, and 1 when the message text has no contrast. Used for message text and captions (the style of `CIMarkdownText`), Markdown quotes (text colour at 70%), code, headings (body line height × scale), quote text and the quote's sender (in `body1`, Inter), the sender name and role, event texts ([`chatEventTextStyle(base)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L21-L23): 12sp, `secondary`, merged into `base`, by default `LocalTextStyle.current`; in both layouts the text direction is left unspecified, which Compose resolves to the layout direction, so that an event starting with a name in the opposite direction keeps the copy of the time at the end of the row), header texts and the time. For names and the white time over media (`lineHeightColor` of `CIMetaView`), f is computed with the message text colour. Line heights in the light and dark themes: message text 22sp, quote text 19.6sp and 19.9sp, event text and time 15.1sp and 15.4sp. +- [`CIMarkdownText`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L488): top padding [`terminalTextTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L141-L145): `TERMINAL_PARAGRAPH_GAP` below a card (the quote, or content other than text: an image, video, voice message, file, link preview or chat link card) and below a header when the text starts with a code block, table or rule; 0 instead when the text starts with empty lines (block Markdown: `leadingEmptyLines`; other text: a line break at its start, except in reports, whose first line holds the reason), which are then the gap (the larger of the two; cards, below); below a header (forwarded, deleted, live, report) and no quote, `TERMINAL_LEVEL_STEP` when the text starts with a heading; otherwise 0. No bottom padding. Its text style: `body1` in `messageTextColor()`, merged with `chatTextStyle` at the `body1` size. The default style of `MarkdownText` is classic and is used outside the rows (the compose context preview). +- Code block cards, table cards and rules of `MarkdownBlocks` are cards (below) without margins; the gap between a card and the block next to it is the larger of `TERMINAL_PARAGRAPH_GAP` and the empty lines typed between them (bubbles: `TERMINAL_BLOCK_TOP_GAP` (5.75sp) above, `TERMINAL_BLOCK_BOTTOM_GAP` (5sp) below). The last block of a message without a meta line (`marksLastBlock`; a live message has the meta line with the typing indicator) is also marked with `messageLastLine()`: the time moved under it is `TERMINAL_META_GAP` below its edge (section 10). In a message of rules only, the rules are at least as wide as the copy of the time (`ruleMinWidth` of `MarkdownBlocks`, measured by `MarkdownText`; user, D31), as in classic, where the meta line sets the width; the time stays beside them unless a wider quote or header widens the item so that the rule leaves no room for the time. +- Text blocks of [`MarkdownBlocks`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownBlocks.kt#L59): a heading that does not start the text adds `TERMINAL_LEVEL_STEP` (4.75sp), also in bubbles (outside chats: no gap); above a heading that starts the text, the gap is the row gap (`terminalRowGap`) or `terminalTextTop`. A block after a heading, other than a heading, has `TERMINAL_HEADING_BOTTOM_GAP` (half of `TERMINAL_LEVEL_STEP`, 2.375sp) above it instead, so a heading is nearer to its own text than to the text above it. Each empty line typed before or between blocks and list entries (`emptyLines`; before the first block `leadingEmptyLines`) adds `emptyLineHeight`: in terminal rows `TERMINAL_PARAGRAPH_GAP`, the gap between messages (user); in bubbles and outside chats one line of the text style, its line height in proportion to the font size in px, as Android sets text line heights above font scale 1.05. The core sends `markdownBlocks` for text with block syntax or an empty line, up to 2000 markup tokens; text without them is one text in all layouts, each of its empty lines one line of the text style. After the last block, the empty lines are the line breaks of the tokens after it (the core removes one final line break of the text), less one when the text does not end with a line break (`trailingEmptyLines`), as in plain text, where the last line holds the time; when there are any, the meta line follows them, also in terminal rows. A gap has at most `MAX_EMPTY_LINES` (100) empty lines. +- Text styles: [`chatTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L82-L89) sets the line height to font size × `CHAT_LINE_HEIGHT_RATIO` (22/16) × f(w) and `LineHeightStyle(Proportional, Trim.None)`, in terminal rows and in bubbles (`usesChatTypography()`: `LocalTerminalLayout` or `LocalBubbleLayout`); outside chats it returns `TextStyle.Default`. Every line takes the full line height, one-line texts included. The space added to a line is split in the ratio of the font's ascent to its descent. On desktop each run of a line is given its own line box; with this alignment, runs of different sizes (the 12sp time in the copy of the meta) are placed on one baseline in a line of the body line height. f(w) = 1 − `CHAT_LINE_HEIGHT_CONTRAST_SLOPE` (0.1515) × (1 − w); w: the L* contrast of the text colour against `MaterialTheme.colors.background`, divided by that of `messageTextColor()`, limited to 0…1, and 1 when the message text has no contrast. Used for message text and captions (the style of `CIMarkdownText`), Markdown quotes (text colour at 70%), code, headings (body line height × scale), quote text and the quote's sender (in `body1`, Inter), the sender name and role, event texts ([`chatEventTextStyle(base)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L20-L22): 12sp, `secondary`, merged into `base`, by default `LocalTextStyle.current`; in both layouts the text direction is left unspecified, which Compose resolves to the layout direction, so that an event starting with a name in the opposite direction keeps the copy of the time at the end of the row), header texts and the time. For names and the white time over media (`lineHeightColor` of `CIMetaView`), f is computed with the message text colour. Line heights in the light and dark themes: message text 22sp, quote text 19.6sp and 19.9sp, event text and time 15.1sp and 15.4sp. - Headings: body size × `TERMINAL_HEADING_RATIO` (1.25) to the power 2, 1, 0 for levels 1, 2, 3, 25, 20 and 16sp for 16sp text; levels 4–6 also at the body size; all bold (also in bubbles; Markdown outside chats: 1.5, 1.3, 1.15); line heights scaled the same. `Modifier.headingBox` lays a heading out with the space of a body line above its capitals and below its last baseline (Inter cap height 2048/2816 em). It uses the px ratio of the body and heading font sizes: Android scales font sizes non-linearly from font scale 1.03 and, above 1.05, sets line heights in proportion to the font size in px, so the capitals are placed as body capitals at every font scale (within 1px at 1, 1.15 and 1.3). -- Files: `TERMINAL_FILE_TOP_GAP` (2sp) above the file row, no padding below, no padding of its icon. Voice messages drawn by `FramedItemView` (with a caption, a quote or a header; `hasText = true`): the layout of a voice message drawn alone (4sp above, 6sp below, its indicator), without its own time; no padding below the item. -- Emoji-only items, also under a quote or a header: `TERMINAL_EMOJI_TOP_GAP` (4.25sp) above, `TERMINAL_EMOJI_BOTTOM_GAP` (1.5sp) below (classic: 8dp; under a quote or header the text paddings of a bubble). Under a quote or a header the emoji is not stretched to the item width, so its reported last line is the emoji itself; `PriorityLayout` places it at the start edge in both directions. -- Item gaps: one gap above each row, [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L140-L141), passed by `ChatItemsList` as `topGap` of the row. It is `TERMINAL_LEVEL_STEP` when an older item exists, the rows are not separated and one of these holds: the gap to the older item is large; the row shows a sender row; either item is an event (content without a terminal sender); the text of the item is at its top (text or unknown content without a file, without quote, header, deletion, live state or report) and its first block is a heading. Otherwise it is 0. `separated` (`terminalRowsSeparated`): a date separator is drawn between the two rows (the older row is revealed, a single item or a revealed group row, and its date differs from that of the oldest item of the row), or the older item is the chat banner. For a collapsed group, `older` is the item older than the group, and `largeGap` is computed against the oldest item of the group. The bottom of a row is `TERMINAL_LEVEL_STEP` when a date separator is drawn below it, 8dp for the newest row, as classic, otherwise 0 (`ChatItemBox(top, bottom)`; classic: half of `BUBBLE_CLOSE_GAP` or `BUBBLE_FAR_GAP` above and below). Above a sender row, `TERMINAL_SENDER_TOP_GAP` (6.5sp) is added; below the name, `TERMINAL_SENDER_BOTTOM_GAP` (5.5sp). The gaps are constants in sp at the top of `TerminalItemView.kt`, converted to dp with the font scale. The bottom padding of call items (8dp), the paddings of voice messages drawn without `FramedItemView` (no caption, quote, header, deletion or live state; 4sp above, 6sp below) and the 6dp between the two rows of the forwarded-from header are classic. -- Vertical gaps, measured from the baseline (or a block's bottom edge) to the top of the tallest letter, a heading's capitals, or a block's top edge: +- Files and voice messages are cards (below): `terminalCardTop(item)` above them (`terminalTop` of `CIFileView`, passed by `FramedItemView`; the top padding of `CIVoiceView`), no padding below, no padding of the file icon. Voice messages drawn by `FramedItemView` (with a caption, a quote or a header; `hasText = true`): the layout of a voice message drawn alone (its indicator), without its own time; no padding below the item. +- Emoji-only items, also under a quote or a header, are cards (below): `terminalCardTop(item)` above, no padding below (classic: 8dp; under a quote or header the text paddings of a bubble). Under a quote or a header the emoji is not stretched to the item width, so its reported last line is the emoji itself; `PriorityLayout` places it at the start edge in both directions. +- Item gaps: one gap above each row, [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L138-L139), passed by `ChatItemsList` as `topGap` of the row. It is `TERMINAL_PARAGRAPH_GAP` when an older item exists, the rows are not separated and one of these holds: the gap to the older item is large; the row shows a sender row; either item is not one-line ([`isOneLine`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L156-L157): text or unknown content without a file, without quote, header, deletion, live state or report, without block Markdown and without a line break in the text, so that a large emoji is one-line and an event is not; user); the older item has reactions, so that the gap stands below its reactions row, and the gap above an item does not change when its first reaction arrives. Otherwise it is 0. `separated` (`terminalRowsSeparated`): a date separator is drawn between the two rows (the older row is revealed, a single item or a revealed group row, and its date differs from that of the oldest item of the row), or the older item is the chat banner. For a collapsed group, `older` is the item older than the group, and `largeGap` is computed against the oldest item of the group. The bottom of a row is `TERMINAL_LEVEL_STEP` when a date separator is drawn below it, 8dp for the newest row, as classic, otherwise 0 (`ChatItemBox(top, bottom)`; classic: half of `BUBBLE_CLOSE_GAP` or `BUBBLE_FAR_GAP` above and below). The sender row has no gap of its own above or below it, other than the gap above a card (cards, below). The gaps are constants in sp at the top of `TerminalItemView.kt`, converted to dp with the font scale. The bottom padding of call items (8dp) and the 6dp between the two rows of the forwarded-from header are classic. +- Vertical gaps, between line boxes and block edges, are multiples of the paragraph unit `TERMINAL_PARAGRAPH_GAP` (P: a third of the line height of 16sp text, 7.33sp; user): ``` -level 1 lines of a quote -level 2 lines of a message; messages of one sender within 60 seconds; a block against the text line or block next to it -level 3 messages of one sender 60 seconds or more apart; sender name → message or header; paragraph break; above a heading, also at the start of a message -level 4 last line of a message → next sender name; above and below an event +0 lines of a message; close one-line messages of one sender; the sender name and the line under it; reactions under a line of text +n × P n empty lines typed in a message; headings add TERMINAL_LEVEL_STEP above and TERMINAL_HEADING_BOTTOM_GAP below +P other messages, also of one sender; a sender change, above the name; above and below an event; next to a card; below a reactions row ``` -- Event, feature and member-created items use [`chatEventPadding()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L25-L28): in terminal rows the text edge at the sides, `TERMINAL_EVENT_TOP_GAP` (8.25sp) above and `TERMINAL_EVENT_BOTTOM_GAP` (1.5sp) below, so that the capitals of the event text are where the capitals of a sender name would be and its last baseline is as far from the row end as that of a message line (classic: 6dp at the sides, above and below). The icons of feature and preference items are centred on the text and take no height (`Modifier.inlineIcon()`); the row of merged feature icons is one event text line high; both also in bubbles. `CIEventView` has no line limit in terminal rows, so the copy of the time stays at the end of the text (user, D23; classic: 4 lines). Voice and call items and reactions start at the text edge. The voice play button and file status circle are filled with the quote colour (`sentQuote`, `receivedQuote`; classic: `sentMessage`, `receivedMessage`). -- Time and status: placed at the end of the row by [`ItemWithMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L222-L236), the baseline of the time on the last baseline of the content (section 10). Message text ends with [`metaReserveCopy`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIMetaView.kt#L226-L272), in both layouts: a transparent copy of the meta with no-break spaces, in `FontWeight.Normal`. In the terminal layout the copy starts with a word joiner (U+2060), which forbids a line break before the copy, also after the three spaces of an idle live message (`noTyping`), so the time is not moved alone to the next line. In bubbles the copy starts with a breaking space (`breakBefore`, user) when text precedes it in its paragraph, so the time alone moves to the next line when it does not fit; the copy of the meta line under a last card or rule (`range` empty) starts without a space. The direction mark of its paragraph follows (U+200E left-to-right, U+200F right-to-left), so that the bidirectional algorithm places the copy at the end of the line, also after words in the other direction on a wrapped last line. Its spaces and texts are appended by [`reserveSpaceForMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIMetaView.kt#L144-L224), which has the conditions of `CIMetaText`, except that the timer is reserved for every timed message, and returns the classic string unchanged, through span parameters: icon spaces and the spaces between them are no-break spaces at the `body1` size in dp (16dp converted to sp with the density, so that they keep their width at every font scale, as the icons do; also after a heading and in event text), 18dp for each icon, wider than a 12dp icon with its spacer (15dp or 16dp); after the 17dp icons one more space is added (22.5dp against 21dp): the sent and received status icons (`tallStatusIcon`, also used by `CIMetaText`) and the via-proxy icon; the time and the timer text of a disappearing message are at 12sp. The copy includes the file encryption and signature icons (`encrypted` and `signedFileVerified` of `MarkdownText`, passed by `CIMarkdownText` from the item). In the terminal layout, when the last word and the copy do not fit in the line, the last word moves to the next line with the time. Text whose paragraph direction (`textLayoutDirection`: right-to-left when the first 50 characters of the message text hold a right-to-left character; all blocks and lines of a message take it) differs from the outer direction (`parentDirection`, passed by the blocks and by the meta line of a live message; otherwise `LocalLayoutDirection`) ends with a line break instead of the copy, so the time is placed on an added empty line. Emoji, and the last code block, table or rule of a message, report their width (`Modifier.messageLastLine()`, `Modifier.messageLastBlock()`); the time moves under them when the row leaves no room for it beside them. The meta line with the time is drawn under such a block only for live messages, for the typing indicator. File text keeps the space reserved for the time at the end of its size line. Images and videos without a caption (`captionlessMedia`) keep the meta in `secondary` beside the media when it fits in the row, otherwise the meta is drawn over the bottom end of the media in white, as in the classic layout (`overlayMeta`). Event items are wrapped in [`ChatEventWithMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L30-L43), which passes the separator and the end of the event text apart (`separator`, `ts`): in the classic layout two spaces and the time without a style, in the terminal layout three transparent no-break spaces in `chatEventStyle` and the transparent `metaReserveCopy` of the meta without status and edit icons, so the last word of the event text is moved to the next line with the time when they do not fit. Each view puts the separator where the classic layout has two spaces (user, D28): after the event text, or in the "Open" and "Accept" links, so the classic output is unchanged. +- Cards: images and videos, link previews, chat link cards, code blocks, tables and rules, files, voice messages, the quote, large emoji, group invitations, and the rounded cards of deleted and error items (`ItemTextCard`, `DecryptionErrorCard`). Each is marked with [`Modifier.messageCard()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L232); the marks are read in terminal rows only. A card has `TERMINAL_PARAGRAPH_GAP` next to text or another card of its item, as the top padding of the lower part. At the top of an item it has none above it: `TerminalChatItemRow` adds `TERMINAL_PARAGRAPH_GAP` under the sender row when the item reports a card at its top. At the bottom of an item it has none below it: `ItemWithMeta` adds `gapBelowCard` when the content reports a card at its bottom, [`terminalReactionsGap(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L153-L154), `TERMINAL_PARAGRAPH_GAP` when reactions follow as a line of text, otherwise 0. +- Event, feature and member-created items use [`chatEventPadding()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L24-L27): in terminal rows the text edge at the sides and no padding above and below, so that the row gap, `TERMINAL_PARAGRAPH_GAP`, separates an event from the rows above and below it (classic: 6dp at the sides, above and below). The icons of feature and preference items are centred on the text and take no height (`Modifier.inlineIcon()`); the row of merged feature icons is one event text line high; both also in bubbles. `CIEventView` has no line limit in terminal rows, so the copy of the time stays at the end of the text (user, D23; classic: 4 lines). Voice and call items and reactions start at the text edge. The voice play button and file status circle are filled with the quote colour (`sentQuote`, `receivedQuote`; classic: `sentMessage`, `receivedMessage`). +- Time and status: placed at the end of the row by [`ItemWithMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L251-L265), the baseline of the time on the last baseline of the content (section 10). Message text ends with [`metaReserveCopy`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIMetaView.kt#L226-L272), in both layouts: a transparent copy of the meta with no-break spaces, in `FontWeight.Normal`. In the terminal layout the copy starts with a word joiner (U+2060), which forbids a line break before the copy, also after the three spaces of an idle live message (`noTyping`), so the time is not moved alone to the next line. In bubbles the copy starts with a breaking space (`breakBefore`, user) when text precedes it in its paragraph, so the time alone moves to the next line when it does not fit; the copy of the meta line under a last card or rule (`range` empty) starts without a space. The direction mark of its paragraph follows (U+200E left-to-right, U+200F right-to-left), so that the bidirectional algorithm places the copy at the end of the line, also after words in the other direction on a wrapped last line. Its spaces and texts are appended by [`reserveSpaceForMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIMetaView.kt#L144-L224), which has the conditions of `CIMetaText`, except that the timer is reserved for every timed message, and returns the classic string unchanged, through span parameters: icon spaces and the spaces between them are no-break spaces at the `body1` size in dp (16dp converted to sp with the density, so that they keep their width at every font scale, as the icons do; also after a heading and in event text), 18dp for each icon, wider than a 12dp icon with its spacer (15dp or 16dp); after the 17dp icons one more space is added (22.5dp against 21dp): the sent and received status icons (`tallStatusIcon`, also used by `CIMetaText`) and the via-proxy icon; the time and the timer text of a disappearing message are at 12sp. The copy includes the file encryption and signature icons (`encrypted` and `signedFileVerified` of `MarkdownText`, passed by `CIMarkdownText` from the item). In the terminal layout, when the last word and the copy do not fit in the line, the last word moves to the next line with the time. Text whose paragraph direction (`textLayoutDirection`: right-to-left when the first 50 characters of the message text hold a right-to-left character; all blocks and lines of a message take it) differs from the outer direction (`parentDirection`, passed by the blocks and by the meta line of a live message; otherwise `LocalLayoutDirection`) ends with a line break instead of the copy, so the time is placed on an added empty line. Emoji, and the last code block, table or rule of a message, report their width (`Modifier.messageLastLine()`); the time moves under them when the row leaves no room for it beside them. The meta line with the time is drawn under such a block only for live messages, for the typing indicator, and after empty lines at the end of the text. File text keeps the space reserved for the time at the end of its size line. Images and videos without a caption (`captionlessMedia`) keep the meta in `secondary` beside the media when it fits in the row, otherwise the meta is drawn over the bottom end of the media in white, as in the classic layout (`overlayMeta`). Event items are wrapped in [`ChatEventWithMeta`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIEventView.kt#L29-L42), which passes the separator and the end of the event text apart (`separator`, `ts`): in the classic layout two spaces and the time without a style, in the terminal layout three transparent no-break spaces in `chatEventStyle` and the transparent `metaReserveCopy` of the meta without status and edit icons, so the last word of the event text is moved to the next line with the time when they do not fit. Each view puts the separator where the classic layout has two spaces (user, D28): after the event text, or in the "Open" and "Accept" links, so the classic output is unchanged. - Group invitations, deleted items and error items (`IntegrityErrorItemView`, `CIRcvDecryptionError`) keep their rounded coloured card. ### Bubbles When `LocalBubbleLayout.current` is true (classic chats, provided by `ChatView` with `LocalTerminalLayout`, the classic theme preview, and the chat item and chat view previews through [`BubblePreview`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1505-L1508)), bubbles follow one inset (plans/2026-10-25-classic-bubbles.md). The previews of deleted and error items clip them as `ChatItemView` does (`clipChatItem`). -- Texts use `chatTextStyle`, as terminal rows: message text, captions, Markdown blocks, quote text and sender (`body1`, Inter), headers, the time, event texts; the texts of `DeletedItemView` and error items through [`bubbleTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L96-L98), `chatTextStyle` in bubbles only, so the cards of terminal rows keep their style (the one-line text of `MarkedDeletedItemView` keeps its style, its line height rounded by `bubbleLineHeight`). Call items are drawn as in master: `ChatItemView` provides `LocalBubbleLayout` false for them. Markdown blocks in bubbles have the gaps of terminal rows (paragraph breaks, headings, cards and rules) and their heading sizes and `headingBox`. -- On desktop, [`bubbleLineHeight(lineHeight)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L100-L106) rounds a line height in bubbles to whole pixels, with the proportional alignment of `chatTextStyle`: `chatTextStyle` applies it in bubbles, and so do the last text of a group invitation (18sp, or "Tap to join" at the line height of Inter, `INTER_LINE_HEIGHT`), "Fix connection" of decryption errors and the size line of files (the line height of Inter) and the text of `MarkedDeletedItemView` (22sp); on Android the line heights are unchanged. Skia draws the baseline of a line at its top plus the rounded ascent and reports the rounded line height less the descent, which Compose rounds into `FirstBaseline` and `LastBaseline`; both are one pixel row only when ascent and descent add up to whole pixels, so the time, placed by reported baselines, is drawn on the baseline of the text (owner report). -- `BUBBLE_TEXT_INSET` (11dp, user) is the distance from a bubble or band edge to the capitals of the text under it, and from the last baseline to the edge under it; in dp, so it keeps its size at larger fonts (user). Message text, captions and an emoji under a quote or header have [`bubbleTextBoxPadding()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L574-L581): that inset less the space of 16sp text with the full line height above its capitals (`BUBBLE_LINE_ABOVE_CAPS`, 6sp) and under its last baseline (`BUBBLE_LINE_BELOW_BASELINE`, 4.375sp), at least 0; 5dp and 6.625dp at font scale 1. `BUBBLE_SIDE_INSET` (14dp, user) is the distance from the bubble sides to message text, captions, an emoji under a quote or header and the end of the time. Header bands, the quote band and deleted and error items use [`Modifier.bubbleTextPadding(firstLineFontSize, bottom)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L570-L572): `BUBBLE_SIDE_INSET` at the sides and the inset by the first and last baselines; a header followed by a quote or a forwarded header has no inset below. The header starts at `BUBBLE_SIDE_INSET` and its icon takes no height. Deleted and error items are drawn by [`ItemTextCard`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt#L34-L53) (`DeletedItemView`, `MarkedDeletedItemView`, `CIMsgError`) and the private `DecryptionErrorCard` (the decryption error items), each with one switch between the bubble and the rounded card of terminal rows: in bubbles they fill the shape of `clipChatItem` (`Surface` with its default `RectangleShape`, user). That shape has no tail for items without message content ([`shapeStyleWithTail`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1333-L1385): `msgContent` null; user): deleted, moderated, blocked, error, decryption error and invalid JSON items. [`chatItemTailRendered(chatItem, tailVisible, revealed)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1224-L1226) tells whether the tail is drawn, from the shape style of the item as `clipChatItem` computes it; `FramedItemView`, `chatItemOffset` and the sender rows of `ChatItemsList` use it. The file row ends `BUBBLE_TEXT_INSET` under the baseline of its size line; the ink bottom of the file icon is aligned to that baseline ([`fileIconOnBaseline`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt#L254-L260): the icon size × `FILE_ICON_INK_INSET`, the space under the ink of `ic_draft_filled`, rounded down). +- Texts use `chatTextStyle`, as terminal rows: message text, captions, Markdown blocks, quote text and sender (`body1`, Inter), headers, the time, event texts; the texts of `DeletedItemView` and error items through [`bubbleTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L91-L93), `chatTextStyle` in bubbles only, so the cards of terminal rows keep their style (the one-line text of `MarkedDeletedItemView` keeps its style, its line height rounded by `bubbleLineHeight`). Call items are drawn as in master: `ChatItemView` provides `LocalBubbleLayout` false for them. Markdown blocks in bubbles have the heading gaps, heading sizes and `headingBox` of terminal rows; cards and rules have `TERMINAL_BLOCK_TOP_GAP` (5.75sp) above and `TERMINAL_BLOCK_BOTTOM_GAP` (5sp) below, and each empty line typed is one line of the text style. +- On desktop, [`bubbleLineHeight(lineHeight)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L95-L101) rounds a line height in bubbles to whole pixels, with the proportional alignment of `chatTextStyle`: `chatTextStyle` applies it in bubbles, and so do the last text of a group invitation (18sp, or "Tap to join" at the line height of Inter, `INTER_LINE_HEIGHT`), "Fix connection" of decryption errors and the size line of files (the line height of Inter) and the text of `MarkedDeletedItemView` (22sp); on Android the line heights are unchanged. Skia draws the baseline of a line at its top plus the rounded ascent and reports the rounded line height less the descent, which Compose rounds into `FirstBaseline` and `LastBaseline`; both are one pixel row only when ascent and descent add up to whole pixels, so the time, placed by reported baselines, is drawn on the baseline of the text (owner report). +- `BUBBLE_TEXT_INSET` (11dp, user) is the distance from a bubble or band edge to the capitals of the text under it, and from the last baseline to the edge under it; in dp, so it keeps its size at larger fonts (user). Message text, captions and an emoji under a quote or header have [`bubbleTextBoxPadding()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L574-L581): that inset less the space of 16sp text with the full line height above its capitals (`BUBBLE_LINE_ABOVE_CAPS`, 6sp) and under its last baseline (`BUBBLE_LINE_BELOW_BASELINE`, 4.375sp), at least 0; 5dp and 6.625dp at font scale 1. `BUBBLE_SIDE_INSET` (14dp, user) is the distance from the bubble sides to message text, captions, an emoji under a quote or header and the end of the time. Header bands, the quote band and deleted and error items use [`Modifier.bubbleTextPadding(firstLineFontSize, bottom)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L570-L572): `BUBBLE_SIDE_INSET` at the sides and the inset by the first and last baselines; a header followed by a quote or a forwarded header has no inset below. The header starts at `BUBBLE_SIDE_INSET` and its icon takes no height. Deleted and error items are drawn by [`ItemTextCard`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/DeletedItemView.kt#L34-L53) (`DeletedItemView`, `MarkedDeletedItemView`, `CIMsgError`) and the private `DecryptionErrorCard` (the decryption error items), each with one switch between the bubble and the rounded card of terminal rows: in bubbles they fill the shape of `clipChatItem` (`Surface` with its default `RectangleShape`, user). That shape has no tail for items without message content ([`shapeStyleWithTail`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1333-L1385): `msgContent` null; user): deleted, moderated, blocked, error, decryption error and invalid JSON items. [`chatItemTailRendered(chatItem, tailVisible, revealed)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L1224-L1226) tells whether the tail is drawn, from the shape style of the item as `clipChatItem` computes it; `FramedItemView`, `chatItemOffset` and the sender rows of `ChatItemsList` use it. The file row ends `BUBBLE_TEXT_INSET` under the baseline of its size line; the ink bottom of the file icon is aligned to that baseline ([`fileIconOnBaseline`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/CIFileView.kt#L255-L261): the icon size × `FILE_ICON_INK_INSET`, the space under the ink of `ic_draft_filled`, rounded down). - The time: [`Modifier.bubbleMeta()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L583-L587) places the baseline of the time `BUBBLE_TEXT_INSET` above the bubble bottom, on the last baseline of the text; ticks without a time where they stand next to a time (`metaBaseline`, shared with `TerminalMetaLayout`). In deleted and error items the time follows the text on its last baseline (`bubbleMetaOnBaseline`, the text aligned by `LastBaseline`), so a wrapped text keeps the time on its last line; in group invitations [`MetaOnLastBaseline(meta, content)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/FramedItemView.kt#L595-L607) places it at the end of the card on its last baseline (the card bottom without a baseline, in intrinsic measurement; user). Message text, an emoji under a quote or header, decryption errors and group invitations end with `metaReserveCopy`; after text it starts with a breaking space (`breakBefore`), so the time alone moves to the next line, except in group invitations, where the word joiner keeps the time with the last word (user); the size line of a file keeps the string of `reserveSpaceForMeta`. - Gaps between rows: `BUBBLE_CLOSE_GAP` (2sp) between close messages, `BUBBLE_FAR_GAP` (8sp) at a large gap, half above and half below each row. Event rows (`isEvent`: items without a sender, `hasTerminalSender` false, other than the chat banner: event, feature, preference and end-to-end encryption items, also collapsed) form runs (user): `eventRunLargeGap` makes the gap between two events close and the gap between an event and another row large; `ChatItemsList` applies it to the gap above a row (`eventGapAbove`) and to the separation below it (`eventGapBelow`, a large gap with the time), so a message above an event shows its tail and time. The avatar column of an event has no 8dp top padding. @@ -417,24 +417,28 @@ Colours: the app, user and chat themes apply as in the classic layout. Wallpaper | Function | Purpose | |---|---| -| [`chatTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L87-L94) | Terminal rows and bubbles (`usesChatTypography()`): line height and line height style of a text (section 4); outside chats: `TextStyle.Default`, so that merging it changes nothing | -| [`terminalItemShowsSender(item, older)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L124-L125) | Whether a row shows the sender row (sender rule below). `older`: the next older item in the list | -| [`sameSender(item, older)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L127-L135) | Private; same sender for grouping | -| [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L140-L141) | The gap above a row (section 4, item gaps): `TERMINAL_LEVEL_STEP` or 0. Used by `ChatItemsList` and the theme preview | -| [`terminalHeadingGap(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L143-L144) | `TERMINAL_LEVEL_STEP` above a heading that starts the text of an item below a quote, a header or a block; added to the top padding of `CIMarkdownText` | -| [`ChatItem.hasQuoteOrHeader`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L838-L839) | A quote, a forwarded header, a deletion, the live state or a report: the item is drawn by `FramedItemView` with a quote or header above its content. Used by `ChatItemView` to choose `EmojiItemView` or `CIVoiceView` and by the heading gaps | -| [`CIContent.hasTerminalSender`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L152-L159) | Also used by the event runs of bubbles (`isEvent` in `ChatView`: false and not the chat banner). True for sent messages, sent deleted and moderated items, sent calls and group invitations, and received content with `showMemberName` (messages, deleted, moderated and blocked items, calls, errors, group invitations, invalid JSON); false for events, feature and preference changes, E2EE info and the chat banner | -| [`TerminalRowInteractionSource`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L161-L175) | Interaction source of the row and its item: press interactions are emitted at the position where the pointer went down in the row, so the ripple starts there | -| [`Modifier.terminalRowIndication(source)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L177-L188) | Records the pointer-down position; hover and press indication of the whole row | -| [`Modifier.terminalStartOffset(offset)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L190-L195) | Shifts the row by the selection offset and narrows it by the same amount | -| [`Modifier.messageLastLine()`, `Modifier.messageLastBlock()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L201-L209) | `messageLastLine()` sets the private alignment lines `LastLineLeft` and `LastLineRight` to the left and right edges of the element: emoji. `messageLastBlock()` also sets `LastBlockBottom` at the bottom edge of the element: the last code block, table or rule of a message without a meta line, which has no bottom margin | -| [`Modifier.inlineIcon()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L211-L220) | Terminal: lays the element out with no height, centred on its position, so that a row with `Alignment.CenterVertically` takes the height of its text and centres the element on it: icons of feature and preference items and of message headers. Also in bubbles; outside chats: the modifier unchanged | -| [`ItemWithMeta(meta, overlayMeta, metaReserved, endButton, content)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L222-L236) | Classic: `content` with the meta passed as `inlineMeta`. Terminal: `content` without meta, and the meta in a box with 12dp end padding at the end of the available width, the message column of the row (private [`TerminalMetaLayout`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L238-L278)). `endButton`, in a box with the same end padding, is placed at the end of the row, centred vertically between the content top and the top of the time box (the whole content when the time is over media); the content is measured in the width less the wider of this box and, without `metaReserved`, the time box. The meta is measured first. Without `metaReserved` and `overlayMeta`, the content is measured in the width less the width of the box, so that it does not reach under the time. `metaReserved` is true for content with its own reserve of the space or a reported last line: text with the transparent copy (`metaReserved` of `FramedItemView`), files, emoji and event items. The first baseline of the box (the baseline of the time; without a time, the baseline of a 12sp time centred in the box) is placed on the last baseline of the content. When the content reports its last line and the line and the box together are wider than the row, the box is placed `TERMINAL_META_GAP` (6sp) under the content and the bottom of the row moves down by that gap and the height of the box. When the box stays beside a last block reported with `LastBlockBottom` at the content bottom (a table, or a code card or rule, which span the width of the item), `TERMINAL_BLOCK_BOTTOM_GAP` is added below the content. Content without a baseline (a message of a rule only, a failed call), and captionless media with `overlayMeta`: the box ends `TERMINAL_META_GAP` above the content bottom; when the content and the box together are wider than the row, the `overlayMeta` box is placed at the bottom end of the content instead, `TERMINAL_META_GAP` above its bottom. Either box is placed at the top of the content at most, and the row is at least as tall as the box. When the rule leaves room for the time beside it, the time stays on the baseline of the last text line above it (D24); otherwise it is placed under the rule. | -| [`ChatItemSender`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L283) | Name, badge, role label, `own`, avatar | -| [`chatItemSender(chatInfo, cItem, range, reversedChatItems, showMemberInfo, showChatInfo)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L285-L332) | Sender of a row (table below) | -| [`SenderNameAndRole(sender, modifier)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L337-L360) | Private; name and badge (13.5sp; primary for own items, secondary otherwise) and role label | -| [`terminalGutter(chatInfo)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L362-L364) | Gutter width: the member image size (scaled by `fontSizeSqrtMultiplier`) plus `CHAT_ITEM_TEXT_PADDING` in groups, 0 in other chats | -| [`TerminalChatItemRow(sender, gutter, topGap, modifier, senderTopGap, content)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L366-L408) | Row layout below | +| [`chatTextStyle(fontSize, color)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L82-L89) | Terminal rows and bubbles (`usesChatTypography()`): line height and line height style of a text (section 4); outside chats: `TextStyle.Default`, so that merging it changes nothing | +| [`terminalItemShowsSender(item, older)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L119-L120) | Whether a row shows the sender row (sender rule below). `older`: the next older item in the list | +| [`sameSender(item, older)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L122-L130) | Private; same sender for grouping | +| [`terminalRowGap(item, older, separated, largeGap, hasSenderRow)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L138-L139) | The gap above a row (section 4, item gaps): `TERMINAL_PARAGRAPH_GAP` or 0. Used by `ChatItemsList` and the theme preview | +| [`terminalTextTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L141-L145) | The top padding of `CIMarkdownText` (section 4) | +| [`terminalCardTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L147-L148) | `TERMINAL_PARAGRAPH_GAP` above the first card of the content (an image, video, link preview, chat link card, file, voice message or large emoji) when a header or the quote is above it, otherwise 0 | +| [`terminalQuoteTop(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L150-L151) | `TERMINAL_PARAGRAPH_GAP` above the quote below a report, deletion or live header, otherwise 0 | +| [`terminalReactionsGap(item)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L153-L154) | `gapBelowCard` of `ItemWithMeta` for `FramedItemView`, `EmojiItemView` and `CIVoiceView`: `TERMINAL_PARAGRAPH_GAP` when the item has reactions, otherwise 0 | +| [`ChatItem.isOneLine`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L156-L157) | The one-line test of the row gap (section 4, item gaps) | +| [`ChatItem.hasQuoteOrHeader`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/ChatItemView.kt#L838-L839) | A quote, a forwarded header, a deletion, the live state or a report: the item is drawn by `FramedItemView` with a quote or header above its content. Used by `ChatItemView` to choose `EmojiItemView` or `CIVoiceView` and by the gaps above cards and text | +| [`CIContent.hasTerminalSender`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L180-L187) | Also used by the event runs of bubbles (`isEvent` in `ChatView`: false and not the chat banner). True for sent messages, sent deleted and moderated items, sent calls and group invitations, and received content with `showMemberName` (messages, deleted, moderated and blocked items, calls, errors, group invitations, invalid JSON); false for events, feature and preference changes, E2EE info and the chat banner | +| [`TerminalRowInteractionSource`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L189-L203) | Interaction source of the row and its item: press interactions are emitted at the position where the pointer went down in the row, so the ripple starts there | +| [`Modifier.terminalRowIndication(source)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L205-L216) | Records the pointer-down position; hover and press indication of the whole row | +| [`Modifier.terminalStartOffset(offset)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L218-L223) | Shifts the row by the selection offset and narrows it by the same amount | +| [`Modifier.messageLastLine()`, `Modifier.messageCard()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L230-L238) | `messageLastLine()` sets the private alignment lines `LastLineLeft` and `LastLineRight` to the left and right edges of the element: emoji, and the last code block, table or rule of a message without a meta line. `messageCard()` sets the private alignment lines `CardTop` and `CardBottom` to the top and bottom edges of a card (section 4, cards) | +| [`Modifier.inlineIcon()`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L240-L249) | Terminal: lays the element out with no height, centred on its position, so that a row with `Alignment.CenterVertically` takes the height of its text and centres the element on it: icons of feature and preference items and of message headers. Also in bubbles; outside chats: the modifier unchanged | +| [`ItemWithMeta(meta, overlayMeta, metaReserved, endButton, gapBelowCard, content)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L251-L265) | Classic: `content` with the meta passed as `inlineMeta`. Terminal: `content` without meta, and the meta in a box with 12dp end padding at the end of the available width, the message column of the row (private [`TerminalMetaLayout`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L267-L307)). `endButton`, in a box with the same end padding, is placed at the end of the row, centred vertically between the content top and the top of the time box (the whole content when the time is over media); the content is measured in the width less the wider of this box and, without `metaReserved`, the time box. The meta is measured first. Without `metaReserved` and `overlayMeta`, the content is measured in the width less the width of the box, so that it does not reach under the time. `metaReserved` is true for content with its own reserve of the space or a reported last line: text with the transparent copy (`metaReserved` of `FramedItemView`), files, emoji and event items. The first baseline of the box (the baseline of the time; without a time, the baseline of a 12sp time centred in the box) is placed on the last baseline of the content. When the content reports its last line and the line and the box together are wider than the row, the box is placed `TERMINAL_META_GAP` (6sp) under the content and the bottom of the row moves down by that gap and the height of the box. When the content reports a card at its bottom (`CardBottom` at the content height), `gapBelowCard` is added below the content (section 4, cards). Content without a baseline (a message of a rule only, a failed call), and captionless media with `overlayMeta`: the box ends `TERMINAL_META_GAP` above the content bottom; when the content and the box together are wider than the row, the `overlayMeta` box is placed at the bottom end of the content instead, `TERMINAL_META_GAP` above its bottom. Either box is placed at the top of the content at most, and the row is at least as tall as the box. When the rule leaves room for the time beside it, the time stays on the baseline of the last text line above it (D24); otherwise it is placed under the rule. | +| [`ChatItemSender`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L312) | Name, badge, role label, `own`, avatar | +| [`chatItemSender(chatInfo, cItem, range, reversedChatItems, showMemberInfo, showChatInfo)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L314-L361) | Sender of a row (table below) | +| [`SenderNameAndRole(sender, modifier)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L366-L390) | Private; name and badge (the `body1` size, semibold; primary for own items, `secondary` otherwise; user) and role label (the same size, medium, `secondary`) | +| [`terminalGutter(chatInfo)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L392-L394) | Gutter width: the member image size (scaled by `fontSizeSqrtMultiplier`) plus `CHAT_ITEM_TEXT_PADDING` in groups, 0 in other chats | +| [`TerminalChatItemRow(sender, gutter, topGap, modifier, content)`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/TerminalItemView.kt#L396-L438) | Row layout below | In `ChatView.kt`, shared with the classic date separator: @@ -446,13 +450,13 @@ In `ChatView.kt`, shared with the classic date separator: ### Row Layout ``` -row padding top: topGap (terminalRowGap), plus senderTopGap (TERMINAL_SENDER_TOP_GAP, 6.5sp) with a sender row +row padding top: topGap (terminalRowGap) gutter terminalGutter(chatInfo) avatar top of the gutter, CHAT_ITEM_TEXT_PADDING from the start, sender rows of groups only one padding 12dp (user, I26): screen edge to the text or the avatar, avatar to the text, time to the screen edge message column starts at the gutter - sender row name and badge (13.5sp; primary for own messages, secondary otherwise), role label; start padding CHAT_ITEM_TEXT_PADDING; text style chatTextStyle(13.5sp) - item ChatItemView; TERMINAL_SENDER_BOTTOM_GAP (5.5sp) below the sender row + sender row name and badge (body1 size, semibold; primary for own messages, secondary otherwise), role label (the same size); start padding CHAT_ITEM_TEXT_PADDING; text style chatTextStyle(body1 size) + item ChatItemView, directly below the sender row; TERMINAL_PARAGRAPH_GAP lower when the item reports a card at its top (CardTop at 0) ``` `ChatItemsList` passes [`showAvatar`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt#L2455) = `terminalItemShowsSender(item, merged.oldest().nextItem)`, and the row gets `chatItemSender(...)` when it is true, `null` otherwise; the [gap above the row](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatView.kt#L2456-L2461), with `terminalRowsSeparated` of the older row (the next merged item of the reversed list), is passed to `ChatViewListItem` as `terminalGap`. @@ -463,9 +467,10 @@ message column starts at the gutter - it is the oldest loaded item; - the older item has no sender (an event); -- `sameSender` is false. +- `sameSender` is false; +- the item is `TERMINAL_NAME_REPEAT_SECONDS` (450, 7.5 minutes; user) or more after the older item, by the shown times (`itemTs`; the 60-second gap compares `createdAt`). -The time between the items and a date change do not repeat the sender row. +A date change does not repeat the sender row. `sameSender`: when either item is posted as the channel (`ChannelRcv`, or `GroupSnd` with `meta.showGroupAsSender`), both must be; two `GroupRcv` items need the same `memberId`; other items need the same direction class. @@ -511,12 +516,12 @@ The selection checkbox (8dp start padding) and the full-row selection click over | Screen | Value | |---|---| | Chat theme ([`ChatWallpaperEditorModal`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt#L1300)) | `activeChatLayout` of the chat | -| Appearance › Themes, preset selector ([`ThemesSection`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L582)) | `profileChatLayout` of the current user, or of none for the app theme destination | +| Appearance › Themes, preset selector ([`ThemesSection`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L581)) | `profileChatLayout` of the current user, or of none for the app theme destination | | Customize theme, profile theme, colour editors | the same, through `profileLayoutIsTerminal` and the `terminal` parameter of `editColor` | With the value true: -- the preview draws two terminal rows ("alice", then "bob" in the own colour) without gutter, the gap between them by `terminalRowGap` and `TERMINAL_SENDER_TOP_GAP`, as in the chat; [`PreviewInEitherLayout`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L338) measures both layouts and shows the active one centred in the larger height, so a layout switch keeps the preview height; +- the preview draws two terminal rows ("alice", then "bob" in the own colour) without gutter, the gap between them by `terminalRowGap`, as in the chat; [`PreviewInEitherLayout`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L337) measures both layouts and shows the active one centred in the larger height, so a layout switch keeps the preview height; - the preview and the preset tiles show the wallpaper colour without the image; - the custom image tile, the image scale, the scale slider and the wallpaper accent row are hidden. @@ -525,5 +530,5 @@ Layout controls: | Control | Values | Stored in | |---|---|---| | Chat theme screen, first section ([`ChatLayoutSection`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt#L1313)) | the chat default, "(chat)" when the chat layout is the default, otherwise "(default)"; the other layout | chat theme record, by [`setChatLayout`](../../common/src/commonMain/kotlin/chat/simplex/common/views/chat/ChatInfoView.kt#L1382) and `apiSetChatUIThemes` | -| Appearance › Themes, app theme destination ([`ChatLayoutRow`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L951)) | Classic, Terminal; the selection is `profileChatLayout(null)` | `appPrefs.chatLayout` | +| Appearance › Themes, app theme destination ([`ChatLayoutRow`](../../common/src/commonMain/kotlin/chat/simplex/common/views/usersettings/Appearance.kt#L950)) | Classic, Terminal; the selection is `profileChatLayout(null)` | `appPrefs.chatLayout` | | Appearance › Themes, profile destination | `profileChatLayout(null)` "(default)"; the other layout | profile theme record, by `saveThemeToDatabase` and `apiSetUserUIThemes` | diff --git a/src/Simplex/Chat/Library/Internal.hs b/src/Simplex/Chat/Library/Internal.hs index f69772e96c..3894e40c46 100644 --- a/src/Simplex/Chat/Library/Internal.hs +++ b/src/Simplex/Chat/Library/Internal.hs @@ -364,10 +364,10 @@ getMessageMentions db user gId msg = case parseMaybeMarkdownList msg of <$> runExceptT (getGroupMemberIdByName db user gId name) msgContentTexts :: MsgContent -> (Text, ParsedMarkdown) -msgContentTexts mc = let t = msgContentText mc in (t, parsedMarkdown t) +msgContentTexts mc = (msgContentText mc, parsedMsgContent mc) ciContentTexts :: CIContent d -> (Text, ParsedMarkdown) -ciContentTexts content = let t = ciContentToText content in (t, parsedMarkdown t) +ciContentTexts content = let t = ciContentToText content in (t, parsedCIContent content t) quoteContent :: forall d. MsgContent -> MsgContent -> Maybe (CIFile d) -> MsgContent quoteContent mc qmc ciFile_ diff --git a/src/Simplex/Chat/Markdown.hs b/src/Simplex/Chat/Markdown.hs index 3250594c5d..140def85f2 100644 --- a/src/Simplex/Chat/Markdown.hs +++ b/src/Simplex/Chat/Markdown.hs @@ -201,7 +201,7 @@ parsedMarkdown s = case T.lines s of Just (c, rest) -> (c == '/', rest) Nothing -> (False, "") _ - | any isBlockSyntax tokens && length [f | FormattedText f _ <- tokens, isMarkup f] <= maxMarkupTokens -> ParsedMarkdown (Just tokens) (L.nonEmpty $ markdownBlocksOf tokens) + | any isBlockSyntax tokens && length [f | FormattedText f _ <- tokens, isMarkup f] <= maxMarkupTokens, blocks@(Just _) <- L.nonEmpty (markdownBlocksOf tokens) -> ParsedMarkdown (Just tokens) blocks | all (isNothing . format) inline -> ParsedMarkdown Nothing Nothing | otherwise -> ParsedMarkdown (Just inline) Nothing where @@ -213,10 +213,8 @@ parsedMarkdown s = case T.lines s of isBlockSyntax :: FormattedText -> Bool isBlockSyntax = \case FormattedText (Just (Markup t)) _ -> case t of - LineBreak -> False SoftBreak -> False HardBreak -> False - ParagraphBreak _ -> False _ -> True _ -> False diff --git a/src/Simplex/Chat/Messages.hs b/src/Simplex/Chat/Messages.hs index d298a1d3c1..ca0a1373f9 100644 --- a/src/Simplex/Chat/Messages.hs +++ b/src/Simplex/Chat/Messages.hs @@ -617,10 +617,19 @@ data CIQuote (c :: ChatType) = CIQuote } deriving (Show) +parsedMsgContent :: MsgContent -> ParsedMarkdown +parsedMsgContent mc = parsedMarkdown $ case mc of + MCVoice {text} -> text + MCReport {text} -> text + _ -> msgContentText mc + +parsedCIContent :: CIContent d -> Text -> ParsedMarkdown +parsedCIContent content t = maybe (parsedMarkdown t) parsedMsgContent $ ciMsgContent content + mkCIQuote :: CIQDirection c -> Maybe ChatItemId -> Maybe SharedMsgId -> UTCTime -> MsgContent -> CIQuote c mkCIQuote chatDir itemId sharedMsgId sentAt content = CIQuote {chatDir, itemId, sharedMsgId, sentAt, content, formattedText, markdownBlocks} where - ParsedMarkdown formattedText markdownBlocks = parsedMarkdown $ msgContentText content + ParsedMarkdown formattedText markdownBlocks = parsedMsgContent content quoteItemId :: CIQuote c -> Maybe ChatItemId quoteItemId CIQuote {itemId} = itemId diff --git a/src/Simplex/Chat/Store/Messages.hs b/src/Simplex/Chat/Store/Messages.hs index ee5a7f1659..d67b1bdae0 100644 --- a/src/Simplex/Chat/Store/Messages.hs +++ b/src/Simplex/Chat/Store/Messages.hs @@ -1121,7 +1121,7 @@ toLocalChatItem currentTs ((itemId, itemTs, AMsgDirection msgDir, itemContentTex cItem d chatDir ciStatus content file = CChatItem d ChatItem {chatDir, meta = ciMeta content ciStatus, content, mentions = M.empty, formattedText, markdownBlocks, quotedItem = Nothing, reactions = [], file} where - ParsedMarkdown formattedText markdownBlocks = parsedMarkdown itemText + ParsedMarkdown formattedText markdownBlocks = parsedCIContent content itemText badItem = Left $ SEBadChatItem itemId (Just itemTs) ciMeta :: CIContent d -> CIStatus d -> CIMeta 'CTLocal d ciMeta content status = @@ -2338,7 +2338,7 @@ toDirectChatItem currentTs (((itemId, itemTs, AMsgDirection msgDir, itemContentT cItem d chatDir ciStatus content file = CChatItem d ChatItem {chatDir, meta = ciMeta content ciStatus, content, mentions = M.empty, formattedText, markdownBlocks, quotedItem = toDirectQuote quoteRow, reactions = [], file} where - ParsedMarkdown formattedText markdownBlocks = parsedMarkdown itemText + ParsedMarkdown formattedText markdownBlocks = parsedCIContent content itemText badItem = Left $ SEBadChatItem itemId (Just itemTs) ciMeta :: CIContent d -> CIStatus d -> CIMeta 'CTDirect d ciMeta content status = @@ -2432,7 +2432,7 @@ toGroupChatItem cItem d chatDir ciStatus content file = CChatItem d ChatItem {chatDir, meta = ciMeta content ciStatus, content, mentions = M.empty, formattedText, markdownBlocks, quotedItem = toGroupQuote quoteRow quotedMember_, reactions = [], file} where - ParsedMarkdown formattedText markdownBlocks = parsedMarkdown itemText + ParsedMarkdown formattedText markdownBlocks = parsedCIContent content itemText badItem = Left $ SEBadChatItem itemId (Just itemTs) ciMeta :: CIContent d -> CIStatus d -> CIMeta 'CTGroup d ciMeta content status = @@ -2578,7 +2578,7 @@ updateDirectChatItem' db User {userId} contactId ci newContent edited live timed updatedChatItem :: ChatItem c d -> CIContent d -> Bool -> Bool -> Maybe CITimed -> UTCTime -> ChatItem c d updatedChatItem ci@ChatItem {meta = meta@CIMeta {itemStatus, itemEdited, itemTimed, itemLive}} newContent edited live timed_ currentTs = let newText = ciContentToText newContent - ParsedMarkdown formattedText markdownBlocks = parsedMarkdown newText + ParsedMarkdown formattedText markdownBlocks = parsedCIContent newContent newText edited' = itemEdited || edited live' = (live &&) <$> itemLive timed' = case timed_ of @@ -3380,7 +3380,7 @@ getChatItemVersions db itemId = do where toChatItemVersion :: (Int64, MsgContent, UTCTime, UTCTime) -> ChatItemVersion toChatItemVersion (chatItemVersionId, msgContent, itemVersionTs, createdAt) = - let ParsedMarkdown formattedText markdownBlocks = parsedMarkdown $ msgContentText msgContent + let ParsedMarkdown formattedText markdownBlocks = parsedMsgContent msgContent in ChatItemVersion {chatItemVersionId, msgContent, formattedText, markdownBlocks, itemVersionTs, createdAt} directCIWithReactions :: DB.Connection -> Contact -> CChatItem 'CTDirect -> IO (CChatItem 'CTDirect) diff --git a/tests/JSONFixtures.hs b/tests/JSONFixtures.hs index e7948ac190..7ca5cbbe52 100644 --- a/tests/JSONFixtures.hs +++ b/tests/JSONFixtures.hs @@ -48,3 +48,6 @@ markdownBlocksSwift = "{\"formattedText\":[{\"format\":{\"_owsf\":true,\"markup\ markdownBlocksTagged :: LB.ByteString markdownBlocksTagged = "{\"formattedText\":[{\"format\":{\"type\":\"markup\",\"token\":{\"type\":\"headingMark\",\"level\":2}},\"text\":\"## \"},{\"text\":\"a\"},{\"format\":{\"type\":\"markup\",\"token\":{\"type\":\"lineBreak\"}},\"text\":\"\\n\"},{\"format\":{\"type\":\"markup\",\"token\":{\"type\":\"listMark\"}},\"text\":\"- \"},{\"format\":{\"type\":\"bold\",\"singleStar\":true},\"text\":\"b\"}],\"markdownBlocks\":[{\"type\":\"heading\",\"level\":2,\"content\":{\"from\":1,\"to\":2}},{\"type\":\"list\",\"items\":[{\"content\":{\"from\":4,\"to\":5},\"items\":[]}]}]}" + +markdownParagraphsTagged :: LB.ByteString +markdownParagraphsTagged = "{\"formattedText\":[{\"text\":\"a\"},{\"format\":{\"type\":\"markup\",\"token\":{\"type\":\"paragraphBreak\",\"lineBreaks\":2}},\"text\":\"\\n\\n\"},{\"text\":\"b\"}],\"markdownBlocks\":[{\"type\":\"paragraph\",\"content\":{\"from\":0,\"to\":1}},{\"type\":\"paragraph\",\"content\":{\"from\":2,\"to\":3}}]}" diff --git a/tests/JSONTests.hs b/tests/JSONTests.hs index 4f37e507f7..3fdbf0416e 100644 --- a/tests/JSONTests.hs +++ b/tests/JSONTests.hs @@ -85,6 +85,8 @@ markdownBlocksJSONTests :: Spec markdownBlocksJSONTests = do it "should encode tokens and blocks" $ J.encode (parsedMarkdown "## a\n- *b*") `shouldBe` markdownBlocksTagged + it "should encode paragraphs of a text with an empty line" $ + J.encode (parsedMarkdown "a\n\nb") `shouldBe` markdownParagraphsTagged it "should decode tokens and blocks of each kind" $ do let ParsedMarkdown ft blocks = parsedMarkdown "# a #\nb\n===\n- *c*\n 1. d\n> e\n\n| x | y |\n|:-|-:|\n| 1 |\n```bash\ncode\n```\n---\ne \nf\\\ng\n- \\*h\n i" J.eitherDecode (J.encode ft) `shouldBe` Right ft diff --git a/tests/MarkdownTests.hs b/tests/MarkdownTests.hs index b26ae8921a..83964bbf50 100644 --- a/tests/MarkdownTests.hs +++ b/tests/MarkdownTests.hs @@ -16,6 +16,8 @@ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Simplex.Chat.Markdown +import Simplex.Chat.Messages (parsedMsgContent) +import Simplex.Chat.Protocol (MsgContent (..), ReportReason (..)) import Simplex.Chat.Types (BoolDef (..)) import Simplex.Messaging.Agent.Protocol (SimplexDomain (..), SimplexNameInfo (..), SimplexNameType (..), SimplexTLD (..)) import Simplex.Messaging.Encoding.String @@ -605,22 +607,19 @@ textsWithoutBlocks :: Spec textsWithoutBlocks = describe "texts without blocks, as on master" do it "no format" do parseMaybeMarkdownList "a\nb" `shouldBe` Nothing - parseMaybeMarkdownList "a\n\nb" `shouldBe` Nothing parseMaybeMarkdownList "a\n" `shouldBe` Nothing parseMaybeMarkdownList "a \nb" `shouldBe` Nothing - parseMaybeMarkdownList "\n\na" `shouldBe` Nothing + parseMaybeMarkdownList "\n\n" `shouldBe` Nothing + parseMaybeMarkdownList "\n \n" `shouldBe` Nothing it "line breaks are text" do - "*a*\n\nb" <<==>> [fmt boldF "a", "\n\nb"] "*a*\nb" <<==>> [fmt boldF "a", "\nb"] "*a*\r\nb" <<==>> [fmt boldF "a", "\r\nb"] "*a* \nb" <<==>> [fmt boldF "a", " \nb"] "*a*\\\nb" <<==>> [fmt boldF "a", "\\\nb"] " a\n*b*" <<==>> [" a\n", fmt boldF "b"] - "\n\n*a*" <<==>> ["\n\n", fmt boldF "a"] it "the final line break is removed" do "*a*\n" ==>> [fmt boldF "a"] "*a*\r\n" ==>> [fmt boldF "a"] - "*a*\n\n" ==>> [fmt boldF "a", "\n"] infix 1 ===>, <===> @@ -751,6 +750,23 @@ breaksInBlocks = describe "line breaks in texts with blocks" do "# a\n\n" <===> ([heading1, "a", lineBr], [Heading 1 (rng 1 2)]) "# a\n\n\n" <===> ([heading1, "a", mk (ParagraphBreak 2) "\n\n"], [Heading 1 (rng 1 2)]) "# a\n " <===> ([heading1, "a", mk (ParagraphBreak 1) "\n "], [Heading 1 (rng 1 2)]) + it "empty lines between paragraphs" do + "a\n\nb" <===> (["a", mk (ParagraphBreak 2) "\n\n", "b"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) + "a\n\n\nb" <===> (["a", mk (ParagraphBreak 3) "\n\n\n", "b"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) + "a\n \t\nb" <===> (["a", mk (ParagraphBreak 2) "\n \t\n", "b"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) + "a\r\n\r\nb" <===> (["a", mk (ParagraphBreak 2) "\r\n\r\n", "b"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) + "a\n\160\nb" <===> (["a", lineBr, "\160", hardBr, "b"], [Paragraph (rng 0 1), Paragraph (rng 2 5)]) + "a\nb\n\nc" <===> (["a", hardBr, "b", mk (ParagraphBreak 2) "\n\n", "c"], [Paragraph (rng 0 3), Paragraph (rng 4 5)]) + "a\\\nb\n\nc" <===> (["a", mk HardBreak "\\\n", "b", mk (ParagraphBreak 2) "\n\n", "c"], [Paragraph (rng 0 3), Paragraph (rng 4 5)]) + "*a*\n\n_b_" <===> ([fmt boldF "a", mk (ParagraphBreak 2) "\n\n", fmt Italic "b"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) + it "empty lines at the start and the end of paragraphs" do + "\na" <===> ([mk (ParagraphBreak 1) "\n", "a"], [Paragraph (rng 1 2)]) + "\n\na" <===> ([mk (ParagraphBreak 2) "\n\n", "a"], [Paragraph (rng 1 2)]) + "\n\n*a*" <===> ([mk (ParagraphBreak 2) "\n\n", fmt boldF "a"], [Paragraph (rng 1 2)]) + "a\n\n" <===> (["a", lineBr], [Paragraph (rng 0 1)]) + "*a*\n\n" <===> ([fmt boldF "a", lineBr], [Paragraph (rng 0 1)]) + "a\n\n\n" <===> (["a", mk (ParagraphBreak 2) "\n\n"], [Paragraph (rng 0 1)]) + "a\n " <===> (["a", mk (ParagraphBreak 1) "\n "], [Paragraph (rng 0 1)]) it "CR before line breaks" do "a\r\nb\r\n- c" <===> (["a", mk HardBreak "\r\n", "b", mk LineBreak "\r\n", bullet "- ", "c"], [Paragraph (rng 0 3), List [entry 5 6 []]]) "a \r\nb\r\n- c" <===> (["a", mk HardBreak " \r\n", "b", mk LineBreak "\r\n", bullet "- ", "c"], [Paragraph (rng 0 3), List [entry 5 6 []]]) @@ -805,7 +821,7 @@ headings = describe "headings" do "> a\n===" <===> ([quoteMark "> ", "a", lineBr, "==="], [Quote (rng 1 2), Paragraph (rng 3 4)]) "- a\n===" <===> ([bullet "- ", "a", lineBr, "==="], [List [entry 1 2 []], Paragraph (rng 3 4)]) noBlocks "a\n= =" - noBlocks "a\n\n===" + "a\n\n===" <===> (["a", mk (ParagraphBreak 2) "\n\n", "==="], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) noBlocks "===" noBlocks "===\na" @@ -1026,7 +1042,7 @@ formatsAcrossLines = describe "formats across line breaks" do "> *a\n> b*" ===> (quoted, [Quote (rng 1 5)]) "> *a*\n> *b*" <===> (quoted, [Quote (rng 1 5)]) it "not across blocks, blank lines and cells" do - parseMaybeMarkdownList "*a\n\nb*" `shouldBe` Nothing + "*a\n\nb*" <===> (["*a", mk (ParagraphBreak 2) "\n\n", "b*"], [Paragraph (rng 0 1), Paragraph (rng 2 3)]) "# *a\nb*" <===> ([heading1, "*a", lineBr, "b*"], [Heading 1 (rng 1 2), Paragraph (rng 3 4)]) "- *a\n- b*" <===> ([bullet "- ", "*a", lineBr, bullet "- ", "b*"], [List [entry 1 2 [], entry 4 5 []]]) "- *a\nb*" <===> ([bullet "- ", "*a", lineBr, "b*"], [List [entry 1 2 []], Paragraph (rng 3 4)]) @@ -1091,22 +1107,35 @@ linearTimeParsing = describe "bounded scans for linear-time parsing" do length <$> blocks `shouldBe` Just 1 noBlocks $ T.replicate 1001 "- a\n" length . filter (\(FormattedText f _) -> f == Just boldF) <$> parseMaybeMarkdownList (T.replicate 1001 "- *a*\n") `shouldBe` Just 1001 + let ParsedMarkdown _ paragraphs = parsedMarkdown $ T.replicate 2000 "a\n\n" + length <$> paragraphs `shouldBe` Just 2000 + parseMaybeMarkdownList (T.replicate 2001 "a\n\n") `shouldBe` Nothing + length . filter (\(FormattedText f _) -> f == Just boldF) <$> parseMaybeMarkdownList (T.replicate 2001 "*a*\n\n") `shouldBe` Just 2001 it "large adversarial texts" do forM_ (["1 ", "[ ", "[a]( ", "< ", "a\n", ">\n", "- a\n", "|\n", "|-|\n", "*a\n"] :: [Text]) $ \p -> length (show $ parseMaybeMarkdownList $ "|a|\n|-|\n" <> T.replicate 4000 p) `shouldSatisfy` (> 0) markdownConsumers :: Spec markdownConsumers = describe "consumers of parsed Markdown" do + it "reports and voice messages are parsed without the prefix of their item text" do + let ft mc = let ParsedMarkdown fts _ = parsedMsgContent mc in fts + ft (MCReport "a\n\n*b*" RRSpam) `shouldBe` ft (MCText "a\n\n*b*") + ft (MCVoice "a\n\n*b*" 10) `shouldBe` ft (MCText "a\n\n*b*") + ft (MCReport "" RRSpam) `shouldBe` Nothing + ft (MCVoice "" 10) `shouldBe` Nothing it "mentionedNames: mentions in blocks, not in code" do mentions "- @alice" `shouldBe` ["alice"] mentions "> @alice" `shouldBe` ["alice"] mentions "# @alice" `shouldBe` ["alice"] mentions "| @alice |\n|---|" `shouldBe` ["alice"] + mentions "a\n\n@alice" `shouldBe` ["alice"] mentions "```\n@alice\n```" `shouldBe` [] mentions "`@alice`" `shouldBe` [] it "hasLinks: links in blocks, not in code" do links "- https://simplex.chat" `shouldBe` True links "| https://simplex.chat |\n|---|" `shouldBe` True + links "a\n\nhttps://simplex.chat" `shouldBe` True + links "a\n\nb" `shouldBe` False links "```\nhttps://simplex.chat\n```" `shouldBe` False it "SimpleX links in blocks and in code" do simplexLinks ("- " <> addr) `shouldBe` True