fix(swift-ios): enable granular text selection (#6110)
This commit is contained in:
1 parent
a4735b84e8
commit
50bd5cbba2
6 files changed
+707
-97
No files matched your search
@@ -7,11 +7,14 @@ enum T3Colors {
|
||||
// system appearance changes as SwiftUI views.
|
||||
static let uiBackground = adaptive(light: rgb(0xF2F2F7), dark: rgb(0x0A0A0A))
|
||||
static let uiTextPrimary = adaptive(light: rgb(0x262626), dark: rgb(0xF5F5F5))
|
||||
static let uiTextSecondary = adaptive(light: rgb(0x525252), dark: rgb(0xA3A3A3))
|
||||
static let uiSurfaceRaised = adaptive(light: rgb(0xF5F5F5), dark: rgb(0x1C1C1C))
|
||||
static let uiAccent = adaptive(light: rgb(0x007AFF), dark: rgb(0x0A84FF))
|
||||
|
||||
static let background = Color(uiColor: uiBackground)
|
||||
static let sheet = color(light: rgb(0xF2F2F7, alpha: 0.98), dark: rgb(0x0E0E0E, alpha: 0.98))
|
||||
static let surface = color(light: rgb(0xFFFFFF), dark: rgb(0x171717))
|
||||
static let surfaceRaised = color(light: rgb(0xF5F5F5), dark: rgb(0x1C1C1C))
|
||||
static let surfaceRaised = Color(uiColor: uiSurfaceRaised)
|
||||
static let input = color(light: rgb(0xFFFFFF), dark: rgb(0x141414))
|
||||
static let border = color(light: rgb(0x000000, alpha: 0.08), dark: rgb(0xFFFFFF, alpha: 0.06))
|
||||
static let inputBorder = color(
|
||||
@@ -26,13 +29,13 @@ enum T3Colors {
|
||||
static let ledgerSelected = surfaceRaised
|
||||
|
||||
static let textPrimary = Color(uiColor: uiTextPrimary)
|
||||
static let textSecondary = color(light: rgb(0x525252), dark: rgb(0xA3A3A3))
|
||||
static let textSecondary = Color(uiColor: uiTextSecondary)
|
||||
static let textTertiary = color(light: rgb(0x737373), dark: rgb(0x8E8E93))
|
||||
static let placeholder = color(light: rgb(0xA3A3A3), dark: rgb(0x8E8E93))
|
||||
|
||||
static let primaryAction = color(light: rgb(0x262626), dark: rgb(0xF5F5F5))
|
||||
static let primaryActionForeground = color(light: rgb(0xFFFFFF), dark: rgb(0x0A0A0A))
|
||||
static let accent = color(light: rgb(0x007AFF), dark: rgb(0x0A84FF))
|
||||
static let accent = Color(uiColor: uiAccent)
|
||||
static let statusRunning = color(light: rgb(0x0284C7), dark: rgb(0x22D3EE))
|
||||
static let statusInput = color(light: rgb(0x4F46E5), dark: rgb(0xA5B4FC))
|
||||
static let success = color(light: rgb(0x16A34A), dark: rgb(0x30D158))
|
||||
|
||||
@@ -11,13 +11,20 @@ struct MarkdownMessageView: View {
|
||||
private let source: String
|
||||
private let revision: MarkdownContentRevision
|
||||
private let isStreaming: Bool
|
||||
private let copyActionTitle: String
|
||||
@State private var selectionSource: MarkdownSelectionSource
|
||||
@State private var renderedDocument: MarkdownRenderedDocument?
|
||||
@State private var streamingRenderer = StreamingMarkdownRenderer()
|
||||
@State private var isSelectingText = false
|
||||
|
||||
init(_ source: String, isStreaming: Bool = false) {
|
||||
init(
|
||||
_ source: String,
|
||||
isStreaming: Bool = false,
|
||||
copyActionTitle: String = "Copy message"
|
||||
) {
|
||||
self.source = source
|
||||
self.isStreaming = isStreaming
|
||||
self.copyActionTitle = copyActionTitle
|
||||
_selectionSource = State(initialValue: MarkdownSelectionSource(source))
|
||||
let revision = MarkdownContentRevision(source)
|
||||
self.revision = revision
|
||||
let initialDocument = if isStreaming {
|
||||
@@ -31,9 +38,13 @@ struct MarkdownMessageView: View {
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
let selectionContext = selectionContext
|
||||
Group {
|
||||
if let displayDocument {
|
||||
MarkdownBlocksView(blocks: displayDocument.blocks)
|
||||
MarkdownBlocksView(
|
||||
blocks: displayDocument.blocks,
|
||||
selectionContext: selectionContext
|
||||
)
|
||||
} else {
|
||||
// Parsing waits briefly so token-by-token streaming cancels stale revisions
|
||||
// instead of scheduling work for content the user will never see.
|
||||
@@ -43,23 +54,7 @@ struct MarkdownMessageView: View {
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
.modifier(MarkdownTextSelectionModifier(isEnabled: isSelectingText))
|
||||
.contextMenu {
|
||||
Button {
|
||||
isSelectingText.toggle()
|
||||
} label: {
|
||||
Label(
|
||||
isSelectingText ? "Done selecting" : "Select text",
|
||||
systemImage: isSelectingText ? "checkmark" : "text.cursor"
|
||||
)
|
||||
}
|
||||
Button {
|
||||
UIPasteboard.general.string = source
|
||||
} label: {
|
||||
Label("Copy message", systemImage: "doc.on.doc")
|
||||
}
|
||||
}
|
||||
.accessibilityAction(named: "Copy message") {
|
||||
.accessibilityAction(named: copyActionTitle) {
|
||||
UIPasteboard.general.string = source
|
||||
}
|
||||
.task(id: RenderRequest(revision: revision, isStreaming: isStreaming)) {
|
||||
@@ -111,6 +106,14 @@ struct MarkdownMessageView: View {
|
||||
}
|
||||
return MarkdownRenderCache.shared.documentImmediately(for: revision)
|
||||
}
|
||||
|
||||
private var selectionContext: MarkdownSelectionContext {
|
||||
selectionSource.text = source
|
||||
return MarkdownSelectionContext(
|
||||
source: selectionSource,
|
||||
copyActionTitle: copyActionTitle
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders streaming revisions outside SwiftUI's task lifecycle so a render
|
||||
@@ -178,22 +181,40 @@ private final class StreamingMarkdownRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
private struct MarkdownTextSelectionModifier: ViewModifier {
|
||||
let isEnabled: Bool
|
||||
private final class MarkdownSelectionSource: @unchecked Sendable {
|
||||
var text: String
|
||||
|
||||
@ViewBuilder
|
||||
func body(content: Content) -> some View {
|
||||
if isEnabled {
|
||||
content.textSelection(.enabled)
|
||||
} else {
|
||||
content
|
||||
init(_ text: String) {
|
||||
self.text = text
|
||||
}
|
||||
}
|
||||
|
||||
private struct MarkdownSelectionContext: Equatable, Sendable {
|
||||
let source: MarkdownSelectionSource
|
||||
let copyActionTitle: String
|
||||
|
||||
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.source === rhs.source && lhs.copyActionTitle == rhs.copyActionTitle
|
||||
}
|
||||
}
|
||||
|
||||
private enum MarkdownTextColor: Equatable, Sendable {
|
||||
case primary
|
||||
case secondary
|
||||
|
||||
var uiColor: UIColor {
|
||||
switch self {
|
||||
case .primary: T3Colors.uiTextPrimary
|
||||
case .secondary: T3Colors.uiTextSecondary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct MarkdownBlocksView: View {
|
||||
let blocks: [MarkdownRenderedBlock]
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
var spacing: CGFloat = 12
|
||||
var textColor: MarkdownTextColor = .primary
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: spacing) {
|
||||
@@ -201,7 +222,11 @@ private struct MarkdownBlocksView: View {
|
||||
// Unchanged blocks share inline runs by reference across
|
||||
// streaming revisions, so equatable comparison skips their
|
||||
// body and layout entirely; only the changed tail re-renders.
|
||||
MarkdownBlockView(block: blocks[index])
|
||||
MarkdownBlockView(
|
||||
block: blocks[index],
|
||||
selectionContext: selectionContext,
|
||||
textColor: textColor
|
||||
)
|
||||
.equatable()
|
||||
}
|
||||
}
|
||||
@@ -210,26 +235,51 @@ private struct MarkdownBlocksView: View {
|
||||
|
||||
private struct MarkdownBlockView: View, Equatable {
|
||||
let block: MarkdownRenderedBlock
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
let textColor: MarkdownTextColor
|
||||
|
||||
@ViewBuilder
|
||||
var body: some View {
|
||||
switch block {
|
||||
case let .paragraph(inline):
|
||||
MarkdownInlineText(inline)
|
||||
.lineSpacing(4)
|
||||
MarkdownInlineText(
|
||||
inline,
|
||||
selectionContext: selectionContext,
|
||||
lineSpacing: 4,
|
||||
textColor: textColor
|
||||
)
|
||||
|
||||
case let .heading(level, inline):
|
||||
MarkdownInlineText(inline)
|
||||
MarkdownInlineText(
|
||||
inline,
|
||||
selectionContext: selectionContext,
|
||||
textColor: textColor
|
||||
)
|
||||
.padding(.top, level <= 2 ? 3 : 1)
|
||||
|
||||
case let .unorderedList(items):
|
||||
MarkdownListView(items: items, start: nil)
|
||||
MarkdownListView(
|
||||
items: items,
|
||||
start: nil,
|
||||
selectionContext: selectionContext,
|
||||
textColor: textColor
|
||||
)
|
||||
|
||||
case let .orderedList(start, items):
|
||||
MarkdownListView(items: items, start: start)
|
||||
MarkdownListView(
|
||||
items: items,
|
||||
start: start,
|
||||
selectionContext: selectionContext,
|
||||
textColor: textColor
|
||||
)
|
||||
|
||||
case let .blockquote(blocks):
|
||||
MarkdownBlocksView(blocks: blocks, spacing: 9)
|
||||
MarkdownBlocksView(
|
||||
blocks: blocks,
|
||||
selectionContext: selectionContext,
|
||||
spacing: 9,
|
||||
textColor: .secondary
|
||||
)
|
||||
.foregroundStyle(T3Colors.textSecondary)
|
||||
.padding(.leading, 14)
|
||||
.overlay(alignment: .leading) {
|
||||
@@ -239,10 +289,19 @@ private struct MarkdownBlockView: View, Equatable {
|
||||
}
|
||||
|
||||
case let .table(table):
|
||||
MarkdownTableView(table: table)
|
||||
MarkdownTableView(
|
||||
table: table,
|
||||
selectionContext: selectionContext,
|
||||
textColor: textColor
|
||||
)
|
||||
|
||||
case let .codeBlock(language, code):
|
||||
MarkdownCodeBlockView(language: language, code: code)
|
||||
case let .codeBlock(language, code, renderedCode):
|
||||
MarkdownCodeBlockView(
|
||||
language: language,
|
||||
code: code,
|
||||
renderedCode: renderedCode,
|
||||
selectionContext: selectionContext
|
||||
)
|
||||
|
||||
case .thematicBreak:
|
||||
Rectangle()
|
||||
@@ -256,6 +315,8 @@ private struct MarkdownBlockView: View, Equatable {
|
||||
|
||||
private struct MarkdownTableView: View {
|
||||
let table: MarkdownRenderedTable
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
let textColor: MarkdownTextColor
|
||||
|
||||
private var columnWidths: [CGFloat] { table.columnWidths }
|
||||
|
||||
@@ -289,8 +350,12 @@ private struct MarkdownTableView: View {
|
||||
) -> some View {
|
||||
GridRow(alignment: .top) {
|
||||
ForEach(cells.indices, id: \.self) { columnIndex in
|
||||
MarkdownInlineText(cells[columnIndex])
|
||||
.lineSpacing(3)
|
||||
MarkdownInlineText(
|
||||
cells[columnIndex],
|
||||
selectionContext: selectionContext,
|
||||
lineSpacing: 3,
|
||||
textColor: textColor
|
||||
)
|
||||
.frame(
|
||||
width: columnWidths[columnIndex],
|
||||
alignment: alignment(for: columnIndex)
|
||||
@@ -309,7 +374,6 @@ private struct MarkdownTableView: View {
|
||||
.frame(width: 1)
|
||||
}
|
||||
}
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
.background(isHeader ? T3Colors.surfaceRaised : T3Colors.surface)
|
||||
@@ -334,6 +398,8 @@ private struct MarkdownTableView: View {
|
||||
private struct MarkdownListView: View {
|
||||
let items: [MarkdownRenderedListItem]
|
||||
let start: Int?
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
let textColor: MarkdownTextColor
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
@@ -342,7 +408,12 @@ private struct MarkdownListView: View {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
marker(for: item, offset: offset)
|
||||
.frame(width: 24, height: 24, alignment: .trailing)
|
||||
MarkdownBlocksView(blocks: item.blocks, spacing: 7)
|
||||
MarkdownBlocksView(
|
||||
blocks: item.blocks,
|
||||
selectionContext: selectionContext,
|
||||
spacing: 7,
|
||||
textColor: textColor
|
||||
)
|
||||
}
|
||||
.accessibilityElement(children: .contain)
|
||||
}
|
||||
@@ -375,6 +446,8 @@ private struct MarkdownListView: View {
|
||||
private struct MarkdownCodeBlockView: View {
|
||||
let language: String?
|
||||
let code: String
|
||||
let renderedCode: MarkdownRenderedInline
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
@State private var wrapOverride: Bool?
|
||||
|
||||
private var wrapsLines: Bool {
|
||||
@@ -424,19 +497,22 @@ private struct MarkdownCodeBlockView: View {
|
||||
.frame(height: 1)
|
||||
|
||||
if wrapsLines {
|
||||
Text(verbatim: code)
|
||||
.font(T3Typography.code)
|
||||
.foregroundStyle(T3Colors.textPrimary.opacity(0.94))
|
||||
.lineSpacing(3)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
MarkdownInlineText(
|
||||
renderedCode,
|
||||
selectionContext: selectionContext,
|
||||
lineSpacing: 3,
|
||||
wrapsLines: true
|
||||
)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(13)
|
||||
} else {
|
||||
ScrollView(.horizontal) {
|
||||
Text(verbatim: code)
|
||||
.font(T3Typography.code)
|
||||
.foregroundStyle(T3Colors.textPrimary.opacity(0.94))
|
||||
.lineSpacing(3)
|
||||
MarkdownInlineText(
|
||||
renderedCode,
|
||||
selectionContext: selectionContext,
|
||||
lineSpacing: 3,
|
||||
wrapsLines: false
|
||||
)
|
||||
.fixedSize(horizontal: true, vertical: true)
|
||||
.padding(13)
|
||||
}
|
||||
@@ -469,25 +545,374 @@ enum MarkdownCodeBlockWrapping {
|
||||
}
|
||||
}
|
||||
|
||||
private struct MarkdownInlineText: View {
|
||||
private let attributedText: AttributedString
|
||||
private let font: Font
|
||||
private struct MarkdownInlineText: UIViewRepresentable {
|
||||
@SwiftUI.Environment(\.dynamicTypeSize) private var dynamicTypeSize
|
||||
@SwiftUI.Environment(\.openURL) private var openURL
|
||||
|
||||
init(_ rendered: MarkdownRenderedInline) {
|
||||
attributedText = rendered.attributedText
|
||||
font = rendered.style.font
|
||||
let rendered: MarkdownRenderedInline
|
||||
let selectionContext: MarkdownSelectionContext
|
||||
let lineSpacing: CGFloat
|
||||
let textColor: MarkdownTextColor
|
||||
let wrapsLines: Bool
|
||||
|
||||
init(
|
||||
_ rendered: MarkdownRenderedInline,
|
||||
selectionContext: MarkdownSelectionContext,
|
||||
lineSpacing: CGFloat = 0,
|
||||
textColor: MarkdownTextColor = .primary,
|
||||
wrapsLines: Bool = true
|
||||
) {
|
||||
self.rendered = rendered
|
||||
self.selectionContext = selectionContext
|
||||
self.lineSpacing = lineSpacing
|
||||
self.textColor = textColor
|
||||
self.wrapsLines = wrapsLines
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Text(attributedText)
|
||||
.font(font)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator()
|
||||
}
|
||||
|
||||
func makeUIView(context: Context) -> UITextView {
|
||||
let textView = UITextView()
|
||||
textView.backgroundColor = .clear
|
||||
textView.isEditable = false
|
||||
textView.isSelectable = true
|
||||
textView.isScrollEnabled = false
|
||||
textView.showsHorizontalScrollIndicator = false
|
||||
textView.showsVerticalScrollIndicator = false
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
textView.textContainer.widthTracksTextView = true
|
||||
textView.textContainer.lineBreakMode = wrapsLines ? .byWordWrapping : .byClipping
|
||||
textView.adjustsFontForContentSizeCategory = true
|
||||
textView.linkTextAttributes = [
|
||||
.foregroundColor: T3Colors.uiAccent,
|
||||
.underlineStyle: 0,
|
||||
]
|
||||
textView.accessibilityTraits = .staticText
|
||||
textView.delegate = context.coordinator
|
||||
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
|
||||
return textView
|
||||
}
|
||||
|
||||
func updateUIView(_ textView: UITextView, context: Context) {
|
||||
let attributedText = context.coordinator.attributedText(
|
||||
from: rendered,
|
||||
lineSpacing: lineSpacing,
|
||||
textColor: textColor,
|
||||
dynamicTypeSize: dynamicTypeSize,
|
||||
wrapsLines: wrapsLines
|
||||
)
|
||||
if context.coordinator.shouldApply(attributedText) {
|
||||
let previousText = context.coordinator.lastAppliedText
|
||||
let previousSelection = textView.selectedRange
|
||||
textView.attributedText = attributedText
|
||||
textView.selectedRange = MarkdownSelectionRestoration.range(
|
||||
previousText: previousText,
|
||||
previousRange: previousSelection,
|
||||
newText: attributedText.string
|
||||
)
|
||||
context.coordinator.didApply(attributedText)
|
||||
}
|
||||
context.coordinator.selectionContext = selectionContext
|
||||
context.coordinator.onOpenURL = { url in
|
||||
openURL(url)
|
||||
}
|
||||
textView.accessibilityCustomActions = context.coordinator.accessibilityActions(
|
||||
title: selectionContext.copyActionTitle
|
||||
)
|
||||
}
|
||||
|
||||
func sizeThatFits(
|
||||
_ proposal: ProposedViewSize,
|
||||
uiView: UITextView,
|
||||
context: Context
|
||||
) -> CGSize? {
|
||||
guard let proposedWidth = proposal.width,
|
||||
proposedWidth.isFinite,
|
||||
proposedWidth > 0
|
||||
else {
|
||||
return wrapsLines ? nil : context.coordinator.unwrappedSize(for: uiView)
|
||||
}
|
||||
return context.coordinator.size(
|
||||
for: uiView,
|
||||
proposedWidth: proposedWidth,
|
||||
wrapsLines: wrapsLines
|
||||
)
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, UITextViewDelegate {
|
||||
private struct CacheKey: Equatable {
|
||||
let lineSpacing: CGFloat
|
||||
let textColor: MarkdownTextColor
|
||||
let dynamicTypeSize: DynamicTypeSize
|
||||
let wrapsLines: Bool
|
||||
}
|
||||
|
||||
private struct SizeKey: Hashable {
|
||||
let proposedWidth: CGFloat
|
||||
let wrapsLines: Bool
|
||||
}
|
||||
|
||||
var selectionContext = MarkdownSelectionContext(
|
||||
source: MarkdownSelectionSource(""),
|
||||
copyActionTitle: "Copy message"
|
||||
)
|
||||
var onOpenURL: ((URL) -> Void)?
|
||||
private var cacheKey: CacheKey?
|
||||
private var cachedRendered: MarkdownRenderedInline?
|
||||
private var cachedAttributedText: NSAttributedString?
|
||||
private var cachedSizes: [SizeKey: CGSize] = [:]
|
||||
private var lastAppliedAttributedText: NSAttributedString?
|
||||
private var cachedAccessibilityTitle: String?
|
||||
private var cachedAccessibilityActions: [UIAccessibilityCustomAction] = []
|
||||
|
||||
func attributedText(
|
||||
from rendered: MarkdownRenderedInline,
|
||||
lineSpacing: CGFloat,
|
||||
textColor: MarkdownTextColor,
|
||||
dynamicTypeSize: DynamicTypeSize,
|
||||
wrapsLines: Bool
|
||||
) -> NSAttributedString {
|
||||
let key = CacheKey(
|
||||
lineSpacing: lineSpacing,
|
||||
textColor: textColor,
|
||||
dynamicTypeSize: dynamicTypeSize,
|
||||
wrapsLines: wrapsLines
|
||||
)
|
||||
if cachedRendered === rendered, key == cacheKey, let cachedAttributedText {
|
||||
return cachedAttributedText
|
||||
}
|
||||
let attributedText = MarkdownSelectableTextAttributes.make(
|
||||
from: rendered,
|
||||
lineSpacing: lineSpacing,
|
||||
foregroundColor: textColor.uiColor,
|
||||
dynamicTypeSize: dynamicTypeSize,
|
||||
wrapsLines: wrapsLines
|
||||
)
|
||||
cacheKey = key
|
||||
cachedRendered = rendered
|
||||
cachedAttributedText = attributedText
|
||||
cachedSizes.removeAll(keepingCapacity: true)
|
||||
return attributedText
|
||||
}
|
||||
|
||||
var lastAppliedText: String {
|
||||
lastAppliedAttributedText?.string ?? ""
|
||||
}
|
||||
|
||||
func shouldApply(_ attributedText: NSAttributedString) -> Bool {
|
||||
lastAppliedAttributedText !== attributedText
|
||||
}
|
||||
|
||||
func didApply(_ attributedText: NSAttributedString) {
|
||||
lastAppliedAttributedText = attributedText
|
||||
}
|
||||
|
||||
func size(
|
||||
for textView: UITextView,
|
||||
proposedWidth: CGFloat,
|
||||
wrapsLines: Bool
|
||||
) -> CGSize {
|
||||
let key = SizeKey(proposedWidth: proposedWidth, wrapsLines: wrapsLines)
|
||||
if let cached = cachedSizes[key] {
|
||||
return cached
|
||||
}
|
||||
let bounds = textView.attributedText.boundingRect(
|
||||
with: CGSize(width: proposedWidth, height: .greatestFiniteMagnitude),
|
||||
options: [.usesLineFragmentOrigin, .usesFontLeading],
|
||||
context: nil
|
||||
)
|
||||
let width = min(proposedWidth, max(1, ceil(bounds.width)))
|
||||
let fittingSize = textView.sizeThatFits(
|
||||
CGSize(width: width, height: .greatestFiniteMagnitude)
|
||||
)
|
||||
let size = CGSize(width: width, height: max(1, ceil(fittingSize.height)))
|
||||
cachedSizes[key] = size
|
||||
return size
|
||||
}
|
||||
|
||||
func unwrappedSize(for textView: UITextView) -> CGSize {
|
||||
let key = SizeKey(proposedWidth: .infinity, wrapsLines: false)
|
||||
if let cached = cachedSizes[key] {
|
||||
return cached
|
||||
}
|
||||
let longestLineLength = textView.attributedText.string
|
||||
.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
.map(\.utf16.count)
|
||||
.max() ?? 0
|
||||
var largestFontPointSize: CGFloat = 0
|
||||
textView.attributedText.enumerateAttribute(
|
||||
.font,
|
||||
in: NSRange(location: 0, length: textView.attributedText.length)
|
||||
) { value, _, _ in
|
||||
largestFontPointSize = max(
|
||||
largestFontPointSize,
|
||||
(value as? UIFont)?.pointSize ?? 0
|
||||
)
|
||||
}
|
||||
let perCharacterWidth = max(16, largestFontPointSize * 1.5)
|
||||
let maximumWidth = max(2_048, CGFloat(longestLineLength) * perCharacterWidth)
|
||||
let bounds = textView.attributedText.boundingRect(
|
||||
with: CGSize(width: maximumWidth, height: .greatestFiniteMagnitude),
|
||||
options: [.usesLineFragmentOrigin, .usesFontLeading],
|
||||
context: nil
|
||||
)
|
||||
let fittingSize = textView.sizeThatFits(
|
||||
CGSize(width: max(1, ceil(bounds.width)), height: .greatestFiniteMagnitude)
|
||||
)
|
||||
let size = CGSize(
|
||||
width: max(1, ceil(bounds.width)),
|
||||
height: max(1, ceil(fittingSize.height))
|
||||
)
|
||||
cachedSizes[key] = size
|
||||
return size
|
||||
}
|
||||
|
||||
func accessibilityActions(title: String) -> [UIAccessibilityCustomAction] {
|
||||
if cachedAccessibilityTitle == title {
|
||||
return cachedAccessibilityActions
|
||||
}
|
||||
cachedAccessibilityTitle = title
|
||||
cachedAccessibilityActions = [
|
||||
UIAccessibilityCustomAction(
|
||||
name: title
|
||||
) { [weak self] _ in
|
||||
self?.copyMessage()
|
||||
return true
|
||||
},
|
||||
]
|
||||
return cachedAccessibilityActions
|
||||
}
|
||||
|
||||
func textView(
|
||||
_ textView: UITextView,
|
||||
editMenuForTextIn range: NSRange,
|
||||
suggestedActions: [UIMenuElement]
|
||||
) -> UIMenu? {
|
||||
let copyMessage = UIAction(
|
||||
title: selectionContext.copyActionTitle,
|
||||
image: UIImage(systemName: "doc.on.doc")
|
||||
) { [weak self] _ in
|
||||
self?.copyMessage()
|
||||
}
|
||||
return UIMenu(children: suggestedActions + [copyMessage])
|
||||
}
|
||||
|
||||
func textView(
|
||||
_ textView: UITextView,
|
||||
primaryActionFor textItem: UITextItem,
|
||||
defaultAction: UIAction
|
||||
) -> UIAction? {
|
||||
guard case let .link(url) = textItem.content else { return defaultAction }
|
||||
return UIAction { [weak self] _ in
|
||||
self?.onOpenURL?(url)
|
||||
}
|
||||
}
|
||||
|
||||
private func copyMessage() {
|
||||
UIPasteboard.general.string = selectionContext.source.text
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum MarkdownSelectableTextAttributes {
|
||||
@MainActor
|
||||
static func make(
|
||||
from rendered: MarkdownRenderedInline,
|
||||
lineSpacing: CGFloat,
|
||||
foregroundColor: UIColor = T3Colors.uiTextPrimary,
|
||||
dynamicTypeSize: DynamicTypeSize = .large,
|
||||
wrapsLines: Bool = true
|
||||
) -> NSAttributedString {
|
||||
let result = NSMutableAttributedString()
|
||||
let paragraphStyle = NSMutableParagraphStyle()
|
||||
paragraphStyle.lineSpacing = lineSpacing
|
||||
paragraphStyle.lineBreakMode = wrapsLines ? .byWordWrapping : .byClipping
|
||||
|
||||
for run in rendered.attributedText.runs {
|
||||
let intent = run.inlinePresentationIntent
|
||||
var attributes: [NSAttributedString.Key: Any] = [
|
||||
.font: font(
|
||||
for: rendered.style,
|
||||
intent: intent,
|
||||
dynamicTypeSize: dynamicTypeSize
|
||||
),
|
||||
.foregroundColor: foregroundColor,
|
||||
.paragraphStyle: paragraphStyle,
|
||||
]
|
||||
if intent?.contains(.code) == true {
|
||||
attributes[.backgroundColor] = T3Colors.uiSurfaceRaised
|
||||
}
|
||||
if intent?.contains(.strikethrough) == true {
|
||||
attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
|
||||
}
|
||||
if let link = run.link {
|
||||
attributes[.link] = link
|
||||
}
|
||||
result.append(
|
||||
NSAttributedString(
|
||||
string: String(rendered.attributedText[run.range].characters),
|
||||
attributes: attributes
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private static func font(
|
||||
for style: MarkdownInlineStyle,
|
||||
intent: InlinePresentationIntent?,
|
||||
dynamicTypeSize: DynamicTypeSize
|
||||
) -> UIFont {
|
||||
var font = style.uiFont(dynamicTypeSize: dynamicTypeSize)
|
||||
if intent?.contains(.code) == true, style != .code {
|
||||
font = UIFont.monospacedSystemFont(
|
||||
ofSize: font.pointSize,
|
||||
weight: .regular
|
||||
)
|
||||
}
|
||||
|
||||
let addsBold = intent?.contains(.stronglyEmphasized) == true
|
||||
let addsItalic = intent?.contains(.emphasized) == true
|
||||
guard addsBold || addsItalic else { return font }
|
||||
|
||||
var traits = font.fontDescriptor.symbolicTraits
|
||||
if addsBold {
|
||||
traits.insert(.traitBold)
|
||||
}
|
||||
if addsItalic {
|
||||
traits.insert(.traitItalic)
|
||||
}
|
||||
if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
|
||||
font = UIFont(descriptor: descriptor, size: 0)
|
||||
}
|
||||
return font
|
||||
}
|
||||
}
|
||||
|
||||
enum MarkdownSelectionRestoration {
|
||||
static func range(
|
||||
previousText: String,
|
||||
previousRange: NSRange,
|
||||
newText: String
|
||||
) -> NSRange {
|
||||
guard newText.utf16.starts(with: previousText.utf16),
|
||||
NSMaxRange(previousRange) <= (newText as NSString).length
|
||||
else {
|
||||
return NSRange(location: 0, length: 0)
|
||||
}
|
||||
return previousRange
|
||||
}
|
||||
}
|
||||
|
||||
enum MarkdownInlineFormatter {
|
||||
static func format(_ source: String, baseFont: Font = .body) -> AttributedString {
|
||||
var attributed = (
|
||||
static func format(_ source: String) -> AttributedString {
|
||||
(
|
||||
try? AttributedString(
|
||||
markdown: source,
|
||||
options: AttributedString.MarkdownParsingOptions(
|
||||
@@ -496,20 +921,5 @@ enum MarkdownInlineFormatter {
|
||||
)
|
||||
)
|
||||
) ?? AttributedString(source)
|
||||
|
||||
let styles = attributed.runs.map { run in
|
||||
(run.range, run.inlinePresentationIntent, run.link)
|
||||
}
|
||||
for (range, intent, link) in styles {
|
||||
if intent?.contains(.code) == true {
|
||||
attributed[range].font = baseFont.monospaced()
|
||||
attributed[range].foregroundColor = T3Colors.textPrimary.opacity(0.9)
|
||||
attributed[range].backgroundColor = T3Colors.surfaceRaised
|
||||
}
|
||||
if link != nil {
|
||||
attributed[range].foregroundColor = T3Colors.accent
|
||||
}
|
||||
}
|
||||
return attributed
|
||||
}
|
||||
}
|
||||
@@ -41,17 +41,41 @@ enum MarkdownInlineStyle: String, Hashable, Sendable {
|
||||
case heading4
|
||||
case tableHeader
|
||||
case tableCell
|
||||
case code
|
||||
|
||||
var font: Font {
|
||||
@MainActor
|
||||
func uiFont(dynamicTypeSize: DynamicTypeSize) -> UIFont {
|
||||
let textStyle: UIFont.TextStyle
|
||||
let weight: UIFont.Weight
|
||||
switch self {
|
||||
case .body: T3Typography.threadBody
|
||||
case .heading1: T3Typography.threadHeading1
|
||||
case .heading2: T3Typography.threadHeading2
|
||||
case .heading3: T3Typography.threadHeading3
|
||||
case .heading4: T3Typography.threadHeading4
|
||||
case .tableHeader: T3Typography.threadBody.weight(.semibold)
|
||||
case .tableCell: T3Typography.threadBody
|
||||
case .body, .tableCell:
|
||||
textStyle = .body
|
||||
weight = .regular
|
||||
case .heading1:
|
||||
textStyle = .title2
|
||||
weight = .bold
|
||||
case .heading2:
|
||||
textStyle = .title3
|
||||
weight = .bold
|
||||
case .heading3:
|
||||
textStyle = .headline
|
||||
weight = .bold
|
||||
case .heading4, .tableHeader:
|
||||
textStyle = .body
|
||||
weight = .semibold
|
||||
case .code:
|
||||
textStyle = .callout
|
||||
weight = .regular
|
||||
}
|
||||
|
||||
let traits = UITraitCollection(
|
||||
preferredContentSizeCategory: UIContentSizeCategory(dynamicTypeSize)
|
||||
)
|
||||
let preferred = UIFont.preferredFont(forTextStyle: textStyle, compatibleWith: traits)
|
||||
if self == .code {
|
||||
return UIFont.monospacedSystemFont(ofSize: preferred.pointSize, weight: weight)
|
||||
}
|
||||
return UIFont.systemFont(ofSize: preferred.pointSize, weight: weight)
|
||||
}
|
||||
|
||||
static func heading(level: Int) -> Self {
|
||||
@@ -127,7 +151,7 @@ indirect enum MarkdownRenderedBlock: Equatable, @unchecked Sendable {
|
||||
case orderedList(start: Int, items: [MarkdownRenderedListItem])
|
||||
case blockquote([MarkdownRenderedBlock])
|
||||
case table(MarkdownRenderedTable)
|
||||
case codeBlock(language: String?, code: String)
|
||||
case codeBlock(language: String?, code: String, inline: MarkdownRenderedInline)
|
||||
case thematicBreak
|
||||
}
|
||||
|
||||
@@ -361,7 +385,8 @@ final class MarkdownRenderCache: @unchecked Sendable {
|
||||
rendered = .table(table)
|
||||
|
||||
case let .codeBlock(language, code):
|
||||
rendered = .codeBlock(language: language, code: code)
|
||||
guard let inline = renderInline(code, style: .code) else { return nil }
|
||||
rendered = .codeBlock(language: language, code: code, inline: inline)
|
||||
|
||||
case .thematicBreak:
|
||||
rendered = .thematicBreak
|
||||
@@ -423,10 +448,12 @@ final class MarkdownRenderCache: @unchecked Sendable {
|
||||
return cached.value
|
||||
}
|
||||
|
||||
let inline = MarkdownRenderedInline(
|
||||
attributedText: MarkdownInlineFormatter.format(source, baseFont: style.font),
|
||||
style: style
|
||||
)
|
||||
let attributedText = if style == .code {
|
||||
AttributedString(source)
|
||||
} else {
|
||||
MarkdownInlineFormatter.format(source)
|
||||
}
|
||||
let inline = MarkdownRenderedInline(attributedText: attributedText, style: style)
|
||||
guard !Task.isCancelled else { return nil }
|
||||
inlineRuns.setObject(
|
||||
MarkdownRenderedInlineBox(inline),
|
||||
|
||||
@@ -1159,7 +1159,6 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
|
||||
|
||||
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
|
||||
(scrollView as? BottomAnchoredTranscriptCollectionView)?.maintainsBottomAnchor = false
|
||||
scrollView.window?.endEditing(false)
|
||||
onDismissKeyboard?()
|
||||
}
|
||||
|
||||
|
||||
@@ -187,7 +187,10 @@ private struct FeatureFilePreviewView: View {
|
||||
switch previewKind {
|
||||
case .markdown:
|
||||
ScrollView {
|
||||
MarkdownMessageView(content.text)
|
||||
MarkdownMessageView(
|
||||
content.text,
|
||||
copyActionTitle: "Copy file contents"
|
||||
)
|
||||
.frame(maxWidth: T3Metrics.readingWidth, alignment: .leading)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 18)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Chat Markdown")
|
||||
@@ -263,4 +264,171 @@ struct MarkdownDocumentTests {
|
||||
#expect(runs.contains { $0.inlinePresentationIntent?.contains(.code) == true })
|
||||
#expect(runs.contains { $0.link == URL(string: "https://example.com") })
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func selectableTextAttributesPreserveInlineFormatting() throws {
|
||||
let revision = MarkdownContentRevision(
|
||||
"Use **bold**, *emphasis*, `code`, ~~removed~~, and [docs](https://example.com)."
|
||||
)
|
||||
let document = try #require(
|
||||
MarkdownRenderCache.shared.documentImmediately(for: revision)
|
||||
)
|
||||
guard case let .paragraph(inline) = document.blocks.first else {
|
||||
Issue.record("Expected a rendered paragraph")
|
||||
return
|
||||
}
|
||||
|
||||
let attributed = MarkdownSelectableTextAttributes.make(
|
||||
from: inline,
|
||||
lineSpacing: 4,
|
||||
foregroundColor: T3Colors.uiTextSecondary
|
||||
)
|
||||
let text = attributed.string as NSString
|
||||
let boldIndex = try #require(index(of: "bold", in: text))
|
||||
let emphasisIndex = try #require(index(of: "emphasis", in: text))
|
||||
let codeIndex = try #require(index(of: "code", in: text))
|
||||
let removedIndex = try #require(index(of: "removed", in: text))
|
||||
let linkIndex = try #require(index(of: "docs", in: text))
|
||||
|
||||
let boldFont = try #require(
|
||||
attributed.attribute(.font, at: boldIndex, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
let emphasisFont = try #require(
|
||||
attributed.attribute(.font, at: emphasisIndex, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
let codeFont = try #require(
|
||||
attributed.attribute(.font, at: codeIndex, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
let paragraphStyle = try #require(
|
||||
attributed.attribute(.paragraphStyle, at: 0, effectiveRange: nil)
|
||||
as? NSParagraphStyle
|
||||
)
|
||||
|
||||
#expect(boldFont.fontDescriptor.symbolicTraits.contains(.traitBold))
|
||||
#expect(emphasisFont.fontDescriptor.symbolicTraits.contains(.traitItalic))
|
||||
#expect(codeFont.fontDescriptor.symbolicTraits.contains(.traitMonoSpace))
|
||||
#expect(
|
||||
attributed.attribute(.backgroundColor, at: codeIndex, effectiveRange: nil)
|
||||
as? UIColor == T3Colors.uiSurfaceRaised
|
||||
)
|
||||
#expect(
|
||||
attributed.attribute(.strikethroughStyle, at: removedIndex, effectiveRange: nil)
|
||||
as? Int == NSUnderlineStyle.single.rawValue
|
||||
)
|
||||
#expect(
|
||||
attributed.attribute(.foregroundColor, at: boldIndex, effectiveRange: nil)
|
||||
as? UIColor == T3Colors.uiTextSecondary
|
||||
)
|
||||
#expect(
|
||||
attributed.attribute(.link, at: linkIndex, effectiveRange: nil) as? URL
|
||||
== URL(string: "https://example.com")
|
||||
)
|
||||
#expect(
|
||||
attributed.string
|
||||
== "Use bold, emphasis, code, removed, and docs."
|
||||
)
|
||||
#expect(paragraphStyle.lineSpacing == 4)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func selectableTextAttributesHonorDynamicTypeSize() throws {
|
||||
let document = try #require(
|
||||
MarkdownRenderCache.shared.documentImmediately(
|
||||
for: MarkdownContentRevision("Readable body text")
|
||||
)
|
||||
)
|
||||
guard case let .paragraph(inline) = document.blocks.first else {
|
||||
Issue.record("Expected a rendered paragraph")
|
||||
return
|
||||
}
|
||||
|
||||
let small = MarkdownSelectableTextAttributes.make(
|
||||
from: inline,
|
||||
lineSpacing: 4,
|
||||
dynamicTypeSize: .small
|
||||
)
|
||||
let accessibility = MarkdownSelectableTextAttributes.make(
|
||||
from: inline,
|
||||
lineSpacing: 4,
|
||||
dynamicTypeSize: .accessibility1
|
||||
)
|
||||
let smallFont = try #require(
|
||||
small.attribute(.font, at: 0, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
let accessibilityFont = try #require(
|
||||
accessibility.attribute(.font, at: 0, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
|
||||
#expect(accessibilityFont.pointSize > smallFont.pointSize)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func codeBlocksReuseSelectableInlineRendering() throws {
|
||||
let literalCode = "x = arr[i](fn)\na **b** c\nprintf(\\\"a\\\\tb\\\");"
|
||||
let cache = MarkdownRenderCache()
|
||||
let first = try #require(
|
||||
cache.documentImmediately(
|
||||
for: MarkdownContentRevision("```swift\n\(literalCode)\n```")
|
||||
)
|
||||
)
|
||||
let second = try #require(
|
||||
cache.documentImmediately(
|
||||
for: MarkdownContentRevision("Before\n\n```swift\n\(literalCode)\n```")
|
||||
)
|
||||
)
|
||||
|
||||
guard case let .codeBlock(_, firstCode, firstInline) = first.blocks.first,
|
||||
case let .codeBlock(_, secondCode, secondInline) = second.blocks.last
|
||||
else {
|
||||
Issue.record("Expected rendered code blocks")
|
||||
return
|
||||
}
|
||||
|
||||
#expect(firstCode == literalCode)
|
||||
#expect(secondCode == firstCode)
|
||||
#expect(firstInline === secondInline)
|
||||
#expect(firstInline.style == .code)
|
||||
|
||||
let attributed = MarkdownSelectableTextAttributes.make(
|
||||
from: firstInline,
|
||||
lineSpacing: 3
|
||||
)
|
||||
let font = try #require(
|
||||
attributed.attribute(.font, at: 0, effectiveRange: nil) as? UIFont
|
||||
)
|
||||
#expect(attributed.string == firstCode)
|
||||
#expect(font.fontDescriptor.symbolicTraits.contains(.traitMonoSpace))
|
||||
}
|
||||
|
||||
@Test
|
||||
func restoresSelectionOnlyWhenTextIsExtended() {
|
||||
let selection = NSRange(location: 7, length: 5)
|
||||
|
||||
#expect(
|
||||
MarkdownSelectionRestoration.range(
|
||||
previousText: "Hello, world",
|
||||
previousRange: selection,
|
||||
newText: "Hello, world!"
|
||||
) == selection
|
||||
)
|
||||
#expect(
|
||||
MarkdownSelectionRestoration.range(
|
||||
previousText: "Hello, world",
|
||||
previousRange: selection,
|
||||
newText: "Different text"
|
||||
) == NSRange(location: 0, length: 0)
|
||||
)
|
||||
#expect(
|
||||
MarkdownSelectionRestoration.range(
|
||||
previousText: "Hello, world",
|
||||
previousRange: NSRange(location: 7, length: 20),
|
||||
newText: "Hello, world!"
|
||||
) == NSRange(location: 0, length: 0)
|
||||
)
|
||||
}
|
||||
|
||||
private func index(of substring: String, in text: NSString) -> Int? {
|
||||
let range = text.range(of: substring)
|
||||
return range.location == NSNotFound ? nil : range.location
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user