Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/deps/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `<br>` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread.
The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `<br>` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). Until [pingdotgg/enriched-markdown#17](https://github.com/pingdotgg/enriched-markdown/pull/17) lands, the tarball comes from that PR's branch (commit `3431ed09`). That PR adds text highlight ranges ([#1218](https://github.com/software-mansion/enriched-markdown/pull/1218)), which read aloud uses to tint the paragraph and the word it speaks. It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread.

To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.18-4287c5d3.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.

Expand Down
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
"react": "catalog:",
"react-dom": "catalog:",
"react-native": "0.88.1",
"react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz",
"react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz",
"react-native-gesture-handler": "~3.5.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.23.0",
Expand Down
12 changes: 12 additions & 0 deletions apps/mobile/src/features/read-aloud/ReadAloudButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,20 @@ import { Pressable } from "react-native";
import { mobilePreferencesAtom } from "../../state/preferences";
import { SymbolView } from "../../components/ui/AppSymbol";
import * as Dialog from "../../components/ui/Dialog";
import type { ReadAloudHighlight } from "@t3tools/client-runtime/read-aloud";
import { readAloudController, warmReadAloud } from "./playback";

/**
* The block and word being read in message `id` (the button's id), as markdown ranges of the
* text that message renders plus text cues, or null while another message or none is read.
*/
export function useReadAloudHighlight(id: string): ReadAloudHighlight | null {
return useSyncExternalStore(readAloudController.subscribeHighlight, () => {
const highlight = readAloudController.getHighlight();
return highlight?.id === id ? highlight : null;
});
}

export function ReadAloudButton({
id,
text,
Expand Down
85 changes: 85 additions & 0 deletions apps/mobile/src/features/read-aloud/ReadAloudMarkdownText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { readAloudShownText } from "@t3tools/shared/read-aloud";
import { useRef, useState } from "react";
import { View, type ViewInstance } from "react-native";
import type {
HighlightLayoutEvent,
RenderedTextChangeEvent,
TextHighlight,
} from "react-native-enriched-markdown";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types";
import { useReadAloudHighlight } from "./ReadAloudButton";
import { followReadAloud } from "./readAloudFollow";

/** The web's `--read-aloud-block` and `--read-aloud-word`: its info blue at these strengths. */
const READ_ALOUD_TINT = {
light: { block: "rgba(59, 130, 246, 0.09)", word: "rgba(59, 130, 246, 0.32)" },
dark: { block: "rgba(59, 130, 246, 0.22)", word: "rgba(59, 130, 246, 0.55)" },
};
const NO_HIGHLIGHTS: ReadonlyArray<TextHighlight> = [];

// Built on the first word read in a view, not for every reply on screen, and kept per render.
const locators = new WeakMap<
RenderedTextChangeEvent,
{ readonly markdown: string; readonly locate: ReturnType<typeof readAloudShownText> }
>();
function locator(markdown: string, shown: RenderedTextChangeEvent) {
const cached = locators.get(shown);
if (cached?.markdown === markdown) return cached.locate;
const locate = readAloudShownText(markdown, shown.text);
locators.set(shown, { markdown, locate });
return locate;
}

/**
* Markdown of a reply that read aloud can read: tints the paragraph and word being read and keeps
* the word in view. `readAloud.markdown` is the text read aloud reads, which can differ from the
* part of it this view shows.
*/
export function ReadAloudMarkdownText(
props: SelectableMarkdownTextProps & {
readonly readAloud: { readonly id: string; readonly markdown: string };
},
) {
const { readAloud, ...markdownProps } = props;
const highlight = useReadAloudHighlight(readAloud.id);
const { themeAppearance } = useAppearancePreferences();
const [shown, setShown] = useState<RenderedTextChangeEvent | null>(null);
const container = useRef<ViewInstance>(null);
const ranges = highlight && shown ? locator(readAloud.markdown, shown)(highlight) : null;
// Code blocks and tables are tinted whole, so only the paragraph tint marks them.
const opaque = shown?.blocks.find(
(block) =>
block.kind !== "text" &&
ranges?.word &&
ranges.word.start < block.end &&
ranges.word.end > block.start,
);
const tint = READ_ALOUD_TINT[themeAppearance === "dark" ? "dark" : "light"];
const highlights = ranges
? [
...(ranges.block ? [{ ...ranges.block, color: tint.block, borderRadius: 4 }] : []),
...(ranges.word && !opaque
? [{ ...ranges.word, color: tint.word, borderRadius: 4, padding: 1 }]
: []),
]
: NO_HIGHLIGHTS;
const onHighlightLayout = ({ highlights: rects }: HighlightLayoutEvent) => {
const target = rects.at(-1);
if (!target) return;
container.current?.measureInWindow((_x, y) =>
followReadAloud(readAloud.id, { top: y + target.y, height: target.height }),
);
};
return (
<View ref={container} collapsable={false} style={{ flexShrink: 1, minWidth: 0 }}>
<SelectableMarkdownText
{...markdownProps}
highlights={highlights}
onRenderedTextChange={setShown}
onHighlightLayout={onHighlightLayout}
/>
</View>
);
}
5 changes: 4 additions & 1 deletion apps/mobile/src/features/read-aloud/playback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ vi.mock("../../state/session", () => ({
}));
vi.mock("@t3tools/client-runtime/voice-input", () => ({
startSpeechSynthesis: vi.fn(() => ({ kind: "audio" })),
getSpeechSynthesisTimings: vi.fn(() => ({ kind: "timings" })),
getSpeechSynthesisModels: vi.fn((_prepared: unknown, provider: string) => ({
kind: "catalog",
provider,
Expand All @@ -57,7 +58,9 @@ vi.mock("../voice-input/voiceDestination", async () => {
defaultModel: "server-model",
speedAppliedByProvider: operation.provider !== "openrouter",
}
: "https://host.test/api/voice/synthesis/audio?token=stream",
: operation.kind === "timings"
? { words: [], done: true }
: { url: "https://host.test/api/voice/synthesis/audio?token=stream", token: "stream" },
};
});

Expand Down
35 changes: 33 additions & 2 deletions apps/mobile/src/features/read-aloud/playback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { m } from "../../i18n/messages";
import {
createReadAloudController,
createReadAloudWarmup,
createTimedWords,
type SpeechPlayback,
type SpokenWord,
} from "@t3tools/client-runtime/read-aloud";
import {
getSpeechSynthesisModels,
getSpeechSynthesisTimings,
prepareSpeechSynthesis,
startSpeechSynthesis,
} from "@t3tools/client-runtime/voice-input";
import { spokenWordAt } from "@t3tools/shared/read-aloud";
import { createAudioPlayer } from "expo-audio";
import * as Speech from "expo-speech";
import * as Option from "effect/Option";
Expand Down Expand Up @@ -46,6 +50,7 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
let started = false;
let offset = 0;
let generation = 0;
const listeners = new Set<(word: SpokenWord | null) => void>();
const player = {
play() {
if (pauseInBackground(settings)) return;
Expand All @@ -62,7 +67,10 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
rate: settings.speed,
useApplicationAudioSession: true,
onBoundary: (event: { charIndex: number }) => {
if (current === generation) offset = start + event.charIndex;
if (current !== generation) return;
offset = start + event.charIndex;
const word = spokenWordAt(text, offset);
for (const listener of listeners) listener(word);
},
onDone: () => {
if (current === generation) done();
Expand Down Expand Up @@ -103,6 +111,12 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
done();
},
finished,
words: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
}

Expand Down Expand Up @@ -143,7 +157,7 @@ export const readAloudController = createReadAloudController(async (text, settin
signal.throwIfAborted();
if (catalog.error) throw new Error(catalog.error);
const model = settings.model || catalog.defaultModel;
const url = await runSpeech(
const { url, token } = await runSpeech(
startSpeechSynthesis(prepared, settings.provider, {
text,
model,
Expand Down Expand Up @@ -175,10 +189,12 @@ export const readAloudController = createReadAloudController(async (text, settin
// Native lock-screen Play bypasses JS, so a paused player must keep revocable ownership.
settings.backgroundPlayback,
);
let timed: ReturnType<typeof createTimedWords> | null = null;
let done: () => void = () => {};
const finished = new Promise<void>((resolve, reject) => {
done = resolve;
player.addListener("playbackStatusUpdate", (status) => {
timed?.refresh();
if (status.didJustFinish) resolve();
else if (status.error) reject(new Error("Could not play the generated speech."));
else if (
Expand Down Expand Up @@ -209,11 +225,26 @@ export const readAloudController = createReadAloudController(async (text, settin
},
pause: () => session.pause(),
stop: () => {
timed?.stop();
stopWatching();
session.stop();
disposeAudioPlayer(player);
done();
},
finished,
words: (listener) => {
timed ??= createTimedWords({
text,
wordTimings: catalog.wordTimings ?? "estimated",
load: (after, signal) =>
runSpeech(getSpeechSynthesisTimings(prepared, token, after), signal),
clock: () => ({
seconds: player.currentTime,
rate: player.playbackRate,
playing: player.playing,
}),
});
return timed.subscribe(listener);
},
};
}, m);
17 changes: 17 additions & 0 deletions apps/mobile/src/features/read-aloud/readAloudFollow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { expect, it } from "vite-plus/test";
import { readAloudFollowDelta } from "./readAloudFollow";

const view = { top: 100, height: 1000 };

it("keeps the word in the middle of the feed and pauses after the user scrolls", () => {
const at = (top: number, userScrolledAt: number | null = null, now = 10_000) =>
readAloudFollowDelta({ target: { top, height: 20 }, view, userScrolledAt, now });
expect(at(500)).toEqual({ delta: 0, resumed: true });
expect(at(1000)).toEqual({ delta: 500, resumed: true });
expect(at(150)).toEqual({ delta: -350, resumed: true });
// A recent scroll waits, even with the word in view.
expect(at(1000, 9_000)).toEqual({ delta: 0, resumed: false });
// Later, a word scrolled out of view stays put until the user brings it back.
expect(at(2000, 1_000)).toEqual({ delta: 0, resumed: false });
expect(at(1000, 1_000)).toEqual({ delta: 500, resumed: true });
});
77 changes: 77 additions & 0 deletions apps/mobile/src/features/read-aloud/readAloudFollow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/** After the user scrolls, following waits this long and for the word to be back in view. */
const FOLLOW_PAUSE_MS = 3_000;
/** The word stays in the middle of the feed; leaving that band scrolls it to 40%. As on the web. */
const FOLLOW_BAND = { top: 0.2, bottom: 0.8, target: 0.4 };

/** A vertical span in window coordinates. */
export interface ReadAloudSpan {
readonly top: number;
readonly height: number;
}

/** The thread feed read aloud scrolls: its visible area and a relative scroll. */
export interface ReadAloudFeed {
readonly measure: (callback: (view: ReadAloudSpan) => void) => void;
readonly scrollBy: (delta: number) => void;
}

/**
* How far to scroll so `target` sits in the follow band of `view`, or 0. While the user's own
* scroll is recent, or has left the word out of view, following waits and never pulls them back.
*/
export function readAloudFollowDelta(input: {
readonly target: ReadAloudSpan;
readonly view: ReadAloudSpan;
readonly userScrolledAt: number | null;
readonly now: number;
}): { readonly delta: number; readonly resumed: boolean } {
const { target, view, userScrolledAt, now } = input;
const bottom = target.top + target.height;
if (userScrolledAt !== null) {
if (now - userScrolledAt < FOLLOW_PAUSE_MS) return { delta: 0, resumed: false };
if (bottom < view.top || target.top > view.top + view.height)
return { delta: 0, resumed: false };
}
const inBand =
target.top >= view.top + view.height * FOLLOW_BAND.top &&
bottom <= view.top + view.height * FOLLOW_BAND.bottom;
return {
delta: inBand ? 0 : target.top - (view.top + view.height * FOLLOW_BAND.target),
resumed: true,
};
}

let feed: ReadAloudFeed | null = null;
let userScrolledAt: number | null = null;
let followingId: string | null = null;

/** The mounted thread feed; read aloud only reads replies on screen, so there is one. */
export function registerReadAloudFeed(next: ReadAloudFeed) {
feed = next;
return () => {
if (feed === next) feed = null;
};
}

/** The user dragged the feed; following pauses so it does not fight them. */
export function markReadAloudUserScroll() {
userScrolledAt = Date.now();
}

/**
* Scrolls the feed so the line read in message `id`, in window coordinates, stays in view.
* Starting another message follows at once, whatever the user scrolled before.
*/
export function followReadAloud(id: string, target: ReadAloudSpan) {
if (id !== followingId) {
followingId = id;
userScrolledAt = null;
}
const current = feed;
current?.measure((view) => {
const next = readAloudFollowDelta({ target, view, userScrolledAt, now: Date.now() });
if (!next.resumed) return;
userScrolledAt = null;
if (Math.abs(next.delta) >= 1) current.scrollBy(next.delta);
});
}
5 changes: 5 additions & 0 deletions apps/mobile/src/features/settings/ReadAloudSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,11 @@ export function ReadAloudSection() {
value={settings.skipCodeBlocks}
onValueChange={(skipCodeBlocks) => change({ skipCodeBlocks })}
/>
<ListToggleRow
label={gt("Highlight words")}
value={settings.highlightWords}
onValueChange={(highlightWords) => change({ highlightWords })}
/>
<ListActionRow
label={
state.id === "preview" && state.status !== "error"
Expand Down
Loading
Loading