Branchwell

Jotley / app · jotley.ai / iOS / Views / iOSNoteDetailComponents.swift

Raw 27.5 KB on c22c50f3614b055549c1ecbf54af0165e0bc8df1
1import CoreData
2//
3// iOSNoteDetailComponents.swift
4// Jotley
5//
6// Supporting views extracted from iOSNoteDetailView.swift
7//
8
9import SwiftUI
10
11struct NoteScrollRange: Equatable {
12 let offset: CGFloat
13 let maximumOffset: CGFloat
14
15 init(_ geometry: ScrollGeometry) {
16 maximumOffset = max(0, geometry.contentSize.height + geometry.contentInsets.top
17 + geometry.contentInsets.bottom - geometry.containerSize.height)
18 offset = min(maximumOffset, max(0, geometry.contentOffset.y + geometry.contentInsets.top))
19 }
20}
21
22struct NoteFooterContentKey: PreferenceKey {
23 static var defaultValue: [UUID: AnyView] = [:]
24 static func reduce(value: inout [UUID: AnyView], nextValue: () -> [UUID: AnyView]) {
25 value.merge(nextValue(), uniquingKeysWith: { _, new in new })
26 }
27}
28
29/// Reserve readable primary-action text before assigning space to the template.
30/// On very narrow windows the template moves above the primary action and +.
31struct NoteSummaryActionsLayout: Layout {
32 var spacing: CGFloat
33
34 private func arrangement(width: CGFloat, subviews: Subviews) -> (templateWidth: CGFloat, stacked: Bool, rowHeight: CGFloat) {
35 let primaryWidth = subviews[1].sizeThatFits(.unspecified).width
36 let captureWidth = subviews.count > 2 ? subviews[2].sizeThatFits(.unspecified).width + spacing : 0
37 let remaining = width - primaryWidth - captureWidth - spacing
38 return (remaining >= 164 ? 164 : 112, remaining < 112, 44)
39 }
40
41 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
42 let width = proposal.width ?? 500
43 let layout = arrangement(width: width, subviews: subviews)
44 return CGSize(width: width, height: layout.stacked ? layout.rowHeight * 2 + 8 : layout.rowHeight)
45 }
46
47 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
48 let layout = arrangement(width: bounds.width, subviews: subviews)
49 let captureWidth = subviews.count > 2 ? subviews[2].sizeThatFits(.unspecified).width : 0
50 let rowY = bounds.maxY - layout.rowHeight
51 let primaryX = layout.stacked ? bounds.minX : bounds.minX + layout.templateWidth + spacing
52 let primaryWidth = bounds.maxX - primaryX - (captureWidth > 0 ? captureWidth + spacing : 0)
53 subviews[0].place(at: CGPoint(x: layout.stacked ? bounds.midX - 82 : bounds.minX,
54 y: layout.stacked ? bounds.minY : rowY),
55 proposal: ProposedViewSize(width: layout.stacked ? 164 : layout.templateWidth, height: layout.rowHeight))
56 subviews[1].place(at: CGPoint(x: primaryX, y: rowY), proposal: ProposedViewSize(width: primaryWidth, height: layout.rowHeight))
57 if subviews.count > 2 {
58 subviews[2].place(at: CGPoint(x: bounds.maxX - captureWidth, y: rowY),
59 proposal: ProposedViewSize(width: captureWidth, height: layout.rowHeight))
60 }
61 }
62}
63
64enum MobileNoteFooterInsets {
65 static let splitBottom: CGFloat = 8
66 static let phoneBottom: CGFloat = 24
67}
68
69struct NotesNewTranscriptionButton: View {
70 let action: () -> Void
71
72 var body: some View {
73 Button(action: action) {
74 Image(systemName: "plus")
75 .font(.system(size: 20, weight: .semibold))
76 }
77 .buttonStyle(JotleyGlassButtonStyle(circular: true, floatsOverContent: true))
78 .accessibilityIdentifier("notesListNewNoteButton")
79 .accessibilityLabel("New live transcription")
80 }
81}
82
83// MARK: - iOS Tag View
84
85struct iOSTagView: View {
86 let tag: String
87 var onRemove: (() -> Void)? = nil
88 @State private var showRemoveButton = false
89
90 var body: some View {
91 HStack(spacing: 4) {
92 Text(tag)
93 .font(.caption)
94 .fixedSize(horizontal: false, vertical: true)
95
96 if showRemoveButton {
97 Button {
98 onRemove?()
99 } label: {
100 Image(systemName: "xmark.circle.fill")
101 .font(.caption2)
102 }
103 .buttonStyle(.plain)
104 .accessibilityLabel("Remove \(tag)")
105 }
106 }
107 .modifier(JotleyNoteTagStyle())
108 .onTapGesture {
109 withAnimation(.easeInOut(duration: 0.2)) {
110 showRemoveButton.toggle()
111 }
112 }
113 }
114}
115
116// MARK: - Add Tag Sheet View
117
118struct AddTagSheetView: View {
119 @ObservedObject var note: Note
120 @Binding var isPresented: Bool
121 @Binding var newTagText: String
122 @Binding var currentTags: [String]
123 var onSave: () -> Void
124
125 @Environment(\.managedObjectContext) private var viewContext
126 @FocusState private var isTextFieldFocused: Bool
127
128 private func getFormattedTag(_ tag: String) -> String {
129 let spacesToDashes = tag.replacingOccurrences(of: " ", with: "-")
130 let validCharacters = CharacterSet.letters.union(CharacterSet(charactersIn: "-0123456789"))
131 return spacesToDashes.components(separatedBy: validCharacters.inverted).joined()
132 }
133
134 private func getCanonicalTag(_ tag: String) -> String {
135 return tag.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
136 }
137
138 var body: some View {
139 NavigationStack {
140 ScrollView(showsIndicators: false) {
141 VStack(alignment: .leading, spacing: 16) {
142 TextField("Enter tag name", text: $newTagText)
143 .font(.body).foregroundStyle(Color.themeTextPrimary)
144 .textFieldStyle(.plain)
145 .focused($isTextFieldFocused)
146 .textInputAutocapitalization(.never)
147 .autocorrectionDisabled()
148 .tint(Color.themePrimaryAccent)
149 .padding(.horizontal, 16).frame(minHeight: 56)
150 .background(Color.themeContentBackground, in: RoundedRectangle(cornerRadius: 14))
151 .overlay {
152 RoundedRectangle(cornerRadius: 14).strokeBorder(
153 isTextFieldFocused ? Color.themePrimaryAccent : Color.themeTextSecondary.opacity(0.25), lineWidth: 1.5)
154 }
155 .submitLabel(.done).onSubmit(addTag)
156 .accessibilityIdentifier("addTagTextField")
157 Button(action: addTag) {
158 JotleyAccentIconLabel(title: "Add Tag", systemImage: "plus")
159 .font(.headline).frame(maxWidth: .infinity)
160 }
161 .buttonStyle(JotleyGlassButtonStyle())
162 .disabled(getCanonicalTag(newTagText).isEmpty || note.tagSet.count >= LocalNoteTags.maximumCount)
163 .accessibilityIdentifier("addTagSaveButton")
164 }
165 .padding(16)
166 }
167 .scrollBounceBehavior(.basedOnSize)
168 .background(Color.themeBackground)
169 .navigationTitle("Add Tag")
170 .navigationBarTitleDisplayMode(.inline)
171 .toolbar {
172 ToolbarItem(placement: .cancellationAction) {
173 Button("Cancel") { newTagText = ""; isPresented = false }
174 .jotleyDismissButtonStyle(inToolbar: true)
175 .accessibilityIdentifier("addTagCancelButton")
176 }
177 .sharedBackgroundVisibility(.hidden)
178 }
179 .tint(Color.themeActionText)
180 .onAppear { isTextFieldFocused = true }
181 }
182 .presentationDetents([.height(220)])
183 .presentationDragIndicator(.visible)
184 .presentationCornerRadius(24)
185 .presentationBackground(Color.themeBackground)
186 .observeThemeChanges()
187 }
188
189 private func addTag() {
190 guard !newTagText.isEmpty, note.tagSet.count < LocalNoteTags.maximumCount else { return }
191
192 let formattedTag = getFormattedTag(newTagText)
193 let canonicalNewTag = getCanonicalTag(formattedTag)
194 guard !canonicalNewTag.isEmpty else { return }
195
196 // Check if a similar tag already exists (case-insensitive)
197 let tagExists = currentTags.contains { existingTag in
198 getCanonicalTag(existingTag) == canonicalNewTag
199 }
200
201 if !tagExists {
202 do {
203 try note.addTagByName(formattedTag, in: viewContext)
204 currentTags = note.tagNames
205 try viewContext.save()
206 onSave()
207 } catch {
208 print("Failed to save tag: \(error)")
209 }
210 }
211
212 newTagText = ""
213 isPresented = false
214 }
215}
216
217// MARK: - Markdown Content View (for Summary with rendered markdown)
218
219struct TranscriptBubbleView: View {
220 let text: String
221 var timestampText: String? = nil
222 var allowsTextSelection: Bool = false
223
224 private var isLikelyMultiLine: Bool {
225 text.count > 80
226 }
227
228 var body: some View {
229 HStack {
230 VStack(alignment: .leading, spacing: 4) {
231 if let timestampText, !timestampText.isEmpty {
232 Text(timestampText)
233 .font(.caption2.monospacedDigit())
234 .foregroundColor(Color.themeTextSecondary.opacity(0.9))
235 }
236
237 if allowsTextSelection {
238 Text(text)
239 .foregroundColor(Color(uiColor: .label))
240 .lineLimit(nil)
241 .multilineTextAlignment(.leading)
242 .textSelection(.enabled)
243 } else {
244 Text(text)
245 .foregroundColor(Color(uiColor: .label))
246 .lineLimit(nil)
247 .multilineTextAlignment(.leading)
248 }
249 }
250 .padding(.horizontal, 12)
251 .padding(.vertical, 8)
252 .frame(maxWidth: isLikelyMultiLine ? .infinity : nil, alignment: .leading)
253 .modifier(JotleyTranscriptCard())
254
255 if !isLikelyMultiLine {
256 Spacer(minLength: 0)
257 }
258 }
259 }
260}
261
262struct MarkdownContentView: View {
263 // The shared color helpers return concrete colors, so this renderer must
264 // observe appearance updates even when its note text has not changed.
265 @ObservedObject private var themeManager = ThemeManager.shared
266 let content: String
267 var body: some View {
268 // Capture the current color as a value outside ForEach. Cached line data
269 // does not change with appearance, so each row needs this explicit input.
270 let textColor = Color.themeTextPrimary
271 return LazyVStack(alignment: .leading, spacing: 8) {
272 ForEach(ParsedNoteMarkdown.rendering(content).lines) { line in
273 if let marker = line.marker {
274 HStack(alignment: .firstTextBaseline, spacing: 8) {
275 Text(marker).frame(minWidth: 16, alignment: .trailing)
276 .accessibilityHidden(true)
277 Text(line.text).textSelection(.enabled)
278 .frame(maxWidth: .infinity, alignment: .leading)
279 }
280 .font(.body).foregroundColor(textColor)
281 .padding(.leading, CGFloat(line.indentation) * 8)
282 .accessibilityElement(children: .combine)
283 .accessibilityLabel("\(marker) \(String(line.text.characters))")
284 .accessibilityIdentifier("markdownListItem-\(line.id)")
285 } else {
286 Text(line.text)
287 .font(line.heading ? .headline : .body)
288 .foregroundColor(textColor)
289 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
290 }
291 }
292 }
293 }
294}
295
296/// Original note-specific Ask AI flow, backed entirely by Apple's local model.
297struct LocalAskNoteView: View {
298 @ObservedObject var note: Note
299 @EnvironmentObject private var store: SharedPersistenceController
300 @Environment(\.dismiss) private var dismiss
301 @Environment(\.scenePhase) private var scenePhase
302 @State private var inputFocused = false
303 @State private var messages: [LocalChatMessage] = []
304 @State private var input = ""
305 @State private var preview = ""
306 @State private var error: String?
307 @State private var task: Task<Void, Never>?
308 @State private var generation: UUID?
309 @State private var showingClear = false
310 @State private var share: LocalSharePayload?
311 private var source: String {
312 let transcript = (note.transcription ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
313 return transcript.isEmpty ? note.summary ?? "" : transcript
314 }
315 private var locale: Locale { Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US") }
316 private var unavailable: String? {
317 #if DEBUG && targetEnvironment(simulator)
318 // Marketing fixtures show an already prepared local-model state.
319 if ProcessInfo.processInfo.environment["JOTLEY_SCREENSHOT_CHAT_READY"] == "1" { return nil }
320 #endif
321 return LocalSummary.readiness(locale: locale)?.replacingOccurrences(of: "summaries", with: "Ask AI")
322 }
323 private var conversation: String { LocalNoteChat.conversationMarkdown(title: note.title, messages: messages) }
324 private var canSubmit: Bool { !showingClear && generation == nil && unavailable == nil }
325 var body: some View {
326 VStack(spacing: 0) {
327 VStack(spacing: 0) {
328 header
329 Divider()
330 ScrollViewReader { proxy in
331 ScrollView {
332 LazyVStack(alignment: .leading, spacing: 16) {
333 if messages.isEmpty { welcome }
334 ForEach(messages) { message in
335 messageBubble(message).id(message.id)
336 }
337 if generation != nil {
338 VStack(alignment: .leading, spacing: 8) {
339 if preview.isEmpty { ProgressView("Thinking on this device…") }
340 else { JotleyChatAnswerText(content: preview) }
341 Button("Stop Answer") { cancel() }
342 .accessibilityIdentifier("askAIStopButton")
343 }.id("answer").padding().modifier(JotleyTranscriptCard())
344 }
345 }.padding()
346 }
347 .scrollDismissesKeyboard(.interactively)
348 .onChange(of: messages.count) { _, _ in
349 if let last = messages.last { proxy.scrollTo(last.id, anchor: .bottom) }
350 }
351 }
352 if let notice = error ?? unavailable {
353 HStack(alignment: .top) {
354 Image(systemName: "info.circle")
355 Text(notice).font(.footnote)
356 if error != nil { Button("Dismiss") { error = nil } }
357 }.foregroundStyle(Color.themeTextSecondary).padding()
358 .accessibilityIdentifier("askAIStatus")
359 }
360 Divider()
361 HStack(alignment: .center, spacing: 12) {
362 ZStack(alignment: .topLeading) {
363 if input.isEmpty {
364 Text("Ask about this note…").foregroundStyle(Color.themeTextSecondary)
365 .allowsHitTesting(false).accessibilityHidden(true)
366 }
367 MobileAskQuestionInput(text: $input, focused: $inputFocused,
368 isEnabled: generation == nil, onSend: send)
369 }
370 .padding(12).frame(minHeight: 44)
371 .modifier(JotleyAskComposerSurface(isFocused: inputFocused))
372 .contentShape(RoundedRectangle(cornerRadius: 20))
373 .onTapGesture { if generation == nil { inputFocused = true } }
374 Button(action: send) {
375 Image(systemName: "arrow.up").font(.system(size: 20, weight: .semibold))
376 .frame(width: 44, height: 44)
377 }.buttonStyle(JotleyGlassButtonStyle(circular: true, keepsDisabledSurfaceVisible: true))
378 .disabled(!canSubmit || input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
379 .accessibilityLabel("Send Question").accessibilityIdentifier("askAISendButton")
380 }.padding()
381 }
382
383 .sheet(item: $share) { ShareSheet(activityItems: $0.items) }
384 .task {
385 guard let id = note.id else { error = "This note is unavailable."; return }
386 do { messages = try store.chatMessages(noteID: id) }
387 catch { self.error = error.localizedDescription }
388 }
389 .onDisappear { cancel() }
390 .onChange(of: scenePhase) { _, phase in if phase == .background { cancel() } }
391 .onReceive(NotificationCenter.default.publisher(for: LiveTranscriptionManager.willBeginTranscription)) { _ in cancel() }
392 .tint(.themePrimaryAccent).observeThemeChanges()
393 }
394 .modifier(JotleyGlassPanel())
395 .allowsHitTesting(!showingClear)
396 .accessibilityHidden(showingClear)
397 .overlay { clearConfirmation }
398 .onChange(of: showingClear) { _, showing in if showing { inputFocused = false } }
399 }
400 @ViewBuilder private var clearConfirmation: some View {
401 if showingClear {
402 JotleyClearChatConfirmation(onCancel: { showingClear = false }, onClear: clearConversation)
403 }
404 }
405 private func clearConversation() {
406 showingClear = false
407 guard let id = note.id else { return }
408 do { try store.clearChat(noteID: id); messages = []; error = nil }
409 catch { self.error = error.localizedDescription }
410 }
411 private var header: some View {
412 HStack(spacing: 12) {
413 Text("Ask AI").font(.system(size: 20, weight: .semibold)).foregroundStyle(Color.themeTextPrimary)
414 Spacer(minLength: 8)
415 Button("Copy Conversation", systemImage: "doc.on.doc") { UIPasteboard.general.string = conversation }
416 .labelStyle(.iconOnly)
417 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
418 .disabled(messages.isEmpty || generation != nil)
419 .accessibilityIdentifier("askAICopyConversationButton")
420 Button("Share Conversation", systemImage: "square.and.arrow.up") { share = LocalSharePayload(items: [conversation]) }
421 .labelStyle(.iconOnly)
422 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
423 .disabled(messages.isEmpty || generation != nil)
424 .accessibilityIdentifier("askAIShareConversationButton")
425 Button("Clear Chat History", systemImage: "arrow.counterclockwise") { showingClear = true }
426 .labelStyle(.iconOnly)
427 .buttonStyle(JotleyGlassButtonStyle(keepsDisabledSurfaceVisible: true))
428 .disabled(messages.isEmpty || generation != nil)
429 .accessibilityIdentifier("askAIClearButton")
430 Button("Done") { dismiss() }
431 .jotleyDismissButtonStyle()
432 .accessibilityIdentifier("askAIDoneButton")
433 }
434 .font(.system(size: 15)).buttonStyle(JotleyGlassButtonStyle()).padding(16)
435 }
436
437 private var welcome: some View {
438 VStack(alignment: .leading, spacing: 16) {
439 Image(systemName: "bubble.left.and.bubble.right.fill").font(.system(size: 40)).foregroundStyle(Color.themePrimaryAccent)
440 Text("Ask about your note").font(.title2.bold()).foregroundStyle(Color.themeTextPrimary)
441 Text(note.title ?? "Untitled").font(.headline)
442 Text("Questions and answers are processed on this device using Apple Intelligence. No note content is sent to an AI service. Conversation history is saved with your notes and follows your optional iCloud setting.")
443 .font(.subheadline).foregroundStyle(Color.themeTextSecondary)
444 if source.utf8.count > 2400 {
445 Text("For long notes, Ask AI selects relevant excerpts. Be specific about the topic you want to find.")
446 .font(.footnote).foregroundStyle(Color.themeTextSecondary)
447 }
448 ForEach(["Summarize the key points", "What are the main topics?", "List any action items"], id: \.self) { suggestion in
449 Button { submit(suggestion, fromComposer: false) } label: {
450 Text(suggestion)
451 }
452 .frame(minHeight: 44).buttonStyle(JotleyGlassButtonStyle()).disabled(!canSubmit)
453 }
454 }.padding(.vertical, 16)
455 }
456 private func messageBubble(_ message: LocalChatMessage) -> some View {
457 HStack {
458 if message.role == "user" { Spacer(minLength: 32) }
459 VStack(alignment: .leading, spacing: 8) {
460 HStack(spacing: 12) {
461 Text(message.role == "user" ? "You" : "Jotley").font(.caption.weight(.semibold))
462 Spacer(minLength: 8)
463 Text(message.timestamp, format: .dateTime.hour().minute())
464 .font(.caption2.monospacedDigit())
465 }.foregroundStyle(Color.themeTextSecondary)
466 if message.role == "assistant" { JotleyChatAnswerText(content: message.content) }
467 else { Text(message.content).textSelection(.enabled).foregroundStyle(Color.themeTextPrimary) }
468 }.padding().modifier(JotleyTranscriptCard(accentOutline: message.role == "user"))
469 if message.role == "assistant" { Spacer(minLength: 32) }
470 }
471 }
472 private func send() {
473 submit(input, fromComposer: true)
474 }
475 private func submit(_ text: String, fromComposer: Bool) {
476 let question = text.trimmingCharacters(in: .whitespacesAndNewlines)
477 guard canSubmit, !question.isEmpty, let id = note.id, !note.isDeleted else { return }
478 let source = source, history = messages
479 do {
480 _ = try LocalNoteChat.prompt(source: source, question: question, history: history)
481 let message = LocalChatMessage(role: "user", content: question)
482 try store.saveChatMessage(message, noteID: id); messages.append(message)
483 } catch { self.error = error.localizedDescription; return }
484 if fromComposer { input = "" }
485 inputFocused = false; preview = ""; error = nil
486 let token = UUID(); generation = token
487 let locale = locale
488 JotleyProcessing.shared.begin()
489 task = Task { @MainActor in
490 defer { JotleyProcessing.shared.end() }
491 defer { if generation == token { generation = nil; task = nil; preview = "" } }
492 do {
493 let answer = try await LocalNoteChat.answer(source: source, question: question, history: history, locale: locale) { value in
494 await MainActor.run { if generation == token { preview = value } }
495 }
496 try Task.checkCancellation()
497 guard generation == token, !note.isDeleted else { return }
498 let message = LocalChatMessage(role: "assistant", content: answer)
499 try store.saveChatMessage(message, noteID: id); messages.append(message)
500 } catch is CancellationError { }
501 catch {
502 if generation == token {
503 self.error = error.localizedDescription
504 if fromComposer { input = question }
505 }
506 }
507 }
508 }
509 private func cancel() {
510 task?.cancel(); task = nil; generation = nil; preview = ""
511 }
512}
513
514
515/// Multiline chat entry with an actual Send return key. SwiftUI's vertical
516/// TextField still inserts a newline with submitLabel(.send) on iPad/iPhone.
517private struct MobileAskQuestionInput: UIViewRepresentable {
518 @Binding var text: String
519 @Binding var focused: Bool
520 let isEnabled: Bool
521 let onSend: () -> Void
522 @ObservedObject private var themeManager = ThemeManager.shared
523
524 final class TextView: UITextView {
525 var insertingLineBreak = false
526 override var keyCommands: [UIKeyCommand]? {
527 let lineBreaks = [UIKeyModifierFlags.shift, .alternate].map { modifiers in
528 let command = UIKeyCommand(input: "\r", modifierFlags: modifiers, action: #selector(insertQuestionLineBreak))
529 command.wantsPriorityOverSystemBehavior = true
530 return command
531 }
532 return lineBreaks + (super.keyCommands ?? [])
533 }
534 @objc private func insertQuestionLineBreak() {
535 insertingLineBreak = true
536 insertText("\n")
537 insertingLineBreak = false
538 }
539 }
540
541 func makeUIView(context: Context) -> TextView {
542 let view = TextView()
543 view.delegate = context.coordinator
544 view.backgroundColor = .clear
545 view.font = .preferredFont(forTextStyle: .body)
546 view.adjustsFontForContentSizeCategory = true
547 view.textContainerInset = .zero
548 view.textContainer.lineFragmentPadding = 0
549 view.returnKeyType = .send
550 view.enablesReturnKeyAutomatically = true
551 view.isScrollEnabled = false
552 view.accessibilityIdentifier = "askAIQuestionField"
553 view.accessibilityLabel = "Ask about this note"
554 view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
555 return view
556 }
557 func updateUIView(_ view: TextView, context: Context) {
558 context.coordinator.parent = self
559 if view.text != text { view.text = text; view.invalidateIntrinsicContentSize() }
560 view.textColor = UIColor(Color.themeTextPrimary)
561 view.tintColor = UIColor(themeManager.currentThemeColor.color)
562 view.isEditable = isEnabled
563 if focused && isEnabled && !view.isFirstResponder { view.becomeFirstResponder() }
564 else if !focused && view.isFirstResponder { view.resignFirstResponder() }
565 }
566 func sizeThatFits(_ proposal: ProposedViewSize, uiView: TextView, context: Context) -> CGSize? {
567 guard let width = proposal.width else { return nil }
568 let lineHeight = uiView.font?.lineHeight ?? 22
569 let fullHeight = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
570 let maximum = lineHeight * 5
571 uiView.isScrollEnabled = fullHeight > maximum
572 return CGSize(width: width, height: max(lineHeight, min(fullHeight, maximum)))
573 }
574 func makeCoordinator() -> Coordinator { Coordinator(self) }
575 final class Coordinator: NSObject, UITextViewDelegate {
576 var parent: MobileAskQuestionInput
577 init(_ parent: MobileAskQuestionInput) { self.parent = parent }
578 func textViewDidChange(_ textView: UITextView) {
579 parent.text = textView.text
580 textView.invalidateIntrinsicContentSize()
581 }
582 func textViewDidBeginEditing(_ textView: UITextView) {
583 if !parent.focused { parent.focused = true }
584 }
585 func textViewDidEndEditing(_ textView: UITextView) {
586 if parent.focused { parent.focused = false }
587 }
588 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText replacement: String) -> Bool {
589 if replacement == "\n", textView.markedTextRange == nil,
590 (textView as? TextView)?.insertingLineBreak != true {
591 parent.onSend()
592 return false
593 }
594 return true
595 }
596 }
597}