Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

update message list scrolling

Prateek Sunald428fc236f74
diff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
index 137a12bc7f..8cfc37625e 100644
--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
@@ -7,7 +7,6 @@
objects = {
/* Begin PBXBuildFile section */
- DACC3DAB2E604C9C00DAF993 /* Sodium in Frameworks */ = {isa = PBXBuildFile; productRef = DA72BCAB2E5F87B000D128FF /* Sodium */; };
DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };
21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };
DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };
@@ -16,6 +15,8 @@
DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };
DBA3E91C2F7A6B9000AA11BB /* iosMath in Frameworks */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* iosMath */; };
DBA3E91D2F7A6B9000AA11BB /* iosMath in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* iosMath */; };
+ DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */ = {isa = PBXBuildFile; productRef = DB9F1C3B2F9D123400ABCD02 /* Markdown */; };
+ DB9F1C3D2F9D123400ABCD02 /* Markdown in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DB9F1C3B2F9D123400ABCD02 /* Markdown */; };
/* End PBXBuildFile section */
@@ -67,6 +68,7 @@
DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */,
DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */,
DBA3E91C2F7A6B9000AA11BB /* iosMath in Frameworks */,
+ DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -78,6 +80,7 @@
DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */,
DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */,
DBA3E91D2F7A6B9000AA11BB /* iosMath in Frameworks (macOS) */,
+ DB9F1C3D2F9D123400ABCD02 /* Markdown in Frameworks (macOS) */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -148,6 +151,7 @@
DAB0F20C2F5E123400ABCD01 /* InferenceRS */,
DAF584662E61BB8300F8A08F /* ZIPFoundation */,
DBA3E91B2F7A6B9000AA11BB /* iosMath */,
+ DB9F1C3B2F9D123400ABCD02 /* Markdown */,
);
productName = ensu;
productReference = DA72BC612E5F87A000D128FF /* ensu.app */;
@@ -175,6 +179,7 @@
DAB0F20C2F5E123400ABCD01 /* InferenceRS */,
DAF584662E61BB8300F8A08F /* ZIPFoundation */,
DBA3E91B2F7A6B9000AA11BB /* iosMath */,
+ DB9F1C3B2F9D123400ABCD02 /* Markdown */,
);
productName = Ensu;
productReference = 77E1DDDF900AB047CB554122 /* Ensu.app */;
@@ -256,11 +261,11 @@
mainGroup = DA72BC582E5F87A000D128FF;
minimizedProjectReferenceProxies = 1;
packageReferences = (
- DA72BCAA2E5F87B000D128FF /* XCRemoteSwiftPackageReference "swift-sodium" */,
DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */,
DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */,
DBA3E91A2F7A6B9000AA11BB /* XCLocalSwiftPackageReference "../../Packages/iosMath" */,
DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */,
+ DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = DA72BC622E5F87A000D128FF /* Products */;
@@ -877,30 +882,25 @@
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
- DA72BCAA2E5F87B000D128FF /* XCRemoteSwiftPackageReference "swift-sodium" */ = {
+ DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */ = {
isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/jedisct1/swift-sodium.git";
+ repositoryURL = "https://github.com/weichsel/ZIPFoundation.git";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 0.9.1;
+ minimumVersion = 0.9.19;
};
};
- DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */ = {
+ DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */ = {
isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/weichsel/ZIPFoundation.git";
+ repositoryURL = "https://github.com/apple/swift-markdown.git";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 0.9.19;
+ minimumVersion = 0.3.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
- DA72BCAB2E5F87B000D128FF /* Sodium */ = {
- isa = XCSwiftPackageProductDependency;
- package = DA72BCAA2E5F87B000D128FF /* XCRemoteSwiftPackageReference "swift-sodium" */;
- productName = Sodium;
- };
DACC3DC82E618D6A00DAF993 /* EnteNetwork */ = {
isa = XCSwiftPackageProductDependency;
productName = EnteNetwork;
@@ -919,6 +919,11 @@
package = DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */;
productName = ZIPFoundation;
};
+ DB9F1C3B2F9D123400ABCD02 /* Markdown */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */;
+ productName = Markdown;
+ };
/* End XCSwiftPackageProductDependency section */
};
rootObject = DA72BC592E5F87A000D128FF /* Project object */;
diff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index e5a90711b8..9c1fadb0a5 100644
--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,6 +1,15 @@
{
- "originHash" : "927afdbad387a731258b2c4708c30c1743c7d2af62c21111bcaf824d096568ae",
+ "originHash" : "a291d59db9116c12b165f53ad1571f7fedc3d45784c5fb90ee54a4b50d191411",
"pins" : [
+ {
+ "identity" : "swift-cmark",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/swiftlang/swift-cmark.git",
+ "state" : {
+ "revision" : "5d9bdaa4228b381639fff09403e39a04926e2dbe",
+ "version" : "0.7.1"
+ }
+ },
{
"identity" : "swift-log",
"kind" : "remoteSourceControl",
@@ -11,12 +20,12 @@
}
},
{
- "identity" : "swift-sodium",
+ "identity" : "swift-markdown",
"kind" : "remoteSourceControl",
- "location" : "https://github.com/jedisct1/swift-sodium.git",
+ "location" : "https://github.com/apple/swift-markdown.git",
"state" : {
- "revision" : "e7e799cd1eaa4d0f6d3eab56832e7f4b377f4a4f",
- "version" : "0.10.0"
+ "revision" : "7d9a5ce307528578dfa777d505496bd5f544ad94",
+ "version" : "0.7.3"
}
},
{
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
index 1b79ac7761..85f00dc56c 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
@@ -1,5 +1,6 @@
#if canImport(EnteCore)
import SwiftUI
+import Markdown
#if os(macOS)
import QuickLookUI
#else
@@ -31,15 +32,17 @@ struct MessageListView: View {
@State private var lastHapticLength = 0
@State private var wasAtBottomBeforeKeyboard = false
@State private var isUserDragging = false
+ @State private var lastContentHeight: CGFloat = 0
+ @State private var lastScrollChange = ScrollChange()
#if os(iOS)
- @State private var haptic = UIImpactFeedbackGenerator(style: .medium)
+ @State private var haptic: UIImpactFeedbackGenerator?
#endif
var body: some View {
GeometryReader { proxy in
ScrollViewReader { scrollProxy in
ScrollView {
- messageListContent()
+ messageListContent(containerHeight: proxy.size.height)
}
.id(sessionId)
.coordinateSpace(name: "scroll")
@@ -68,72 +71,20 @@ struct MessageListView: View {
let distanceToBottom = value - proxy.size.height
isAtBottom = distanceToBottom <= threshold
}
- .onChange(of: messages.count) { _ in
- scrollToBottom(scrollProxy, animated: isGenerating)
- }
- .onChange(of: sessionId) { _ in
- autoScrollEnabled = true
- DispatchQueue.main.async {
- scrollToBottom(scrollProxy, force: true, animated: false)
- }
- }
- .onChange(of: streamingResponse) { newValue in
- #if os(iOS)
- if isGenerating {
- let length = newValue.count
- if length > lastHapticLength {
- haptic.impactOccurred()
- haptic.prepare()
- lastHapticLength = length
- }
- }
- #endif
- scrollToBottom(scrollProxy, animated: false)
- }
- .onChange(of: keyboardHeight) { newValue in
- if newValue > 0 {
- wasAtBottomBeforeKeyboard = isAtBottom
- }
- if wasAtBottomBeforeKeyboard {
- autoScrollEnabled = true
+ .onPreferenceChange(ContentHeightKey.self) { newHeight in
+ let delta = newHeight - lastContentHeight
+ lastContentHeight = newHeight
+ if delta > 1, autoScrollEnabled, !isUserDragging {
scrollToBottom(scrollProxy, force: true, animated: false)
}
- if newValue == 0 {
- wasAtBottomBeforeKeyboard = false
- }
}
- .onChange(of: inputBarHeight) { _ in
- if autoScrollEnabled && !isUserDragging {
- scrollToBottom(scrollProxy, force: true, animated: false)
- }
- }
- .onChange(of: isGenerating) { newValue in
- if newValue {
- autoScrollEnabled = true
- lastHapticLength = 0
- #if os(iOS)
- haptic.prepare()
- #endif
- #if os(iOS) || os(macOS)
- if #available(iOS 17.0, macOS 14.0, *) {
- scrollToBottom(scrollProxy, force: true, animated: false)
- } else {
- scrollToBottom(scrollProxy, force: true, animated: false)
- }
- #else
- scrollToBottom(scrollProxy, force: true, animated: false)
- #endif
- }
- }
- .onChange(of: isAtBottom) { newValue in
- if newValue && !isUserDragging {
- autoScrollEnabled = true
- scrollToBottom(scrollProxy, force: true, animated: false)
- }
+ .onChange(of: currentScrollChange) { newValue in
+ handleScrollChange(newValue, scrollProxy: scrollProxy)
}
.onAppear {
+ lastScrollChange = currentScrollChange
#if os(iOS)
- haptic.prepare()
+ prepareHaptic()
#endif
scrollToBottom(scrollProxy, force: true, animated: false)
}
@@ -144,24 +95,121 @@ struct MessageListView: View {
}
}
+ private var currentScrollChange: ScrollChange {
+ ScrollChange(
+ messagesCount: messages.count,
+ sessionId: sessionId,
+ streamingLength: streamingResponse.count,
+ keyboardHeight: keyboardHeight,
+ inputBarHeight: inputBarHeight,
+ isGenerating: isGenerating,
+ isAtBottom: isAtBottom
+ )
+ }
+
+ private func handleScrollChange(_ newValue: ScrollChange, scrollProxy: ScrollViewProxy) {
+ let previous = lastScrollChange
+ lastScrollChange = newValue
+
+ if newValue.messagesCount != previous.messagesCount {
+ scrollToBottom(scrollProxy, animated: newValue.isGenerating)
+ }
+
+ if newValue.sessionId != previous.sessionId {
+ autoScrollEnabled = true
+ scrollToBottom(scrollProxy, force: true, animated: false)
+ }
+
+ if newValue.streamingLength != previous.streamingLength {
+ #if os(iOS)
+ if newValue.isGenerating {
+ let length = newValue.streamingLength
+ if length > lastHapticLength {
+ impactHaptic()
+ lastHapticLength = length
+ }
+ }
+ #endif
+ scrollToBottom(scrollProxy, animated: false)
+ }
+
+ if newValue.keyboardHeight != previous.keyboardHeight {
+ if newValue.keyboardHeight > 0 {
+ wasAtBottomBeforeKeyboard = isAtBottom
+ }
+ if wasAtBottomBeforeKeyboard {
+ autoScrollEnabled = true
+ scrollToBottom(scrollProxy, force: true, animated: false)
+ }
+ if newValue.keyboardHeight == 0 {
+ wasAtBottomBeforeKeyboard = false
+ }
+ }
+
+ if newValue.inputBarHeight != previous.inputBarHeight {
+ if autoScrollEnabled && !isUserDragging {
+ scrollToBottom(scrollProxy, force: true, animated: false)
+ }
+ }
+
+ if newValue.isGenerating != previous.isGenerating {
+ if newValue.isGenerating {
+ autoScrollEnabled = true
+ lastHapticLength = 0
+ #if os(iOS)
+ prepareHaptic()
+ #endif
+ scrollToBottom(scrollProxy, force: true, animated: false)
+ }
+ }
+
+ if newValue.isAtBottom != previous.isAtBottom {
+ if newValue.isAtBottom && !isUserDragging {
+ autoScrollEnabled = true
+ scrollToBottom(scrollProxy, force: true, animated: false)
+ }
+ }
+ }
+
+ #if os(iOS)
+ private func prepareHaptic() {
+ let generator = haptic ?? UIImpactFeedbackGenerator(style: .medium)
+ haptic = generator
+ generator.prepare()
+ }
+
+ private func impactHaptic() {
+ let generator = haptic ?? UIImpactFeedbackGenerator(style: .medium)
+ haptic = generator
+ generator.impactOccurred()
+ generator.prepare()
+ }
+ #endif
+
@ViewBuilder
- private func messageListContent() -> some View {
+ private func messageListContent(containerHeight: CGFloat) -> some View {
+ let emptyStateMinHeight = max(0, containerHeight - contentBottomPadding - (EnsuSpacing.lg * 2))
+
VStack(alignment: .leading, spacing: 0) {
LazyVStack(alignment: .leading, spacing: EnsuSpacing.lg) {
if messages.isEmpty && !isGenerating {
- VStack(spacing: EnsuSpacing.sm) {
- Text(emptyStateTitle)
- .font(EnsuTypography.h2)
- .foregroundStyle(EnsuColor.textPrimary)
- if let emptyStateSubtitle {
- Text(emptyStateSubtitle)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textMuted)
+ VStack {
+ Spacer(minLength: 0)
+ VStack(spacing: EnsuSpacing.sm) {
+ Text(emptyStateTitle)
+ .font(EnsuTypography.h2)
+ .foregroundStyle(EnsuColor.textPrimary)
+ if let emptyStateSubtitle {
+ Text(emptyStateSubtitle)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
}
+ .multilineTextAlignment(.center)
+ Spacer(minLength: 0)
}
- .multilineTextAlignment(.center)
- .frame(maxWidth: .infinity, alignment: .top)
- .padding(.top, EnsuSpacing.lg)
+ .frame(maxWidth: .infinity)
+ .frame(minHeight: emptyStateMinHeight)
}
ForEach(messages) { message in
@@ -213,6 +261,12 @@ struct MessageListView: View {
}
)
}
+ .background(
+ GeometryReader { geo in
+ Color.clear
+ .preference(key: ContentHeightKey.self, value: geo.size.height)
+ }
+ )
}
private var messageTransition: AnyTransition {
@@ -273,6 +327,14 @@ private struct BottomOffsetKey: PreferenceKey {
}
}
+private struct ContentHeightKey: PreferenceKey {
+ static var defaultValue: CGFloat = 0
+
+ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
+ value = nextValue()
+ }
+}
+
private struct AttachmentPreviewItem: Identifiable {
let url: URL
var id: String { url.path }
@@ -846,11 +908,11 @@ private struct MarkdownView: View {
}
}
-private func markdownText(_ text: String) -> Text {
+private func markdownText(_ text: String) -> SwiftUI.Text {
if let attributed = try? AttributedString(markdown: text) {
- return Text(attributed)
+ return SwiftUI.Text(attributed)
}
- return Text(text)
+ return SwiftUI.Text(text)
}
private enum MarkdownBlock: Identifiable {
@@ -876,49 +938,54 @@ private enum MarkdownParser {
if !code.isEmpty {
blocks.append(.code(text: code))
}
- } else {
- blocks.append(contentsOf: parseTextBlocks(segment))
+ continue
+ }
+
+ for piece in splitByMathBlocks(segment) {
+ switch piece {
+ case .math(let latex):
+ let trimmed = latex.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty {
+ blocks.append(.math(text: trimmed))
+ }
+ case .markdown(let markdown):
+ blocks.append(contentsOf: parseMarkdownBlocks(markdown))
+ }
}
}
return blocks
}
- private static func parseTextBlocks(_ text: String) -> [MarkdownBlock] {
+ private enum Segment {
+ case markdown(String)
+ case math(String)
+ }
+
+ private static func splitByMathBlocks(_ text: String) -> [Segment] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
- var blocks: [MarkdownBlock] = []
- var paragraph: [String] = []
- var listItems: [String] = []
+ var segments: [Segment] = []
+ var markdownLines: [String] = []
var mathLines: [String] = []
var mathEndDelimiter: String? = nil
- func flushParagraph() {
- if !paragraph.isEmpty {
- blocks.append(.paragraph(text: paragraph.joined(separator: "\n")))
- paragraph.removeAll()
- }
- }
-
- func flushList() {
- if !listItems.isEmpty {
- blocks.append(.list(items: listItems))
- listItems.removeAll()
+ func flushMarkdown() {
+ if !markdownLines.isEmpty {
+ segments.append(.markdown(markdownLines.joined(separator: "\n")))
+ markdownLines.removeAll()
}
}
func flushMath() {
- if mathEndDelimiter != nil {
- if !mathLines.isEmpty {
- blocks.append(.math(text: mathLines.joined(separator: "\n")))
- }
- mathLines.removeAll()
- mathEndDelimiter = nil
+ if !mathLines.isEmpty {
+ segments.append(.math(mathLines.joined(separator: "\n")))
}
+ mathLines.removeAll()
+ mathEndDelimiter = nil
}
func startMath(endDelimiter: String, initialContent: String? = nil) {
- flushParagraph()
- flushList()
+ flushMarkdown()
mathEndDelimiter = endDelimiter
mathLines.removeAll()
if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines), !initial.isEmpty {
@@ -966,7 +1033,8 @@ private enum MarkdownParser {
let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)
if content.hasSuffix("\\]") {
let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)
- blocks.append(.math(text: inner))
+ flushMarkdown()
+ segments.append(.math(inner))
} else {
startMath(endDelimiter: "\\]", initialContent: content)
}
@@ -977,7 +1045,8 @@ private enum MarkdownParser {
let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)
if content.hasSuffix("$$") {
let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)
- blocks.append(.math(text: inner))
+ flushMarkdown()
+ segments.append(.math(inner))
} else {
startMath(endDelimiter: "$$", initialContent: content)
}
@@ -986,62 +1055,162 @@ private enum MarkdownParser {
if isBracketMathLine(trimmed) {
let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)
- blocks.append(.math(text: inner))
+ flushMarkdown()
+ segments.append(.math(inner))
continue
}
- if trimmed.isEmpty {
- flushParagraph()
- flushList()
- continue
+ markdownLines.append(line)
+ }
+
+ if mathEndDelimiter != nil {
+ flushMath()
+ } else {
+ flushMarkdown()
+ }
+
+ return segments
+ }
+
+ private static func parseMarkdownBlocks(_ markdown: String) -> [MarkdownBlock] {
+ guard !markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }
+ let document = Document(parsing: markdown)
+ var blocks: [MarkdownBlock] = []
+ for child in document.children {
+ blocks.append(contentsOf: blocks(for: child))
+ }
+ return blocks
+ }
+
+ private static func blocks(for markup: Markup) -> [MarkdownBlock] {
+ switch markup {
+ case let heading as Heading:
+ let text = renderInlineChildren(heading)
+ guard !text.isEmpty else { return [] }
+ let level = max(1, min(heading.level, 3))
+ return [.heading(level: level, text: text)]
+ case let paragraph as Paragraph:
+ let text = renderInlineChildren(paragraph)
+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }
+ return [.paragraph(text: text)]
+ case let blockQuote as BlockQuote:
+ let text = renderBlockQuote(blockQuote)
+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }
+ return [.blockquote(text: text)]
+ case let codeBlock as CodeBlock:
+ let code = codeBlock.code.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !code.isEmpty else { return [] }
+ return [.code(text: code)]
+ case _ as ThematicBreak:
+ return [.divider]
+ case let orderedList as OrderedList:
+ let items = orderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ return items.isEmpty ? [] : [.list(items: items)]
+ case let unorderedList as UnorderedList:
+ let items = unorderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ return items.isEmpty ? [] : [.list(items: items)]
+ default:
+ var blocks: [MarkdownBlock] = []
+ for child in markup.children {
+ blocks.append(contentsOf: blocks(for: child))
}
+ return blocks
+ }
+ }
- if trimmed == "---" || trimmed == "***" || trimmed == "___" {
- flushParagraph()
- flushList()
- blocks.append(.divider)
+ private static func renderBlockQuote(_ quote: BlockQuote) -> String {
+ var parts: [String] = []
+ for child in quote.children {
+ if let paragraph = child as? Paragraph {
+ let text = renderInlineChildren(paragraph)
+ if !text.isEmpty {
+ parts.append(text)
+ }
continue
}
-
- if trimmed.hasPrefix("# ") || trimmed.hasPrefix("## ") || trimmed.hasPrefix("### ") {
- flushParagraph()
- flushList()
- let level = trimmed.prefix(3).filter { $0 == "#" }.count
- let headingText = trimmed.drop(while: { $0 == "#" || $0 == " " })
- blocks.append(.heading(level: max(1, min(level, 3)), text: String(headingText)))
+ if let heading = child as? Heading {
+ let text = renderInlineChildren(heading)
+ if !text.isEmpty {
+ parts.append(text)
+ }
continue
}
-
- if trimmed.hasPrefix(">") {
- flushParagraph()
- flushList()
- let quote = trimmed.drop(while: { $0 == ">" || $0 == " " })
- blocks.append(.blockquote(text: String(quote)))
+ if let list = child as? OrderedList {
+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ if !items.isEmpty {
+ parts.append(items.joined(separator: "\n"))
+ }
continue
}
-
- if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") {
- flushParagraph()
- let item = trimmed.dropFirst(2)
- listItems.append(String(item))
+ if let list = child as? UnorderedList {
+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ if !items.isEmpty {
+ parts.append(items.joined(separator: "\n"))
+ }
continue
}
+ }
+ return parts.joined(separator: "\n")
+ }
- if let range = trimmed.range(of: ". "),
- let leading = Int(trimmed[..<range.lowerBound]) {
- flushParagraph()
- listItems.append(String(trimmed[range.upperBound...]))
- _ = leading
+ private static func renderListItem(_ item: ListItem) -> String {
+ var parts: [String] = []
+ for child in item.children {
+ if let paragraph = child as? Paragraph {
+ let text = renderInlineChildren(paragraph)
+ if !text.isEmpty {
+ parts.append(text)
+ }
+ continue
+ }
+ if let list = child as? OrderedList {
+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ if !items.isEmpty {
+ parts.append(items.joined(separator: "\n"))
+ }
+ continue
+ }
+ if let list = child as? UnorderedList {
+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }
+ if !items.isEmpty {
+ parts.append(items.joined(separator: "\n"))
+ }
continue
}
-
- paragraph.append(line)
}
+ return parts.joined(separator: "\n")
+ }
- flushParagraph()
- flushList()
- flushMath()
- return blocks
+ private static func renderInlineChildren(_ markup: Markup) -> String {
+ markup.children.map(renderInline(from:)).joined()
+ }
+
+ private static func renderInline(from markup: Markup) -> String {
+ switch markup {
+ case let text as Text:
+ return text.string
+ case _ as SoftBreak:
+ return " "
+ case _ as LineBreak:
+ return "\n"
+ case let emphasis as Emphasis:
+ return "*" + renderInlineChildren(emphasis) + "*"
+ case let strong as Strong:
+ return "**" + renderInlineChildren(strong) + "**"
+ case let inlineCode as InlineCode:
+ return "`\(inlineCode.code)`"
+ case let strikethrough as Strikethrough:
+ return "~~" + renderInlineChildren(strikethrough) + "~~"
+ case let link as Link:
+ let label = renderInlineChildren(link)
+ let destination = link.destination ?? ""
+ return destination.isEmpty ? label : "[\(label)](\(destination))"
+ default:
+ if markup.children.isEmpty {
+ return ""
+ }
+ return renderInlineChildren(markup)
+ }
}
}
@@ -1116,6 +1285,17 @@ private struct BlockQuoteView: View {
.clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
}
}
+
+private struct ScrollChange: Equatable {
+ var messagesCount: Int = 0
+ var sessionId: UUID?
+ var streamingLength: Int = 0
+ var keyboardHeight: CGFloat = 0
+ var inputBarHeight: CGFloat = 0
+ var isGenerating: Bool = false
+ var isAtBottom: Bool = true
+}
+
#else
import SwiftUI