Skip to content

Commit

Permalink
🐛 Fix Message scrollToBottom
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmai-dev committed Oct 3, 2024
1 parent ba25a8c commit e2b133e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
38 changes: 22 additions & 16 deletions ChatMLX/Features/Conversation/ConversationDetailView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ struct ConversationDetailView: View {
@State private var toastMessage = ""
@State private var toastType: AlertToast.AlertType = .regular
@State private var loading = true
@State private var scrollViewProxy: ScrollViewProxy?

@Namespace var bottomId
@FocusState private var isInputFocused: Bool

var body: some View {
Expand Down Expand Up @@ -93,38 +93,40 @@ struct ConversationDetailView: View {
}
}
.padding()
.id(bottomId)
}
.onChange(
of: conversation.messages.last,
{
proxy.scrollTo(bottomId, anchor: .bottom)
{ _, _ in
scrollToBottom()
}
)
.onAppear {
proxy.scrollTo(bottomId, anchor: .bottom)
scrollViewProxy = proxy
scrollToBottom()
}
}
}

private func scrollToBottom() {
guard let lastMessageId = conversation.messages.last?.id, let scrollViewProxy else {
return
}

withAnimation {
scrollViewProxy.scrollTo(lastMessageId, anchor: .bottom)
}
}

@MainActor
@ViewBuilder
private func EditorToolbar() -> some View {
HStack {
Button {
withAnimation {
if displayStyle == .markdown {
displayStyle = .plain
} else {
displayStyle = .markdown
}
displayStyle = (displayStyle == .markdown) ? .plain : .markdown
}
} label: {
if displayStyle == .markdown {
Image("plaintext")
} else {
Image("markdown")
}
Image(displayStyle == .markdown ? "plaintext" : "markdown")
}

Button(action: {
Expand Down Expand Up @@ -296,7 +298,11 @@ struct ConversationDetailView: View {

Message(context: viewContext).user(content: trimmedMessage, conversation: conversation)

runner.generate(conversation: conversation, in: viewContext)
runner.generate(conversation: conversation, in: viewContext) {
scrollToBottom()
}

scrollToBottom()

Task(priority: .background) {
do {
Expand Down
6 changes: 5 additions & 1 deletion ChatMLX/Utilities/LLMRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ class LLMRunner {
]
}

func generate(conversation: Conversation, in context: NSManagedObjectContext) {
func generate(
conversation: Conversation, in context: NSManagedObjectContext,
progressing: @escaping () -> Void = {}
) {
guard !running else { return }
running = true

Expand Down Expand Up @@ -157,6 +160,7 @@ class LLMRunner {
let text = tokenizer.decode(tokens: tokens)
Task { @MainActor in
assistantMessage.content = text
progressing()
}
}

Expand Down

0 comments on commit e2b133e

Please sign in to comment.