diff --git a/apps/desktop/package.json b/apps/desktop/package.json index dcaf3d027ebbb..3c99a16cec2f1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.12", + "version": "0.1.13", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh index 7f277fdcbf9c2..bff93bf0597d3 100644 --- a/apps/desktop/resources/installer.nsh +++ b/apps/desktop/resources/installer.nsh @@ -5,9 +5,13 @@ !else ${StrRep} !define T3StrRep '${StrRep}' + Var t3AppWasRunning !endif !macro customAppRunningMessages + !ifndef BUILD_UNINSTALLER + StrCpy $t3AppWasRunning 1 + !endif Push $0 Push $1 ${If} $IsPowerShellAvailable == 0 @@ -39,4 +43,12 @@ WinShell::SetLnkAUMI "$newStartMenuLink" "${APP_ID}" ${EndIf} !endif + + # The template relaunches after a silent install only with --force-run, which WinGet does not pass. + ${If} ${Silent} + ${AndIfNot} ${isForceRun} + ${AndIf} $t3AppWasRunning == 1 + HideWindow + ${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "" + ${EndIf} !macroend diff --git a/apps/desktop/src/app/DesktopAppActivation.test.ts b/apps/desktop/src/app/DesktopAppActivation.test.ts index 2bf1e716a99a8..bde215855b4a2 100644 --- a/apps/desktop/src/app/DesktopAppActivation.test.ts +++ b/apps/desktop/src/app/DesktopAppActivation.test.ts @@ -1,4 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off -- This adapter test binds a real local socket or Windows named pipe and verifies its cleanup. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeEvents from "node:events"; import * as NodeFSP from "node:fs/promises"; import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; @@ -14,9 +16,15 @@ import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppContr import * as HostProcess from "@t3tools/shared/HostProcess"; import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import { afterEach, describe, expect } from "vite-plus/test"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts"; +import * as DesktopWindow from "../window/DesktopWindow.ts"; +import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import { startDesktopAppControlServer } from "./DesktopAppActivation.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; const openServers: Array<{ close: () => Promise }> = []; @@ -163,4 +171,65 @@ describe("desktop app control server", () => { }); }), ); + + it.effect("fails an in-flight request when the renderer process is gone", () => + Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + const userId = yield* HostProcess.UserId; + const root = yield* Effect.acquireRelease( + Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-app-crash-test-"))), + (dir) => Effect.promise(() => NodeFSP.rm(dir, { recursive: true, force: true })), + ); + const stateDir = NodePath.join(root, "userdata"); + const target = makeTarget(stateDir, platform, userId); + + let resolveDispatched: () => void = () => undefined; + const dispatched = new Promise((resolve) => { + resolveDispatched = resolve; + }); + const webContents = Object.assign(new NodeEvents.EventEmitter(), { + isDestroyed: () => false, + send: (channel: string) => { + if (channel === DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL) resolveDispatched(); + }, + }); + + const layer = DesktopAppActivation.layer.pipe( + Layer.provide( + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + stateDir, + platform, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + ), + Layer.provide( + Layer.succeed(DesktopWindow.DesktopWindow, { + activate: Effect.void, + } as unknown as DesktopWindow.DesktopWindow["Service"]), + ), + Layer.provide( + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents } as unknown as Electron.BrowserWindow), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ), + Layer.provide(NodeServices.layer), + ); + + yield* Effect.gen(function* () { + const activation = yield* DesktopAppActivation.DesktopAppActivation; + yield* activation.start; + yield* activation.setRendererReady(true); + + const response = exchange(target.address, request("before-crash", platform)); + yield* Effect.promise(() => dispatched); + webContents.emit("render-process-gone", {}, { reason: "crashed", exitCode: 1 }); + + expect(yield* Effect.promise(() => response)).toMatchObject({ + ok: false, + requestId: "before-crash", + code: "renderer-unavailable", + }); + expect(webContents.listenerCount("render-process-gone")).toBe(0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), + ); }); diff --git a/apps/desktop/src/app/DesktopAppActivation.ts b/apps/desktop/src/app/DesktopAppActivation.ts index 094033192e088..5c999729f6b5c 100644 --- a/apps/desktop/src/app/DesktopAppActivation.ts +++ b/apps/desktop/src/app/DesktopAppActivation.ts @@ -374,9 +374,11 @@ export const make = Effect.gen(function* () { if (event.isMainFrame && !event.isSameDocument) clearRegisteredRenderer(); }; webContents.on("did-start-navigation", onNavigation); + webContents.on("render-process-gone", onUnavailable); webContents.once("destroyed", onUnavailable); detachRendererListeners = () => { webContents.removeListener("did-start-navigation", onNavigation); + webContents.removeListener("render-process-gone", onUnavailable); webContents.removeListener("destroyed", onUnavailable); }; } diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 3fd839ad95dc9..efe6c06a43b92 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -53,11 +53,12 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { `if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`, '[ "$1" = --appimage-mount ] || exit 9', '[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8', - `echo $$ >'${root}/mounter.pid'`, - canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open. + // Trapped before the mount is announced, or the test's probe can arrive first and be lost. "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT", "trap 'echo mounted >&3 2>/dev/null' WINCH", + `echo $$ >'${root}/mounter.pid'`, + canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', "while :; do sleep 0.05; done", "", ].join("\n"), diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index b58b583fd6cd5..40d1703f1a82f 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -3,12 +3,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform"; import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; @@ -28,22 +31,25 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect( Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }), ), ); -function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref | null = null) { +// `key` models Electron's os_crypt key: replacing it orphans everything encrypted before. +function layerSafeStorageFor(available: boolean, key: Ref.Ref | null = null) { + const prefix = Effect.gen(function* () { + return key === null ? "encrypted:" : `encrypted:${yield* Ref.get(key)}:`; + }); return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, { isEncryptionAvailable: Effect.succeed(available), - encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)), + encryptString: (value) => + prefix.pipe(Effect.map((current) => textEncoder.encode(`${current}${value}`))), decryptString: (value) => { return Effect.gen(function* () { const decoded = textDecoder.decode(value); - if ( - !decoded.startsWith("encrypted:") || - (failDecrypt !== null && (yield* Ref.get(failDecrypt))) - ) { + const current = yield* prefix; + if (!decoded.startsWith(current)) { return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({ cause: new Error("invalid encrypted catalog"), }); } - return decoded.slice("encrypted:".length); + return decoded.slice(current.length); }); }, selectedStorageBackend: Effect.succeedNone, @@ -53,7 +59,7 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref | function layerFor( baseDir: string, encryptionAvailable = true, - failDecrypt: Ref.Ref | null = null, + key: Ref.Ref | null = null, fileSystemLayer: Layer.Layer = NodeServices.layer, ) { const layerEnvironment = DesktopEnvironment.layer({ @@ -71,7 +77,7 @@ function layerFor( Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), ), ); - const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, failDecrypt); + const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, key); const layerDependencies = Layer.mergeAll( layerEnvironment, layerSafeStorage, @@ -102,6 +108,9 @@ const withStore = ( }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopConnectionCatalogStore", () => { + const emptyCatalog = + '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; + it.effect("persists and reads an encrypted connection catalog", () => withStore( Effect.gen(function* () { @@ -265,44 +274,162 @@ describe("DesktopConnectionCatalogStore", () => { ), ); - it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () => + it.effect("preserves a catalog encrypted with a lost key and starts a fresh one", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-connection-catalog-test-", }); - const failDecrypt = yield* Ref.make(false); - const layer = layerFor(baseDir, true, failDecrypt); + const key = yield* Ref.make("original-key"); const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layer), + Effect.provide(layerFor(baseDir, true, key)), ); - + const stateDir = path.join(baseDir, "userdata"); + const catalogPath = path.join(stateDir, "connection-catalog.json"); assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); - yield* Ref.set(failDecrypt, true); + const original = yield* fileSystem.readFileString(catalogPath); + yield* Ref.set(key, "regenerated-key"); + + const results = yield* Effect.all([store.get, store.get], { concurrency: "unbounded" }); + assert.deepStrictEqual(results, [Option.none(), Option.none()]); + const findBackups = Effect.gen(function* () { + const backups: Array = []; + for (const name of yield* fileSystem.readDirectory(stateDir)) { + const entryPath = path.join(stateDir, name); + if ( + entryPath !== catalogPath && + (yield* fileSystem.readFileString(entryPath)) === original + ) { + backups.push(entryPath); + } + } + return backups; + }); + assert.equal((yield* findBackups).length, 1); + + const fresh = '{"schemaVersion":1,"targets":[],"profiles":[]}'; + assert.isTrue(yield* store.set(fresh)); + assert.deepStrictEqual(yield* store.get, Option.some(fresh)); + assert.equal((yield* findBackups).length, 1); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("preserves the undecryptable catalog even when a save replaces it mid-read", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const key = yield* Ref.make("original-key"); + const writer = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, key)), + ); + assert.isTrue(yield* writer.set(emptyCatalog)); + const stateDir = path.join(baseDir, "userdata"); + const catalogPath = path.join(stateDir, "connection-catalog.json"); + const original = yield* fileSystem.readFileString(catalogPath); + const readerKey = yield* Ref.make("regenerated-key"); + const preserving = yield* Deferred.make(); + const saved = yield* Deferred.make(); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide( + layerFor( + baseDir, + true, + readerKey, + Layer.succeed(FileSystem.FileSystem, { + ...fileSystem, + exists: (entryPath) => + entryPath.endsWith(".undecryptable") + ? Deferred.succeed(preserving, undefined).pipe( + Effect.andThen(Deferred.await(saved)), + Effect.andThen(fileSystem.exists(entryPath)), + ) + : fileSystem.exists(entryPath), + }), + ), + ), + ); + const read = yield* Effect.forkChild(store.get); + yield* Deferred.await(preserving); + assert.isTrue(yield* writer.set(`${emptyCatalog}\n`)); + yield* Deferred.succeed(saved, undefined); + assert.deepStrictEqual(yield* Fiber.join(read), Option.none()); + + const backups = (yield* fileSystem.readDirectory(stateDir)).filter((name) => + name.endsWith(".undecryptable"), + ); + assert.equal(backups.length, 1); + assert.equal( + yield* fileSystem.readFileString(path.join(stateDir, backups[0] ?? "")), + original, + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps an undecryptable catalog in place when it cannot be preserved", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const key = yield* Ref.make("original-key"); + const writable = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, key)), + ); + const catalogPath = path.join(baseDir, "userdata", "connection-catalog.json"); + assert.isTrue(yield* writable.set('{"schemaVersion":1,"targets":[]}')); + const original = yield* fileSystem.readFileString(catalogPath); + const writeFailure = (method: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method, + pathOrDescriptor: catalogPath, + }), + ); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide( + layerFor( + baseDir, + true, + key, + Layer.succeed(FileSystem.FileSystem, { + ...fileSystem, + copy: () => writeFailure("copy"), + copyFile: () => writeFailure("copyFile"), + link: () => writeFailure("link"), + remove: () => writeFailure("remove"), + rename: () => writeFailure("rename"), + writeFile: () => writeFailure("writeFile"), + writeFileString: () => writeFailure("writeFileString"), + }), + ), + ), + ); + yield* Ref.set(key, "regenerated-key"); + const error = yield* store.get.pipe(Effect.flip); assert.instanceOf( error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError, + DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError, ); - assert.equal(error.operation, "decrypt-catalog"); - assert.equal(error.catalogPath, path.join(baseDir, "userdata", "connection-catalog.json")); - assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError); - const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError; - assert.instanceOf(decryptError.cause, Error); - assert.equal(decryptError.cause.message, "invalid encrypted catalog"); - assert.equal( - error.message, - `Desktop connection catalog protection failed during decrypt-catalog at ${path.join(baseDir, "userdata", "connection-catalog.json")}.`, + assert.equal(error.operation, "preserve-undecryptable-catalog"); + const saveError = yield* store.set(emptyCatalog).pipe(Effect.flip); + assert.equal(saveError.operation, "preserve-undecryptable-catalog"); + assert.isFalse( + (yield* fileSystem.readDirectory(path.dirname(catalogPath))).some((name) => + name.endsWith(".undecryptable"), + ), ); - assert.notEqual(error.message, decryptError.message); - yield* Ref.set(failDecrypt, false); - assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}')); + assert.equal(yield* fileSystem.readFileString(catalogPath), original); }).pipe(Effect.provide(NodeServices.layer)), ); - const emptyCatalog = - '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; const savedFilesHolding = Effect.fn(function* (stateDir: string, contents: string) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -338,28 +465,34 @@ describe("DesktopConnectionCatalogStore", () => { ), ); - it.effect("keeps a catalog that no longer decrypts when the next save replaces it", () => + it.effect("preserves the original catalog when saving after key loss without reading first", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-connection-catalog-test-", }); - const failDecrypt = yield* Ref.make(false); + const key = yield* Ref.make("original-key"); const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layerFor(baseDir, true, failDecrypt)), + Effect.provide(layerFor(baseDir, true, key)), ); const stateDir = path.join(baseDir, "userdata"); - assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); - const original = yield* fileSystem.readFileString( - path.join(stateDir, "connection-catalog.json"), + const catalogPath = path.join(stateDir, "connection-catalog.json"); + assert.isTrue(yield* store.set(emptyCatalog)); + const original = JSON.stringify( + JSON.parse(yield* fileSystem.readFileString(catalogPath)), + null, + 2, ); + yield* fileSystem.writeFileString(catalogPath, original); - yield* Ref.set(failDecrypt, true); - yield* store.get.pipe(Effect.flip); + yield* Ref.set(key, "regenerated-key"); assert.isTrue(yield* store.set(emptyCatalog)); - assert.isNotEmpty(yield* savedFilesHolding(stateDir, original)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + const backups = yield* savedFilesHolding(stateDir, original); + assert.equal(backups.length, 1); + assert.isTrue(backups[0]?.endsWith(".undecryptable")); + assert.deepStrictEqual(yield* store.get, Option.some(emptyCatalog)); + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts index 5db49e5f9504c..c394cf9c08d2c 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` names the backup of an undecryptable catalog by its content. +import * as NodeCrypto from "node:crypto"; + import { BearerConnectionCredential, BearerConnectionProfile, @@ -12,10 +15,10 @@ import { } from "@t3tools/client-runtime/platform"; import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Clock from "effect/Clock"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -56,6 +59,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-directory", "write-temporary-file", "replace-catalog-file", + "preserve-undecryptable-catalog", "keep-unreadable-catalog", ]); @@ -69,7 +73,6 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([ const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([ "check-encryption-availability", "encrypt-catalog", - "decrypt-catalog", ]); export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedError()( @@ -161,6 +164,7 @@ export class DesktopConnectionCatalogStore extends Context.Service< | DesktopConnectionCatalogStoreDecodeError | DesktopConnectionCatalogStoreMigrationError | DesktopConnectionCatalogStoreProtectionError + | DesktopConnectionCatalogStoreWriteError >; readonly set: ( catalog: string, @@ -187,13 +191,7 @@ function decodeSecretBytes( ); } -const readDocument = ( - fileSystem: FileSystem.FileSystem, - catalogPath: string, -): Effect.Effect< - Option.Option, - DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError -> => +const readDocument = (fileSystem: FileSystem.FileSystem, catalogPath: string) => fileSystem.readFileString(catalogPath).pipe( Effect.catch((error) => error.reason._tag === "NotFound" @@ -207,8 +205,9 @@ const readDocument = ( ), Effect.flatMap((raw) => raw === null - ? Effect.succeed(Option.none()) + ? Effect.succeedNone : decodeEncryptedConnectionCatalogDocumentJson(raw).pipe( + Effect.map((document) => ({ document, raw })), Effect.asSome, Effect.mapError( (cause) => @@ -225,21 +224,11 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")( readonly fileSystem: FileSystem.FileSystem; readonly path: Path.Path; readonly catalogPath: string; - readonly document: EncryptedConnectionCatalogDocument; + readonly contents: string; readonly suffix: string; }): Effect.fn.Return { const directory = input.path.dirname(input.catalogPath); const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`; - const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreWriteError({ - operation: "encode-document", - path: input.catalogPath, - cause, - }), - ), - ); yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe( Effect.mapError( (cause) => @@ -251,7 +240,7 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")( ), ); yield* Effect.gen(function* () { - yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe( + yield* input.fileSystem.writeFileString(tempPath, input.contents).pipe( Effect.mapError( (cause) => new DesktopConnectionCatalogStoreWriteError({ @@ -400,41 +389,8 @@ export const make = Effect.gen(function* () { ), ); - const decryptDocument = (document: EncryptedConnectionCatalogDocument) => - decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe( - Effect.flatMap((encryptedCatalog) => - safeStorage.decryptString(encryptedCatalog).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreProtectionError({ - operation: "decrypt-catalog", - catalogPath, - cause, - }), - ), - ), - ), - ); - - // A catalog this build cannot decrypt or decode may still hold another build's saved - // environments and credentials, so a save copies it aside instead of destroying it. - const keepUnreadableCatalog = Effect.gen(function* () { - const readable = yield* readDocument(fileSystem, catalogPath).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.succeed(true), - onSome: (document) => - decryptDocument(document).pipe( - Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson), - Effect.as(true), - ), - }), - ), - Effect.orElseSucceed(() => false), - ); - if (readable) { - return; - } + // An unreadable catalog may still hold another build's saved environments and credentials. + const keepUnreadableCatalogFile = Effect.gen(function* () { const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`; yield* fileSystem.copyFile(catalogPath, keptPath).pipe( Effect.mapError( @@ -466,16 +422,100 @@ export const make = Effect.gen(function* () { ), ), ); + const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson({ + version: 1, + encryptedCatalog, + }).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "encode-document", + path: catalogPath, + cause, + }), + ), + ); const suffix = (yield* random.uuidV4()).replace(/-/g, ""); yield* writeDocument({ fileSystem, path, catalogPath, - document: { version: 1, encryptedCatalog }, + contents: `${encoded}\n`, suffix, }); }); + // Electron regenerates its key when the OS keyring entry is lost, orphaning the catalog for + // good. Read it as empty so the user can reconnect, but keep a copy first: the catalog stays + // in place until the next save replaces it, and the content-derived name keeps repeated and + // concurrent reads to one backup. + const preserveUndecryptableCatalog = Effect.fn( + "desktop.connectionCatalogStore.preserveUndecryptableCatalog", + )(function* ( + contents: string, + encryptedCatalog: Uint8Array, + decryptError: ElectronSafeStorage.ElectronSafeStorageDecryptError, + ) { + const digest = NodeCrypto.createHash("sha256").update(encryptedCatalog).digest("hex"); + const backupPath = `${catalogPath}.${digest}.undecryptable`; + const preserveError = (cause: unknown) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "preserve-undecryptable-catalog", + path: backupPath, + cause, + }); + if (!(yield* fileSystem.exists(backupPath).pipe(Effect.mapError(preserveError)))) { + const suffix = (yield* random.uuidV4()).replace(/-/g, ""); + // Back up the document that failed to decrypt, not the file at `catalogPath`: a + // concurrent `set` may already have replaced it. + yield* writeDocument({ fileSystem, path, catalogPath: backupPath, contents, suffix }).pipe( + Effect.mapError(preserveError), + ); + yield* Effect.logWarning( + "The desktop connection catalog can no longer be decrypted; starting a new one.", + { catalogPath, backupPath, reason: decryptError._tag }, + ); + } + }); + + const decryptDocument = Effect.fn("desktop.connectionCatalogStore.decryptDocument")( + function* (snapshot: { + readonly document: EncryptedConnectionCatalogDocument; + readonly raw: string; + }) { + const encryptedCatalog = yield* decodeSecretBytes( + catalogPath, + snapshot.document.encryptedCatalog, + ); + return yield* safeStorage.decryptString(encryptedCatalog).pipe( + Effect.asSome, + Effect.catchTags({ + ElectronSafeStorageDecryptError: (error) => + preserveUndecryptableCatalog(snapshot.raw, encryptedCatalog, error).pipe( + Effect.as(Option.none()), + ), + }), + ); + }, + ); + + const keepUnreadableCatalog = readDocument(fileSystem, catalogPath).pipe( + Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: decryptDocument })), + Effect.flatMap( + Option.match({ + onNone: () => Effect.void, + onSome: (catalog) => + decodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(Effect.asVoid), + }), + ), + Effect.catchTags({ + DesktopConnectionCatalogStoreReadError: () => keepUnreadableCatalogFile, + DesktopConnectionCatalogStoreDocumentDecodeError: () => keepUnreadableCatalogFile, + DesktopConnectionCatalogStoreDecodeError: () => keepUnreadableCatalogFile, + SchemaError: () => keepUnreadableCatalogFile, + }), + ); + const migrateLegacyCatalog = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); @@ -526,7 +566,7 @@ export const make = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); } - return Option.some(yield* decryptDocument(document.value)); + return yield* decryptDocument(document.value); }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")), set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) { if (!(yield* encryptionAvailable)) { diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 1eb6f00da37cb..20ee28c680740 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -1166,6 +1166,55 @@ describe("DesktopBrowserHost", () => { }), ); + // regression: #44003 agent typing into a cross-site iframe field was refused while the preview was unfocused + it.effect("types into the cross-site frame holding an unfocused guest's focus", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; + // The page's focus is an iframe whose document it cannot read; that frame focuses a field. + const debuggee = makeDebuggee({ + answer: (method, sessionId) => { + if (method === "Runtime.evaluate") { + return sessionId === undefined + ? { result: { type: "object", value: false, objectId: "FOCUSED-IFRAME" } } + : { result: { type: "undefined" } }; + } + if (method === "DOM.describeNode") return { node: { frameId: "FRAME" } }; + if (method === "Runtime.releaseObject") return {}; + return undefined; + }, + }); + host.attach(key, debuggee.tab); + const errors: Array = []; + yield* host.events.pipe( + Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type !== "cdp") return; + const { error } = decodeCdpError(event.message); + if (error) errors.push(error.message); + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + debuggee.emit("Target.attachedToTarget", { + sessionId: "FRAME-SESSION", + targetInfo: { targetId: "FRAME", type: "iframe" }, + }); + + yield* command(host, 1, "Input.insertText"); + yield* settle; + debuggee.release(); + yield* settle; + + expect(errors).toEqual([]); + expect(debuggee.methods).toContain("Input.insertText"); + expect(debuggee.sessionIds[debuggee.methods.indexOf("Input.insertText")]).toBe( + "FRAME-SESSION", + ); + }).pipe(Effect.scoped), + ); + it.effect("fails mouse input whose frame detaches before taking it, then moves on", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index b0fe8509a51fa..7eb049ab8cdae 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -20,6 +20,7 @@ import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts import { type FrameDetachWatch, type PointerRoute, + routeKeysToFrame, routeMouseToFrame, sendPageCommand, } from "./GuestInput.ts"; @@ -500,6 +501,7 @@ export const make = Effect.gen(function* () { if (tab.relay) return tab.relay; const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee; const routeHidden = routeMouseToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab)); + const routeKeys = routeKeysToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab)); // Read when the pointer queue reaches the event: a guest the window shows routes its own input. const routeMouse: PointerRoute = (params) => shownTabs.get(keyOf(tab.key)) === true ? Promise.resolve(null) : routeHidden(params); @@ -521,6 +523,7 @@ export const make = Effect.gen(function* () { sessionId, routeMouse, refuseAnnotated, + routeKeys, ); if (method === "Network.clearBrowserCookies") await cookiesCleared?.(); return result; diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 6ab33e3896e4e..0473450be3c61 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -20,9 +20,25 @@ const FOCUSED_DOCUMENT = `(() => { } })()`; +/** The cross-site frame element holding the document's focus, past same-site frames; null if none does. */ +const FOCUSED_CROSS_SITE_FRAME = `(() => { + let doc = document; + for (;;) { + const active = doc.activeElement; + if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return null; + if (!active.contentDocument) return active; + doc = active.contentDocument; + } +})()`; + /** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */ const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]); +const editingCommands = (params: Record) => + Array.isArray(params["commands"]) + ? params["commands"].filter((command) => EDITING_COMMANDS.has(command)) + : undefined; + const CROSS_SITE_FOCUS_MESSAGE = "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first."; @@ -152,7 +168,7 @@ interface FrameRoute { export type PointerRoute = (params: Record) => Promise; const FRAME_GONE_MESSAGE = - "The frame under the pointer went away before it took this input. Check the page before retrying."; + "The frame went away before it took this input. Check the page before retrying."; const MAX_FRAME_DEPTH = 8; const ROUTE_DEADLINE = "1 second"; @@ -182,6 +198,62 @@ export const routeMouseToFrame = return { ...routed, onDetach }; }; +/** Finds the cross-site frame holding an unfocused guest's focus, if it has a session; null when none does. */ +export type KeyRoute = (params: Record) => Promise; + +/** + * Direct input cannot reach a cross-site frame, and the page session's CDP keys follow window + * focus into the app. The focused frame's own session delivers them to that frame. + */ +export const routeKeysToFrame = + ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, + onDetach: FrameDetachWatch, + ): KeyRoute => + async (params) => { + if (frameSessions.size === 0) return null; + const sessionId = await Effect.runPromise( + Effect.promise(() => locateFocusedFrame(debuggee, frameSessions)).pipe( + Effect.timeoutOption(ROUTE_DEADLINE), + Effect.map(Option.getOrNull), + ), + ); + if (!sessionId) return null; + const commands = editingCommands(params); + return { params: commands ? { ...params, commands } : params, sessionId, onDetach }; + }; + +const locateFocusedFrame = async ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, +) => { + let sessionId: string | undefined; + for (let depth = 0; depth < MAX_FRAME_DEPTH; depth++) { + try { + const { result } = (await debuggee.sendCommand( + "Runtime.evaluate", + { expression: FOCUSED_CROSS_SITE_FRAME }, + sessionId, + )) as { readonly result: { readonly objectId?: string } }; + if (result.objectId === undefined) return sessionId ?? null; + const { objectId } = result; + const { node } = (await debuggee + .sendCommand("DOM.describeNode", { objectId }, sessionId) + .finally(() => { + debuggee.sendCommand("Runtime.releaseObject", { objectId }, sessionId).catch(() => {}); + })) as { readonly node: { readonly frameId?: string } }; + // A cross-site frame's target id is its frame id. + const frameSession = node.frameId === undefined ? undefined : frameSessions.get(node.frameId); + if (frameSession === undefined) return null; + sessionId = frameSession; + } catch { + return null; + } + } + return null; +}; + /** Chromium can drop the reply to input on a frame that detaches before acknowledging it. */ const sendToFrame = (debuggee: Electron.Debugger, method: string, route: FrameRoute) => new Promise((resolve, reject) => { @@ -296,6 +368,7 @@ export const sendPageCommand = async ( sessionId?: string, routeMouse?: PointerRoute, beforeDispatch?: () => void, + routeKeys?: KeyRoute, ): Promise => { if (method === "Input.dispatchMouseEvent") { return sendPointerCommand( @@ -334,7 +407,10 @@ export const sendPageCommand = async ( return debuggee.sendCommand(method, params); } if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) { - throw new Error(CROSS_SITE_FOCUS_MESSAGE); + const routed = routeKeys ? await routeKeys(params) : null; + if (!routed) throw new Error(CROSS_SITE_FOCUS_MESSAGE); + beforeDispatch?.(); + return sendToFrame(debuggee, method, routed); } beforeDispatch?.(); switch (method) { @@ -343,9 +419,7 @@ export const sendPageCommand = async ( return {}; case "Input.dispatchKeyEvent": { for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event); - const commands = Array.isArray(params["commands"]) - ? params["commands"].filter((command) => EDITING_COMMANDS.has(command)) - : []; + const commands = editingCommands(params) ?? []; // Runs after the page handles the keys, so the reply also waits for them. await evaluate( debuggee, diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index f993a572a4a2c..ad01a897026c5 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -158,6 +158,11 @@ const dmSansFonts = { bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf", } as const; +const mesloFonts = { + regular: "./assets/fonts/MesloLGS-NF-Regular.ttf", + bold: "./assets/fonts/MesloLGS-NF-Bold.ttf", +} as const; + const widgetsPlugin: NonNullable[number] = [ "expo-widgets", { @@ -358,7 +363,13 @@ const config: ExpoConfig = { "expo-font", { ios: { - fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold], + fonts: [ + dmSansFonts.regular, + dmSansFonts.medium, + dmSansFonts.bold, + mesloFonts.regular, + mesloFonts.bold, + ], }, android: { fonts: [ @@ -379,6 +390,14 @@ const config: ExpoConfig = { { path: dmSansFonts.bold, weight: 700 }, ], }, + { + // One family for both weights, as on iOS, so fontWeight picks the bold file. + fontFamily: "MesloLGS-NF-Regular", + fontDefinitions: [ + { path: mesloFonts.regular, weight: 400 }, + { path: mesloFonts.bold, weight: 700 }, + ], + }, ], }, }, diff --git a/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf b/apps/mobile/assets/fonts/MesloLGS-NF-Bold.ttf similarity index 100% rename from apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Bold.ttf rename to apps/mobile/assets/fonts/MesloLGS-NF-Bold.ttf diff --git a/apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf b/apps/mobile/assets/fonts/MesloLGS-NF-Regular.ttf similarity index 100% rename from apps/mobile/modules/t3-terminal/android/src/main/assets/fonts/MesloLGS-NF-Regular.ttf rename to apps/mobile/assets/fonts/MesloLGS-NF-Regular.ttf diff --git a/apps/mobile/assets/fonts/THIRD_PARTY_NOTICES.md b/apps/mobile/assets/fonts/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000000..7f3d07de89106 --- /dev/null +++ b/apps/mobile/assets/fonts/THIRD_PARTY_NOTICES.md @@ -0,0 +1,8 @@ +# Third-party notices + +## MesloLGS NF (the bundled monospace font choice) + +- Files: `MesloLGS-NF-{Regular,Bold}.ttf` +- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs) +- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher +- License: Apache License 2.0 diff --git a/apps/mobile/deps/README.md b/apps/mobile/deps/README.md index 935cfb387b7ba..d4ed5d5c3c206 100644 --- a/apps/mobile/deps/README.md +++ b/apps/mobile/deps/README.md @@ -16,6 +16,6 @@ Push the commit and tag before submitting the app change, replace the old archiv ## `react-native-enriched-markdown` -Built 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`), the iOS streaming memory bounds, `onSelectionCopy` and iOS Copy as Markdown keeping bold spans whole 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)), line breaks in copied table cells written as `
` ([#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)), iOS code blocks too big for one backing store drawing through tiles, so a tall block with long lines no longer shows an empty pane ([#1231](https://github.com/software-mansion/enriched-markdown/pull/1231)), and a long-pressed iOS blockquote lifting on the background it sits on instead of drawing its text over the thread ([#1232](https://github.com/software-mansion/enriched-markdown/pull/1232)). +Built 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`), the iOS streaming memory bounds, `onSelectionCopy` and iOS Copy as Markdown keeping bold spans whole 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)), line breaks in copied table cells written as `
` ([#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)), iOS code blocks too big for one backing store drawing through tiles, so a tall block with long lines no longer shows an empty pane ([#1231](https://github.com/software-mansion/enriched-markdown/pull/1231)), a long-pressed iOS blockquote lifting on the background it sits on instead of drawing its text over the thread ([#1232](https://github.com/software-mansion/enriched-markdown/pull/1232)), and iOS resolving the `ui-monospace` font family to SF Mono like Fabric text does, so the System monospace choice is not drawn in SF Pro ([#1251](https://github.com/software-mansion/enriched-markdown/pull/1251)). 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.19-a01cbf49.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. diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz deleted file mode 100644 index 6ba7734e6509e..0000000000000 Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-9a8bc858.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-9a8bc858.tgz new file mode 100644 index 0000000000000..e8581340be373 Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-9a8bc858.tgz differ diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 79010054c1492..a51038be51be3 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -17,7 +17,7 @@ /* ─── Typography ────────────────────────────────────────────────────── */ @theme { - /* Keep these native family names aligned with app.config.ts. */ + /* Defaults only: the font preference swaps these at runtime (src/lib/fontFamilies.ts). */ --font-sans: "DMSans-Regular"; --font-medium: "DMSans-Medium"; --font-bold: "DMSans-Bold"; @@ -46,6 +46,7 @@ /* ─── Custom utilities ──────────────────────────────────────────────── */ @utility font-t3-medium { font-family: var(--font-medium); + font-weight: 500; } @utility font-t3-bold { diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt index 6f90e2e12fa4e..0129f3b09c8de 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt @@ -284,6 +284,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView( } fun setFontFamily(fontFamily: String) { + chipTypeface = T3ContextChip.typefaceFor(fontFamily) editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) { Typeface.MONOSPACE } else { @@ -291,6 +292,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView( } applyLineHeight() editor.applyPlaceholder() + applyTokenSpans() } fun setFontSize(fontSize: Float) { @@ -489,6 +491,8 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView( x >= minOf(left, right) && x <= maxOf(left, right) } + private var chipTypeface = T3ContextChip.typefaceFor("DMSans-Regular") + private fun applyTokenSpans() { val editable = editor.text ?: return editable.getSpans( @@ -511,6 +515,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView( tintsIcon = token.tintsIcon ), fontSize = editor.textSize, + chipTypeface = chipTypeface, color = T3ContextChip.color(token.accent, editor.currentTextColor), maximumWidth = ( editor.width.takeIf { diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt index 05aa101655fbe..27c795090201e 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt @@ -16,6 +16,7 @@ import kotlin.math.min class T3ContextChip( content: Content, fontSize: Float, + chipTypeface: Typeface, private val color: Int, maximumWidth: Float, density: Float @@ -30,14 +31,14 @@ class T3ContextChip( private val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = fontSize - typeface = chipTypeface() + typeface = chipTypeface color = this@T3ContextChip.color } private val em = fontSize private val detailPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = fontSize * 0.84f - typeface = chipTypeface() + typeface = chipTypeface color = this@T3ContextChip.color } private val detailText = if (content.detail.isEmpty()) "" else " ${content.detail}" @@ -87,13 +88,13 @@ class T3ContextChip( } companion object { - private const val CHIP_FONT_FAMILY = "DMSans-Medium" + private const val DM_SANS_MEDIUM = "DMSans-Medium" - // Matches the iOS chips; builds without the bundled font keep the platform medium. - private fun chipTypeface(): Typeface { + /** Matches the iOS chips: DM Sans text gets DM Sans Medium, anything else the platform medium. */ + fun typefaceFor(fontFamily: String): Typeface { val fonts = ReactFontManager.getInstance() - return if (CHIP_FONT_FAMILY in fonts.customFontFamilies) { - fonts.getTypeface(CHIP_FONT_FAMILY, Typeface.NORMAL, null) + return if (fontFamily.startsWith("DMSans") && DM_SANS_MEDIUM in fonts.customFontFamilies) { + fonts.getTypeface(DM_SANS_MEDIUM, Typeface.NORMAL, null) } else { Typeface.create("sans-serif-medium", Typeface.NORMAL) } diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 2f24b0d98752c..35e5dce241b37 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -1066,7 +1066,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString { let color = token.accent.flatMap { UIColor(composerHex: $0) } ?? UIColor(composerHex: theme.text) ?? .label - let chipFont = UIFont(name: "DMSans-Medium", size: fontSize) + let chipFont = (fontFamily.hasPrefix("DMSans") ? UIFont(name: "DMSans-Medium", size: fontSize) : nil) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium) let icon = token.iconUri.flatMap(iconImage(for:)).map { token.tintsIcon == true ? Self.tinted($0, color: color) : $0 diff --git a/apps/mobile/modules/t3-review-diff/android/build.gradle b/apps/mobile/modules/t3-review-diff/android/build.gradle index d360d1580f1d4..58682864c2111 100644 --- a/apps/mobile/modules/t3-review-diff/android/build.gradle +++ b/apps/mobile/modules/t3-review-diff/android/build.gradle @@ -20,6 +20,7 @@ android { dependencies { implementation project(':expo-modules-core') + implementation 'com.facebook.react:react-android' testImplementation 'junit:junit:4.13.2' testImplementation 'org.robolectric:robolectric:4.16.1' } diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index 3334efd268bc3..2aec7390fb2f5 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -1,6 +1,7 @@ package expo.modules.t3reviewdiff import android.content.Context +import android.content.res.AssetManager import android.graphics.Canvas import android.graphics.Color import android.graphics.LinearGradient @@ -10,6 +11,7 @@ import android.graphics.RectF import android.graphics.Shader import android.graphics.Typeface import android.text.TextPaint +import com.facebook.react.common.assets.ReactFontManager import kotlin.math.ceil import kotlin.math.max import kotlin.math.min @@ -31,16 +33,23 @@ internal class ReviewDiffCanvasDrawing(context: Context) { clearShadowLayer() } - private val italicCodeTypeface by lazy { - Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC) - } - private val boldItalicCodeTypeface by lazy { - Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC) - } + private val assets = context.assets + private var typefaces = ReviewDiffTypefaces(assets, "monospace", "sans-serif", "sans-serif") init { - textPaint.typeface = ReviewDiffTypefaces.regular - uiPaint.typeface = Typeface.DEFAULT_BOLD + textPaint.typeface = typefaces.regular + uiPaint.typeface = typefaces.uiBold + } + + fun applyFonts(style: DiffStyle) { + if (typefaces.matches(style)) return + typefaces = ReviewDiffTypefaces( + assets, + style.codeFontFamily, + style.uiFontFamily, + style.uiBoldFontFamily, + ) + textPaint.typeface = typefaces.regular } fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF { @@ -162,23 +171,24 @@ internal class ReviewDiffCanvasDrawing(context: Context) { } fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) { - paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + paint.typeface = if (isBoldFontWeight(weight)) typefaces.uiBold else typefaces.ui configureTextPaint(paint, color, size) } fun configureMonospacePaint(color: Int, size: Float, weight: String) { - textPaint.typeface = ReviewDiffTypefaces.forWeight(weight) + textPaint.typeface = typefaces.forWeight(weight) configureTextPaint(textPaint, color, size) } fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) { val tokenBold = fontStyle and 2 != 0 val italic = fontStyle and 1 != 0 + applyFonts(style) textPaint.typeface = when { - tokenBold && italic -> boldItalicCodeTypeface - tokenBold -> ReviewDiffTypefaces.bold - italic -> italicCodeTypeface - else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight) + tokenBold && italic -> typefaces.boldItalic + tokenBold -> typefaces.bold + italic -> typefaces.italic + else -> typefaces.forWeight(style.codeFontWeight) } configureTextPaint(textPaint, color, style.codeFontSizePx) textPaint.isUnderlineText = fontStyle and 4 != 0 @@ -597,10 +607,27 @@ internal class ReviewDiffCanvasDrawing(context: Context) { Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)) } -private object ReviewDiffTypefaces { - val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL) - private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL) - val bold: Typeface = Typeface.create("monospace", Typeface.BOLD) +/** Family names come from React Native; `monospace` and `sans-serif` select the platform fonts. */ +private class ReviewDiffTypefaces( + assets: AssetManager, + private val codeFamily: String, + private val uiFamily: String, + private val uiBoldFamily: String +) { + private val fonts = ReactFontManager.getInstance() + val regular: Typeface = fonts.getTypeface(codeFamily, Typeface.NORMAL, assets) + private val medium: Typeface = + if (codeFamily == "monospace") Typeface.create("monospace-medium", Typeface.NORMAL) else regular + val bold: Typeface = fonts.getTypeface(codeFamily, Typeface.BOLD, assets) + val italic: Typeface = fonts.getTypeface(codeFamily, Typeface.ITALIC, assets) + val boldItalic: Typeface = fonts.getTypeface(codeFamily, Typeface.BOLD_ITALIC, assets) + val ui: Typeface = fonts.getTypeface(uiFamily, Typeface.NORMAL, assets) + val uiBold: Typeface = fonts.getTypeface(uiBoldFamily, Typeface.BOLD, assets) + + fun matches(style: DiffStyle): Boolean = + style.codeFontFamily == codeFamily && + style.uiFontFamily == uiFamily && + style.uiBoldFontFamily == uiBoldFamily fun forWeight(weight: String): Typeface = when (weight.lowercase()) { "medium", "semibold", "semi-bold" -> medium diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 2888917a89044..9c97f4e525c11 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -664,7 +664,10 @@ internal data class DiffStyle( val fileHeaderMetaFontSizePx: Float, val fileHeaderMetaFontWeight: String, val fileHeaderSubtextFontSizePx: Float, - val fileHeaderSubtextFontWeight: String + val fileHeaderSubtextFontWeight: String, + val codeFontFamily: String, + val uiFontFamily: String, + val uiBoldFontFamily: String ) { companion object { fun defaults(density: Float): DiffStyle = DiffStyle( @@ -687,6 +690,9 @@ internal data class DiffStyle( fileHeaderMetaFontWeight = "semibold", fileHeaderSubtextFontSizePx = 11f * density, fileHeaderSubtextFontWeight = "medium", + codeFontFamily = "monospace", + uiFontFamily = "sans-serif", + uiBoldFontFamily = "sans-serif", ) fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try { @@ -743,6 +749,9 @@ internal data class DiffStyle( "fileHeaderSubtextFontWeight", fallback.fileHeaderSubtextFontWeight, ), + codeFontFamily = json.optString("codeFontFamily", fallback.codeFontFamily), + uiFontFamily = json.optString("uiFontFamily", fallback.uiFontFamily), + uiBoldFontFamily = json.optString("uiBoldFontFamily", fallback.uiBoldFontFamily), ) } catch (_: Exception) { fallback @@ -854,6 +863,7 @@ private class DiffCanvasView(context: Context) : View(context) { var style: DiffStyle = DiffStyle.defaults(density) set(value) { field = value + drawing.applyFonts(value) rebuildOffsets() } var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 07d9a58a3553c..ed0b8419ee93b 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -185,6 +185,8 @@ private struct ReviewDiffNativeStylePayload: Decodable { let fileHeaderStatusFontWeight: String? let emptyStateFontSize: Double? let emptyStateFontWeight: String? + let codeFontFamily: String? + let uiFontFamily: String? } private struct ReviewDiffNativeStyle: Equatable { @@ -219,6 +221,8 @@ private struct ReviewDiffNativeStyle: Equatable { let fileHeaderStatusFontWeight: UIFont.Weight let emptyStateFontSize: CGFloat let emptyStateFontWeight: UIFont.Weight + let codeFontFamily: String? + let uiFontFamily: String? static func resolve(_ payload: ReviewDiffNativeStylePayload?) -> ReviewDiffNativeStyle { ReviewDiffNativeStyle( @@ -252,7 +256,9 @@ private struct ReviewDiffNativeStyle: Equatable { fileHeaderStatusFontSize: metric(payload?.fileHeaderStatusFontSize, fallback: 10), fileHeaderStatusFontWeight: fontWeight(payload?.fileHeaderStatusFontWeight, fallback: .semibold), emptyStateFontSize: metric(payload?.emptyStateFontSize, fallback: 13), - emptyStateFontWeight: fontWeight(payload?.emptyStateFontWeight, fallback: .semibold) + emptyStateFontWeight: fontWeight(payload?.emptyStateFontWeight, fallback: .semibold), + codeFontFamily: payload?.codeFontFamily, + uiFontFamily: payload?.uiFontFamily ) } @@ -327,7 +333,9 @@ private struct ReviewDiffNativeStyle: Equatable { fileHeaderStatusFontSize: fileHeaderStatusFontSize, fileHeaderStatusFontWeight: fileHeaderStatusFontWeight, emptyStateFontSize: emptyStateFontSize, - emptyStateFontWeight: emptyStateFontWeight + emptyStateFontWeight: emptyStateFontWeight, + codeFontFamily: codeFontFamily, + uiFontFamily: uiFontFamily ) } } @@ -1453,35 +1461,43 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } private var codeFont: UIFont { - UIFont.monospacedSystemFont(ofSize: style.codeFontSize, weight: style.codeFontWeight) + reviewDiffFont( + family: style.codeFontFamily, size: style.codeFontSize, weight: style.codeFontWeight, monospaced: true) } private var lineNumberFont: UIFont { - UIFont.monospacedSystemFont(ofSize: style.lineNumberFontSize, weight: style.lineNumberFontWeight) + reviewDiffFont( + family: style.codeFontFamily, size: style.lineNumberFontSize, weight: style.lineNumberFontWeight, monospaced: true) } private var hunkFont: UIFont { - UIFont.monospacedSystemFont(ofSize: style.hunkFontSize, weight: style.hunkFontWeight) + reviewDiffFont( + family: style.codeFontFamily, size: style.hunkFontSize, weight: style.hunkFontWeight, monospaced: true) } private var fileHeaderFont: UIFont { - UIFont.systemFont(ofSize: style.fileHeaderFontSize, weight: style.fileHeaderFontWeight) + reviewDiffFont( + family: style.uiFontFamily, size: style.fileHeaderFontSize, weight: style.fileHeaderFontWeight, monospaced: false) } private var fileHeaderMetaFont: UIFont { - UIFont.systemFont(ofSize: style.fileHeaderMetaFontSize, weight: style.fileHeaderMetaFontWeight) + reviewDiffFont( + family: style.uiFontFamily, size: style.fileHeaderMetaFontSize, weight: style.fileHeaderMetaFontWeight, monospaced: false) } private var fileHeaderSubtextFont: UIFont { - UIFont.systemFont(ofSize: style.fileHeaderSubtextFontSize, weight: style.fileHeaderSubtextFontWeight) + reviewDiffFont( + family: style.uiFontFamily, size: style.fileHeaderSubtextFontSize, weight: style.fileHeaderSubtextFontWeight, monospaced: false) } private var fileHeaderStatusFont: UIFont { - UIFont.systemFont(ofSize: style.fileHeaderStatusFontSize, weight: style.fileHeaderStatusFontWeight) + reviewDiffFont( + family: style.uiFontFamily, size: style.fileHeaderStatusFontSize, weight: style.fileHeaderStatusFontWeight, monospaced: false) } private var emptyStateFont: UIFont { - UIFont.systemFont(ofSize: style.emptyStateFontSize, weight: style.emptyStateFontWeight) + reviewDiffFont( + family: style.uiFontFamily, size: style.emptyStateFontSize, weight: style.emptyStateFontWeight, monospaced: false) } private lazy var horizontalPanGesture: UIPanGestureRecognizer = { @@ -2983,3 +2999,20 @@ private extension UIColor { self.init(red: red, green: green, blue: blue, alpha: alpha) } } + +/// Resolves a React Native family name; system names such as `System` and `ui-monospace` have no +/// UIFont of that name and fall through to the platform font. +private func reviewDiffFont( + family: String?, size: CGFloat, weight: UIFont.Weight, monospaced: Bool +) -> UIFont { + if let family, let base = UIFont(name: family, size: size) { + let descriptor = UIFontDescriptor(fontAttributes: [ + .family: base.familyName, + .traits: [UIFontDescriptor.TraitKey.weight: weight], + ]) + return UIFont(descriptor: descriptor, size: size) + } + return monospaced + ? .monospacedSystemFont(ofSize: size, weight: weight) + : .systemFont(ofSize: size, weight: weight) +} diff --git a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md index 91e74e697bab0..df57a3df57766 100644 --- a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md +++ b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md @@ -26,10 +26,3 @@ The web terminal vendors a WebAssembly build from the same revision and uses the Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both artifacts in sync when updating the repository-root `native/libghostty-vt`. - -## MesloLGS NF (Android terminal font) - -- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf` -- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs) -- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher -- License: Apache License 2.0 diff --git a/apps/mobile/modules/t3-terminal/android/build.gradle b/apps/mobile/modules/t3-terminal/android/build.gradle index b7d24702b0a38..b3c7ba87aff38 100644 --- a/apps/mobile/modules/t3-terminal/android/build.gradle +++ b/apps/mobile/modules/t3-terminal/android/build.gradle @@ -41,6 +41,7 @@ android { dependencies { implementation project(':expo-modules-core') + implementation 'com.facebook.react:react-android' testImplementation 'junit:junit:4.13.2' testImplementation 'org.robolectric:robolectric:4.16.1' } diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt index 2734b0ceaa00b..327e7c969c5b4 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt @@ -34,6 +34,10 @@ class T3TerminalModule : Module() { view.fontSize = fontSize.toFloat() } + Prop("fontFamily") { view: T3TerminalView, fontFamily: String -> + view.fontFamily = fontFamily + } + Prop("focusRequest") { view: T3TerminalView, focusRequest: Double -> view.focusRequest = focusRequest } diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt index c41d2d545ca61..d7804184fbaf4 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt @@ -105,6 +105,13 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex emitResize() } + var fontFamily: String = "monospace" + set(value) { + field = value + terminalCanvas.fontFamily = value + emitResize() + } + var appearanceScheme: String = "dark" // The PTY grid shared by every attached client, or empty before the server reports one. diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt index 7991383590dee..0d705320e152b 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt @@ -8,7 +8,6 @@ import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface -import android.util.Log import android.view.ActionMode import android.view.GestureDetector import android.view.HapticFeedbackConstants @@ -17,28 +16,17 @@ import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.widget.OverScroller +import com.facebook.react.common.assets.ReactFontManager import kotlin.math.ceil import kotlin.math.max import kotlin.math.min -internal object TerminalTypefaces { - private var loaded = false - var regular: Typeface = Typeface.MONOSPACE - private set - var bold: Typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD) - private set - - @Suppress("TooGenericExceptionCaught") // Typeface.createFromAsset exposes RuntimeException. - fun ensureLoaded(context: Context) { - if (loaded) return - loaded = true - try { - regular = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Regular.ttf") - bold = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Bold.ttf") - } catch (error: RuntimeException) { - Log.w("TerminalCanvasView", "bundled terminal font unavailable, using monospace", error) - } - } +private class TerminalTypefaces(context: Context, family: String) { + private val fonts = ReactFontManager.getInstance() + val regular: Typeface = fonts.getTypeface(family, Typeface.NORMAL, context.assets) + val bold: Typeface = fonts.getTypeface(family, Typeface.BOLD, context.assets) + val italic: Typeface = fonts.getTypeface(family, Typeface.ITALIC, context.assets) + val boldItalic: Typeface = fonts.getTypeface(family, Typeface.BOLD_ITALIC, context.assets) } /** @@ -76,14 +64,7 @@ internal class TerminalCanvasView(context: Context) : View(context) { private val scaledDensity = density * resources.configuration.fontScale private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG) - init { - TerminalTypefaces.ensureLoaded(context) - } - - private val regularTypeface = TerminalTypefaces.regular - private val boldTypeface = TerminalTypefaces.bold - private val italicTypeface = Typeface.create(TerminalTypefaces.regular, Typeface.ITALIC) - private val boldItalicTypeface = Typeface.create(TerminalTypefaces.bold, Typeface.ITALIC) + private var typefaces = TerminalTypefaces(context, "monospace") private val gestureDetector = GestureDetector(context, TerminalGestureListener()) private val contentPadding = 8f * density private var frame: TerminalFrame? = null @@ -154,6 +135,15 @@ internal class TerminalCanvasView(context: Context) : View(context) { updateCellMetrics() } + /** A React Native family name; `monospace` selects the system monospace font. */ + var fontFamily: String = "monospace" + set(value) { + if (field == value) return + field = value + typefaces = TerminalTypefaces(context, value) + updateCellMetrics() + } + var cellWidthPx: Float = 1f private set var cellHeightPx: Float = 1f @@ -164,7 +154,7 @@ internal class TerminalCanvasView(context: Context) : View(context) { isClickable = true isFocusable = true isFocusableInTouchMode = true - paint.typeface = regularTypeface + paint.typeface = typefaces.regular updateCellMetrics() } @@ -282,7 +272,7 @@ internal class TerminalCanvasView(context: Context) : View(context) { private fun updateCellMetrics() { paint.textSize = fontSizeSp * scaledDensity - paint.typeface = regularTypeface + paint.typeface = typefaces.regular cellWidthPx = ceil(paint.measureText("M").toDouble()).toFloat().coerceAtLeast(1f) val metrics = paint.fontMetrics val glyphHeight = metrics.descent - metrics.ascent @@ -296,10 +286,10 @@ internal class TerminalCanvasView(context: Context) : View(context) { val bold = flags and FLAG_BOLD != 0 val italic = flags and FLAG_ITALIC != 0 paint.typeface = when { - bold && italic -> boldItalicTypeface - bold -> boldTypeface - italic -> italicTypeface - else -> regularTypeface + bold && italic -> typefaces.boldItalic + bold -> typefaces.bold + italic -> typefaces.italic + else -> typefaces.regular } paint.textSize = fontSizeSp * scaledDensity paint.color = color diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift index 84f2b6ca13f0c..5412aab0decbc 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift @@ -32,6 +32,10 @@ public class T3TerminalModule: Module { view.fontSize = CGFloat(fontSize) } + Prop("fontFamily") { (view: T3TerminalView, fontFamily: String) in + view.fontFamily = fontFamily + } + Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in view.focusRequest = focusRequest } diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift index 1ed02e6a16cbf..ef8f5ca656715 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -284,7 +284,16 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte var fontSize: CGFloat = 10 { didSet { guard oldValue != fontSize else { return } - inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) + inputField.font = terminalMonoFont(family: fontFamily, size: max(fontSize, 13)) + applyConfigInPlace() + } + } + + /// A React Native family name; `ui-monospace` selects the system monospace font. + var fontFamily: String = "ui-monospace" { + didSet { + guard oldValue != fontFamily else { return } + inputField.font = terminalMonoFont(family: fontFamily, size: max(fontSize, 13)) applyConfigInPlace() } } @@ -360,7 +369,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte inputField.backgroundColor = UIColor.clear inputField.textColor = UIColor.clear inputField.tintColor = UIColor.clear - inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) + inputField.font = terminalMonoFont(family: fontFamily, size: max(fontSize, 13)) inputField.placeholder = "" inputField.autocorrectionType = .no inputField.autocapitalizationType = .none @@ -585,7 +594,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte else { return } inputField.resignFirstResponder() - let controller = TerminalTextSelectionViewController(text: text, fontSize: fontSize) + let controller = TerminalTextSelectionViewController( + text: text, font: terminalMonoFont(family: fontFamily, size: max(fontSize, 14))) let navigation = UINavigationController(rootViewController: controller) navigation.modalPresentationStyle = .pageSheet presenter.present(navigation, animated: !UIAccessibility.isReduceMotionEnabled) @@ -964,7 +974,10 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte } private func writeThemeConfigFile() -> String? { - let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n" + // Ghostty finds fonts by CoreText family name, which for the system face is a hidden ".SF" name. + let family = terminalMonoFont(family: fontFamily, size: fontSize).familyName + let configContents = + "\(themeConfig)\nfont-family = \"\(family)\"\nfont-size = \(String(format: "%g", Double(fontSize)))\n" let url = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") @@ -980,3 +993,10 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte } } } + +func terminalMonoFont(family: String, size: CGFloat) -> UIFont { + if family != "ui-monospace", let font = UIFont(name: family, size: size) { + return font + } + return .monospacedSystemFont(ofSize: size, weight: .regular) +} diff --git a/apps/mobile/modules/t3-terminal/ios/TerminalTextSelectionViewController.swift b/apps/mobile/modules/t3-terminal/ios/TerminalTextSelectionViewController.swift index 5eb2960d93068..048355aa510aa 100644 --- a/apps/mobile/modules/t3-terminal/ios/TerminalTextSelectionViewController.swift +++ b/apps/mobile/modules/t3-terminal/ios/TerminalTextSelectionViewController.swift @@ -2,11 +2,11 @@ import UIKit final class TerminalTextSelectionViewController: UIViewController { private let text: String - private let fontSize: CGFloat + private let font: UIFont - init(text: String, fontSize: CGFloat) { + init(text: String, font: UIFont) { self.text = text - self.fontSize = fontSize + self.font = font super.init(nibName: nil, bundle: nil) } @@ -26,7 +26,7 @@ final class TerminalTextSelectionViewController: UIViewController { let textView = UITextView() textView.text = text - textView.font = .monospacedSystemFont(ofSize: max(fontSize, 14), weight: .regular) + textView.font = font textView.textColor = .label textView.backgroundColor = .systemBackground textView.isEditable = false diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 7bd79fd0ecc6d..bb82578410298 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -125,7 +125,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.19-3757a449.tgz", + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.19-9a8bc858.tgz", "react-native-gesture-handler": "~3.5.0", "react-native-image-viewing": "^0.2.2", "react-native-keyboard-controller": "1.23.0", diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsx index 19aeeed4bfbe1..348c6ba248ff2 100644 --- a/apps/mobile/src/components/ComposerContextSheet.tsx +++ b/apps/mobile/src/components/ComposerContextSheet.tsx @@ -18,7 +18,6 @@ import { changeRequestTermKind } from "../lib/changeRequestTerm"; import { videoMimeType } from "@t3tools/shared/video"; import { Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { REVIEW_MONO_FONT_FAMILY } from "../features/review/reviewDiffRendering"; import { ReviewCommentCard, useReviewCommentColors } from "../features/review/ReviewCommentCard"; import { composerAttachmentInlineUri, @@ -58,8 +57,7 @@ function ContextField(props: { ) : ( {props.value} @@ -248,9 +246,8 @@ export function ComposerContextSheet(props: { > ({ importComposerContextClipboa vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) })); vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) })); vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" })); +vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ fontFamilies: { regular: "System" } }), +})); vi.mock("../features/settings/appearance/useScaledTextRole", () => ({ useComposerTextRole: () => ({ fontSize: 16, lineHeight: 22 }), })); diff --git a/apps/mobile/src/components/PdfPreview.android.tsx b/apps/mobile/src/components/PdfPreview.android.tsx index 89328245a43c6..ca884d2039c64 100644 --- a/apps/mobile/src/components/PdfPreview.android.tsx +++ b/apps/mobile/src/components/PdfPreview.android.tsx @@ -1,3 +1,4 @@ +import { FilePasswordPrompt } from "../features/files/FilePasswordPrompt"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import * as Effect from "effect/Effect"; @@ -49,6 +50,10 @@ const preparedPdfAtom = Atom.family((uri: string) => ); export function PdfPreview(props: { readonly uri: string }) { + return ; +} + +function PdfPreviewSession(props: { readonly uri: string }) { const gt = useGT(); const atom = preparedPdfAtom(props.uri); const prepared = useAtomValue(atom); @@ -56,9 +61,13 @@ export function PdfPreview(props: { readonly uri: string }) { // A render failure belongs to the downloaded copy that failed; Retry replaces it. const [unrenderable, setUnrenderable] = useState(null); const file = prepared._tag === "Success" && !prepared.waiting ? prepared.value : null; + const [challenge, setChallenge] = useState<{ file: typeof file; incorrect: boolean } | null>( + null, + ); + const [attempt, setAttempt] = useState<{ file: typeof file; password: string } | null>(null); const error = file !== null && unrenderable === file - ? gt("The PDF could not be rendered. It may be damaged or password protected.") + ? gt("The PDF could not be rendered. It may be damaged.") : prepared._tag === "Failure" && !prepared.waiting ? Option.getOrElse(AsyncResult.error(prepared), () => gt("The PDF could not be loaded.")) : null; @@ -78,19 +87,36 @@ export function PdfPreview(props: { readonly uri: string }) { return ; return ( - { - const url = pdfLinkUrl(href, props.uri); - if (url !== null) void tryOpenExternalUrl(url, "file-preview"); - }} - onError={() => { - setUnrenderable(file); - }} - style={{ flex: 1, width: "100%" }} - /> + + {challenge !== null && challenge.file === file ? ( + { + setAttempt({ file, password }); + setChallenge(null); + }} + /> + ) : ( + { + setAttempt(null); + setChallenge({ file, incorrect }); + }} + source={{ uri: localUri }} + initialPage={pdfInitialPage(props.uri) - 1} + enableAnnotationRendering + enableDoubleTapZoom + onLinkPress={({ url: href }) => { + const url = pdfLinkUrl(href, props.uri); + if (url !== null) void tryOpenExternalUrl(url, "file-preview"); + }} + onError={() => { + setUnrenderable(file); + }} + style={{ flex: 1, width: "100%" }} + /> + )} + ); } diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 1730619e0a357..e49213517e63c 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -129,6 +129,7 @@ import IconTextIncrease from "@tabler/icons-react-native/IconTextIncrease"; import IconTool from "@tabler/icons-react-native/IconTool"; import IconTrash from "@tabler/icons-react-native/IconTrash"; import IconTypography from "@tabler/icons-react-native/IconTypography"; +import IconLetterCase from "@tabler/icons-react-native/IconLetterCase"; import IconDownload from "@tabler/icons-react-native/IconDownload"; import IconSitemap from "@tabler/icons-react-native/IconSitemap"; import IconUpload from "@tabler/icons-react-native/IconUpload"; @@ -290,6 +291,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "ellipsis.bubble": IconMessageDots, robot: IconRobot, "text.word.spacing": IconLetterSpacing, + textformat: IconLetterCase, "textformat.size": IconTypography, "textformat.size.larger": IconTextIncrease, "textformat.size.smaller": IconTextDecrease, diff --git a/apps/mobile/src/connection/app-state-wakeups.test.ts b/apps/mobile/src/connection/app-state-wakeups.test.ts new file mode 100644 index 0000000000000..f78e83f41cc92 --- /dev/null +++ b/apps/mobile/src/connection/app-state-wakeups.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { mobileApplicationActiveWakeup } from "./app-state-wakeups"; + +describe("mobileApplicationActiveWakeup", () => { + it.each([ + ["inactive without background", null, 5_000, null], + ["background just under 10 s", 0, 9_999, "application-active-probe"], + ["background of 10 s or more", 0, 10_000, "application-active-long"], + ] as const)("%s", (_case, backgroundedAtMs, activeAtMs, expected) => { + expect(mobileApplicationActiveWakeup(backgroundedAtMs, activeAtMs)).toBe(expected); + }); +}); diff --git a/apps/mobile/src/connection/app-state-wakeups.ts b/apps/mobile/src/connection/app-state-wakeups.ts index d50646edd1ca5..ce310f70c1dc2 100644 --- a/apps/mobile/src/connection/app-state-wakeups.ts +++ b/apps/mobile/src/connection/app-state-wakeups.ts @@ -10,9 +10,10 @@ export type MobileApplicationActiveWakeup = Extract< export function mobileApplicationActiveWakeup( backgroundedAtMs: number | null, activeAtMs: number, -): MobileApplicationActiveWakeup { - return backgroundedAtMs !== null && - activeAtMs - backgroundedAtMs >= MOBILE_LONG_BACKGROUND_AFTER_MS +): MobileApplicationActiveWakeup | null { + // iOS goes inactive without suspending for Control Center, alerts, and the app switcher. + if (backgroundedAtMs === null) return null; + return activeAtMs - backgroundedAtMs >= MOBILE_LONG_BACKGROUND_AFTER_MS ? "application-active-long" : "application-active-probe"; } diff --git a/apps/mobile/src/connection/background-activity.test.ts b/apps/mobile/src/connection/background-activity.test.ts index 170ba4efa9c90..a82df32ee430d 100644 --- a/apps/mobile/src/connection/background-activity.test.ts +++ b/apps/mobile/src/connection/background-activity.test.ts @@ -1,13 +1,71 @@ -import { EnvironmentId, WS_METHODS } from "@t3tools/contracts"; +import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; +import { type ClientActivityReportInput, EnvironmentId, WS_METHODS } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import * as TestClock from "effect/testing/TestClock"; +import { vi } from "vite-plus/test"; +const appState = vi.hoisted(() => { + const state: { current: string; listener: ((next: string) => void) | undefined } = { + current: "active", + listener: undefined, + }; + return state; +}); + +vi.mock("react-native", () => ({ + AppState: { + get currentState() { + return appState.current; + }, + addEventListener: (_event: string, listener: (next: string) => void) => { + appState.listener = listener; + return { remove: () => (appState.listener = undefined) }; + }, + }, +})); + +const reports = vi.hoisted((): Array => []); + +vi.mock("@t3tools/client-runtime/rpc", async (importOriginal) => { + const { void: sent } = await import("effect/Effect"); + return { + ...(await importOriginal()), + request: (_method: string, input: ClientActivityReportInput) => { + reports.push(input); + return sent; + }, + }; +}); + +vi.mock("expo-secure-store", () => ({ + deleteItemAsync: vi.fn(), + getItemAsync: vi.fn(), + setItemAsync: vi.fn(), +})); + +import * as MobileSecureStorage from "../persistence/mobile-secure-storage"; +import * as MobileStorage from "../persistence/mobile-storage"; +import { layerReporter } from "./background-activity"; import { onRetainedMobileBackgroundScopesChange, observeMobileBackgroundActivitySubscription, retainedMobileBackgroundScopes, } from "./background-activity-scopes"; +function setup() { + appState.current = "active"; + appState.listener = undefined; + reports.length = 0; +} + +function changeAppState(next: string) { + appState.current = next; + appState.listener?.(next); +} + describe("mobile background activity", () => { it.effect("retains VCS demand only while the mobile subscription is active", () => Effect.gen(function* () { @@ -85,4 +143,73 @@ describe("mobile background activity", () => { removeListener(); }), ); + + it.effect("ignores inactive and skips periodic reports while backgrounded", () => + Effect.gen(function* () { + setup(); + const entries = yield* SubscriptionRef.make( + new Map([[EnvironmentId.make("environment-reporter-test"), {}]]), + ); + let calls = 0; + const registry = EnvironmentRegistry.EnvironmentRegistry.of({ + entries, + run: () => { + calls += 1; + return Effect.void; + }, + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const secureStorage = MobileSecureStorage.MobileSecureStorage.of({ + getItem: () => Effect.succeed("device"), + setItem: () => Effect.void, + removeItem: () => Effect.void, + }); + + yield* Layer.build( + layerReporter.pipe( + Layer.provide(MobileStorage.layer), + Layer.provide(Layer.succeed(MobileSecureStorage.MobileSecureStorage, secureStorage)), + Layer.provide(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)), + ), + ); + yield* TestClock.adjust("1 second"); + expect(calls).toBe(1); + + changeAppState("background"); + yield* TestClock.adjust("1 second"); + expect(calls).toBe(2); + + yield* TestClock.adjust("60 seconds"); + expect(calls).toBe(2); + + changeAppState("active"); + yield* TestClock.adjust("1 second"); + expect(calls).toBe(3); + + yield* TestClock.adjust("25 seconds"); + expect(calls).toBe(4); + + changeAppState("inactive"); + yield* TestClock.adjust("25 seconds"); + expect(calls).toBe(5); + expect(reports.at(-1)).toMatchObject({ + appState: "inactive", + visible: true, + focused: true, + recentlyInteracted: true, + }); + + changeAppState("active"); + yield* TestClock.adjust("1 second"); + expect(calls).toBe(5); + + changeAppState("background"); + yield* TestClock.adjust("1 second"); + expect(calls).toBe(6); + expect(reports.at(-1)).toMatchObject({ appState: "background", visible: false }); + + changeAppState("unknown"); + yield* TestClock.adjust("30 seconds"); + expect(calls).toBe(6); + }), + ); }); diff --git a/apps/mobile/src/connection/background-activity.ts b/apps/mobile/src/connection/background-activity.ts index 66eb2b10e0263..1d2201756ab7f 100644 --- a/apps/mobile/src/connection/background-activity.ts +++ b/apps/mobile/src/connection/background-activity.ts @@ -36,6 +36,11 @@ function normalizeAppState( return "unknown"; } +// Control Center, alerts, and the app switcher leave the app on screen as `inactive`. +function isForeground(state: string | null | undefined): boolean { + return state === "active" || state === "inactive"; +} + export const layerObserver = Layer.succeed( EnvironmentRpcSubscriptionObserver, EnvironmentRpcSubscriptionObserver.of({ @@ -57,7 +62,7 @@ export const layerReporter = Layer.effectDiscard( const report = Effect.gen(function* () { const observedAtMs = yield* Clock.currentTimeMillis; - const active = appState === "active"; + const foreground = isForeground(appState); const entries = yield* SubscriptionRef.get(registry.entries); yield* Effect.forEach( entries.keys(), @@ -69,9 +74,9 @@ export const layerReporter = Layer.effectDiscard( environmentId: environmentId as EnvironmentId, clientId, clientKind: "mobile", - visible: active, - focused: active, - recentlyInteracted: active, + visible: foreground, + focused: foreground, + recentlyInteracted: foreground, appState: normalizeAppState(appState), scopes: [ ...BASELINE_SCOPES, @@ -93,8 +98,9 @@ export const layerReporter = Layer.effectDiscard( Effect.sync(() => { const removeScopeListener = onRetainedMobileBackgroundScopesChange(requestReport); const subscription = AppState.addEventListener("change", (nextState) => { + const changed = isForeground(appState) !== isForeground(nextState); appState = nextState; - requestReport(); + if (changed) requestReport(); }); return { removeScopeListener, subscription }; }), @@ -113,9 +119,8 @@ export const layerReporter = Layer.effectDiscard( Stream.runForEach(() => report), Effect.forkScoped, ); - yield* Effect.sync(requestReport).pipe( - Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)), - Effect.forkScoped, - ); + yield* Effect.sync(() => { + if (isForeground(appState)) requestReport(); + }).pipe(Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)), Effect.forkScoped); }), ); diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index 38ea76218534c..feb555b492529 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -126,10 +126,8 @@ const layerWakeups = Wakeups.layer({ return; } if (state === "active") { - Queue.offerUnsafe( - queue, - mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()), - ); + const wakeup = mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()); + if (wakeup !== null) Queue.offerUnsafe(queue, wakeup); backgroundedAtMs = null; } }); diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index fa6f4402890fc..79fbc964b2806 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -42,6 +42,10 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( providerCatalogsOnDemand: true, providerCatalogDigests: true, providerStatusDeltas: true, + // Halves idle pings. The timeout is checked on ping ticks, after an unanswered ping + // and 15 s with no frame: within 25 s of the last frame (20 s at the 5 s default), + // and a host stalled for 10 s can lose the socket (15 s at the default). + pingInterval: "10 seconds", }), ), Layer.provideMerge( diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 6dc38aa6eb82e..ac84a0ddeb352 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -457,6 +457,7 @@ function PairingInputRow({ accessibilityLabel={label} autoCapitalize="none" autoCorrect={false} + lineBreakModeIOS="middle" textAlignVertical="center" className="min-h-[48px] flex-1 self-stretch rounded-none border-0 bg-transparent p-0 text-base leading-[23px]" /> diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts index cc2587d14f8b2..d6973c8c8bfd1 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts @@ -100,6 +100,11 @@ export interface NativeReviewDiffStyle { readonly fileHeaderPathRightPadding?: number; readonly fileHeaderCountColumnWidth?: number; readonly fileHeaderCountGap?: number; + /** Family names as React Native takes them; a system family name selects the platform font. */ + readonly codeFontFamily?: string; + readonly uiFontFamily?: string; + /** Android only: bundled families register one file per name, so bold needs its own. */ + readonly uiBoldFontFamily?: string; readonly codeFontSize?: number; readonly codeFontWeight?: string; readonly lineNumberFontSize?: number; diff --git a/apps/mobile/src/features/files/AttachmentDocumentBody.tsx b/apps/mobile/src/features/files/AttachmentDocumentBody.tsx index a04972d6dd752..f90c03434ed37 100644 --- a/apps/mobile/src/features/files/AttachmentDocumentBody.tsx +++ b/apps/mobile/src/features/files/AttachmentDocumentBody.tsx @@ -8,6 +8,7 @@ import type { useAttachmentDocument } from "../../lib/attachmentDocument"; import { HtmlRenderWebView } from "../threads/HtmlRenderWebView"; import { AudioFilePreview } from "./AudioFilePreview"; import { DelimitedFilePreview } from "./DelimitedFilePreview"; +import { EpubFilePreview } from "./EpubFilePreview"; import { FileMarkdownPreview } from "./FileMarkdownPreview"; import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback"; import { SourceFileSurface } from "./SourceFileSurface"; @@ -89,6 +90,8 @@ export function AttachmentDocumentBody(props: { ); } if (!document.uri) return null; + if (document.kind === "epub") + return ; if (document.kind === "audio") { return ; } diff --git a/apps/mobile/src/features/files/EpubFilePreview.tsx b/apps/mobile/src/features/files/EpubFilePreview.tsx new file mode 100644 index 0000000000000..534d6d3fb2755 --- /dev/null +++ b/apps/mobile/src/features/files/EpubFilePreview.tsx @@ -0,0 +1,65 @@ +import { epubPreviewUrl } from "@t3tools/shared/filePreview"; +import { useGT } from "gt-react-native"; +import { useState } from "react"; +import { View } from "react-native"; +import { WebView } from "react-native-webview"; +import { useContentBottomInset, useContentTopInset } from "../../components/ui/useBarInset"; +import { tryOpenWebLink } from "../../lib/openExternalUrl"; +import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback"; + +export function EpubFilePreview(props: { readonly uri: string | null; readonly name: string }) { + const gt = useGT(); + const header = useContentTopInset(); + const bottom = useContentBottomInset(); + const url = props.uri ? epubPreviewUrl(props.uri, props.name) : null; + const [failed, setFailed] = useState(false); + if (!props.uri) return ; + if (!url || failed) { + return ( + + + {gt("The file could not be rendered.")} + + + ); + } + const page = url.split("#", 1)[0]; + return ( + + { + if (event.nativeEvent.data === "unavailable") setFailed(true); + }} + onShouldStartLoadWithRequest={(request) => + request.url === "about:srcdoc" || + request.url === "about:blank" || + request.url.split("#", 1)[0] === page + } + onOpenWindow={(event) => { + void tryOpenWebLink(event.nativeEvent.targetUrl, "file-preview"); + }} + onError={() => setFailed(true)} + onHttpError={(event) => { + if (event.nativeEvent.url.split("#", 1)[0] === page) setFailed(true); + }} + startInLoadingState + renderLoading={() => } + style={{ flex: 1, backgroundColor: "transparent" }} + /> + + ); +} diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 2e8d030d2b2f8..6feedd0317df1 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -17,7 +17,6 @@ import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; import { tryOpenWebLink } from "../../lib/openExternalUrl"; -import { FONT_FAMILIES } from "../../lib/fontFamilies"; import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { @@ -49,7 +48,7 @@ interface MarkdownPreviewStyles { } export function useMarkdownPreviewStyles(): MarkdownPreviewStyles { - const { appearance } = useAppearancePreferences(); + const { appearance, fontFamilies, monoFontFamily } = useAppearancePreferences(); const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize); const theme = useUniwindTheme(); const body = theme["--color-md-body"]; @@ -59,8 +58,8 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles { const codeBackground = theme["--color-md-code-bg"]; const codeText = theme["--color-md-code-text"]; const horizontalRule = theme["--color-md-hr"]; - const regularFontFamily = FONT_FAMILIES.regular; - const boldFontFamily = FONT_FAMILIES.bold; + const regularFontFamily = fontFamilies.regular; + const boldFontFamily = fontFamilies.bold; return { nativeTextStyle: { @@ -81,6 +80,7 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles { fontFamily: regularFontFamily, headingFontFamily: boldFontFamily, boldFontFamily, + monoFontFamily, }, }; } diff --git a/apps/mobile/src/features/files/FilePasswordPrompt.tsx b/apps/mobile/src/features/files/FilePasswordPrompt.tsx new file mode 100644 index 0000000000000..fd92b14c8fbeb --- /dev/null +++ b/apps/mobile/src/features/files/FilePasswordPrompt.tsx @@ -0,0 +1,45 @@ +import { useGT } from "gt-react-native"; +import { useState } from "react"; +import { Keyboard, View } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { SecretTextInput } from "../../components/ui/SecretTextInput"; + +export function FilePasswordPrompt(props: { + readonly incorrect: boolean; + readonly onSubmit: (password: string) => void; +}) { + const gt = useGT(); + const [password, setPassword] = useState(""); + const submit = (value: string) => { + if (value.length === 0) return; + setPassword(""); + Keyboard.dismiss(); + props.onSubmit(value); + }; + return ( + + + + {props.incorrect + ? gt("Incorrect password. Try again.") + : gt("This file requires a password.")} + + + @@ -1090,19 +1161,28 @@ function RightPanelTab( return (
{ + if (event.target === event.currentTarget) onActivate(surface, event.shiftKey); + }} onMouseDown={preventTabMiddleButtonDefault} onMouseUp={preventTabMiddleButtonDefault} onAuxClick={(event) => onAuxClick(event, surface)} onContextMenu={(event) => onContextMenu(event, surface)} {...listeners} ref={setNodeRef} - style={{ transform: CSS.Translate.toString(transform), transition }} + style={{ transform: translation, transition }} className={cn( "cursor-pointer group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs", props.ownsDesktopTitleBar && "[-webkit-app-region:no-drag]", props.active ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/60 hover:text-foreground", + props.selected && + "bg-primary/15 text-foreground ring-1 ring-inset ring-primary/50 hover:bg-primary/20", + props.selected && + !isDragging && + "in-data-dragging-selection:relative in-data-dragging-selection:z-10 in-data-dragging-selection:transform-(--selected-tab-drag-transform)! in-data-dragging-selection:transition-none!", isDragging && "relative z-10", )} > @@ -1111,7 +1191,7 @@ function RightPanelTab( ); } -export function RightPanelTabs(props: RightPanelTabsProps) { +export function RightPanelTabs({ ref, ...props }: RightPanelTabsProps) { const gt = useGT(); const messages = useMessages(); const focusedSurface = props.surfaces.find((surface) => surface.id === props.activeSurfaceId); @@ -1121,12 +1201,43 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const tabListRef = useRef(null); const addSurfaceTriggerRef = useRef(null); const [renamingDevice, setRenamingDevice] = useState(null); + const [selection, setSelection] = useState<{ + scope: RightPanelTabsProps["selectionScope"]; + anchorId: string; + endId: string; + } | null>(null); const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false); const [tabScrollState, setTabScrollState] = useState({ hasOverflow: false, canScrollLeft: false, canScrollRight: false, }); + const anchorIndex = selection + ? props.surfaces.findIndex((surface) => surface.id === selection.anchorId) + : -1; + const endIndex = selection + ? props.surfaces.findIndex((surface) => surface.id === selection.endId) + : -1; + const hasSelection = + selection !== null && + props.open !== false && + selection.scope === props.selectionScope && + selection.anchorId === props.activeSurfaceId && + anchorIndex >= 0 && + endIndex >= 0; + if (selection !== null && !hasSelection) setSelection(null); + const selectedSurfaces = hasSelection + ? props.surfaces.slice(Math.min(anchorIndex, endIndex), Math.max(anchorIndex, endIndex) + 1) + : []; + const selectedIds = selectedSurfaces.map((surface) => surface.id); + const clearSelection = useStableCallback(() => setSelection(null)); + useImperativeHandle(ref, () => ({ + closeSelectedTabs: () => { + if (!hasSelection) return false; + props.onCloseSelectedSurfaces(selectedSurfaces); + return true; + }, + })); const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; @@ -1314,7 +1425,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }); } items.push( - { id: "close", label: gt("Close") }, + selectedIds.includes(surface.id) + ? { id: "close-selected", label: gt("Close selected tabs") } + : { id: "close", label: gt("Close") }, { id: "close-others", label: gt("Close others"), @@ -1367,6 +1480,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) { case "close": props.onCloseSurface(surface); break; + case "close-selected": + props.onCloseSelectedSurfaces(selectedSurfaces); + break; case "close-others": props.onCloseOtherSurfaces(surface); break; @@ -1386,7 +1502,20 @@ export function RightPanelTabs(props: RightPanelTabsProps) { event.stopPropagation(); props.onCloseSurface(surface); }; - const onActivateTab = useStableCallback(props.onActivate); + const onActivateTab = useStableCallback( + (surface: RightPanelSurface, extendSelection: boolean) => { + if (extendSelection && focusedSurface) { + setSelection( + surface.id === focusedSurface.id + ? null + : { scope: props.selectionScope, anchorId: focusedSurface.id, endId: surface.id }, + ); + return; + } + setSelection(null); + props.onActivate(surface); + }, + ); const onCloseTab = useStableCallback(props.onCloseSurface); const onTabAuxClick = useStableCallback(handleTabAuxClick); const onTabContextMenu = useStableCallback( @@ -1493,9 +1622,20 @@ export function RightPanelTabs(props: RightPanelTabsProps) { ownsDesktopTitleBar && tabScrollState.hasOverflow && "[-webkit-app-region:no-drag]", )} data-right-panel-tab-list + onKeyDown={(event) => { + if (!hasSelection || event.key !== "Escape" || event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + clearSelection(); + }} > -
- +
+ {props.surfaces.map((surface) => { const previewTabId = previewTabIdOf(surface, props.previewSessions); const favicon = previewFaviconOf( @@ -1507,8 +1647,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) { + canMarkLatestRunUnread(thread.latestRun) && threadRuntimeCanArchive(thread.runtime), + ); // Presets sync across environments, so the first selected thread's stand for all. const menuOpenedAt = new Date(); const snoozePresets = resolveSnoozePresets( @@ -2446,7 +2452,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ] : []), - { id: "mark-unread", label: gt("Mark unread ({count})", { count }) }, + ...(markUnreadThreads.length > 0 + ? [ + { + id: "mark-unread" as const, + label: gt("Mark unread ({count})", { count: markUnreadThreads.length }), + }, + ] + : []), { id: "delete", label: gt("Delete ({count})", { count }), @@ -2556,9 +2569,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; } if (clicked.value === "mark-unread") { - for (const threadKey of threadKeys) { - const thread = threadByKeyRef.current.get(threadKey); - if (thread) markThreadUnread(scopeThreadRef(thread.environmentId, thread.id)); + for (const thread of markUnreadThreads) { + markThreadUnread(scopeThreadRef(thread.environmentId, thread.id)); } clearSelection(); return; @@ -2743,7 +2755,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), isRegeneratingTitle, isRunning: !threadRuntimeCanArchive(thread.runtime), - hasCompletedRun: thread.latestRun?.completedAt != null, + hasCompletedRun: canMarkLatestRunUnread(thread.latestRun), canShareWithGuest: appAtomRegistry.get( canShareWithGuestAtom(threadRef.environmentId), ), diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 7a32aef8c416d..407a6aa542e27 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -17,7 +17,11 @@ import { import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; import { useRightPanelStore } from "~/rightPanelStore"; -import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; +import { + importPastedComposerText, + type PastedComposerClipboard, + readPastedComposerClipboard, +} from "../composerInlineTokenPaste"; import { questionAttachmentDraftId, trackOpenQuestionAttachmentDraft, @@ -330,9 +334,12 @@ export interface ChatComposerHandle { hasPendingAttachments: () => boolean; insertTextAtEnd: ( text: string, - options?: { ensureLeadingBoundary?: boolean; clipboardData?: DataTransfer }, + options?: { ensureLeadingBoundary?: boolean; clipboardPaste?: PastedComposerClipboard }, + ) => boolean; + pasteTextAtEnd: ( + clipboardData: DataTransfer, + options: { bypassAutoAttachment: boolean }, ) => boolean; - pasteTextAtEnd: (text: string, options?: { bypassAutoAttachment?: boolean }) => boolean; citeAssistantText: ( citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor, @@ -2848,27 +2855,31 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : bannerItems; + const canInsertComposerText = + !activePendingIsResponding && + !isChoiceOnlyPendingQuestion && + (pendingUserInputs.length === 0 || Boolean(activePendingProgress?.activeQuestion)) && + !projectSelectionRequired && + !speechInput.freezesEditor; + const insertComposerText = ( text: string, position: "cursor" | "end", options?: { ensureLeadingBoundary?: boolean; citationCommentAnchor?: AssistantCitationSourceAnchor; - clipboardData?: DataTransfer; + clipboardPaste?: PastedComposerClipboard; }, ): boolean => { if ( text.length === 0 || - activePendingIsResponding || - (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) || - projectSelectionRequired || - speechInput.freezesEditor || + !canInsertComposerText || (options?.citationCommentAnchor && !composerEditorRef.current) ) { return false; } - if (options?.clipboardData) { - text = importPastedComposerText(options.clipboardData, importContextFragment); + if (options?.clipboardPaste) { + text = importPastedComposerText(options.clipboardPaste, importContextFragment); } const prompt = promptRef.current; const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; @@ -3038,13 +3049,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const addComposerFoldersStable = useStableCallback(addComposerFolders); - const onComposerPaste = (event: React.ClipboardEvent) => { + const onComposerPaste = ( + event: React.ClipboardEvent, + readClipboard: (plainTextOnly: boolean) => PastedComposerClipboard, + ) => { const { files, folders } = splitTransferredFiles(event.clipboardData); const plainText = event.clipboardData.getData("text/plain"); const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); - const pastedContext = - !isLiteralPendingAnswer && - (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const paste = readClipboard(bypassAutoAttachment); + const pastedContext = Boolean(paste.context?.records.length); const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; const htmlImageContent = canAttachFiles && plainText.length > 0 @@ -3077,7 +3090,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) htmlHasImageAndText: htmlImageContent === "image-and-text", }); if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); - if (!foldPastedText(plainText, bypassAutoAttachment)) { + if (!foldPastedText(paste.text, bypassAutoAttachment)) { return; } @@ -3343,21 +3356,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) countPreparingComposerImages(attachmentTargetKey) > 0 || pendingDraftWork.has(attachmentTargetKey), insertTextAtEnd: insertComposerTextAtEndStable, - pasteTextAtEnd: (text: string, options) => { - if (speechInput.freezesEditor) return false; + pasteTextAtEnd: (clipboardData, options) => { + if (!canInsertComposerText) return false; const shortcutArmed = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); - const bypassAutoAttachment = options?.bypassAutoAttachment === true || shortcutArmed; + const bypassAutoAttachment = options.bypassAutoAttachment || shortcutArmed; + if (composerEditorRef.current?.pasteAtCodeBlockEnd(clipboardData)) return true; + const paste = readPastedComposerClipboard( + clipboardData, + bypassAutoAttachment || isLiteralPendingAnswer, + ); + if (paste.context?.records.length) { + return insertComposerTextAtEndStable(paste.text, { clipboardPaste: paste }); + } const promptLength = promptRef.current.length; if ( - !foldPastedText(text, bypassAutoAttachment, { + foldPastedText(paste.text, bypassAutoAttachment, { start: promptLength, end: promptLength, }) ) { - return false; + focusComposer(); + return true; } - focusComposer(); - return true; + return insertComposerTextAtEndStable(paste.text); }, citeAssistantText: (citation, sourceAnchor) => insertComposerTextStable( @@ -3554,6 +3575,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeThread, addComposerAttachments, addComposerFoldersStable, + canInsertComposerText, foldPastedText, composerDraftTarget, composerModelOptions, diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx index 2bb38a3782f50..817ffd7a42990 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.browser.test.tsx @@ -26,6 +26,22 @@ const prompt: PendingUserInput = { ], }; +function panel(onToggleOption: (questionId: string, optionValue: string) => void) { + return ( + + ); +} + it.each<{ focus: string; control: ReactNode; toggles: boolean }>([ { focus: "a page button", control: ", typed: "", toggles: true }, +])( + "digit shortcut with focus in $focus inside a shadow root toggles an option: $toggles", + async ({ html, nested, typed, toggles }) => { + const onToggleOption = vi.fn(); + await using screen = await render( + <> +
+ {panel(onToggleOption)} + , + ); + await expect.element(screen.getByText("Incremental")).toBeVisible(); + let root = screen.getByTestId("shadow-host").element().attachShadow({ mode: "open" }); + if (nested) + root = root.appendChild(document.createElement("div")).attachShadow({ mode: "open" }); + root.innerHTML = html; + const focused = root.querySelector("[data-focus]")!; + focused.focus(); + + await userEvent.keyboard("1"); + + expect(onToggleOption.mock.calls).toEqual(toggles ? [["question", "Incremental"]] : []); + expect("value" in focused ? focused.value : focused.textContent).toBe(typed); + }, +); diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index a83b57e6cc258..a720459cac76a 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -11,6 +11,7 @@ import { CheckboxMark } from "../ui/checkbox"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { Kbd } from "../ui/kbd"; import { cn } from "~/lib/utils"; +import { isEditableFocused } from "~/lib/editableFocus"; import { isInSideChatPane } from "~/lib/sideChatPane"; import { ComposerBanner } from "./ComposerBanner"; import ChatMarkdown from "../ChatMarkdown"; @@ -155,14 +156,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( const handler = (event: globalThis.KeyboardEvent) => { if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; const target = event.target; - if (isInSideChatPane(target)) return; - if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { - return; - } + if (isInSideChatPane(target) || isEditableFocused(target)) return; if ( target instanceof HTMLElement && target.closest( - 'select, [contenteditable]:not([contenteditable="false"]), [role="dialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]', + '[role="dialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]', ) ) { return; diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.ts b/apps/web/src/components/chat/ComposerStashMenu.test.ts index 38e0714c3a4a6..12b4e11548733 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.test.ts +++ b/apps/web/src/components/chat/ComposerStashMenu.test.ts @@ -29,4 +29,18 @@ describe("stashEntrySnippet", () => { }); expect(stashEntrySnippet(entry(`Summarize ${file} please`))).toBe("Summarize README.md please"); }); + + it("counts unreadable and still-saving images in an image-only prompt", () => { + expect(stashEntrySnippet({ ...entry(""), unreadableImageNames: ["shot.png"] })).toBe( + "(1 image)", + ); + expect( + stashEntrySnippet({ + ...entry(""), + droppedImageNames: ["big.png"], + unreadableImageNames: ["shot.png"], + }), + ).toBe("(2 images)"); + expect(stashEntrySnippet({ ...entry(""), pendingImageCount: 1 })).toBe("(1 image)"); + }); }); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 0d0d214931697..ccc4280db77ff 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -32,7 +32,8 @@ export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResol const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_MAX_CHARS - 1 : SNIPPET_MAX_CHARS; return `${trimmed.slice(0, end).trimEnd()}…`; } - const imageCount = entry.attachments.length + entry.droppedImageNames.length; + const imageCount = + entry.attachments.length + missingImageCount(entry) + (entry.pendingImageCount ?? 0); const fileCount = entry.files?.length ?? 0; const attachmentCount = imageCount + fileCount; if (attachmentCount === 0) { diff --git a/apps/web/src/components/chat/MarkdownCopy.browser.test.tsx b/apps/web/src/components/chat/MarkdownCopy.browser.test.tsx index 94a9c4d87bdf8..d0887db56e3c5 100644 --- a/apps/web/src/components/chat/MarkdownCopy.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownCopy.browser.test.tsx @@ -153,3 +153,51 @@ describe("copying a table as HTML", () => { } }); }); + +describe("copying a table as PNG", () => { + it("writes the drawn table as one image/png clipboard item", async () => { + await using screen = await render( + + + + Name + Date + + + + + Ada + 11 Oct + + + , + // The table renders no links and reads no route. + { router: false }, + ); + const items: ClipboardItem[] = []; + const write = vi.spyOn(navigator.clipboard, "write").mockImplementation(async (data) => { + items.push(...data); + // Settle the promised image as the browser would before the write resolves. + await Promise.all(data.flatMap((item) => item.types.map((type) => item.getType(type)))); + }); + + try { + await userEvent.click(screen.getByRole("button", { name: "Copy table" })); + await userEvent.click(page.getByRole("menuitem", { name: "Copy as PNG" })); + await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument(); + + expect(items).toHaveLength(1); + const [item] = items; + expect(item?.types).toEqual(["image/png"]); + const png = await item!.getType("image/png"); + expect(png.type).toBe("image/png"); + const table = screen.container.querySelector("table")!.getBoundingClientRect(); + const bitmap = await createImageBitmap(png); + // The table plus a 16px margin on each side, at the screen's pixel density. + expect(bitmap.width).toBe(Math.floor((table.width + 32) * devicePixelRatio)); + expect(bitmap.height).toBe(Math.floor((table.height + 32) * devicePixelRatio)); + } finally { + write.mockRestore(); + } + }); +}); diff --git a/apps/web/src/components/chat/MarkdownTable.tsx b/apps/web/src/components/chat/MarkdownTable.tsx index 3abec62576005..1b498ab794ffe 100644 --- a/apps/web/src/components/chat/MarkdownTable.tsx +++ b/apps/web/src/components/chat/MarkdownTable.tsx @@ -14,23 +14,36 @@ import { ScrollArea } from "../ui/scroll-area"; import { reportMarkdownActionFailure, type TableCopyFormat } from "./markdownActionFailure"; import { SharedTooltipTrigger } from "../ui/shared-tooltip"; -const TABLE_COPY_SERIALIZERS: Record string> = { +type TableTextFormat = Exclude; + +const TABLE_COPY_SERIALIZERS: Record string> = { markdown: serializeTableElementToMarkdown, csv: serializeTableElementToCsv, html: serializeTableElementToHtml, }; +// Loaded on first use; the clipboard write still starts inside the click. +const renderTablePng = (table: HTMLTableElement) => + import("./tablePng").then((module) => module.renderTablePng(table)); + export function MarkdownTable({ children, ...props }: ComponentProps<"table">) { const gt = useGT(); const containerRef = useRef(null); - const { copyToClipboard, isCopied: copied } = useCopyToClipboard({ + const { + copyToClipboard, + copyPngToClipboard, + isCopied: copied, + } = useCopyToClipboard({ timeout: 1200, onError: (cause, format) => reportMarkdownActionFailure({ operation: "copy-table", format }, cause), }); const copyLabel = copied ? gt("Copied") : gt("Copy table"); + // Insecure origins (plain http over a LAN or tailnet) have no async clipboard for images. + const canCopyPng = + typeof ClipboardItem !== "undefined" && typeof navigator.clipboard?.write === "function"; - const handleCopy = (format: TableCopyFormat) => { + const handleCopy = (format: TableTextFormat) => { const table = containerRef.current?.querySelector("table"); if (!table) return; const text = TABLE_COPY_SERIALIZERS[format](table); @@ -43,6 +56,12 @@ export function MarkdownTable({ children, ...props }: ComponentProps<"table">) { ); }; + const handleCopyPng = () => { + const table = containerRef.current?.querySelector("table"); + if (!table) return; + copyPngToClipboard(() => renderTablePng(table), "png"); + }; + return (
@@ -78,6 +97,11 @@ export function MarkdownTable({ children, ...props }: ComponentProps<"table">) { handleCopy("html")}> Copy as HTML + {canCopyPng ? ( + + Copy as PNG + + ) : null}
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 5ebe6aaae180c..8450f8abb3f83 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -796,6 +796,23 @@ describe("MessagesTimeline messages", () => { }); }); + it("keeps minimap marks apart in a thread with many user messages", async () => { + setup(); + const entries = Array.from({ length: 400 }, (_, index) => + message(`Question ${index}`, {}, `user-${index}`), + ); + await using screen = await renderTimeline(entries); + const tops = () => + [...screen.container.querySelectorAll("[data-minimap-strip]")] + .map((strip) => strip.getBoundingClientRect().top) + .sort((a, b) => a - b); + await vi.waitFor(() => expect(tops().length).toBeGreaterThan(1)); + const markTops = tops(); + const gaps = markTops.slice(1).map((top, index) => top - markTops[index]!); + // A mark is 2px tall; closer than 4px apart and neighbours read as one bar. + expect(Math.min(...gaps)).toBeGreaterThanOrEqual(4); + }); + it("keeps the minimap off the copy button when the chat lane is shifted left", async () => { setup(); const pageSize = { width: window.innerWidth, height: window.innerHeight }; diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index fc7a5e07e3a74..37a61de763de3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -5261,3 +5261,42 @@ describe("workEntryReadOutput", () => { ).toBe("/workspace/t3code/src/app.ts\n~/.claude/CLAUDE.md\n~/.gitconfig"); }); }); + +it("updates cached rows whose spacing or setup handoff changed without new content", () => { + const working: MessagesTimelineRow = { + kind: "working", + id: "working", + createdAt: "2026-01-01T00:00:00Z", + continuesWorkLog: true, + }; + const snapshot: WorktreeSetupSnapshot = { + threadId: ThreadId.make("thread-setup"), + phase: "failed", + startedAt: "2026-01-01T00:00:00Z", + endedAt: "2026-01-01T00:01:00Z", + branch: "feature", + baseRef: "main", + worktreePath: null, + setupScript: null, + stages: [], + error: null, + sequence: 3, + }; + const setup: MessagesTimelineRow = { + kind: "worktree-setup", + id: "setup", + createdAt: snapshot.startedAt, + snapshot, + embedded: false, + }; + const cached = computeStableMessagesTimelineRows([setup, working], { + result: [], + byId: new Map(), + }); + const { continuesWorkLog: _continued, ...settledWorking } = working; + const next = computeStableMessagesTimelineRows( + [{ ...setup, embedded: true }, settledWorking], + cached, + ); + expect(next.result).toEqual([{ ...setup, embedded: true }, settledWorking]); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 90b324598ba72..caf4daa172062 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -383,6 +383,27 @@ export function resolveTimelineMinimapTopPercent(index: number, itemCount: numbe return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100; } +// Strips are 2px tall; centers 4px apart or closer merge into one bar once layout +// rounds their positions. +const TIMELINE_MINIMAP_MIN_MARK_SPACING = 5; + +/** Strips that fit the measured rail; past that, neighbouring items share one. */ +export function resolveTimelineMinimapMarkCount(itemCount: number, railHeight: number): number { + if (railHeight <= 0) return itemCount; + const capacity = Math.floor(railHeight / TIMELINE_MINIMAP_MIN_MARK_SPACING) + 1; + return Math.min(itemCount, Math.max(2, capacity)); +} + +/** The strip nearest the item's own position on the rail. */ +export function resolveTimelineMinimapMarkIndex( + itemIndex: number, + itemCount: number, + markCount: number, +): number { + if (markCount >= itemCount) return itemIndex; + return Math.round((itemIndex / (itemCount - 1)) * (markCount - 1)); +} + export function resolveTimelineMinimapIndexFromPointer(input: { readonly itemCount: number; readonly railTop: number; @@ -2767,7 +2788,7 @@ export function computeStableMessagesTimelineRows( } function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean { - if (a.kind !== b.kind || a.id !== b.id) return false; + if (a.kind !== b.kind || a.id !== b.id || a.continuesWorkLog !== b.continuesWorkLog) return false; switch (a.kind) { case "working": @@ -2783,8 +2804,10 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.label === bt.label ); } - case "worktree-setup": - return a.snapshot === (b as typeof a).snapshot; + case "worktree-setup": { + const bw = b as typeof a; + return a.snapshot === bw.snapshot && a.embedded === bw.embedded; + } case "assistant-meta": { const bm = b as typeof a; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 07e42d0a6542e..681424d957979 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -961,17 +961,23 @@ const ConversationTimeline = memo(function ConversationTimeline({ firstBufferedRow.getBoundingClientRect().top : state.scroll; const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll }); + // Long threads share a strip between items; it is in view if any of them is. + const stripsInView = new Map(); for (const [index, item] of minimapItems.entries()) { const strip = minimapStripMap.get(item.id); + if (!strip) continue; const inView = isTimelineMinimapTurnVisible( item.rowIndex, minimapItems[index + 1]?.rowIndex, visibleRange.start, visibleRange.end, ); + stripsInView.set(strip, inView || stripsInView.get(strip) === true); + } + for (const [strip, inView] of stripsInView) { const next = inView ? "true" : "false"; // Avoid dirtying style state on every scroll tick for unchanged strips. - if (strip && strip.dataset.inView !== next) { + if (strip.dataset.inView !== next) { strip.dataset.inView = next; } } diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 9e2b436d5552e..01ae586a0ca1b 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -6,12 +6,15 @@ import { Button } from "../ui/button"; import { resolveTimelineMinimapHeightStyle, resolveTimelineMinimapIndexFromPointer, + resolveTimelineMinimapMarkCount, + resolveTimelineMinimapMarkIndex, resolveTimelineMinimapNavigationInteractive, resolveTimelineMinimapTopPercent, TIMELINE_MINIMAP_MIN_ITEMS, } from "./MessagesTimeline.logic"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; +import { observeResize } from "~/lib/observeResize"; // A release outside the window can skip `mouseup`, so the next button-free // `mousemove` also counts. @@ -57,6 +60,15 @@ export function TimelineMinimap({ return () => node.removeEventListener("wheel", onWheel); }; + const [railHeight, setRailHeight] = useState(0); + const railRef = (node: HTMLDivElement | null) => { + if (!node) return; + setRailHeight(node.getBoundingClientRect().height); + return observeResize(node, ([entry]) => { + if (entry) setRailHeight(entry.contentRect.height); + }); + }; + const pressedOnStripRef = useRef(false); const [passThrough, setPassThrough] = useState(false); @@ -78,6 +90,18 @@ export function TimelineMinimap({ const nextItem = resolvedCurrentIndex === null || atEnd ? null : (items[resolvedCurrentIndex + 1] ?? null); + // A rail too short for every item groups neighbours onto one strip; the pointer and + // keyboard still resolve single items. + const markCount = resolveTimelineMinimapMarkCount(items.length, railHeight); + const marks: TimelineMinimapItem[][] = Array.from({ length: markCount }, () => []); + for (const [index, item] of items.entries()) { + marks[resolveTimelineMinimapMarkIndex(index, items.length, markCount)]?.push(item); + } + const activeMarkIndex = + resolvedActiveIndex === null + ? null + : resolveTimelineMinimapMarkIndex(resolvedActiveIndex, items.length, markCount); + const resolveActiveIndexFromPointer = (event: MouseEvent) => { const rect = event.currentTarget.getBoundingClientRect(); return resolveTimelineMinimapIndexFromPointer({ @@ -122,6 +146,7 @@ export function TimelineMinimap({ "absolute top-1/2 -translate-y-1/2", hitStripWidth > 0 && !passThrough ? "pointer-events-auto" : "pointer-events-none", )} + ref={railRef} onMouseDown={() => { if (pressedOnStripRef.current) return; pressedOnStripRef.current = true; @@ -191,10 +216,10 @@ export function TimelineMinimap({ onMouseDown={(event) => event.preventDefault()} type="button" > - {items.map((item, index) => { - const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`; + {marks.map((markItems, index) => { + const top = `${resolveTimelineMinimapTopPercent(index, markCount)}%`; const activeDistance = - resolvedActiveIndex === null ? null : Math.abs(index - resolvedActiveIndex); + activeMarkIndex === null ? null : Math.abs(index - activeMarkIndex); return ( // Compositor-friendly on purpose: in-view state and the hover // fisheye animate constantly (every scroll tick and streaming @@ -215,13 +240,15 @@ export function TimelineMinimap({ )} data-in-view="false" data-minimap-strip - key={item.id} + key={markItems[0]?.id ?? index} ref={(node) => { - if (node) { - stripMap.set(item.id, node); - } else { - stripMap.delete(item.id); - } + if (!node) return; + for (const item of markItems) stripMap.set(item.id, node); + return () => { + for (const item of markItems) { + if (stripMap.get(item.id) === node) stripMap.delete(item.id); + } + }; }} style={{ top }} /> diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index ceb37bcfbc8e5..2db7717dd8211 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -20,7 +20,7 @@ import { getProviderOptionCurrentLabel, getProviderOptionDescriptors, isClaudeUltrathinkPrompt, - normalizeModelSlug, + resolveSelectableModel, } from "@t3tools/shared/model"; import { msg, T, useMessages } from "gt-react"; import { memo } from "react"; @@ -129,7 +129,7 @@ function getSelectedTraits( const caps = getProviderModelCapabilities(models, model, provider, includePlanAgent); const modelIsUnavailable = keepsUnavailableModelOptions(provider, model) && - !models.some((candidate) => candidate.slug === normalizeModelSlug(model, provider)); + resolveSelectableModel(provider, model, models) === null; const descriptors = modelIsUnavailable ? buildUnavailableModelOptionDescriptors( includePlanAgent diff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx index b8d4bdad4b382..b69e499d22d75 100644 --- a/apps/web/src/components/chat/composerProviderState.tsx +++ b/apps/web/src/components/chat/composerProviderState.tsx @@ -12,7 +12,7 @@ import { getProviderOptionCurrentValue, getProviderOptionDescriptors, isClaudeUltrathinkPrompt, - normalizeModelSlug, + resolveSelectableModel, withImplicitFastModeDefault, } from "@t3tools/shared/model"; @@ -87,9 +87,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com includePlanAgent, } = input; if (keepsUnavailableModelOptions(provider, model)) { - const normalizedModel = normalizeModelSlug(model, provider); - const modelIsInCatalog = models.some((candidate) => candidate.slug === normalizedModel); - if (!modelIsInCatalog) { + if (resolveSelectableModel(provider, model, models) === null) { const preservedOptions = modelOptions?.filter( (option) => includePlanAgent || option.id !== "agent" || option.value !== "plan", ); diff --git a/apps/web/src/components/chat/markdownActionFailure.ts b/apps/web/src/components/chat/markdownActionFailure.ts index 4ecfd7ab194f1..016d831197397 100644 --- a/apps/web/src/components/chat/markdownActionFailure.ts +++ b/apps/web/src/components/chat/markdownActionFailure.ts @@ -1,4 +1,4 @@ -export type TableCopyFormat = "markdown" | "csv" | "html"; +export type TableCopyFormat = "markdown" | "csv" | "html" | "png"; interface MarkdownActionFailureContext { readonly operation: string; diff --git a/apps/web/src/components/chat/markdownFragments.ts b/apps/web/src/components/chat/markdownFragments.ts index 9acacb8c65fe2..01171ca1ac893 100644 --- a/apps/web/src/components/chat/markdownFragments.ts +++ b/apps/web/src/components/chat/markdownFragments.ts @@ -21,6 +21,11 @@ function normalizeSanitizedFragmentId(id: string): string { return normalizedId; } +export function normalizeMarkdownFragmentId(hrefOrId: string): string { + const raw = hrefOrId.startsWith("#") ? decodeMarkdownFragmentId(hrefOrId) : hrefOrId; + return normalizeSanitizedFragmentId(raw); +} + function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null { const decodedId = decodeMarkdownFragmentId(href); const normalizedId = normalizeSanitizedFragmentId(decodedId); diff --git a/apps/web/src/components/chat/tablePng.browser.test.ts b/apps/web/src/components/chat/tablePng.browser.test.ts new file mode 100644 index 0000000000000..4c0ba67c9744f --- /dev/null +++ b/apps/web/src/components/chat/tablePng.browser.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { renderTablePng } from "./tablePng"; + +const MARGIN = 16; +const BACKDROP = [12, 34, 56] as const; + +interface Pixels { + readonly width: number; + readonly height: number; + readonly origin: DOMRect; + /** Whether any pixel inside a viewport rect differs from the backdrop. */ + readonly hasInk: (rect: DOMRect) => boolean; + readonly at: (x: number, y: number) => readonly number[]; + /** Alpha of the image's last pixel. */ + readonly cornerAlpha: number; +} + +async function readPng(blob: Blob, table: HTMLTableElement): Promise { + expect(blob.type).toBe("image/png"); + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext("2d")!; + context.drawImage(bitmap, 0, 0); + const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height); + const origin = table.getBoundingClientRect(); + const scale = bitmap.width / (origin.width + MARGIN * 2); + const index = (x: number, y: number) => + (Math.round((y - origin.top + MARGIN) * scale) * bitmap.width + + Math.round((x - origin.left + MARGIN) * scale)) * + 4; + const at = (x: number, y: number) => Array.from(data.subarray(index(x, y), index(x, y) + 3)); + const hasInk = (rect: DOMRect) => { + for (let y = rect.top; y < rect.bottom; y += 1 / scale) { + for (let x = rect.left; x < rect.right; x += 1 / scale) { + const pixel = at(x, y); + if (pixel.some((channel, i) => Math.abs(channel - BACKDROP[i]!) > 24)) return true; + } + } + return false; + }; + return { + width: bitmap.width, + height: bitmap.height, + origin, + hasInk, + at, + cornerAlpha: data[data.length - 1]!, + }; +} + +/** Mounts a table over a known backdrop; disposing removes it. */ +function mountTable(cells: string, style = "") { + const host = document.createElement("div"); + host.style.cssText = `background: rgb(${BACKDROP.join(",")}); color: white; padding: 40px; font: 14px/20px sans-serif;`; + host.innerHTML = `${cells}
`; + document.body.append(host); + return { + table: host.querySelector("table")!, + [Symbol.dispose]: () => host.remove(), + }; +} + +function textRects(element: Element): DOMRect[] { + const range = document.createRange(); + range.selectNodeContents(element); + return [...range.getClientRects()]; +} + +describe("renderTablePng", () => { + it("draws the table at its layout size over the backdrop behind it", async () => { + using mounted = mountTable( + `Name`, + // A fractional height, so the canvas size is rounded. + "width: 300px; height: 40.6px", + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + expect(pixels.width).toBe(Math.floor((pixels.origin.width + MARGIN * 2) * devicePixelRatio)); + expect(pixels.height).toBe(Math.floor((pixels.origin.height + MARGIN * 2) * devicePixelRatio)); + expect(pixels.cornerAlpha).toBe(255); + + // The margin shows the backdrop, the rule keeps its color, and the empty cell stays empty. + expect(pixels.at(pixels.origin.left - MARGIN / 2, pixels.origin.top)).toEqual([...BACKDROP]); + const [nameCell, emptyCell] = table.querySelectorAll("td"); + const name = nameCell!.getBoundingClientRect(); + expect(pixels.at(name.left + name.width / 2, name.bottom - 1)).toEqual([255, 0, 0]); + expect(pixels.hasInk(textRects(nameCell!)[0]!)).toBe(true); + const empty = emptyCell!.getBoundingClientRect(); + expect(pixels.hasInk(new DOMRect(empty.left, empty.top, empty.width, empty.height - 2))).toBe( + false, + ); + }); + + it("draws every line of wrapped text where layout put it", async () => { + using mounted = mountTable( + `alpha beta gamma delta epsilon zeta eta theta iota kappadone`, + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + const lines = textRects(table.querySelector("td")!); + expect(lines.length).toBeGreaterThan(2); + for (const line of lines) expect(pixels.hasInk(line)).toBe(true); + // Nothing spills into the gap after the wrapped column. + const done = table.querySelectorAll("td")[1]!.getBoundingClientRect(); + expect(pixels.hasInk(new DOMRect(done.left, done.top, 20, done.height))).toBe(false); + }); + + it("cuts an overflowing chip with an ellipsis inside the chip", async () => { + using mounted = mountTable( + `a-very-long-file-name.tsxx`, + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + const chipElement = document.getElementById("chip")!; + const chip = chipElement.getBoundingClientRect(); + // Chromium reports the visible part of the cut text as its own, shorter rect. + const visibleRight = Math.min(...textRects(chipElement).map((rect) => rect.right)); + expect(visibleRight).toBeLessThan(chip.right - 4); + const tail = (top: number, bottom: number) => + new DOMRect(visibleRight + 1, top, chip.right - visibleRight - 1, bottom - top); + // After the last whole glyph only the ellipsis's dots remain: low on the line, not letters. + expect(pixels.hasInk(tail(chip.top, chip.top + chip.height * 0.45))).toBe(false); + expect(pixels.hasInk(tail(chip.top + chip.height * 0.45, chip.bottom))).toBe(true); + expect(pixels.hasInk(new DOMRect(chip.right, chip.top, 50, chip.height))).toBe(false); + }); + + it("clips a block's background to the box that hides its overflow", async () => { + using mounted = mountTable( + `
x`, + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + const clip = document.getElementById("clip")!.getBoundingClientRect(); + expect(pixels.at(clip.left + 30, clip.top + 10)).toEqual([255, 0, 0]); + expect(pixels.hasInk(new DOMRect(clip.right + 1, clip.top, 50, clip.height))).toBe(false); + }); + + it("draws a sprite icon from the shared symbol it points at", async () => { + const sprite = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + sprite.style.display = "none"; + sprite.innerHTML = ``; + document.body.append(sprite); + using _sprite = { [Symbol.dispose]: () => sprite.remove() }; + using mounted = mountTable( + ``, + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + const icon = document.getElementById("icon")!.getBoundingClientRect(); + expect(pixels.at(icon.left + 10, icon.top + 10)).toEqual([0, 255, 0]); + }); + + it("leaves visually hidden text out", async () => { + using mounted = mountTable( + `hidden label`, + ); + const { table } = mounted; + const pixels = await readPng(await renderTablePng(table), table); + expect(pixels.hasInk(document.getElementById("cell")!.getBoundingClientRect())).toBe(false); + }); +}); diff --git a/apps/web/src/components/chat/tablePng.ts b/apps/web/src/components/chat/tablePng.ts new file mode 100644 index 0000000000000..37275f539ce96 --- /dev/null +++ b/apps/web/src/components/chat/tablePng.ts @@ -0,0 +1,614 @@ +import { type Canvas2D, createCanvas } from "~/lib/imageCanvas"; +import { encodeCanvas } from "~/lib/imageCompression"; + +/* + * Paints a rendered table onto a canvas from the layout the browser has already computed: one + * read pass over the table (computed styles and client rects, no DOM writes), then plain canvas + * draws and an asynchronous PNG encode. Nothing is cloned, no styles are inlined, and nothing is + * laid out a second time, as an SVG snapshot would. + */ + +/** Space around the table, in CSS pixels, so the outer columns are not cut at the image edge. */ +const MARGIN = 16; +const MAX_SCALE = 3; +/** iOS Safari's canvas area limit. A larger table is drawn at a lower scale to fit. */ +const MAX_CANVAS_AREA = 16_777_216; +const MAX_CANVAS_SIDE = 16_384; +const ELLIPSIS = "…"; +/** Stands in for "no clip" on the axis an `overflow-x`/`overflow-y` box leaves visible. */ +const UNBOUNDED = 1e6; +const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; + +interface Box { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +type DrawOp = + | { kind: "fill"; box: Box; color: string; radius: number; alpha: number } + | { kind: "stroke"; box: Box; color: string; width: number; radius: number; alpha: number } + | { + kind: "text"; + text: string; + x: number; + y: number; + font: string; + color: string; + direction: CanvasDirection; + letterSpacing: string; + alpha: number; + } + | { kind: "image"; box: Box; image: Promise; alpha: number } + | { kind: "clip"; box: Box } + | { kind: "unclip" }; + +interface Ellipsis { + /** The content edge that text must not cross. */ + readonly right: number; + done: boolean; +} + +interface Scope { + readonly style: CSSStyleDeclaration; + readonly alpha: number; + /** Inside an inline-level box: painted with the text, after every block background. */ + readonly inline: boolean; + /** Decorations propagate to descendant text without being inherited in computed style. */ + readonly decorations: readonly CSSStyleDeclaration[]; + readonly ellipsis: Ellipsis | null; +} + +const PRESERVED_SPACES = /^(?:pre|pre-wrap|break-spaces)$/; + +function isTransparent(color: string): boolean { + return color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color); +} + +function isOpaque(color: string): boolean { + return !color.startsWith("rgba(") && !color.includes("/"); +} + +function canvasFont(style: CSSStyleDeclaration): string { + // Canvas fonts take a keyword for oblique, not an angle. + const fontStyle = style.fontStyle.startsWith("oblique") ? "oblique" : style.fontStyle; + return `${fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; +} + +function transformText(text: string, transform: string): string { + if (transform === "uppercase") return text.toUpperCase(); + if (transform === "lowercase") return text.toLowerCase(); + if (transform === "capitalize") + return text.replace( + /(^|\s)(\p{L})/gu, + (_, space: string, letter: string) => space + letter.toUpperCase(), + ); + return text; +} + +function cornerRadius(value: string, box: Box): number { + const radius = Number.parseFloat(value) || 0; + return value.endsWith("%") ? (Math.min(box.width, box.height) * radius) / 100 : radius; +} + +/** Replays draw ops; `images[i]` is the decoded source for an image op at index `i`. */ +function paintOps( + context: Canvas2D["context"], + scale: number, + ops: readonly DrawOp[], + images: readonly (CanvasImageSource | null)[], +): void { + context.textBaseline = "alphabetic"; + context.textAlign = "left"; + // Snaps hard edges to device pixels so 1px rules stay crisp at any scale. + const snap = (value: number) => Math.round(value * scale) / scale; + let font = ""; + for (const [index, op] of ops.entries()) { + switch (op.kind) { + case "fill": { + context.globalAlpha = op.alpha; + context.fillStyle = op.color; + if (op.radius > 0) { + context.beginPath(); + context.roundRect(op.box.x, op.box.y, op.box.width, op.box.height, op.radius); + context.fill(); + } else { + const x = snap(op.box.x); + const y = snap(op.box.y); + context.fillRect( + x, + y, + Math.max(snap(op.box.x + op.box.width) - x, 1 / scale), + Math.max(snap(op.box.y + op.box.height) - y, 1 / scale), + ); + } + break; + } + case "stroke": { + const inset = op.width / 2; + context.globalAlpha = op.alpha; + context.strokeStyle = op.color; + context.lineWidth = op.width; + context.beginPath(); + context.roundRect( + op.box.x + inset, + op.box.y + inset, + op.box.width - op.width, + op.box.height - op.width, + Math.max(op.radius - inset, 0), + ); + context.stroke(); + break; + } + case "text": { + context.globalAlpha = op.alpha; + // Parsing a font string is the costly part of a text draw; most runs share one. + if (op.font !== font) { + font = op.font; + context.font = op.font; + } + context.fillStyle = op.color; + context.direction = op.direction; + context.letterSpacing = op.letterSpacing; + context.fillText(op.text, op.x, op.y); + break; + } + case "image": { + const image = images[index]; + if (!image) break; + context.globalAlpha = op.alpha; + context.drawImage(image, op.box.x, op.box.y, op.box.width, op.box.height); + break; + } + case "clip": { + context.save(); + context.beginPath(); + context.rect(op.box.x, op.box.y, op.box.width, op.box.height); + context.clip(); + break; + } + case "unclip": { + context.restore(); + // A restore puts the saved font back too. + font = ""; + break; + } + } + } +} + +/** Copies a rendered `` (and the backdrop behind it) into a PNG. */ +export async function renderTablePng(table: HTMLTableElement): Promise { + // A detached table measures 0 x 0 and would copy an empty image over the clipboard. + if (!table.isConnected) throw new Error("The table left the page before it was drawn."); + const bounds = table.getBoundingClientRect(); + const width = bounds.width + MARGIN * 2; + const height = bounds.height + MARGIN * 2; + const scale = Math.min( + Math.max(window.devicePixelRatio || 1, 1), + MAX_SCALE, + MAX_CANVAS_SIDE / width, + MAX_CANVAS_SIDE / height, + Math.sqrt(MAX_CANVAS_AREA / (width * height)), + ); + // Rounding down keeps the canvas inside both caps; at most a pixel of margin is lost. + const surface = createCanvas( + Math.max(1, Math.floor(width * scale)), + Math.max(1, Math.floor(height * scale)), + "srgb", + ); + if (!surface) throw new Error("A canvas is unavailable for the table image."); + const { canvas, context } = surface; + + const originX = bounds.left - MARGIN; + const originY = bounds.top - MARGIN; + const toBox = (rect: DOMRect): Box => ({ + x: rect.left - originX, + y: rect.top - originY, + width: rect.width, + height: rect.height, + }); + + // CSS paints block backgrounds and borders before inline content, whatever the tree order. + const blockOps: DrawOp[] = []; + const contentOps: DrawOp[] = []; + const objectUrls: string[] = []; + const range = document.createRange(); + const fontMetrics = new Map(); + let graphemes: Intl.Segmenter | undefined; + + const metricsFor = (font: string) => { + let metrics = fontMetrics.get(font); + if (!metrics) { + context.font = font; + const measured = context.measureText("x"); + metrics = { + ascent: measured.fontBoundingBoxAscent, + descent: measured.fontBoundingBoxDescent, + }; + fontMetrics.set(font, metrics); + } + return metrics; + }; + + /** A text rect is its line box or its content area; the baseline sits the same in both. */ + const baselineIn = (rect: DOMRect, font: string) => { + const { ascent, descent } = metricsFor(font); + return rect.top - originY + (rect.height - ascent - descent) / 2 + ascent; + }; + + const paintBox = (rect: DOMRect, style: CSSStyleDeclaration, alpha: number, ops: DrawOp[]) => { + const box = toBox(rect); + if (box.width <= 0 || box.height <= 0) return; + const radius = cornerRadius(style.borderTopLeftRadius, box); + if (!isTransparent(style.backgroundColor)) { + ops.push({ kind: "fill", box, color: style.backgroundColor, radius, alpha }); + } + const sides = (["Top", "Right", "Bottom", "Left"] as const).map((side) => ({ + side, + width: + style[`border${side}Style`] === "none" || style[`border${side}Style`] === "hidden" + ? 0 + : Number.parseFloat(style[`border${side}Width`]) || 0, + color: style[`border${side}Color`], + })); + const [first] = sides; + if ( + radius > 0 && + first && + sides.every((side) => side.width === first.width && side.color === first.color) + ) { + if (first.width > 0 && !isTransparent(first.color)) { + ops.push({ kind: "stroke", box, color: first.color, width: first.width, radius, alpha }); + } + return; + } + for (const { side, width: lineWidth, color } of sides) { + if (lineWidth <= 0 || isTransparent(color)) continue; + const edge: Box = + side === "Top" + ? { ...box, height: lineWidth } + : side === "Bottom" + ? { ...box, y: box.y + box.height - lineWidth, height: lineWidth } + : side === "Left" + ? { ...box, width: lineWidth } + : { ...box, x: box.x + box.width - lineWidth, width: lineWidth }; + ops.push({ kind: "fill", box: edge, color, radius: 0, alpha }); + } + }; + + const pushText = (text: string, rect: DOMRect, scope: Scope) => { + const { style } = scope; + const font = canvasFont(style); + contentOps.push({ + kind: "text", + text: transformText(text, style.textTransform), + x: rect.left - originX, + y: baselineIn(rect, font), + font, + color: style.color, + direction: style.direction === "rtl" ? "rtl" : "ltr", + letterSpacing: style.letterSpacing === "normal" ? "0px" : style.letterSpacing, + alpha: scope.alpha, + }); + }; + + /** A word broken across lines is drawn one line at a time. */ + const pushBrokenWord = (node: Text, offset: number, word: string, scope: Scope) => { + graphemes ??= new Intl.Segmenter(undefined, { granularity: "grapheme" }); + let run = ""; + let runRect: DOMRect | null = null; + for (const { segment, index } of graphemes.segment(word)) { + range.setStart(node, offset + index); + range.setEnd(node, offset + index + segment.length); + const rect = range.getBoundingClientRect(); + if (runRect && Math.abs(rect.top - runRect.top) < 1) { + run += segment; + continue; + } + if (runRect && run) pushText(run, runRect, scope); + run = segment; + runRect = rect; + } + if (runRect && run) pushText(run, runRect, scope); + }; + + /** Draws the longest prefix that fits before the ellipsis, as `text-overflow` does. */ + const pushTruncated = (node: Text, start: number, end: number, scope: Scope, right: number) => { + context.font = canvasFont(scope.style); + const limit = right - context.measureText(ELLIPSIS).width; + range.setStart(node, start); + let low = start; + let high = end; + let fitRight = 0; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + range.setEnd(node, middle); + const rect = range.getBoundingClientRect(); + if (rect.right <= limit) { + low = middle; + fitRight = rect.right; + } else { + high = middle - 1; + } + } + // Never end on half of a surrogate pair. + if (low > start && /[\uD800-\uDBFF]/.test(node.data[low - 1] ?? "")) low -= 1; + range.setEnd(node, Math.max(low, start + 1)); + const lineRect = range.getBoundingClientRect(); + const text = node.data.slice(start, low).trimEnd(); + if (text) pushText(text, lineRect, scope); + else fitRight = lineRect.left; + const markRect = new DOMRect(fitRight, lineRect.top, 0, lineRect.height); + pushText(ELLIPSIS, markRect, scope); + }; + + const pushDecorations = (rects: DOMRectList, scope: Scope) => { + if (!scope.decorations.length) return; + const font = canvasFont(scope.style); + const fontSize = Number.parseFloat(scope.style.fontSize) || 16; + const { ascent } = metricsFor(font); + for (const decoration of scope.decorations) { + const thickness = Math.max( + 1, + Number.parseFloat(decoration.textDecorationThickness) || fontSize / 16, + ); + const lines = decoration.textDecorationLine.split(" "); + for (const rect of rects) { + const baseline = baselineIn(rect, font); + for (const line of lines) { + const y = + line === "underline" + ? baseline + fontSize * 0.1 + : line === "line-through" + ? baseline - fontSize * 0.28 + : line === "overline" + ? baseline - ascent + : null; + if (y === null) continue; + contentOps.push({ + kind: "fill", + box: { + x: rect.left - originX, + y: y - thickness / 2, + width: rect.width, + height: thickness, + }, + color: decoration.textDecorationColor, + radius: 0, + alpha: scope.alpha, + }); + } + } + } + }; + + const visitText = (node: Text, scope: Scope) => { + const { style } = scope; + if (style.visibility !== "visible") return; + const data = node.data; + const start = data.search(/\S/); + if (start < 0) return; + const end = data.trimEnd().length; + range.setStart(node, start); + range.setEnd(node, end); + const rects = range.getClientRects(); + const [firstRect] = rects; + if (!firstRect) return; + const { ellipsis } = scope; + if (ellipsis?.done) return; + + const slice = data.slice(start, end); + const text = PRESERVED_SPACES.test(style.whiteSpace) + ? slice + : slice.replace(/[ \t\n\r\f]+/g, " "); + // Chromium adds a rect for the part an ellipsis leaves visible, so a cut line has two. + if ( + ellipsis && + style.direction !== "rtl" && + [...rects].some((rect) => rect.right > ellipsis.right + 0.5) && + [...rects].every((rect) => Math.abs(rect.top - firstRect.top) < 1) + ) { + ellipsis.done = true; + pushTruncated(node, start, end, scope, ellipsis.right); + } else if (rects.length === 1 && !/[\t\n\r\f]/.test(text)) { + pushText(text, firstRect, scope); + } else { + // Wrapped lines, bidi runs, and tabs: place each word where layout put it. + for (const match of slice.matchAll(/\S+/g)) { + const wordStart = start + match.index; + range.setStart(node, wordStart); + range.setEnd(node, wordStart + match[0].length); + const wordRects = range.getClientRects(); + const [wordRect] = wordRects; + if (!wordRect) continue; + if (wordRects.length === 1) pushText(match[0], wordRect, scope); + else pushBrokenWord(node, wordStart, match[0], scope); + } + } + pushDecorations(rects, scope); + }; + + const visitSvg = (svg: SVGSVGElement, style: CSSStyleDeclaration, alpha: number) => { + const rect = svg.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + const clone = svg.cloneNode(true) as SVGSVGElement; + // Sprite icons point at a shared elsewhere in the document; carry it along. + const defs = document.createElementNS(svg.namespaceURI, "defs"); + const copied = new Set(); + const pending = [...clone.querySelectorAll("use")]; + for (let use = pending.pop(); use; use = pending.pop()) { + const href = use.getAttribute("href") ?? use.getAttributeNS(XLINK_NAMESPACE, "href"); + const id = href?.startsWith("#") ? href.slice(1) : null; + if (!id || copied.has(id) || svg.querySelector(`#${CSS.escape(id)}`)) continue; + const target = document.getElementById(id); + if (!target) continue; + copied.add(id); + const copy = target.cloneNode(true) as Element; + defs.append(copy); + pending.push(...copy.querySelectorAll("use")); + } + if (copied.size) clone.prepend(defs); + if (!clone.hasAttribute("viewBox")) { + clone.setAttribute("viewBox", `0 0 ${rect.width} ${rect.height}`); + } + // Rasterize at the output scale so icons stay sharp. + clone.setAttribute("width", String(rect.width * scale)); + clone.setAttribute("height", String(rect.height * scale)); + clone.style.color = style.color; + const url = URL.createObjectURL( + new Blob([new XMLSerializer().serializeToString(clone)], { type: "image/svg+xml" }), + ); + objectUrls.push(url); + const image = new Image(); + image.src = url; + contentOps.push({ + kind: "image", + box: toBox(rect), + image: image.decode().then( + () => image, + () => null, + ), + alpha, + }); + }; + + const visitImage = (image: HTMLImageElement, style: CSSStyleDeclaration, alpha: number) => { + if (!image.complete || image.naturalWidth === 0) return; + // A cross-origin image would taint the canvas and fail the whole encode, so test it alone. + const probe = createCanvas(1, 1, "srgb"); + try { + probe?.context.drawImage(image, 0, 0, 1, 1); + probe?.context.getImageData(0, 0, 1, 1); + } catch { + return; + } + const rect = image.getBoundingClientRect(); + const inset = (side: "Top" | "Right" | "Bottom" | "Left") => + (Number.parseFloat(style[`border${side}Width`]) || 0) + + (Number.parseFloat(style[`padding${side}`]) || 0); + const box = toBox(rect); + contentOps.push({ + kind: "image", + box: { + x: box.x + inset("Left"), + y: box.y + inset("Top"), + width: box.width - inset("Left") - inset("Right"), + height: box.height - inset("Top") - inset("Bottom"), + }, + image: Promise.resolve(image), + alpha, + }); + }; + + const visitElement = (element: Element, parent: Scope | null) => { + const style = getComputedStyle(element); + // Clipping hides visually hidden labels; other clip shapes are skipped too. + const clipRect = style.getPropertyValue("clip"); + if ( + style.display === "none" || + style.clipPath !== "none" || + (clipRect !== "" && clipRect !== "auto") + ) { + return; + } + const alpha = (parent?.alpha ?? 1) * (Number.parseFloat(style.opacity) || 0); + if (alpha <= 0) return; + const visible = style.visibility === "visible"; + if (element instanceof SVGSVGElement) { + if (visible) visitSvg(element, style, alpha); + return; + } + // Shapes inside an SVG belong to its root; MathML still descends to its text. + if (element instanceof SVGElement) return; + if (element instanceof HTMLImageElement) { + if (visible) visitImage(element, style, alpha); + return; + } + + const inline = (parent?.inline ?? false) || style.display.startsWith("inline"); + if (visible) { + for (const rect of element.getClientRects()) { + paintBox(rect, style, alpha, inline ? contentOps : blockOps); + } + } + + const clipsX = style.overflowX !== "visible"; + const clipsY = style.overflowY !== "visible"; + let clip: Box | null = null; + let ellipsis = parent?.ellipsis ?? null; + if (clipsX || clipsY) { + const box = toBox(element.getBoundingClientRect()); + const left = box.x + (Number.parseFloat(style.borderLeftWidth) || 0); + const top = box.y + (Number.parseFloat(style.borderTopWidth) || 0); + const right = box.x + box.width - (Number.parseFloat(style.borderRightWidth) || 0); + const bottom = box.y + box.height - (Number.parseFloat(style.borderBottomWidth) || 0); + clip = { + x: clipsX ? left : -UNBOUNDED, + y: clipsY ? top : -UNBOUNDED, + width: clipsX ? right - left : UNBOUNDED * 2, + height: clipsY ? bottom - top : UNBOUNDED * 2, + }; + // Both passes: a clipped block's descendants can be block-level boxes too. + blockOps.push({ kind: "clip", box: clip }); + contentOps.push({ kind: "clip", box: clip }); + if (clipsX && style.textOverflow === "ellipsis") { + const contentRight = right - (Number.parseFloat(style.paddingRight) || 0); + ellipsis = { right: contentRight + originX, done: false }; + } + } + const scope: Scope = { + style, + alpha, + inline, + decorations: + style.textDecorationLine === "none" + ? (parent?.decorations ?? []) + : [...(parent?.decorations ?? []), style], + ellipsis, + }; + for (const child of element.childNodes) { + if (child instanceof Element) visitElement(child, scope); + else if (child instanceof Text) visitText(child, scope); + } + if (clip) { + blockOps.push({ kind: "unclip" }); + contentOps.push({ kind: "unclip" }); + } + }; + + // The backdrop: the nearest opaque background behind the table and every layer above it. + const backdrops: string[] = []; + for (let element = table.parentElement; element; element = element.parentElement) { + const color = getComputedStyle(element).backgroundColor; + if (isTransparent(color)) continue; + backdrops.push(color); + if (isOpaque(color)) break; + } + + visitElement(table, null); + try { + const images = await Promise.all( + contentOps.map((op) => (op.kind === "image" ? op.image : null)), + ); + + // In device pixels: the canvas rounds its size, and a scaled fill could leave its last row half covered. + context.fillStyle = "#fff"; + context.fillRect(0, 0, canvas.width, canvas.height); + for (const color of backdrops.toReversed()) { + context.fillStyle = color; + context.fillRect(0, 0, canvas.width, canvas.height); + } + context.scale(scale, scale); + paintOps(context, scale, blockOps, []); + paintOps(context, scale, contentOps, images); + + // A worker encode: Chromium runs main-thread encodes as idle tasks, ~1 s on a busy page. + const blob = await encodeCanvas(canvas, "srgb", 1, "image/png"); + if (!blob) throw new Error("The table image could not be encoded."); + return blob; + } finally { + for (const url of objectUrls) URL.revokeObjectURL(url); + } +} diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts index 0e498cef85d9c..dd1e0020ace9e 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.test.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -79,6 +79,24 @@ describe("resolveTimelineMinimapPreview", () => { ); }); + it("runs a tight list item's inline text together, as in a paragraph", () => { + const preview = resolveTimelineMinimapPreview({ + id: "turn-1", + rowIndex: 0, + userText: null, + assistantText: + "Done:\n\n- **Cache**: warm on start.\n- Run `vp test`, then [ship](https://example.com/ship).", + }); + expect(preview?.assistantText).toBe("Done: Cache: warm on start. Run vp test, then ship."); + const nested = resolveTimelineMinimapPreview({ + id: "turn-1", + rowIndex: 0, + userText: null, + assistantText: "- **One**\n - two\n\n three\n- ```\n four\n ```", + }); + expect(nested?.assistantText).toBe("One two three four"); + }); + it("does not split a surrogate pair at the preview slice boundary", () => { const linkStart = "[Build log](https://example.com/builds/1042/log?sig="; const linkEnd = ") "; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index fc7f79bb8e440..8d9734319c2fa 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -61,8 +61,10 @@ function resolveFinalAssistantTextForTurn( } // Elements whose children run together; every other element is separated by a space. +// A tight list item holds its text bare, without the paragraph a loose one wraps it in. const INLINE_PARENTS = new Set([ "p", + "li", "h1", "h2", "h3", diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index e99d02a24b4dc..e09bde48e406f 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1796,6 +1796,13 @@ export function useComposerSend(input: ComposerSendInput) { }; const onSendLatest = useStableCallback(onSend); + const reportDraftChangedBeforeSend = () => { + if (currentRouteThreadKeyRef.current !== routeThreadKey || !activeThread) return; + setThreadError( + activeThread.id, + m(msg("Draft changed while preparing this message. Review it and send again.")), + ); + }; const waitBeforeSend = async (pending: Promise) => { const finishWatching = watchComposerSendEdits(composerDraftTarget); const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey); @@ -1816,12 +1823,7 @@ export function useComposerSend(input: ComposerSendInput) { ? "edited" : watchedStatus; const sameRoute = currentRouteThreadKeyRef.current === routeThreadKey; - if (draftStatus === "edited" && sameRoute && activeThread) { - setThreadError( - activeThread.id, - m(msg("Draft changed while preparing this message. Review it and send again.")), - ); - } + if (draftStatus === "edited") reportDraftChangedBeforeSend(); return { result, draftReady: draftStatus === "ready", sameRoute }; }; const sendWithEnvironmentRefresh = async (...args: Parameters) => { @@ -1839,8 +1841,9 @@ export function useComposerSend(input: ComposerSendInput) { const workspaceDefault = draftId && !sendInFlightRef.current ? readPendingWorkspaceDefault(draftId) : null; if (workspaceDefault === null) return sendWithEnvironmentRefresh(...args); - const { draftReady, sameRoute } = await waitBeforeSend(workspaceDefault); - if (!draftReady || !sameRoute) return; + const { result, draftReady, sameRoute } = await waitBeforeSend(workspaceDefault); + if (result === "moved") reportDraftChangedBeforeSend(); + if (result === false || result === "moved" || !draftReady || !sameRoute) return; return sendWithEnvironmentRefreshLatest(...args); }; // No load-balancing refresh: it bails once the draft is no longer displayed, which is the diff --git a/apps/web/src/components/chat/usePasteToFocusComposer.ts b/apps/web/src/components/chat/usePasteToFocusComposer.ts index 84672cc570c56..1f34f20aa47d0 100644 --- a/apps/web/src/components/chat/usePasteToFocusComposer.ts +++ b/apps/web/src/components/chat/usePasteToFocusComposer.ts @@ -1,5 +1,4 @@ import { pasteTextToFocusComposer, shouldRedirectInputToComposer } from "./composerFocusRedirect"; -import { readPastedComposerContext } from "../composerInlineTokenPaste"; import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { useEffect, useRef } from "react"; import { isMacPlatform } from "../../lib/utils"; @@ -37,11 +36,7 @@ export function usePasteToFocusComposer( if (text === null || clipboardData === null) return; const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current; pasteAsTextShortcutUntilRef.current = 0; - if ( - ((readPastedComposerContext(clipboardData)?.records.length ?? 0) === 0 && - composerRef.current?.pasteTextAtEnd(text, { bypassAutoAttachment })) || - composerRef.current?.insertTextAtEnd(text, { clipboardData }) - ) { + if (composerRef.current?.pasteTextAtEnd(clipboardData, { bypassAutoAttachment })) { event.preventDefault(); event.stopPropagation(); } diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index efb7f5c1701c0..5182862e81023 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -30,8 +30,7 @@ import { isBrowserSettingsReadError } from "../../browser/openFileInPreview"; import { addBrowserSurface } from "../preview/addBrowserSurface"; import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus"; import { subscribePreviewAction } from "../preview/previewActionBus"; -import { floatDeviceSurface } from "../preview/agentOpenedPreviews"; -import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore"; +import { floatBrowserSurface, floatDeviceSurface } from "../preview/agentOpenedPreviews"; import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic"; import type { useDeviceState } from "../../state/device"; import { stackedThreadToast, toastManager } from "../ui/toast"; @@ -65,7 +64,6 @@ interface RightPanelActionsInput { readonly gitCwd: string | null; readonly activeProjectCwd: string | null; readonly onDiffPanelOpen: (() => void) | undefined; - readonly closeRightPanelSurface: (surface: RightPanelSurface) => void; } /** @@ -74,7 +72,6 @@ interface RightPanelActionsInput { */ export function useRightPanelActions(input: RightPanelActionsInput) { const { - closeRightPanelSurface, activeThreadRef, activeProject, activeRightPanelSurface, @@ -102,9 +99,6 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const onToggleDiff = () => { - if (!isServerThread) { - return; - } if (!diffOpen) { onDiffPanelOpen?.(); } @@ -142,7 +136,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const duplicateBrowserSurfaceStable = useStableCallback(duplicateBrowserSurface); const createBrowserSurfaceStable = useStableCallback(createBrowserSurface); const addDiffSurface = () => { - if (!activeThreadRef || !isServerThread || !diffAvailable) return; + if (!activeThreadRef || !diffAvailable) return; useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch"); useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); @@ -179,9 +173,11 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const closePreviewPanel = () => { if (activeThreadRef) { if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) { - usePreviewMiniPlayerStore - .getState() - .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId)); + floatBrowserSurface( + activeThreadRef, + activeRightPanelSurface.resourceId, + activePreviewState, + ); } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) { floatDeviceSurface( activeThreadRef, @@ -269,11 +265,11 @@ export function useRightPanelActions(input: RightPanelActionsInput) { useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized); }; const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized); - const moveRightPanelSurface = (surfaceId: string, toIndex: number) => { + const moveRightPanelSurfaces = (surfaceIds: readonly string[], targetId: string) => { if (activeThreadRef) - useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex); + useRightPanelStore.getState().moveSurfaces(activeThreadRef, surfaceIds, targetId); }; - const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface); + const moveRightPanelSurfacesStable = useStableCallback(moveRightPanelSurfaces); const copyRightPanelFilePath = (relativePath: string) => { if (typeof window === "undefined" || !navigator.clipboard?.writeText) { toastManager.add( @@ -330,10 +326,6 @@ export function useRightPanelActions(input: RightPanelActionsInput) { if (!event.repeat) toggleRightPanelMaximized(); }, "threadPanel.toggle": () => toggleThreadPanel(), - "rightPanel.close": ({ event }) => { - if (!activeRightPanelSurface) return false; - if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface); - }, "diff.toggle": () => onToggleDiff(), } satisfies ChatShortcutCommands; @@ -350,7 +342,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { createBrowserSurface, createBrowserSurfaceStable, duplicateBrowserSurfaceStable, - moveRightPanelSurfaceStable, + moveRightPanelSurfacesStable, onOpenToolDiffStable, onToggleDiffStable, openChangesFromThreadPanelStable, diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index d201cd3adc71a..84697e144e374 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -7,15 +7,14 @@ import { import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; -import { importPastedComposerText } from "./composerInlineTokenPaste"; +import { importPastedComposerText, readPastedComposerClipboard } from "./composerInlineTokenPaste"; const thread = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("thread-1"), }; -const clipboard = (data: Record) => ({ - getData: (type: string) => data[type] ?? "", -}); +const clipboard = (data: Record) => + readPastedComposerClipboard({ getData: (type) => data[type] ?? "" }); const chip = (title: string) => `[${title}](t3-context://v1/thread/${threadContextRecord(thread, title).contextId})`; @@ -48,15 +47,28 @@ describe("importPastedComposerText", () => { importAll([]), ); expect(text).toBe(chip("Login")); + const withBrackets = clipboard({ + "text/plain": String.raw`[Fix \[login\]](t3-thread://v2/env-1/thread-1)`, + }); + expect(importPastedComposerText(withBrackets, importAll([]))).toBe(chip("Fix login")); }); it("keeps the link when the composer cannot take the thread", () => { - const pasted = "https://app.t3.codes/threads/env-1/thread-1"; + const pasted = ""; expect(importPastedComposerText(clipboard({ "text/plain": pasted }), () => new Map())).toBe( pasted, ); }); + it("drops a leading BOM so a fenced link example stays literal and the link after it a chip", () => { + const fenced = "~~~\n\n~~~"; + const text = importPastedComposerText( + clipboard({ "text/plain": `\uFEFF${fenced}\n` }), + importAll([]), + ); + expect(text).toBe(`${fenced}\n${chip("Thread")}`); + }); + it("imports CRLF and CR clipboard text with LF line breaks", () => { expect( importPastedComposerText(clipboard({ "text/plain": "x\r\n\r\ny\rz" }), () => new Map()), diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 0e1a84aa71af2..1ff492401b53a 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -16,37 +16,41 @@ import { threadLinkContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { restorePastedMarkdownLinks } from "~/markdown-clipboard"; import { readThreadShell } from "~/state/entities"; const threadTitle = (ref: ScopedThreadRef) => readThreadShell(ref)?.title; -// Matches ProseMirror's default clipboard parser, which a custom handlePaste bypasses. +// Matches ProseMirror's default clipboard parser, which a custom handlePaste bypasses. A leading +// BOM is not content, and kept it would stop a first-line fence from opening a code block. export function readPastedPlainText(clipboardData: Pick): string { - return clipboardData.getData("text/plain").replace(/\r\n?/g, "\n"); + return clipboardData + .getData("text/plain") + .replace(/^\uFEFF/, "") + .replace(/\r\n?/g, "\n"); } -/** Pasted thread links count as context too, so they become chips like a copied chip does. */ -export function readPastedComposerContext( +export function readPastedComposerClipboard( clipboardData: Pick, -): ComposerContextClipboardFragment | null { - const pastedText = clipboardData.getData("text/plain"); - const decodedFragment = + plainTextOnly = false, +) { + const plain = readPastedPlainText(clipboardData); + if (plainTextOnly || !plain) return { text: plain, context: null }; + const html = clipboardData.getData("text/html"); + const text = restorePastedMarkdownLinks(plain, html); + const copied = decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ?? - decodeComposerContextClipboardHtml(clipboardData.getData("text/html")); - const threads = threadLinkContextReferences( - pastedText, - decodedFragment?.records ?? [], - threadTitle, - ); + decodeComposerContextClipboardHtml(html); + const threads = threadLinkContextReferences(text, copied?.records ?? [], threadTitle); const source = - decodedFragment?.source ?? + copied?.source ?? (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null); - if (source === null) return null; + if (source === null) return { text, context: null }; const pastedIds = new Set( collectComposerContextReferences(threads.text).map((occurrence) => occurrence.contextId), ); const records = new Map(); - for (const record of [...(decodedFragment?.records ?? []), ...threads.records]) { + for (const record of [...(copied?.records ?? []), ...threads.records]) { if ( record.kind === "preview-annotation" && !("payload" in record) && @@ -57,23 +61,24 @@ export function readPastedComposerContext( } records.set(record.contextId, record); } - return { + const context: ComposerContextClipboardFragment = { version: 1, source, records: [...records.values()].filter((record) => pastedIds.has(record.contextId)), }; + return { text, context }; } +export type PastedComposerClipboard = ReturnType; + export function importPastedComposerText( - clipboardData: Pick, + { text: pastedText, context: fragment }: PastedComposerClipboard, importContextFragment?: ( fragment: ComposerContextClipboardFragment, ) => ReadonlyMap, ): string { - const pastedText = readPastedPlainText(clipboardData); - const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null; const rewrittenIds = - fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null; + fragment && fragment.records.length > 0 ? importContextFragment?.(fragment) : null; if (!rewrittenIds || rewrittenIds.size === 0) return pastedText; const nextId = (contextId: string) => { const id = rewrittenIds.get(contextId); diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 260583c8f2f79..3cd65800545a3 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -82,10 +82,10 @@ import JSZip from "jszip"; import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip"; import BinaryViewer from "./BinaryViewer"; import { decodeImagePreview } from "./decodeImagePreview"; -import type { BinaryWorkerResult } from "./binaryPreviewProtocol"; +import { formatArchiveModifiedDate, type BinaryWorkerResult } from "./binaryPreviewProtocol"; import type { TextPreviewResult } from "./largeTextProtocol"; import type { ReactElement } from "react"; -import type { OfficeWorkerResult } from "./officePreviewProtocol"; +import type { OfficeWorkerRequest, OfficeWorkerResult } from "./officePreviewProtocol"; import { previewErrorText } from "./previewFailureMessages"; // Real worker imports and WASM initialization can exceed waitFor's default second @@ -238,8 +238,8 @@ describe("bounded binary previews", () => { } }); - it("names archive folders whose paths have leading or repeated slashes", async () => { - const bytes = new Uint8Array(2048); + it("names archive folders whose paths have leading slashes, repeated slashes or ./", async () => { + const bytes = new Uint8Array(3072); const write = (offset: number, value: string) => bytes.set(new TextEncoder().encode(value), offset); const member = (offset: number, name: string, content: string) => { @@ -259,6 +259,8 @@ describe("bounded binary previews", () => { }; member(0, "/a//hello.txt", "nested hello"); member(1024, "a/hello.txt", "plain hello"); + // `tar cf x.tar .` names every member from "./". + member(2048, "./a/dot.txt", "dot hello"); const src = URL.createObjectURL(new Blob([bytes])); try { await using screen = await render(); @@ -271,14 +273,17 @@ describe("bounded binary previews", () => { const preview = () => screen.container.querySelector("pre")?.textContent; await vi.waitFor(() => expect(rows()).toEqual(["a"]), 10_000); await act(() => buttons()[0]!.click()); - await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); - await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(rows()).toEqual(["dot.txt", "hello.txt", "hello.txt"])); + await act(() => buttons()[1]!.click()); await vi.waitFor(() => expect(preview()).toContain("nested hello"), 10_000); await act(() => back().click()); - await act(() => buttons()[1]!.click()); + await act(() => buttons()[2]!.click()); await vi.waitFor(() => expect(preview()).toContain("plain hello"), 10_000); await act(() => back().click()); - await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(preview()).toContain("dot hello"), 10_000); + await act(() => back().click()); + await vi.waitFor(() => expect(rows()).toEqual(["dot.txt", "hello.txt", "hello.txt"])); const parent = () => screen.container.querySelector('[aria-label="Parent folder"]')!; await act(() => parent().click()); @@ -316,6 +321,32 @@ describe("bounded binary previews", () => { } }); + it("dates an archive folder by its own ZIP record when its children come first", async () => { + const zip = new JSZip(); + const fileDate = new Date("2022-01-02T00:00:00Z"); + zip.file("docs/readme.txt", "a".repeat(1024), { createFolders: false, date: fileDate }); + zip.file("docs/sub/nested.txt", "b".repeat(1024), { createFolders: false, date: fileDate }); + zip.file("docs/", null, { dir: true, date: new Date("2024-10-19T00:00:00Z") }); + zip.file("docs/sub/", null, { dir: true, date: new Date("2023-07-08T00:00:00Z") }); + zip.file("docs/later.txt", "c".repeat(1024), { + createFolders: false, + date: new Date("2025-05-06T00:00:00Z"), + }); + const src = URL.createObjectURL(new Blob([await zip.generateAsync({ type: "arraybuffer" })])); + try { + await using screen = await render(); + await vi.waitFor(() => { + expect( + [...screen.container.querySelectorAll("tbody td")].map((cell) => + cell.textContent?.trim(), + ), + ).toEqual(["docs", "3 KB", formatArchiveModifiedDate("2024-10-19T00:00:00.000")]); + }, 10_000); + } finally { + URL.revokeObjectURL(src); + } + }); + it("uses a PAX size override for the following TAR payload and bounds it", async () => { const archive = (size: string) => { const header = (name: string, size: number, type: string) => { @@ -1665,9 +1696,9 @@ it.each(["archive", "sqlite"] as const)( ); it("loads a font attachment through the lazy preview", async () => { - const { default: fontUrl } = - await import("../../../node_modules/@betteroffice/fonts/assets/Carlito-Regular.ttf?url"); - const file = await (await fetch(fontUrl)).blob(); + const { loadBundledFontBytes, resolveBundledFamilyFace } = await import("@betteroffice/fonts"); + const bytes = await loadBundledFontBytes(resolveBundledFamilyFace("Carlito", false, false)!); + const file = new Blob([bytes], { type: "font/ttf" }); await using screen = await render( ((resolve) => + worker.addEventListener( + "message", + (event: MessageEvent) => resolve(event.data), + { once: true }, + ), + ); + worker.postMessage(request, transfer); + return response; +} + it.each(["rtf", "epub", "ods"] as const)( "preserves %s document text through the worker and attachment viewer", async (kind) => { @@ -2173,32 +2220,20 @@ it.each(["rtf", "epub", "ods"] as const)( type: "module", }); try { - const result = await new Promise((resolve) => { - worker.addEventListener( - "message", - (event: MessageEvent) => resolve(event.data), - { once: true }, - ); - worker.postMessage({ type: "open", kind, bytes }, [bytes]); - }); + const result = await officeWorkerReply(worker, { type: "open", kind, bytes }, [bytes]); if (kind === "ods") { expect(result.type).toBe("ods"); if (result.type !== "ods") throw new Error("Expected spreadsheet"); expect(result.sheets[0]!.rows).toEqual([["North", "150"]]); - } else { + } else if (kind !== "epub") { expect(result.type).toBe("document"); if (result.type !== "document") throw new Error("Expected document"); const body = new DOMParser().parseFromString(result.pages[0]!.html, "text/html").body; - if (kind === "epub") { - expect(body.querySelectorAll("br")).toHaveLength(2); - expect(body.querySelectorAll("hr")).toHaveLength(1); - } else { - expect(body.textContent).toContain("10–20 —•‘a’“b”"); - expect(body.textContent).toContain("Name\tValue\t12\t34\t"); - expect(body.textContent).toContain("Unicode:–end"); - expect(body.textContent).not.toContain("hidden"); - expect(body.querySelectorAll("br")).toHaveLength(3); - } + expect(body.textContent).toContain("10–20 —•‘a’“b”"); + expect(body.textContent).toContain("Name\tValue\t12\t34\t"); + expect(body.textContent).toContain("Unicode:–end"); + expect(body.textContent).not.toContain("hidden"); + expect(body.querySelectorAll("br")).toHaveLength(3); } } finally { worker.terminate(); @@ -2233,6 +2268,284 @@ it.each(["rtf", "epub", "ods"] as const)( }, ); +it("renders EPUB publisher styles and follows an anchored link to a fixed-layout section", async () => { + const archive = new JSZip() + .file("META-INF/container.xml", '') + .file( + "OPS/book.opf", + ` + + + + + + + + + + + `, + ) + .file( + "OPS/nav.xhtml", + ` + + `, + ) + .file( + "OPS/front.xhtml", + ` + +
+

Opening

+      npm test
See illustration + ExternalUnsafeLegacy link +

Figure See table for details.

+ x2 + a + bc + x + + Illustration +

Fallback text

+
+
Worksheet + + + + + + +
+ +
Value
+ + + + + `, + ) + .file( + "OPS/styles/book.css", + `@import "accent.css"; + @namespace epub "http://www.idpf.org/2007/ops"; + section[epub|type="chapter"] { background-image: url("../illustration.svg"); } + #opening { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg=="); }`, + ) + .file("OPS/styles/accent.css", "\uFEFF#opening { color: rgb(30, 45, 60); }") + .file( + "OPS/illustration.svg", + ` + + + + + + + `, + ) + .file("OPS/styles/poster.css", "#poster { fill: rgb(230, 200, 12); }") + .file( + "OPS/art.xhtml", + ` + + More illustrations`, + ); + const file = await archive.generateAsync({ type: "blob" }); + await using screen = await render( +
+ +
, + ); + function frame() { + return screen.container.querySelector("iframe"); + } + // The cold worker parse takes most of a second; wait for the frame's onLoad pass before asserting. + await vi.waitFor( + () => { + const doc = frame()?.contentDocument; + expect(doc?.body.dir).toBe("rtl"); + expect(doc?.querySelector("epub-nested-link")).toBeNull(); + }, + { timeout: 10_000 }, + ); + await vi.waitFor(() => { + const doc = frame()?.contentDocument; + expect(doc?.querySelector("pre")?.textContent).toBe("\n npm test"); + expect(doc?.getElementById("pagebreak")?.textContent).toBe(""); + const caption = doc?.querySelector("#caption > a"); + expect(caption?.textContent).toBe("Figure See table for details."); + expect(caption?.querySelector("big")?.textContent).toBe("Figure"); + expect(caption?.querySelector("a")?.getAttribute("data-epub-anchor")).toBe("figure"); + expect(doc?.querySelector('a[href="#"][aria-disabled="true"]')?.textContent).toBe( + "Legacy link", + ); + const table = doc?.querySelector("table"); + const cell = table?.querySelector("td"); + expect(table?.querySelector(":scope > tr > td")).toBe(cell); + expect(doc!.defaultView!.getComputedStyle(table!).borderSpacing).toBe("0px"); + const cellStyle = doc!.defaultView!.getComputedStyle(cell!); + expect(cellStyle.paddingTop).toBe("0px"); + expect(cellStyle.textAlign).toMatch(/center$/); + expect(cellStyle.verticalAlign).toBe("top"); + expect(doc?.querySelector("mfrac")?.namespaceURI).toBe("http://www.w3.org/1998/Math/MathML"); + expect( + Array.from(doc?.querySelectorAll("#interval mo") ?? [], (operator) => operator.textContent), + ).toEqual(["[", ";", ";", "]"]); + const tupleFences = Array.from(doc?.querySelectorAll("#tuple > mo") ?? []); + expect(tupleFences.map((operator) => operator.textContent)).toEqual(["⟨", "⟩"]); + for (const fence of tupleFences) expect(fence.getBoundingClientRect().width).toBeGreaterThan(0); + const videos = doc?.querySelectorAll("video"); + expect(videos?.[0]?.getAttribute("preload")).toBeNull(); + expect(videos?.[0]?.autoplay).toBe(false); + expect(videos?.[1]?.preload).toBe("metadata"); + expect(doc?.querySelector("object")).toBeNull(); + expect(doc?.querySelector("#object-fallback")?.textContent).toBe("Fallback text"); + const illustration = doc?.querySelector("img#illustrated-object"); + expect(illustration?.alt).toBe("Illustration"); + expect(illustration?.naturalWidth).toBeGreaterThan(0); + const workbook = doc?.querySelector("#workbook"); + expect(workbook?.querySelector("legend")?.textContent).toBe("Worksheet"); + expect(workbook?.hasAttribute("action")).toBe(false); + expect(workbook?.hasAttribute("onsubmit")).toBe(false); + const answer = workbook?.querySelector("#answer"); + expect(answer?.labels?.[0]?.textContent).toBe("Answer"); + expect(answer?.checked).toBe(true); + expect(answer?.autofocus).toBe(false); + expect(workbook?.querySelector("textarea")?.value).toBe("\nExample"); + expect(workbook?.querySelector("select")?.value).toBe("Second"); + expect(workbook?.querySelector("button")?.hasAttribute("formaction")).toBe(false); + expect(workbook?.querySelector('input[type="image"]')?.src).toMatch(/^blob:/); + expect(workbook?.querySelector("meter")?.value).toBe(75); + expect( + workbook?.querySelectorAll( + "input:disabled, textarea:disabled, select:disabled, button:disabled", + ), + ).toHaveLength(5); + expect(doc?.querySelector('a[data-epub-external][href="#"]')?.textContent).toBe("External"); + expect( + doc?.querySelector('a[href="https://example.invalid/"],a[href^="javascript:"]'), + ).toBeNull(); + expect(doc!.defaultView!.getComputedStyle(doc!.querySelector("#opening")!).color).toBe( + "rgb(30, 45, 60)", + ); + expect( + doc!.defaultView!.getComputedStyle(doc!.querySelector("#opening")!).backgroundImage, + ).toContain("blob:"); + expect(doc!.defaultView!.getComputedStyle(doc!.querySelector("#swatch")!).fill).toBe( + "rgb(0, 0, 255)", + ); + expect( + doc!.defaultView!.getComputedStyle(doc!.querySelector("section")!).backgroundImage, + ).toContain("blob:"); + }); + const link = frame()!.contentDocument!.querySelector("a[href]")!; + link.click(); + await vi.waitFor(() => { + const doc = frame()?.contentDocument; + expect(doc?.querySelector("svg#figure rect")).toBeTruthy(); + expect(doc?.querySelector("base")).toBeNull(); + expect(doc?.querySelector('a[href="#"]')?.getAttribute("data-epub-external")).toBe( + "https://publisher.example/illustrations", + ); + expect(frame()?.contentWindow?.innerWidth).toBe(1000); + expect(frame()?.getBoundingClientRect().width).toBeGreaterThan(0); + expect(frame()?.getBoundingClientRect().width).toBeLessThan(1000); + }); + await screen.getByRole("button", { name: "Next chapter" }).click(); + await vi.waitFor(() => { + const doc = frame()?.contentDocument; + const poster = doc?.querySelector("#poster"); + expect(poster).toBeTruthy(); + expect(doc!.defaultView!.getComputedStyle(poster!).fill).toBe("rgb(230, 200, 12)"); + expect(doc?.querySelector("marker#arrow")?.getAttribute("orient")).toBe("auto"); + expect(doc?.querySelector("line")?.getAttribute("marker-end")).toBe("url(#arrow)"); + expect(doc?.scrollingElement?.scrollHeight).toBe(100); + }); + await screen.getByRole("button", { name: "Previous chapter" }).click(); + await vi.waitFor(() => + expect(frame()?.contentDocument?.querySelector("svg#figure")).toBeTruthy(), + ); + await screen.getByRole("button", { name: "Previous chapter" }).click(); + await vi.waitFor(() => expect(frame()?.contentDocument?.querySelector("#opening")).toBeTruthy()); +}); + +it("highlights EPUB narration cues during playback and pauses on chapter change", async () => { + const sampleRate = 8_000; + const pcm = new Uint8Array(44 + sampleRate * 2 * 8); + const header = new DataView(pcm.buffer); + const encoder = new TextEncoder(); + pcm.set(encoder.encode("RIFF"), 0); + pcm.set(encoder.encode("WAVEfmt "), 8); + pcm.set(encoder.encode("data"), 36); + header.setUint32(4, pcm.length - 8, true); + header.setUint32(16, 16, true); + header.setUint16(20, 1, true); + header.setUint16(22, 1, true); + header.setUint32(24, sampleRate, true); + header.setUint32(28, sampleRate * 2, true); + header.setUint16(32, 2, true); + header.setUint16(34, 16, true); + header.setUint32(40, pcm.length - 44, true); + const { default: JSZip } = await import("jszip"); + const file = await new JSZip() + .file( + "META-INF/container.xml", + '', + ) + .file( + "book.opf", + ` + + + + `, + ) + .file( + "chapter.xhtml", + '

First phrase

Second phrase

', + ) + .file("end.xhtml", "

End

") + .file( + "read.smil", + ` + + + `, + ) + .file("audio.wav", pcm) + .generateAsync({ type: "blob" }); + await using screen = await render( +
+ +
, + ); + const read = screen.getByRole("button", { name: "Read aloud" }); + await expect.element(read).toBeVisible(); + const player = screen.container.querySelector("audio")!; + player.muted = true; + const activePhrase = () => + screen.container + .querySelector("iframe") + ?.contentDocument?.querySelector(".t3-epub-narration-active")?.id; + await read.click(); + await vi.waitFor(() => expect(activePhrase()).toBe("first")); + player.currentTime = 4.1; + await vi.waitFor(() => expect(activePhrase()).toBe("second")); + await screen.getByRole("button", { name: "Next chapter" }).click(); + await vi.waitFor(() => expect(player.paused).toBe(true)); +}); + it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)( "bounds %s image pixels before returning browser markup", async (kind) => { @@ -2294,21 +2607,15 @@ it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)( type: "module", }); try { - const result = await new Promise((resolve) => { - worker.addEventListener( - "message", - (event: MessageEvent) => resolve(event.data), - { once: true }, - ); - worker.postMessage( - { - type: "open", - kind: kind === "html" || kind === "encoded-html" ? "ipynb" : kind, - bytes, - }, - [bytes], - ); - }); + const result = await officeWorkerReply( + worker, + { + type: "open", + kind: kind === "html" || kind === "encoded-html" ? "ipynb" : kind, + bytes, + }, + [bytes], + ); if (result.type === "notebook") { const output = result.cells[0]!.outputs[0]!; expect(output.kind).toBe( @@ -2324,10 +2631,21 @@ it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)( } if (width !== 2) expect(result.cells[0]!.outputs[0]!.text).toBe("retained caption"); } else { - expect(result.type).toBe("document"); - if (result.type !== "document") throw new Error("Expected document"); - expect(result.pages[0]!.html.includes(" ["min", "max", "width"].map((name) => column.getAttribute(name)), ); - // The engine ignores `defaultColWidth`, so the columns it sizes are spelled out. expect(columns).toEqual([ [String(OFFICE_PREVIEW_MAX_COLUMNS - 1), String(OFFICE_PREVIEW_MAX_COLUMNS), "20"], // Hidden columns keep their span past the limit, so they stay hidden. [String(OFFICE_PREVIEW_MAX_COLUMNS + 1), String(OFFICE_PREVIEW_MAX_COLUMNS + 30), null], - ["1", String(OFFICE_PREVIEW_MAX_COLUMNS - 2), "30"], ]); } finally { worker.terminate(); @@ -948,7 +948,8 @@ it.each(['', ''])( ) .file("xl/styles.xml")! .async("string"); - expect(styles).toContain(""); + expect(styles).toContain(underline); + expect(styles).toContain('numFmtId="007"'); const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), { type: "module", }); @@ -1037,7 +1038,7 @@ it("keeps spreadsheet dates on their calendar day west of UTC", async () => { "open", { bytes, - view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } }, + view: { digitWidth: 7, themeFonts: { major: "Calibri Light", minor: "Calibri" } }, }, { transfer: [bytes] }, ); @@ -1087,3 +1088,50 @@ it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async ( expect(screen.container.textContent).not.toContain("Preview limited"); expect(screen.container.querySelector('[role="alert"]')).toBeNull(); }); + +it.each([ + [ + new URL("../../../test/fixtures/file-passwords/locked.docx", import.meta.url), + "docx", + "Unlocked Word", + ], + [ + new URL("../../../test/fixtures/file-passwords/standard.docx", import.meta.url), + "docx", + "Unlocked Word", + ], + [ + new URL("../../../test/fixtures/file-passwords/locked.odt", import.meta.url), + "odt", + "Unlocked Writer", + ], + [ + new URL("../../../test/fixtures/file-passwords/locked.epub", import.meta.url), + "epub", + "Unlocked EPUB", + ], +] as const)("opens the password-protected document at %s", async (src, kind, content) => { + const blob = await fetch(src).then((response) => response.blob()); + const file = new File([blob], `locked.${kind}`, { type: "application/octet-stream" }); + await using screen = await render( + , + ); + const password = screen.getByLabelText("File password"); + await password.fill("wrong"); + await screen.getByRole("button", { name: "Unlock" }).click(); + await expect.element(screen.getByText("Incorrect password. Try again.")).toBeVisible(); + await password.fill("open me"); + await screen.getByRole("button", { name: "Unlock" }).click(); + if (kind === "docx") await expect.element(screen.getByText(content)).toBeVisible(); + else { + await vi.waitFor(() => { + const frame = screen.container.querySelector("iframe"); + expect(frame?.getAttribute("srcdoc")).toContain(content); + }); + } +}); diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 1d88ee7989efb..262fdef5253c8 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -1,3 +1,4 @@ +import { FilePasswordPrompt } from "./FilePasswordPrompt"; /* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */ import { decodeFilePreviewText, filePreviewKind } from "@t3tools/shared/filePreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; @@ -21,6 +22,7 @@ import { FileSurfaceNotice, } from "./fileSurfaceChrome"; import { + compareArchiveRows, formatArchiveModifiedDate, SQLITE_PAGE_SIZE, type BinaryWorkerRequest, @@ -112,6 +114,7 @@ export default function BinaryViewer(props: { const [selectedTable, setSelectedTable] = useState(""); const [page, setPage] = useState(0); const [busy, setBusy] = useState(true); + const [incorrectPassword, setIncorrectPassword] = useState(null); const [error, setError] = useState(null); const workerRef = useRef(null); const timerRef = useRef | null>(null); @@ -155,7 +158,8 @@ export default function BinaryViewer(props: { if (timerRef.current) clearTimeout(timerRef.current); const result = event.data; setBusy(false); - if (result.type === "error") setError(previewFailureText(result)); + if (result.type === "password") setIncorrectPassword(result.incorrect); + else if (result.type === "error") setError(previewFailureText(result)); else if (result.type === "archive") setArchive(result); else if (result.type === "entry") setEntry(result); else if (result.type === "rows") setRows(result); @@ -198,7 +202,8 @@ export default function BinaryViewer(props: { { path: string; entryPath: string; directory: boolean; size: number; modified: string | null } >(); for (const item of archive?.entries ?? []) { - const name = item.path.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"); + // `tar cf x.tar .` names members "./src/a.txt"; list them from the archive root. + const name = item.path.replace(/^(?:\.?\/)+|\/+$/g, "").replace(/\/{2,}/g, "/"); if (!name.startsWith(folder)) continue; const rest = name.slice(folder.length); if (!rest) continue; @@ -208,8 +213,10 @@ export default function BinaryViewer(props: { // Files stay keyed by their raw name so `/a.txt` and `a.txt` remain two openable rows. const key = directory ? `d:${path}` : `f:${item.path}`; const previous = children.get(key); - if (previous && directory) previous.size += item.size; - else + if (previous && directory) { + previous.size += item.size; + if (slash < 0 && item.directory) previous.modified = item.modified; + } else children.set(key, { path, entryPath: item.path, @@ -311,7 +318,15 @@ export default function BinaryViewer(props: { ) : null} - {error ? ( + {incorrectPassword !== null ? ( + { + setIncorrectPassword(null); + send({ type: "unlock", password }); + }} + /> + ) : error ? ( - {[...children.values()] - .sort( - (a, b) => - Number(b.directory) - Number(a.directory) || a.path.localeCompare(b.path), - ) - .map((item) => ( - - - - - - {formatAttachmentSize(item.size, messages)} - - - {formatArchiveModifiedDate(item.modified)} - - - ))} + {[...children.values()].sort(compareArchiveRows).map((item) => ( + + + + + + {formatAttachmentSize(item.size, messages)} + + + {formatArchiveModifiedDate(item.modified)} + + + ))} {children.size === 0 ? ( diff --git a/apps/web/src/components/files/ChunkedMarkdown.tsx b/apps/web/src/components/files/ChunkedMarkdown.tsx index 10322beee7fe3..f3076d43e1c57 100644 --- a/apps/web/src/components/files/ChunkedMarkdown.tsx +++ b/apps/web/src/components/files/ChunkedMarkdown.tsx @@ -1,25 +1,55 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; -import { useRef, type KeyboardEventHandler } from "react"; +import { useRef, type KeyboardEventHandler, type MouseEvent as ReactMouseEvent } from "react"; +import { normalizeMarkdownFragmentId } from "~/components/chat/markdownFragments"; import { Spinner } from "~/components/ui/spinner"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { FileMarkdownPreview } from "./FileMarkdownPreview"; import { + buildMarkdownFootnotesSection, + findFootnoteRefChunkIndex, + joinMarkdownChunks, LARGE_MARKDOWN_CHUNK_MAX_CHARS, type MarkdownChunk, - withMarkdownDefinitions, + type MarkdownFootnotes, + type MarkdownFootnotesSection, + prepareMarkdownChunk, } from "@t3tools/shared/markdownChunks"; const ESTIMATED_LINE_PX = 24; const MAX_SAVED_POSITIONS = 100; +const FOOTNOTE_TARGET_ID = /^fn-\d+$/; +const FOOTNOTE_REF_ID = /^fnref-(\d+)(?:-(\d+))?$/; + +const CHUNK_FOOTNOTES_OMIT: MarkdownExtensions = { footnotes: "omit" }; +const CHUNK_FOOTNOTES_OMIT_SEEDED: MarkdownExtensions = { footnotes: "omit-seeded" }; +const CHUNK_FOOTNOTES_ONLY: MarkdownExtensions = { footnotes: "only" }; /** Reading positions outlive the preview, which unmounts when the file or thread changes. */ const savedPositions = new Map(); -interface ChunkItem { - readonly index: number; - readonly start: number; - readonly chunk: MarkdownChunk; +type ChunkItem = + | { + readonly kind: "chunk"; + readonly index: number; + readonly start: number; + readonly chunk: MarkdownChunk; + } + | { + readonly kind: "footnotes"; + readonly index: number; + readonly section: MarkdownFootnotesSection; + }; + +function findScopedFragmentTarget( + container: HTMLElement, + normalizedId: string, +): HTMLElement | null { + for (const element of container.querySelectorAll("[id]")) { + if (normalizeMarkdownFragmentId(element.id) === normalizedId) return element; + } + return null; } /** Renders Markdown pieces in a virtualized list; task offsets are file offsets. */ @@ -27,6 +57,8 @@ export function ChunkedMarkdown(props: { readonly chunks: readonly MarkdownChunk[]; /** Link definitions from the whole file, so references resolve across pieces. */ readonly definitions: string; + /** Document-wide footnote metadata so references and definitions resolve across pieces. */ + readonly footnotes?: MarkdownFootnotes | undefined; /** Shows a spinner after the last chunk while more of the file streams in. */ readonly loading?: boolean; readonly cwd: string; @@ -43,10 +75,16 @@ export function ChunkedMarkdown(props: { let start = 0; let lines = 0; for (const [index, chunk] of chunks.entries()) { - items.push({ index, start, chunk }); + items.push({ kind: "chunk", index, start, chunk }); lines += chunk.lines; start += chunk.text.length + 1; } + const footnotesSection = buildMarkdownFootnotesSection(props.definitions, props.footnotes); + const footnotesItemIndex = footnotesSection !== null ? items.length : null; + if (footnotesSection !== null) { + items.push({ kind: "footnotes", index: items.length, section: footnotesSection }); + } + const containerRef = useRef(null); const listRef = useRef(null); const positionKey = JSON.stringify([ props.threadRef.environmentId, @@ -63,18 +101,95 @@ export function ChunkedMarkdown(props: {
); if (awaitingSaved) return spinner; + + const handleFragmentClickCapture = (event: ReactMouseEvent) => { + // Without shared footnotes each piece keeps its own section, which ChatMarkdown resolves. + if ( + !props.footnotes || + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + const target = event.target; + if (!(target instanceof Element)) return; + const anchor = target.closest('a[href^="#"]'); + if (!anchor) return; + const href = anchor.getAttribute("href"); + if (!href) return; + const container = containerRef.current; + if (!container) return; + + const normalizedId = normalizeMarkdownFragmentId(href); + const isFootnoteTarget = FOOTNOTE_TARGET_ID.test(normalizedId); + const refMatch = isFootnoteTarget ? null : FOOTNOTE_REF_ID.exec(normalizedId); + if (!isFootnoteTarget && !refMatch) return; + + const local = findScopedFragmentTarget(container, normalizedId); + if (local) { + event.preventDefault(); + event.stopPropagation(); + local.scrollIntoView({ block: "start" }); + return; + } + + let targetIndex: number | null = null; + if (isFootnoteTarget) { + targetIndex = footnotesItemIndex; + } else if (refMatch) { + const fnNumber = Number(refMatch[1]); + const occurrence = refMatch[2] ? Number(refMatch[2]) : 1; + targetIndex = findFootnoteRefChunkIndex(props.footnotes, fnNumber, occurrence); + } + if (targetIndex === null || !listRef.current) return; + + event.preventDefault(); + event.stopPropagation(); + void listRef.current + .scrollToIndex({ index: targetIndex, viewPosition: 0, animated: false }) + .then(() => { + const mounted = containerRef.current + ? findScopedFragmentTarget(containerRef.current, normalizedId) + : null; + mounted?.scrollIntoView({ block: "start" }); + }); + }; + + const extraData = props.footnotes + ? `${props.definitions}\0${props.footnotes.stubs}\0${props.footnotes.definitions}\0${props.footnotes.chunkRefs.map((refs) => refs.join(",")).join("|")}` + : props.definitions; + return (
{ // Select All only reaches rendered pieces; copying all of it copies the whole file. const list = event.currentTarget.firstElementChild; - if (!list || !window.getSelection()?.containsNode(list)) return; + const selection = window.getSelection(); + if (!list || !selection?.rangeCount) return; + // Chromium's containsNode says false for a list selected through its parent's children. + const range = selection.getRangeAt(0); + const listRange = document.createRange(); + listRange.selectNode(list); + if ( + range.compareBoundaryPoints(Range.START_TO_START, listRange) > 0 || + range.compareBoundaryPoints(Range.END_TO_END, listRange) < 0 + ) { + return; + } event.preventDefault(); - event.clipboardData.setData("text/plain", chunks.map((chunk) => chunk.text).join("\n")); + // A rendered piece's own handler already wrote just its part. + event.clipboardData.clearData(); + event.clipboardData.setData("text/plain", joinMarkdownChunks(chunks)); }} > @@ -100,41 +215,83 @@ export function ChunkedMarkdown(props: { savedPositions.delete(savedPositions.keys().next().value!); } }} - extraData={props.definitions} - keyExtractor={(item) => String(item.index)} + extraData={extraData} + keyExtractor={(item) => (item.kind === "footnotes" ? "footnotes" : String(item.index))} estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX} drawDistance={800} recycleItems={false} className="h-full scrollbar-gutter-both" contentContainerClassName="py-5" ListFooterComponent={props.loading ? spinner : null} - renderItem={({ item }) => ( -
- {item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS ? ( - // One block this long (a huge fence or HTML block) is too slow to parse. -
-                {item.chunk.text}
-              
- ) : ( + renderItem={({ item }) => { + if (item.kind === "footnotes") { + return ( +
+ { + const markerOffset = item.section.fileOffset(input.markerOffset); + if (markerOffset !== null) { + onTaskListChange({ markerOffset, checked: input.checked }); + } + }) + } + /> +
+ ); + } + if (item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS) { + return ( +
+ {/* One block this long (a huge fence or HTML block) is too slow to parse. */} +
+                  {item.chunk.text}
+                
+
+ ); + } + const prepared = prepareMarkdownChunk( + item.chunk.text, + item.index, + props.definitions, + props.footnotes, + ); + const extensions = + prepared.footnotesMode === "omit-seeded" + ? CHUNK_FOOTNOTES_OMIT_SEEDED + : prepared.footnotesMode === "omit" + ? CHUNK_FOOTNOTES_OMIT + : undefined; + return ( +
onTaskListChange({ - markerOffset: item.start + input.markerOffset, + markerOffset: item.start + input.markerOffset - prepared.offsetShift, checked: input.checked, })) } /> - )} -
- )} +
+ ); + }} />
); diff --git a/apps/web/src/components/files/EpubMediaDialog.tsx b/apps/web/src/components/files/EpubMediaDialog.tsx new file mode 100644 index 0000000000000..15273bf4d8d3c --- /dev/null +++ b/apps/web/src/components/files/EpubMediaDialog.tsx @@ -0,0 +1,80 @@ +import { useGT } from "gt-react"; +import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "~/components/ui/dialog"; + +const localBlob = (src: string | null) => (src?.startsWith("blob:") ? src : undefined); + +export function EpubMediaDialog(props: { + readonly media: HTMLMediaElement; + readonly onClose: () => void; +}) { + const gt = useGT(); + const media = props.media; + const src = localBlob(media.getAttribute("src")); + const sources = Array.from(media.querySelectorAll("source"), (source) => ( + + )); + const tracks = Array.from(media.querySelectorAll("track"), (track) => ( + + )); + const isVideo = media.localName === "video"; + const title = + media.title || + media.getAttribute("aria-label") || + (isVideo ? gt("Video preview") : gt("Audio preview")); + return ( + { + if (!open) props.onClose(); + }} + > + + + {title} + +
+ {isVideo ? ( + + ) : ( + + )} +
+
+
+ ); +} diff --git a/apps/web/src/components/files/EpubNarration.tsx b/apps/web/src/components/files/EpubNarration.tsx new file mode 100644 index 0000000000000..a8b87c5b91b67 --- /dev/null +++ b/apps/web/src/components/files/EpubNarration.tsx @@ -0,0 +1,145 @@ +import { useGT } from "gt-react"; +import { HeadphonesIcon, PauseIcon } from "lucide-react"; +import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; +import { Button } from "~/components/ui/button"; +import type { EpubNarrationCue } from "./officePreviewProtocol"; + +export function EpubNarration(props: { + readonly cues: readonly EpubNarrationCue[]; + readonly frame: RefObject; +}) { + const gt = useGT(); + const audio = useRef(null); + const [playing, setPlaying] = useState(false); + const [failed, setFailed] = useState(false); + const active = useRef(false); + const index = useRef(0); + const request = useRef(0); + const highlight = useRef(null); + + function mark(cue: EpubNarrationCue | undefined) { + const doc = props.frame.current?.contentDocument; + const target = cue?.anchor ? doc?.getElementById(cue.anchor) : null; + if (target === highlight.current) return; + highlight.current?.classList.remove("t3-epub-narration-active"); + highlight.current = target ?? null; + if (!target || !doc?.defaultView) return; + target.classList.add("t3-epub-narration-active"); + const rect = target.getBoundingClientRect(); + if (rect.top < 0 || rect.bottom > doc.defaultView.innerHeight) + target.scrollIntoView({ block: "nearest", inline: "nearest" }); + } + + function pause() { + active.current = false; + request.current++; + audio.current?.pause(); + setPlaying(false); + } + + function finish() { + pause(); + index.current = 0; + if (audio.current) audio.current.removeAttribute("src"); + mark(undefined); + } + + function play(cue: EpubNarrationCue, resume: boolean) { + const player = audio.current; + if (!player) return; + const command = ++request.current; + const sameSource = player.getAttribute("src") === cue.src; + if (!sameSource) player.src = cue.src; + if (!resume || !sameSource) player.currentTime = cue.begin; + void player.play().catch(() => { + if (command !== request.current) return; + finish(); + setFailed(true); + }); + } + + function advance() { + const previous = props.cues[index.current]; + const next = props.cues[++index.current]; + if (!next) return finish(); + const player = audio.current; + if ( + !player || + player.ended || + previous?.src !== next.src || + previous.end === undefined || + Math.abs(next.begin - previous.end) > 0.02 + ) { + play(next, false); + } + } + + function synchronize() { + const player = audio.current; + const cue = props.cues[index.current]; + if (!active.current || !player || !cue) return; + if (!player.seeking && cue.end !== undefined && player.currentTime >= cue.end) { + advance(); + } + if (active.current) mark(props.cues[index.current]); + } + + const synchronizeWhilePlaying = useEffectEvent(synchronize); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel narration callbacks when the chapter is replaced. + useEffect(() => { + const player = audio.current; + if (!player) return; + let timer: number | undefined; + const stop = () => window.clearInterval(timer); + const start = () => { + stop(); + synchronizeWhilePlaying(); + timer = window.setInterval(() => synchronizeWhilePlaying(), 50); + }; + player.addEventListener("playing", start); + player.addEventListener("pause", stop); + return () => { + active.current = false; + request.current++; + stop(); + player.removeEventListener("playing", start); + player.removeEventListener("pause", stop); + player.pause(); + highlight.current?.classList.remove("t3-epub-narration-active"); + }; + }, []); + + const toggle = () => { + if (active.current) return pause(); + const cue = props.cues[index.current]; + if (!cue) return; + setFailed(false); + setPlaying(true); + active.current = true; + play(cue, true); + }; + + return ( +
+ + {failed ? ( + + {gt("Could not play narration.")} + + ) : null} +
+ ); +} diff --git a/apps/web/src/components/files/EpubViewer.tsx b/apps/web/src/components/files/EpubViewer.tsx new file mode 100644 index 0000000000000..202a146f3fa38 --- /dev/null +++ b/apps/web/src/components/files/EpubViewer.tsx @@ -0,0 +1,313 @@ +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; +import { + ChevronLeftIcon, + ChevronRightIcon, + MinusIcon, + PlusIcon, + RotateCcwIcon, +} from "lucide-react"; +import { T, useGT, useMessages } from "gt-react"; +import { useEffect, useRef, useState } from "react"; +import { + Select, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "~/components/ui/select"; +import { observeResize } from "~/lib/observeResize"; +import { externalUrl } from "./office/links"; +import { useTheme } from "~/hooks/useTheme"; +import { FileSurfaceAction, FileSurfaceLoading } from "./fileSurfaceChrome"; +import type { EpubLocation, EpubPage, OfficeWorkerResult } from "./officePreviewProtocol"; +import { epubSource, prepareEpubDocument } from "./epubSource"; +import { EpubNarration } from "./EpubNarration"; +import { EpubMediaDialog } from "./EpubMediaDialog"; +import { Button } from "~/components/ui/button"; +import { previewFailureText } from "./previewFailureMessages"; + +type Book = Extract; +type PageResponse = Extract; + +function goToAnchor(doc: Document, anchor: string | undefined) { + if (anchor) (doc.getElementById(anchor) ?? doc.getElementsByName(anchor)[0])?.scrollIntoView(); + else doc.defaultView?.scrollTo(0, 0); +} + +function ReadingFrame(props: { + readonly page: EpubPage; + readonly name: string; + readonly location: EpubLocation; + readonly zoom: number; + readonly navigate: (location: EpubLocation) => void; +}) { + const gt = useGT(); + const { resolvedTheme } = useTheme(); + const container = useRef(null); + const frame = useRef(null); + const fixed = props.page.fixed; + const [size, setSize] = useState({ width: 0, height: 0 }); + const [media, setMedia] = useState([]); + const [openMedia, setOpenMedia] = useState(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Fit the authored viewport to its container as the preview resizes. + useEffect(() => { + const element = container.current; + if (!element || !fixed) return; + const measure = () => setSize({ width: element.clientWidth, height: element.clientHeight }); + measure(); + return observeResize(element, measure); + }, [fixed]); + const scale = fixed + ? Math.min(size.width / fixed.width, size.height / fixed.height) * props.zoom + : 1; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Change the sandboxed document's reading size without reloading or losing position. + useEffect(() => { + if (!fixed) + frame.current?.contentDocument?.documentElement?.style.setProperty( + "zoom", + String(props.zoom), + "important", + ); + }, [fixed, props.zoom]); + const anchor = props.location.anchor; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A table-of-contents entry can change the anchor within the current document. + useEffect(() => { + const doc = frame.current?.contentDocument; + if (doc?.body) goToAnchor(doc, anchor); + }, [anchor]); + const darkPage = resolvedTheme === "dark" && !props.page.styles?.length && !fixed; + const srcDoc = epubSource(props.page, darkPage); + return ( + <> + {props.page.narration?.length && !openMedia ? ( + + ) : null} + {media.length > 0 ? ( +
+ {media.map((item, index) => ( + + ))} +
+ ) : null} + {openMedia ? setOpenMedia(null)} /> : null} +
+
+