Skip to content

armgit / ente

Public Imported from GitHub
0

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

[ensu] Fix long-text input handling across platforms

setalpd7c88baca3d7
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
index eb5fad8627..20eff65036 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
@@ -1,7 +1,6 @@
package io.ente.ensu.chat
import androidx.compose.foundation.background
-import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -249,8 +248,9 @@ internal fun MessageInput(
fieldValue = newValue
onMessageChange(newValue.text)
},
- modifier = Modifier.weight(1f).focusRequester(focusRequester).focusable(),
+ modifier = Modifier.weight(1f).focusRequester(focusRequester),
textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),
+ visualTransformation = LongMessageVisualTransformation,
minLines = 1,
maxLines = 5,
keyboardOptions =
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LongMessageVisualTransformation.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LongMessageVisualTransformation.kt
new file mode 100644
index 0000000000..46f9a5c9d8
--- /dev/null
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LongMessageVisualTransformation.kt
@@ -0,0 +1,149 @@
+package io.ente.ensu.chat
+
+import android.icu.lang.UCharacter
+import android.icu.lang.UCharacterDirection
+import android.icu.text.BreakIterator
+import android.text.TextDirectionHeuristics
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.ParagraphStyle
+import androidx.compose.ui.text.input.OffsetMapping
+import androidx.compose.ui.text.input.TransformedText
+import androidx.compose.ui.text.input.VisualTransformation
+import java.util.Locale
+import java.util.TreeSet
+
+internal object LongMessageVisualTransformation : VisualTransformation {
+ private const val LongParagraphLength = 8192
+ private const val LayoutSectionLength = 2048
+
+ override fun filter(text: AnnotatedString): TransformedText {
+ val breaks = TreeSet<Int>()
+ var characters: BreakIterator? = null
+ var words: BreakIterator? = null
+ var start = 0
+ while (start < text.length) {
+ val end = text.text.indexOf('\n', start).let { if (it < 0) text.length else it }
+ if (
+ end - start > LongParagraphLength &&
+ !hasDirectionSensitiveText(text.text, start, end)
+ ) {
+ val iterator =
+ characters
+ ?: BreakIterator.getCharacterInstance(Locale.ROOT).also {
+ it.setText(text.text)
+ characters = it
+ }
+ val direction = paragraphDirection(text.text, start, end)
+ val wordIterator =
+ words
+ ?: BreakIterator.getWordInstance(Locale.getDefault()).also {
+ it.setText(text.text)
+ words = it
+ }
+ var previousWordBoundary = start
+ var nextWordBoundary = wordIterator.following(start)
+ val paragraphBreaks = mutableListOf<Int>()
+ var sectionStart = start
+ var preservesDirection = true
+ while (sectionStart < end) {
+ val boundary =
+ if (end - sectionStart > LayoutSectionLength) {
+ val target = sectionStart + LayoutSectionLength
+ while (
+ nextWordBoundary != BreakIterator.DONE && nextWordBoundary <= target
+ ) {
+ if (
+ iterator.isBoundary(nextWordBoundary) &&
+ (!isPunctuation(
+ Character.codePointBefore(text.text, nextWordBoundary)
+ ) ||
+ !isPunctuation(
+ Character.codePointAt(text.text, nextWordBoundary)
+ ))
+ ) {
+ previousWordBoundary = nextWordBoundary
+ }
+ nextWordBoundary = wordIterator.next()
+ }
+ if (previousWordBoundary > sectionStart) {
+ previousWordBoundary
+ } else {
+ iterator.following(target - 1).let {
+ if (it == BreakIterator.DONE || it >= end) end else it
+ }
+ }
+ } else {
+ end
+ }
+ if (paragraphDirection(text.text, sectionStart, boundary) != direction) {
+ preservesDirection = false
+ break
+ }
+ if (boundary < end) paragraphBreaks.add(boundary)
+ sectionStart = boundary
+ }
+ if (preservesDirection) breaks.addAll(paragraphBreaks)
+ }
+ start = end + 1
+ }
+ if (breaks.isEmpty()) return TransformedText(text, OffsetMapping.Identity)
+
+ text.paragraphStyles.forEach {
+ breaks.add(it.start)
+ breaks.add(it.end)
+ }
+ breaks.add(text.length)
+ val styled = AnnotatedString.Builder()
+ var previous = 0
+ breaks.forEach { end ->
+ if (end > previous) {
+ val section = text.subSequence(previous, end)
+ styled.append(section)
+ if (section.paragraphStyles.isEmpty()) {
+ styled.addStyle(ParagraphStyle(), previous, end)
+ }
+ }
+ previous = end
+ }
+ return TransformedText(styled.toAnnotatedString(), OffsetMapping.Identity)
+ }
+
+ private fun isPunctuation(codePoint: Int): Boolean =
+ when (Character.getType(codePoint)) {
+ Character.CONNECTOR_PUNCTUATION.toInt(),
+ Character.DASH_PUNCTUATION.toInt(),
+ Character.END_PUNCTUATION.toInt(),
+ Character.FINAL_QUOTE_PUNCTUATION.toInt(),
+ Character.INITIAL_QUOTE_PUNCTUATION.toInt(),
+ Character.OTHER_PUNCTUATION.toInt(),
+ Character.START_PUNCTUATION.toInt() -> true
+ else -> false
+ }
+
+ private fun hasDirectionSensitiveText(text: String, start: Int, end: Int): Boolean {
+ var index = start
+ while (index < end) {
+ val codePoint = Character.codePointAt(text, index)
+ when (UCharacter.getDirection(codePoint)) {
+ UCharacterDirection.RIGHT_TO_LEFT,
+ UCharacterDirection.RIGHT_TO_LEFT_ARABIC,
+ UCharacterDirection.ARABIC_NUMBER,
+ UCharacterDirection.LEFT_TO_RIGHT_EMBEDDING,
+ UCharacterDirection.LEFT_TO_RIGHT_OVERRIDE,
+ UCharacterDirection.RIGHT_TO_LEFT_EMBEDDING,
+ UCharacterDirection.RIGHT_TO_LEFT_OVERRIDE,
+ UCharacterDirection.POP_DIRECTIONAL_FORMAT,
+ UCharacterDirection.LEFT_TO_RIGHT_ISOLATE.toInt(),
+ UCharacterDirection.RIGHT_TO_LEFT_ISOLATE.toInt(),
+ UCharacterDirection.FIRST_STRONG_ISOLATE.toInt(),
+ UCharacterDirection.POP_DIRECTIONAL_ISOLATE.toInt() -> return true
+ }
+ index += Character.charCount(codePoint)
+ }
+ return false
+ }
+
+ private fun paragraphDirection(text: String, start: Int, end: Int): Pair<Boolean, Boolean> =
+ TextDirectionHeuristics.FIRSTSTRONG_LTR.isRtl(text, start, end - start) to
+ TextDirectionHeuristics.FIRSTSTRONG_RTL.isRtl(text, start, end - start)
+}
diff --git a/apple/apps/ensu/Ensu/Chat/ChatView.swift b/apple/apps/ensu/Ensu/Chat/ChatView.swift
index 24593e3f8a..48fdb0bcee 100644
--- a/apple/apps/ensu/Ensu/Chat/ChatView.swift
+++ b/apple/apps/ensu/Ensu/Chat/ChatView.swift
@@ -8,7 +8,7 @@ struct ChatView: View {
@StateObject private var viewState = ChatViewState()
@StateObject private var keyboard = KeyboardObserver()
- @FocusState private var isInputFocused: Bool
+ @State private var isInputFocused = false
private var editingMessage: RenderedChatMessage? {
guard let editingId = viewModel.editingMessageId else { return nil }
diff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
index 5570957d91..372e7d286d 100644
--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
@@ -24,10 +24,9 @@ struct MessageInputView: View {
let onUserFocus: () -> Void
let onDismissKeyboard: () -> Void
- @FocusState.Binding var isFocused: Bool
+ @Binding var isFocused: Bool
@State private var selectedPhotoItem: PhotosPickerItem?
- @State private var inputResetToken = UUID()
private let placeholder = "Write a message..."
@@ -53,7 +52,6 @@ struct MessageInputView: View {
}
let inputVerticalPadding: CGFloat = 10
- let textFieldPadding: CGFloat = 6
let bottomPadding: CGFloat = EnsuSpacing.md
@@ -123,20 +121,11 @@ struct MessageInputView: View {
}
HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {
- TextField(placeholder, text: $text, axis: .vertical)
- .id(inputResetToken)
- .focused($isFocused)
- .onChange(of: isFocused) { focused in
- if focused {
- onUserFocus()
- }
- }
- .lineLimit(1...5)
- .font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.textPrimary)
- .textInputAutocapitalization(.sentences)
- .padding(.vertical, textFieldPadding)
- .onSubmit {
+ MessageTextView(
+ text: $text,
+ isFocused: $isFocused,
+ moveCursorToEndToken: moveCursorToEndToken,
+ onSubmit: {
if canSend {
onSend()
isFocused = false
@@ -144,20 +133,23 @@ struct MessageInputView: View {
onDismissKeyboard()
}
}
- .onChange(of: text) { newValue in
- if newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- && !isFocused
- {
- inputResetToken = UUID()
- }
+ )
+ .padding(.vertical, 6)
+ .overlay(alignment: .topLeading) {
+ if text.isEmpty {
+ Text(placeholder)
+ .font(EnsuTypography.message)
+ .foregroundStyle(Color(uiColor: .placeholderText))
+ .padding(.vertical, 6)
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
}
- .background(
- CursorEndSynchronizer(
- token: moveCursorToEndToken,
- text: text
- )
- .frame(width: 0, height: 0)
- )
+ }
+ .onChange(of: isFocused) { focused in
+ if focused {
+ onUserFocus()
+ }
+ }
if editingMessage == nil && supportsImageAttachments {
let canUseAttachment =
@@ -286,6 +278,7 @@ struct MessageInputView: View {
.frame(width: 32, height: 32)
}
}
+ .accessibilityLabel(isGenerating ? "Stop response" : "Send message")
.disabled(isDownloading || (!canSend && !isGenerating))
}
.padding(.horizontal, EnsuSpacing.inputHorizontal)
@@ -435,90 +428,3 @@ struct InputBarHeightKey: PreferenceKey {
value = nextValue()
}
}
-
-private struct CursorEndSynchronizer: UIViewRepresentable {
- let token: UUID
- let text: String
-
- func makeCoordinator() -> Coordinator {
- Coordinator()
- }
-
- func makeUIView(context: Context) -> UIView {
- let view = UIView(frame: .zero)
- view.isUserInteractionEnabled = false
- return view
- }
-
- func updateUIView(_ uiView: UIView, context: Context) {
- guard context.coordinator.lastToken != token else { return }
- context.coordinator.lastToken = token
-
- DispatchQueue.main.async {
- Self.moveCursorToEnd(from: uiView, text: text)
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
- Self.moveCursorToEnd(from: uiView, text: text)
- }
- }
-
- private static func moveCursorToEnd(from view: UIView, text: String) {
- var currentView: UIView? = view
- while let candidate = currentView {
- let inputs = candidate.cursorEndTextInputs()
- let target =
- inputs.first(where: { $0.isFirstResponder })
- ?? inputs.first(where: { $0.cursorText == text })
- if let target {
- target.moveCursorToEnd()
- return
- }
- currentView = candidate.superview
- }
- }
-
- final class Coordinator {
- var lastToken: UUID?
- }
-}
-
-@MainActor
-private protocol CursorEndTextInput: AnyObject {
- var cursorText: String { get }
- var isFirstResponder: Bool { get }
- func moveCursorToEnd()
-}
-
-extension UITextField: CursorEndTextInput {
- var cursorText: String {
- text ?? ""
- }
-
- func moveCursorToEnd() {
- let end = endOfDocument
- selectedTextRange = textRange(from: end, to: end)
- }
-}
-
-extension UITextView: CursorEndTextInput {
- var cursorText: String {
- text ?? ""
- }
-
- func moveCursorToEnd() {
- selectedRange = NSRange(location: (text as NSString).length, length: 0)
- }
-}
-
-private extension UIView {
- func cursorEndTextInputs() -> [CursorEndTextInput] {
- var inputs: [CursorEndTextInput] = []
- if let input = self as? CursorEndTextInput {
- inputs.append(input)
- }
- for subview in subviews {
- inputs.append(contentsOf: subview.cursorEndTextInputs())
- }
- return inputs
- }
-}
diff --git a/apple/apps/ensu/Ensu/Chat/MessageTextView.swift b/apple/apps/ensu/Ensu/Chat/MessageTextView.swift
new file mode 100644
index 0000000000..ae1ff39f35
--- /dev/null
+++ b/apple/apps/ensu/Ensu/Chat/MessageTextView.swift
@@ -0,0 +1,110 @@
+import SwiftUI
+import UIKit
+
+struct MessageTextView: UIViewRepresentable {
+ @Binding var text: String
+ @Binding var isFocused: Bool
+ let moveCursorToEndToken: UUID
+ let onSubmit: () -> Void
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
+
+ func makeUIView(context: Context) -> UITextView {
+ let view = TextView(usingTextLayoutManager: true)
+ view.onSubmit = { [weak coordinator = context.coordinator] in
+ coordinator?.parent.onSubmit()
+ }
+ view.delegate = context.coordinator
+ view.backgroundColor = .clear
+ view.font = .systemFont(ofSize: 15)
+ view.textColor = UIColor(EnsuColor.textPrimary)
+ view.textContainerInset = .zero
+ view.textContainer.lineFragmentPadding = 0
+ view.isScrollEnabled = true
+ view.alwaysBounceVertical = false
+ view.autocapitalizationType = .sentences
+ view.accessibilityLabel = "Write a message..."
+ view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
+ return view
+ }
+
+ func updateUIView(_ uiView: UITextView, context: Context) {
+ context.coordinator.parent = self
+ if uiView.text != text {
+ uiView.undoManager?.removeAllActions()
+ uiView.text = text
+ }
+ if context.coordinator.lastCursorToken != moveCursorToEndToken {
+ context.coordinator.lastCursorToken = moveCursorToEndToken
+ uiView.selectedRange = NSRange(location: (text as NSString).length, length: 0)
+ }
+ if isFocused != uiView.isFirstResponder {
+ DispatchQueue.main.async { [weak uiView, weak coordinator = context.coordinator] in
+ guard let uiView, let coordinator else { return }
+ if coordinator.parent.isFocused {
+ uiView.becomeFirstResponder()
+ } else {
+ uiView.resignFirstResponder()
+ }
+ }
+ }
+ }
+
+ func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize?
+ {
+ guard let width = proposal.width, width > 0, width.isFinite else { return nil }
+ return CGSize(width: width, height: Self.height(for: text, width: width))
+ }
+
+ private static func height(for text: String, width: CGFloat) -> CGFloat {
+ let font = UIFont.systemFont(ofSize: 15)
+ let maximumHeight = ceil(font.lineHeight * 5)
+ let scalars = text.unicodeScalars.prefix(1025)
+ guard scalars.count <= 1024 else { return maximumHeight }
+ let sample = String(String.UnicodeScalarView(scalars)) + "\u{200B}"
+ let bounds = (sample as NSString).boundingRect(
+ with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
+ options: [.usesLineFragmentOrigin, .usesFontLeading],
+ attributes: [.font: font], context: nil)
+ return ceil(min(maximumHeight, max(font.lineHeight, bounds.height)))
+ }
+
+ private final class TextView: UITextView {
+ var onSubmit: (() -> Void)?
+
+ override var keyCommands: [UIKeyCommand]? {
+ let submit = UIKeyCommand(
+ input: "\r", modifierFlags: .command, action: #selector(submitMessage))
+ submit.wantsPriorityOverSystemBehavior = true
+ return (super.keyCommands ?? []) + [submit]
+ }
+
+ @objc private func submitMessage() {
+ guard markedTextRange == nil else { return }
+ onSubmit?()
+ }
+ }
+
+ final class Coordinator: NSObject, UITextViewDelegate {
+ var parent: MessageTextView
+ var lastCursorToken: UUID?
+
+ init(_ parent: MessageTextView) {
+ self.parent = parent
+ }
+
+ func textViewDidChange(_ textView: UITextView) {
+ parent.text = textView.text
+ }
+
+ func textViewDidBeginEditing(_ textView: UITextView) {
+ if !parent.isFocused { parent.isFocused = true }
+ }
+
+ func textViewDidEndEditing(_ textView: UITextView) {
+ if parent.isFocused { parent.isFocused = false }
+ }
+ }
+}
diff --git a/web/apps/ensu/src/components/chat/ChatInput.tsx b/web/apps/ensu/src/components/chat/ChatInput.tsx
index d16c7a8b85..4a090535ce 100644
--- a/web/apps/ensu/src/components/chat/ChatInput.tsx
+++ b/web/apps/ensu/src/components/chat/ChatInput.tsx
@@ -6,6 +6,7 @@ import React, {
forwardRef,
memo,
useImperativeHandle,
+ useLayoutEffect,
useRef,
useState,
} from "react";
@@ -62,6 +63,10 @@ export const ChatInput = memo(
const [input, setInput] = useState(initialText);
const inputRef = useRef<HTMLTextAreaElement | null>(null);
+ useLayoutEffect(() => {
+ if (inputRef.current) updateInputLayout(inputRef.current, input);
+ }, [input]);
+
useImperativeHandle(
ref,
() => ({
@@ -95,7 +100,7 @@ export const ChatInput = memo(
<InputBase
multiline
inputComponent="textarea"
- inputProps={{ rows: 1, type: undefined }}
+ inputProps={{ rows: 1, type: undefined, wrap: "soft" }}
inputRef={inputRef}
placeholder={
isDownloading
@@ -103,6 +108,20 @@ export const ChatInput = memo(
: "Write a message..."
}
value={input}
+ onPasteCapture={(event) => {
+ const textarea = inputRef.current;
+ if (!textarea) return;
+ const pasted =
+ event.clipboardData.getData("text/plain");
+ const next =
+ textarea.value.slice(0, textarea.selectionStart) +
+ pasted +
+ textarea.value.slice(textarea.selectionEnd);
+ updateInputLayout(textarea, next);
+ requestAnimationFrame(() =>
+ updateInputLayout(textarea, textarea.value),
+ );
+ }}
onChange={(event) => {
const text = event.target.value;
setInput(text);
@@ -116,6 +135,7 @@ export const ChatInput = memo(
}}
sx={{
flex: 1,
+ minWidth: 0,
bgcolor: "transparent",
borderRadius: 2,
px: 1.5,
@@ -129,6 +149,7 @@ export const ChatInput = memo(
color: "text.base",
"& textarea": {
fieldSizing: "content",
+ width: "100%",
maxHeight: "8.5em",
overflowY: "auto",
padding: 0,
@@ -207,3 +228,20 @@ export const ChatInput = memo(
);
}),
);
+
+function updateInputLayout(textarea: HTMLTextAreaElement, text: string) {
+ let run = 0;
+ let expensive = false;
+ for (let i = 0; i < text.length; i++) {
+ const code = text.charCodeAt(i);
+ run = code > 32 && code < 127 ? run + 1 : 0;
+ if (run > 16384) {
+ expensive = true;
+ break;
+ }
+ }
+ textarea.style.setProperty("field-sizing", expensive ? "fixed" : "content");
+ textarea.style.height = expensive ? "8.5em" : "";
+ textarea.style.fontKerning = expensive ? "none" : "";
+ textarea.style.fontVariantLigatures = expensive ? "none" : "";
+}