Skip to content

Commit adfbb27

Browse files
committed
fix(mobile): match desktop bidi alignment in iOS composer
1 parent f002666 commit adfbb27

6 files changed

Lines changed: 269 additions & 8 deletions

File tree

‎apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ private struct ComposerControlledDocumentPayload: Decodable {
2424
let tokensJson: String
2525
let mostRecentEventCount: Int
2626
let isNativeEcho: Bool
27+
let paragraphDirections: [ComposerParagraphDirectionPayload]?
28+
}
29+
30+
private struct ComposerParagraphDirectionPayload: Decodable {
31+
let start: Int
32+
let end: Int
33+
let direction: String
2734
}
2835

2936
private struct ComposerThemePayload: Decodable {
@@ -424,6 +431,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
424431
private var value = ""
425432
private var tokensJson = "[]"
426433
private var tokens: [ComposerTokenPayload] = []
434+
private var paragraphDirections: [ComposerParagraphDirectionPayload] = []
435+
private var paragraphDirectionValue = ""
427436
private var requestedSelection: ComposerSelectionPayload?
428437
private var theme = ComposerThemePayload(
429438
text: "#262626",
@@ -659,6 +668,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
659668
}
660669
let previousSelection = sourceSelection()
661670
value = document.value
671+
paragraphDirections = document.paragraphDirections ?? []
672+
paragraphDirectionValue = document.value
662673
requestedSelection = document.selection
663674
applyControlledDocument(force: tokensNeedRebuild)
664675
applyRequestedSelection()
@@ -869,6 +880,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
869880
let shouldForce = force || hasDeferredForcedRebuild
870881
let currentSource = textView.serializedText()
871882
guard shouldForce || currentSource != value || !documentMatchesExpectedTokens() else {
883+
applyParagraphDirections()
872884
updatePlaceholderVisibility()
873885
return
874886
}
@@ -884,6 +896,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
884896
requestedSelection = nil
885897
textView.selectedRange = displayRange(for: targetSelection)
886898
restoreBaseTypingAttributes()
899+
applyParagraphDirections()
887900
isApplyingControlledValue = false
888901
if currentSource != value || previousSelection.start != targetSelection.start || previousSelection.end != targetSelection.end {
889902
revealSelectionAfterLayout()
@@ -1060,20 +1073,57 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
10601073
return nil
10611074
}
10621075

1063-
private func baseAttributes() -> [NSAttributedString.Key: Any] {
1064-
let font = UIFont(name: fontFamily, size: fontSize)
1065-
?? UIFont.systemFont(ofSize: fontSize)
1076+
private func paragraphStyle(direction: String? = nil) -> NSMutableParagraphStyle {
10661077
let paragraph = NSMutableParagraphStyle()
1067-
paragraph.alignment = .left
1078+
if let direction {
1079+
paragraph.alignment = direction == "rtl" ? .right : .left
1080+
paragraph.baseWritingDirection = direction == "rtl" ? .rightToLeft : .leftToRight
1081+
}
10681082
paragraph.minimumLineHeight = lineHeight
10691083
paragraph.maximumLineHeight = lineHeight
1084+
return paragraph
1085+
}
1086+
1087+
private func baseAttributes() -> [NSAttributedString.Key: Any] {
1088+
let font = UIFont(name: fontFamily, size: fontSize)
1089+
?? UIFont.systemFont(ofSize: fontSize)
10701090
return [
10711091
.font: font,
10721092
.foregroundColor: UIColor(composerHex: theme.text) ?? .label,
1073-
.paragraphStyle: paragraph,
1093+
.paragraphStyle: paragraphStyle(),
10741094
]
10751095
}
10761096

1097+
private func applyParagraphDirections() {
1098+
guard !paragraphDirections.isEmpty, textView.markedTextRange == nil,
1099+
textView.serializedText() == paragraphDirectionValue else { return }
1100+
let wasApplyingControlledValue = isApplyingControlledValue
1101+
isApplyingControlledValue = true
1102+
let selection = textView.selectedRange
1103+
let sourceLength = (paragraphDirectionValue as NSString).length
1104+
textView.textStorage.beginEditing()
1105+
for paragraph in paragraphDirections {
1106+
guard paragraph.start >= 0, paragraph.end >= paragraph.start,
1107+
paragraph.end <= sourceLength else { continue }
1108+
let range = displayRange(for: ComposerSelectionPayload(start: paragraph.start, end: paragraph.end))
1109+
guard range.length > 0 else { continue }
1110+
let style = paragraphStyle(direction: paragraph.direction)
1111+
let current = textView.textStorage.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle
1112+
if current != style {
1113+
textView.textStorage.addAttribute(.paragraphStyle, value: style, range: range)
1114+
}
1115+
}
1116+
textView.textStorage.endEditing()
1117+
if textView.selectedRange != selection { textView.selectedRange = selection }
1118+
let sourceCaret = textView.sourceOffset(forDisplayOffset: selection.location)
1119+
if let paragraph = paragraphDirections.last(where: { $0.start <= sourceCaret }) {
1120+
var attributes = baseAttributes()
1121+
attributes[.paragraphStyle] = paragraphStyle(direction: paragraph.direction)
1122+
textView.typingAttributes = attributes
1123+
}
1124+
isApplyingControlledValue = wasApplyingControlledValue
1125+
}
1126+
10771127
private func applyTypography() {
10781128
let font = UIFont(name: fontFamily, size: fontSize)
10791129
?? UIFont.systemFont(ofSize: fontSize)
@@ -1087,7 +1137,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
10871137
guard textView.markedTextRange == nil else {
10881138
return
10891139
}
1090-
textView.typingAttributes = baseAttributes()
1140+
var attributes = baseAttributes()
1141+
// UIKit selects the paragraph's style when the caret moves; retain its bidi direction.
1142+
if let paragraph = textView.typingAttributes[.paragraphStyle] {
1143+
attributes[.paragraphStyle] = paragraph
1144+
}
1145+
textView.typingAttributes = attributes
10911146
}
10921147

10931148
private func applyTheme() {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2+
func check(_ condition: Bool, _ message: String) {
3+
if !condition {
4+
FileHandle.standardError.write(Data((message + "\n").utf8))
5+
exit(1)
6+
}
7+
}
8+
let editor = T3ComposerEditorView()
9+
editor.frame = CGRect(x: 0, y: 0, width: 350, height: 200)
10+
let text = "React עדכון הקוד בעברית\nEnglish stays left.\n"
11+
let start = ("React עדכון הקוד בעברית\n" as NSString).length
12+
let count = (text as NSString).length
13+
let document: [String: Any] = [
14+
"value": text, "tokensJson": "[]", "mostRecentEventCount": 0, "isNativeEcho": false,
15+
"selection": ["start": count, "end": count],
16+
"paragraphDirections": [
17+
["start": 0, "end": start, "direction": "rtl"],
18+
["start": start, "end": count, "direction": "ltr"],
19+
["start": count, "end": count, "direction": "ltr"]
20+
]
21+
]
22+
editor.setControlledDocumentJson(String(data: try JSONSerialization.data(withJSONObject: document), encoding: .utf8)!)
23+
let input = editor.subviews.compactMap { $0 as? UITextView }.first!
24+
check(input.attributedText.string == text, "Source text changed")
25+
check(input.selectedRange == NSRange(location: count, length: 0), "Caret changed")
26+
let rtl = input.textStorage.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as! NSParagraphStyle
27+
let ltr = input.textStorage.attribute(.paragraphStyle, at: start, effectiveRange: nil) as! NSParagraphStyle
28+
check(rtl.alignment == .right && rtl.baseWritingDirection == .rightToLeft, "Hebrew must align and read RTL")
29+
check(ltr.alignment == .left && ltr.baseWritingDirection == .leftToRight, "English must align and read LTR")
30+
editor.layoutSubviews()
31+
input.layoutManager.ensureLayout(for: input.textContainer)
32+
let rtlGlyphs = input.layoutManager.glyphRange(forCharacterRange: NSRange(location: 0, length: start - 1), actualCharacterRange: nil)
33+
let ltrGlyphs = input.layoutManager.glyphRange(forCharacterRange: NSRange(location: start, length: count - start - 1), actualCharacterRange: nil)
34+
let rtlBounds = input.layoutManager.boundingRect(forGlyphRange: rtlGlyphs, in: input.textContainer)
35+
let ltrBounds = input.layoutManager.boundingRect(forGlyphRange: ltrGlyphs, in: input.textContainer)
36+
check(rtlBounds.maxX > 340 && ltrBounds.minX < 1, "Rendered paragraphs must use opposite edges")
37+
let originalStorage = input.textStorage
38+
var echo = document
39+
echo["isNativeEcho"] = true
40+
editor.setControlledDocumentJson(String(data: try JSONSerialization.data(withJSONObject: echo), encoding: .utf8)!)
41+
check(input.textStorage === originalStorage && input.selectedRange.location == count, "Echo must preserve text storage and caret")
42+
let typing = input.typingAttributes[.paragraphStyle] as! NSParagraphStyle
43+
check(typing.baseWritingDirection == .leftToRight, "Trailing empty paragraph must inherit English")
44+
print("Native paragraph alignment, bidi, text and selection: PASS")
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#!/bin/bash
2+
set -euo pipefail
3+
module_dir=$(cd "$(dirname "$0")/.." && pwd)
4+
sdk=$(xcrun --sdk macosx --show-sdk-path)
5+
output=$(mktemp -d)
6+
trap 'rm -rf "$output"' EXIT
7+
# Exercise the real UIKit editor without loading the Expo bridge.
8+
python3 - "$module_dir" "$output/main.swift" <<'PYTHON'
9+
import sys
10+
from pathlib import Path
11+
module = Path(sys.argv[1])
12+
source = (module / "ios/T3ComposerEditorView.swift").read_text().replace("import ExpoModulesCore\n", "")
13+
stubs = """
14+
15+
public final class AppContext {}
16+
open class ExpoView: UIView {
17+
public required init(appContext: AppContext? = nil) { super.init(frame: .zero) }
18+
@available(*, unavailable)
19+
public required init?(coder: NSCoder) { fatalError() }
20+
}
21+
final class EventDispatcher { func callAsFunction(_ payload: [String: Any] = [:]) {} }
22+
enum T3ComposerClipboard {
23+
static func write(text: String, fragment: String) {}
24+
static func read() -> [String: String] { [:] }
25+
}
26+
"""
27+
Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n" + (module / "tests/ios/main.swift").read_text())
28+
PYTHON
29+
xcrun swiftc -O -target "$(uname -m)-apple-ios16.4-macabi" -sdk "$sdk" \
30+
-F "$sdk/System/iOSSupport/System/Library/Frameworks" \
31+
"$output/main.swift" -o "$output/composer-tests"
32+
"$output/composer-tests"

‎apps/mobile/src/native/T3ComposerEditor.ios.tsx‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
22
import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
33
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4+
import { composerParagraphDirections } from "@t3tools/shared/textDirection";
45
import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
56
import { requireNativeView } from "expo";
67
import {
@@ -175,10 +176,18 @@ export function ComposerEditor({
175176
);
176177

177178
const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
179+
const editorTokens = useMemo(
180+
() => composerContextEditorTokens(props.value, tokens, skillLabels),
181+
[props.value, tokens, skillLabels],
182+
);
183+
const paragraphDirections = useMemo(
184+
() => composerParagraphDirections(props.value, editorTokens),
185+
[props.value, editorTokens],
186+
);
178187
const chipTextColor = createNativeComposerTheme(theme).text;
179188
const tokensJson = useMemo(() => {
180189
return JSON.stringify(
181-
composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
190+
editorTokens.map((token) => {
182191
const record =
183192
token.type === "context"
184193
? props.context?.records.find((record) => record.contextId === token.contextId)
@@ -209,7 +218,7 @@ export function ComposerEditor({
209218
};
210219
}),
211220
);
212-
}, [props.value, tokens, props.context, skillLabels, theme, chipTextColor]);
221+
}, [editorTokens, props.context, skillLabels, theme, chipTextColor]);
213222
// Every render resolves against the snapshot history, so a render whose
214223
// (value, selection) lags the acknowledged native state is stamped behind
215224
// the native revision and rejected by the editor instead of re-applying a
@@ -234,6 +243,7 @@ export function ComposerEditor({
234243
value: props.value,
235244
selection: isNativeEcho ? null : (selection ?? null),
236245
tokensJson,
246+
paragraphDirections,
237247
mostRecentEventCount: controlledEventCount,
238248
isNativeEcho,
239249
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import { composerParagraphDirections } from "@t3tools/shared/textDirection";
3+
4+
function directions(text: string) {
5+
return composerParagraphDirections(text).map((paragraph) => paragraph.direction);
6+
}
7+
8+
describe("composerParagraphDirections", () => {
9+
it("uses the desktop word majority and first-word tie break per paragraph", () => {
10+
expect(
11+
directions("React עדכון הקוד בעברית\nEnglish stays left.\nשלום React\nReact שלום"),
12+
).toEqual(["rtl", "ltr", "rtl", "ltr"]);
13+
});
14+
15+
it("inherits prose direction across empty and numeric paragraphs, without inheriting code", () => {
16+
expect(directions("اكتب الدالة\n\n42\n```\n// احسب مجموع القيم هنا\n```\n\nfix it\n")).toEqual([
17+
"rtl",
18+
"rtl",
19+
"rtl",
20+
"ltr",
21+
"ltr",
22+
"ltr",
23+
"rtl",
24+
"ltr",
25+
"ltr",
26+
]);
27+
});
28+
29+
it("excludes inline code and native chips from the word count", () => {
30+
expect(directions("`useEffect` ו `useLayoutEffect` בעברית `React`")).toEqual(["rtl"]);
31+
const chip = "@long-english-file-name ";
32+
expect(composerParagraphDirections(chip + "שלום", [{ start: 0, end: chip.length }])).toEqual([
33+
{ start: 0, end: chip.length + 4, direction: "rtl" },
34+
]);
35+
});
36+
37+
it("keeps a list or quote in one direction, as the desktop composer does", () => {
38+
expect(directions("- Vitest\n- اختبر الدالة الجديدة\n- وأضف تعليق")).toEqual([
39+
"rtl",
40+
"rtl",
41+
"rtl",
42+
]);
43+
expect(directions("> React\n> עדכון הקוד בעברית")).toEqual(["rtl", "rtl"]);
44+
});
45+
46+
it("uses native UTF-16 offsets and includes the trailing empty paragraph", () => {
47+
expect(composerParagraphDirections("😀 שלום\r\nEnglish\n")).toEqual([
48+
{ start: 0, end: 9, direction: "rtl" },
49+
{ start: 9, end: 17, direction: "ltr" },
50+
{ start: 17, end: 17, direction: "ltr" },
51+
]);
52+
});
53+
});

‎packages/shared/src/textDirection.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,73 @@ export function textDirection(text: string): TextDirection | undefined {
3131

3232
const markdownParser = unified().use(remarkParse).freeze();
3333

34+
function maskTextRanges(
35+
text: string,
36+
ranges: ReadonlyArray<{ start: number; end: number }>,
37+
replacement = " ",
38+
) {
39+
let offset = 0;
40+
const parts: string[] = [];
41+
for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
42+
const start = Math.max(offset, range.start);
43+
const end = Math.min(text.length, range.end);
44+
if (end <= start) continue;
45+
parts.push(text.slice(offset, start), text.slice(start, end).replace(/[^\r\n]/g, replacement));
46+
offset = end;
47+
}
48+
return parts.join("") + text.slice(offset);
49+
}
50+
51+
/** Native paragraph ranges, using the desktop composer's prose-only word majority. */
52+
export function composerParagraphDirections(
53+
text: string,
54+
chips: ReadonlyArray<{ start: number; end: number }> = [],
55+
) {
56+
// A chip is an atom, not indentation that could turn following prose into a code block.
57+
const source = maskTextRanges(text, chips, "\ufffc");
58+
const document = markdownParser.parse(source);
59+
const code: Array<{ start: number; end: number }> = [];
60+
const codeBlocks: Array<{ start: number; end: number }> = [];
61+
const visit = (node: Root | RootContent): void => {
62+
if (node.type === "code" || node.type === "inlineCode") {
63+
const start = node.position?.start.offset;
64+
const end = node.position?.end.offset;
65+
if (start !== undefined && end !== undefined) {
66+
code.push({ start, end });
67+
if (node.type === "code") codeBlocks.push({ start, end });
68+
}
69+
} else if ("children" in node) node.children.forEach(visit);
70+
};
71+
visit(document);
72+
const prose = maskTextRanges(source, code);
73+
const groups = document.children.flatMap((node) => {
74+
const start = node.position?.start.offset;
75+
const end = node.position?.end.offset;
76+
return (node.type === "list" || node.type === "blockquote") &&
77+
start !== undefined &&
78+
end !== undefined
79+
? [{ start, end, direction: textDirection(prose.slice(start, end)) }]
80+
: [];
81+
});
82+
let previous: TextDirection | undefined;
83+
const paragraphs: Array<{ start: number; end: number; direction: TextDirection }> = [];
84+
for (const line of text.matchAll(/[^\r\n]*(?:\r\n|[\r\n]|$)/g)) {
85+
const start = line.index;
86+
const end = start + line[0].length;
87+
if (start === end && text.length > 0 && !/[\r\n]$/.test(text)) continue;
88+
if (codeBlocks.some((block) => start < block.end && end > block.start)) {
89+
paragraphs.push({ start, end, direction: "ltr" });
90+
continue;
91+
}
92+
const group = groups.find((block) => start < block.end && end > block.start);
93+
const direction =
94+
(group ? group.direction : textDirection(prose.slice(start, end))) ?? previous;
95+
paragraphs.push({ start, end, direction: direction ?? "ltr" });
96+
previous = direction;
97+
}
98+
return paragraphs;
99+
}
100+
34101
export function markdownCodeParts(markdown: string) {
35102
const parts: Array<{ text: string; code: boolean; start: number }> = [];
36103
let offset = 0;

0 commit comments

Comments
 (0)