Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge e371cc280b Fix relay client test clock input
Co-authored-by: Julius Marminge <[email protected]>
2026-06-15 16:14:35 +00:00
Cursor AgentandJulius Marminge 1690e15f58 Refine shared Effect idioms
Co-authored-by: Julius Marminge <[email protected]>
2026-06-15 16:13:30 +00:00
890 changed files with 64361 additions and 60318 deletions

No files matched your search

+46
View File
@@ -60,6 +60,52 @@ jobs:
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
-79
View File
@@ -180,46 +180,12 @@ jobs:
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3code-relay...
- id: relay_state
name: Read production relay tracing config
shell: bash
run: |
vp run --filter t3code-relay deploy \
--stage prod \
--read-state \
--github-output \
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
- name: Upload relay client tracing config
uses: actions/upload-artifact@v7
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing.env
if-no-files-found: error
retention-days: 1
- id: public_config
name: Resolve production relay public config
shell: bash
@@ -306,20 +272,6 @@ jobs:
cache: true
run-install: true
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -556,20 +508,6 @@ jobs:
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -732,20 +670,6 @@ jobs:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -792,9 +716,6 @@ jobs:
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
@@ -1,297 +0,0 @@
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 Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
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";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.cause, permissionError);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -1,328 +0,0 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
"DesktopConnectionCatalogStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
"DesktopConnectionCatalogStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode the desktop connection catalog.";
}
}
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
"DesktopConnectionCatalogStoreReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
"DesktopConnectionCatalogStoreMigrationError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to migrate legacy desktop saved environments.";
}
}
export interface DesktopConnectionCatalogStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
DesktopConnectionCatalogStoreShape
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
PlatformError.PlatformError | Schema.SchemaError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.catalogPath);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const layer = Layer.effect(
DesktopConnectionCatalogStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry;
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
yield* writeCatalog(encoded);
return Option.some(encoded);
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
}),
);
@@ -99,7 +99,6 @@ export const layer = Layer.effect(
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
@@ -1,9 +1,9 @@
import * as Electron from "electron";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
+11 -7
View File
@@ -10,10 +10,12 @@ import {
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -57,9 +59,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
+5 -3
View File
@@ -20,9 +20,11 @@ export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
+1 -1
View File
@@ -59,7 +59,7 @@ function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInpu
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getConnectionCatalog = makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -1,11 +1,11 @@
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
+1 -2
View File
@@ -29,7 +29,6 @@ import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
@@ -118,7 +117,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopSavedEnvironments.layer,
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
+10 -4
View File
@@ -42,10 +42,16 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
setConnectionCatalog: (catalog) =>
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
getSavedEnvironmentRegistry: () =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
-101
View File
@@ -128,58 +128,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
const loadURL = vi.fn(async () => undefined);
const listeners = new Map<string, (...args: never[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "about:blank",
getTitle: () => "",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.navigate("tab_pending", "localhost:3200");
expect(yield* manager.automationStatus("tab_pending")).toEqual({
available: false,
visible: true,
tabId: "tab_pending",
url: "http://localhost:3200/",
title: "",
loading: true,
});
yield* manager.registerWebview("tab_pending", 42);
yield* Effect.yieldNow;
expect(loadURL).toHaveBeenCalledOnce();
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -241,55 +189,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("keeps element picking active during subframe navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isFocused: () => true,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
yield* Effect.yieldNow;
listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
yield* Effect.yieldNow;
expect(pick.pollUnsafe()).toBeUndefined();
listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
expect(yield* Fiber.join(pick)).toBeNull();
}),
),
);
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
withManager((manager) =>
Effect.gen(function* () {
+13 -97
View File
@@ -1195,103 +1195,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) {
return [
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
tabs,
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const next: PreviewTabState = {
...current,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
updatedAt: registeredAt,
};
return [
Option.some({
state: next,
pendingUrl,
}),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
Effect.ignore,
);
}
yield* update(tabId, {
webContentsId,
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor: tab.zoomFactor,
});
if (Option.isNone(registration)) {
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt("registerWebview.sendTheme", () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
if (
pendingUrl &&
latestNavStatus?.kind === "Loading" &&
latestNavStatus.url === pendingUrl &&
wc.getURL() !== pendingUrl
) {
runFork(
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
Effect.ignore,
),
);
}
});
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
const wc = yield* requireWebContents(tabId);
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
const updatedAt = yield* currentIso;
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
const next: PreviewTabState = {
tabId,
webContentsId: current?.webContentsId ?? null,
navStatus: {
kind: "Loading",
url,
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
},
canGoBack: current?.canGoBack ?? false,
canGoForward: current?.canGoForward ?? false,
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
controller: current?.controller ?? "none",
updatedAt,
};
return [
next,
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
yield* attempt("navigate.reload", () => wc.reload());
return;
@@ -1421,14 +1344,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
};
const onDestroyed = () => settle(null);
const onNavigated = (
_event: Electron.Event,
_url: string,
_isInPlace: boolean,
isMainFrame: boolean,
) => {
if (isMainFrame) settle(null);
};
const onNavigated = () => settle(null);
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
yield* attempt("pickElement.register", () => {
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
@@ -272,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -309,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("surfaces malformed saved environment documents", () =>
it.effect("treats malformed saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -318,15 +298,10 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
const secretError = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
}),
),
);
@@ -82,16 +82,6 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
}
}
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
)<{
@@ -103,7 +93,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
}
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
@@ -114,16 +103,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly removeEnvironment: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
@@ -193,20 +176,18 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
): Effect.Effect<SavedEnvironmentRegistryDocument> {
return fileSystem.readFileString(registryPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed({ version: 1, records: [] }),
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
),
}),
),
);
}
@@ -286,39 +267,21 @@ export const layer = Layer.effect(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!document.records.some((record) => record.environmentId === environmentId)) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.filter((record) => record.environmentId !== environmentId),
});
},
),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
);
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
@@ -336,7 +299,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
@@ -368,7 +331,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
);
if (
!document.records.some(
(record) =>
@@ -405,18 +368,6 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records),
removeEnvironment: (environmentId) =>
Ref.update(recordsRef, (records) =>
records.filter((record) => record.environmentId !== environmentId),
).pipe(
Effect.andThen(
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
),
),
getSecret: (environmentId) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
+1 -14
View File
@@ -68,7 +68,6 @@ function makeFakeBrowserWindow() {
once: vi.fn(),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
setAutoHideCursor: vi.fn(),
setTitle: vi.fn(),
setTitleBarOverlay: vi.fn(),
show: vi.fn(),
@@ -79,7 +78,6 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
}
@@ -136,17 +134,10 @@ function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
readonly openedExternalUrls?: unknown[];
}) {
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: (options) =>
Effect.sync(() => {
input.createdWindowOptions?.push(options);
}).pipe(
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
Effect.as(input.window),
),
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
main: Ref.get(input.mainWindow),
currentMainOrFirst: Ref.get(input.mainWindow),
focusedMainOrFirst: Ref.get(input.mainWindow),
@@ -214,12 +205,10 @@ describe("DesktopWindow", () => {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
createdWindowOptions,
});
yield* Effect.gen(function* () {
@@ -229,8 +218,6 @@ describe("DesktopWindow", () => {
yield* desktopWindow.handleBackendReady;
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
-5
View File
@@ -193,7 +193,6 @@ const make = Effect.gen(function* () {
minHeight: 620,
show: false,
autoHideMenuBar: true,
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
...iconOption,
title: environment.displayName,
@@ -207,10 +206,6 @@ const make = Effect.gen(function* () {
},
});
if (environment.platform === "darwin") {
window.setAutoHideCursor(false);
}
yield* previewManager.setMainWindow(window);
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
if (
+15 -43
View File
@@ -1,6 +1,4 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
@@ -38,17 +36,17 @@ const {
</a>
<div class="nav-right">
<a
class="nav-stars"
href={GITHUB_REPOSITORY_URL}
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
@@ -64,7 +62,7 @@ const {
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
@@ -331,36 +329,23 @@ const {
gap: 8px;
}
.nav-stars {
.nav-gh {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.02);
border-radius: 8px;
color: var(--fg-muted);
font-size: 13px;
letter-spacing: -0.01em;
white-space: nowrap;
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-stars:hover {
.nav-gh:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.04);
}
.nav-stars strong {
color: var(--fg);
font-weight: 600;
}
.nav-stars svg {
color: var(--warn);
flex-shrink: 0;
border-color: var(--border-strong);
}
.main {
@@ -422,17 +407,4 @@ const {
padding-right: 20px;
}
}
@media (max-width: 420px) {
.nav-inner {
gap: 12px;
}
.nav-stars {
height: 34px;
gap: 6px;
padding: 0 12px;
font-size: 12px;
}
}
</style>
-6
View File
@@ -1,6 +0,0 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
users: "100,000",
} as const;
+66 -181
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -56,12 +55,11 @@ const mobileEndorsementRows = [
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="download-label">Download for macOS</span>
</a>
<a class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
Star on GitHub
</a>
</div>
@@ -84,8 +82,8 @@ const mobileEndorsementRows = [
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
<div class="container">
<div class="endorsements-head">
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
<p>Some of them even tweeted about it.</p>
<h2 id="endorsements-title">Developers love T3 Code</h2>
<p>Real reactions from people building with T3 Code today.</p>
</div>
</div>
@@ -284,6 +282,10 @@ const mobileEndorsementRows = [
<div class="section-head open-head">
<div class="eyebrow">Open source</div>
<h2>If you don't like something, fork it.</h2>
<p>
T3 Code is as open as they come. We built this app to be modifiable,
customizable, and forkable. Go nuts - that's the whole point.
</p>
</div>
<div class="open-grid">
@@ -303,44 +305,43 @@ const mobileEndorsementRows = [
</div>
</div>
<div class="tile open-pitch">
<div class="open-pitch-copy">
<ul class="open-pitch-list">
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
</li>
</ul>
<div class="open-stats">
<div class="tile open-stat">
<div class="open-stat-val">MIT</div>
<div class="open-stat-lbl">License · commercial-friendly</div>
</div>
<div class="open-pitch-footer">
<div class="open-pitch-meta">
<span>MIT licensed</span>
<span aria-hidden="true">·</span>
<span>{MARKETING_STATS.githubStars} stars</span>
</div>
<div class="open-pitch-actions">
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork on GitHub
</a>
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
Browse source
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
<div class="tile open-stat">
<div class="open-stat-val">TypeScript</div>
<div class="open-stat-lbl">End-to-end, strictly typed</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">1 monorepo</div>
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">No telemetry</div>
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
</div>
</div>
</div>
<div class="open-ctas">
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
Star on GitHub
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork the repo
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
Read CONTRIBUTING.md
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
</div>
</section>
@@ -514,7 +515,7 @@ const mobileEndorsementRows = [
.hero-title {
font-size: clamp(38px, 5.6vw, 76px);
margin: 48px auto 22px;
margin: 28px auto 22px;
max-width: 20ch;
text-wrap: balance;
}
@@ -530,42 +531,12 @@ const mobileEndorsementRows = [
.hero-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
margin-bottom: 56px;
}
.hero-source-link {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--fg-muted);
font-size: 14px;
font-weight: 500;
letter-spacing: -0.01em;
transition: color 0.18s ease;
}
.hero-source-link:hover {
color: var(--fg);
}
.hero-source-mark {
flex-shrink: 0;
}
.hero-source-arrow {
flex-shrink: 0;
opacity: 0.6;
transition: transform 0.18s ease, opacity 0.18s ease;
}
.hero-source-link:hover .hero-source-arrow {
transform: translate(2px, -2px);
opacity: 1;
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
@@ -685,30 +656,6 @@ const mobileEndorsementRows = [
}
}
@media (max-width: 340px) {
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode {
left: 0;
}
.hero-float-mark.hf-cursor {
right: 0;
}
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
height: 30px;
}
}
.hero-preview {
max-width: 1180px;
margin: 0 auto;
@@ -812,11 +759,6 @@ const mobileEndorsementRows = [
margin-bottom: 18px;
}
.endorsements-count {
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.endorsements-head p {
color: var(--fg-muted);
font-size: 18px;
@@ -1020,11 +962,12 @@ const mobileEndorsementRows = [
text-align: center;
margin: 0 auto 56px;
}
.open-head p { margin: 0 auto; }
.open-grid {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 20px;
gap: 20px; margin-bottom: 32px;
}
.open-term { padding: 0; overflow: hidden; }
@@ -1066,85 +1009,27 @@ const mobileEndorsementRows = [
animation: blink 1s steps(2) infinite;
}
.open-pitch {
padding: 32px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 32px;
background:
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
}
.open-pitch-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 16px;
}
.open-pitch-list li {
display: flex;
align-items: flex-start;
gap: 12px;
font-size: 15px;
line-height: 1.5;
color: var(--fg-muted);
}
.open-pitch-list strong {
color: var(--fg);
font-weight: 600;
}
.open-pitch-mark {
flex: none;
.open-stats {
display: grid;
place-items: center;
width: 22px;
height: 22px;
margin-top: 1px;
border-radius: 7px;
color: var(--accent);
background: var(--accent-dim);
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.open-stat {
padding: 22px;
display: flex; flex-direction: column; gap: 6px;
}
.open-stat-val {
font-size: 22px; font-weight: 500;
letter-spacing: -0.015em;
}
.open-stat-lbl {
font-family: var(--font-mono); font-size: 10.5px;
color: var(--fg-dim); letter-spacing: 0.04em;
}
.open-pitch-footer {
display: flex;
flex-direction: column;
gap: 18px;
}
.open-pitch-meta {
display: flex;
align-items: center;
gap: 8px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 11px;
}
.open-pitch-actions {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.open-source-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-muted);
font-size: 13px;
font-weight: 500;
transition: color 0.18s ease;
}
.open-source-link:hover {
color: var(--fg);
.open-ctas {
display: flex; gap: 10px;
justify-content: center; flex-wrap: wrap;
}
/* ── Final CTA ────────────────────────────────────────── */
-5
View File
@@ -131,11 +131,6 @@ const config: ExpoConfig = {
{
ios: {
deploymentTarget: "18.0",
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
extraPods: [
{ name: "GoogleUtilities", modular_headers: true },
{ name: "RecaptchaInterop", modular_headers: true },
],
},
},
],
+2 -2
View File
@@ -13,7 +13,7 @@
"neutral": "#F5F5F5",
"border": "#E5E5EA",
"ring": "#A3A3A3",
"muted": "#F2F2F7",
"muted": "#F5F5F5",
"shadow": "#000000"
},
"darkColors": {
@@ -30,7 +30,7 @@
"neutral": "#1C1C1C",
"border": "#2A2A2A",
"ring": "#525252",
"muted": "#0E0E0E",
"muted": "#1C1C1C",
"shadow": "#000000"
},
"design": {
+1 -2
View File
@@ -1,8 +1,7 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote",
"promptToConfigurePushNotifications": false
"appVersionSource": "remote"
},
"build": {
"development": {
+5 -15
View File
@@ -18,7 +18,7 @@
--color-foreground: #262626;
--color-foreground-secondary: #525252;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #8e8e93;
--color-foreground-tertiary: #a3a3a3;
/* Borders & separators */
--color-border: rgba(0, 0, 0, 0.08);
@@ -28,9 +28,6 @@
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(0, 0, 0, 0.04);
--color-subtle-strong: rgba(0, 0, 0, 0.08);
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
--color-inline-skill-foreground: #a21caf;
/* Primary action */
--color-primary: #262626;
@@ -61,8 +58,6 @@
/* Header / glass chrome */
--color-header: rgba(255, 255, 255, 0.97);
--color-header-border: rgba(0, 0, 0, 0.06);
--color-glass-surface: rgba(255, 255, 255, 0.72);
--color-glass-tint: rgba(255, 255, 255, 0.18);
/* StatusBar */
--color-status-bar: #f2f2f7;
@@ -110,8 +105,8 @@
/* Text */
--color-foreground: #f5f5f5;
--color-foreground-secondary: #a3a3a3;
--color-foreground-muted: #8e8e93;
--color-foreground-tertiary: #636366;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #525252;
/* Borders & separators */
--color-border: rgba(255, 255, 255, 0.06);
@@ -121,9 +116,6 @@
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(255, 255, 255, 0.04);
--color-subtle-strong: rgba(255, 255, 255, 0.08);
--color-inline-skill-background: rgba(217, 70, 239, 0.12);
--color-inline-skill-border: rgba(217, 70, 239, 0.25);
--color-inline-skill-foreground: #f0abfc;
/* Primary action */
--color-primary: #f5f5f5;
@@ -144,18 +136,16 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-placeholder: #8e8e93;
--color-placeholder: #737373;
/* Icons */
--color-icon: #f5f5f5;
--color-icon-muted: #a3a3a3;
--color-icon-subtle: #8e8e93;
--color-icon-subtle: #737373;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
--color-glass-surface: rgba(23, 23, 23, 0.78);
--color-glass-tint: rgba(23, 23, 23, 0.24);
/* StatusBar */
--color-status-bar: #0a0a0a;
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,6 +0,0 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3ComposerEditorModule"]
}
}
@@ -1,21 +0,0 @@
Pod::Spec.new do |s|
s.name = 'T3ComposerEditor'
s.version = '1.0.0'
s.summary = 'Native attributed composer editor for T3 Code mobile.'
s.description = 'UIKit-backed rich text composer with atomic skill and file tokens.'
s.author = 'T3 Tools'
s.homepage = 'https://t3tools.com'
s.platforms = {
:ios => '16.4',
}
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
# Swift/Objective-C compatibility
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
}
s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
end
@@ -1,71 +0,0 @@
import ExpoModulesCore
public class T3ComposerEditorModule: Module {
public func definition() -> ModuleDefinition {
Name("T3ComposerEditor")
View(T3ComposerEditorView.self) {
Prop("value") { (view: T3ComposerEditorView, value: String) in
view.setValue(value)
}
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
view.setSelectionJson(selectionJson)
}
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
view.setThemeJson(themeJson)
}
Prop("placeholder") { (view: T3ComposerEditorView, placeholder: String) in
view.setPlaceholder(placeholder)
}
Prop("fontFamily") { (view: T3ComposerEditorView, fontFamily: String) in
view.setFontFamily(fontFamily)
}
Prop("fontSize") { (view: T3ComposerEditorView, fontSize: Double) in
view.setFontSize(CGFloat(fontSize))
}
Prop("lineHeight") { (view: T3ComposerEditorView, lineHeight: Double) in
view.setLineHeight(CGFloat(lineHeight))
}
Prop("contentInsetVertical") { (view: T3ComposerEditorView, contentInsetVertical: Double) in
view.setContentInsetVertical(CGFloat(contentInsetVertical))
}
Prop("editable") { (view: T3ComposerEditorView, editable: Bool) in
view.setEditable(editable)
}
Prop("scrollEnabled") { (view: T3ComposerEditorView, scrollEnabled: Bool) in
view.setScrollEnabled(scrollEnabled)
}
Prop("autoFocus") { (view: T3ComposerEditorView, autoFocus: Bool) in
view.setAutoFocus(autoFocus)
}
Prop("autoCorrect") { (view: T3ComposerEditorView, autoCorrect: Bool) in
view.setAutoCorrect(autoCorrect)
}
Prop("spellCheck") { (view: T3ComposerEditorView, spellCheck: Bool) in
view.setSpellCheck(spellCheck)
}
Events(
"onComposerChange",
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerPasteImages",
"onComposerContentSizeChange"
)
AsyncFunction("focus") { (view: T3ComposerEditorView) in
view.focusEditor()
}
AsyncFunction("blur") { (view: T3ComposerEditorView) in
view.blurEditor()
}
AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
view.setSelection(start: start, end: end)
}
}
}
}
@@ -1,819 +0,0 @@
import ExpoModulesCore
import UIKit
private struct ComposerTokenPayload: Decodable {
let type: String
let source: String
let label: String
let iconUri: String?
let start: Int
let end: Int
}
private struct ComposerSelectionPayload: Decodable {
let start: Int
let end: Int
}
private struct ComposerThemePayload: Decodable {
let text: String
let placeholder: String
let chipBackground: String
let chipBorder: String
let chipText: String
let skillBackground: String
let skillBorder: String
let skillText: String
let fileTint: String
}
private struct ComposerChipStyle {
let tint: UIColor
let backgroundColor: UIColor
let borderColor: UIColor
let textColor: UIColor
}
private final class ComposerTextAttachment: NSTextAttachment {
let source: String
init(source: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
self.source = source
super.init(data: nil, ofType: nil)
self.image = image
bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
}
required init?(coder: NSCoder) {
nil
}
}
private final class ComposerTextView: UITextView {
private static let pastedImageDirectoryName = "t3-composer-paste"
private static let stalePastedImageAge: TimeInterval = 60 * 60
var onPasteImages: (([String]) -> Void)?
var onAttributedMutation: (() -> Void)?
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
let pasteboard = UIPasteboard.general
if pasteboard.hasImages ||
pasteboard.itemProviders.contains(where: {
$0.canLoadObject(ofClass: UIImage.self)
}) {
return true
}
}
return super.canPerformAction(action, withSender: sender)
}
override func paste(_ sender: Any?) {
let pasteboard = UIPasteboard.general
let imageProviders = pasteboard.itemProviders.filter {
$0.canLoadObject(ofClass: UIImage.self)
}
if !imageProviders.isEmpty {
loadImages(from: imageProviders)
return
}
let images = pasteboard.images ?? []
if !images.isEmpty {
let urls = images.compactMap(Self.writeTemporaryImage)
if !urls.isEmpty {
onPasteImages?(urls)
return
}
}
super.paste(sender)
}
override func deleteBackward() {
guard selectedRange.length == 0, selectedRange.location > 0 else {
super.deleteBackward()
return
}
let previousOffset = selectedRange.location - 1
if textStorage.attribute(.attachment, at: previousOffset, effectiveRange: nil)
is ComposerTextAttachment {
replaceDisplayRange(NSRange(location: previousOffset, length: 1))
return
}
super.deleteBackward()
}
private func replaceDisplayRange(_ range: NSRange) {
guard let start = position(from: beginningOfDocument, offset: range.location),
let end = position(from: start, offset: range.length),
let textRange = textRange(from: start, to: end) else {
return
}
replace(textRange, withText: "")
}
private func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
var images = [UIImage?](repeating: nil, count: providers.count)
for (index, provider) in providers.enumerated() {
group.enter()
provider.loadObject(ofClass: UIImage.self) { object, _ in
defer { group.leave() }
guard let image = object as? UIImage else {
return
}
lock.lock()
images[index] = image
lock.unlock()
}
}
group.notify(queue: .main) { [weak self] in
let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage)
if !urls.isEmpty {
self?.onPasteImages?(urls)
}
}
}
override func copy(_ sender: Any?) {
guard selectedRange.length > 0 else {
return super.copy(sender)
}
UIPasteboard.general.string = serializedText(in: selectedRange)
}
override func cut(_ sender: Any?) {
guard isEditable, selectedRange.length > 0 else {
return super.cut(sender)
}
copy(sender)
textStorage.replaceCharacters(in: selectedRange, with: "")
selectedRange = NSRange(location: selectedRange.location, length: 0)
onAttributedMutation?()
}
func serializedText() -> String {
serializedText(in: NSRange(location: 0, length: attributedText.length))
}
func serializedText(in range: NSRange) -> String {
guard range.length > 0 else {
return ""
}
let source = NSMutableString()
let nsString = attributedText.string as NSString
var cursor = range.location
let end = NSMaxRange(range)
attributedText.enumerateAttribute(.attachment, in: range) { value, attachmentRange, _ in
if attachmentRange.location > cursor {
source.append(
nsString.substring(
with: NSRange(location: cursor, length: attachmentRange.location - cursor)
)
)
}
if let attachment = value as? ComposerTextAttachment {
source.append(attachment.source)
} else {
source.append(nsString.substring(with: attachmentRange))
}
cursor = NSMaxRange(attachmentRange)
}
if cursor < end {
source.append(nsString.substring(with: NSRange(location: cursor, length: end - cursor)))
}
return source as String
}
func sourceOffset(forDisplayOffset displayOffset: Int) -> Int {
let boundedOffset = max(0, min(attributedText.length, displayOffset))
if boundedOffset == 0 {
return 0
}
var sourceOffset = 0
let range = NSRange(location: 0, length: boundedOffset)
attributedText.enumerateAttribute(.attachment, in: range) { value, attributeRange, _ in
if let attachment = value as? ComposerTextAttachment {
sourceOffset += (attachment.source as NSString).length
} else {
sourceOffset += attributeRange.length
}
}
return sourceOffset
}
private static func writeTemporaryImage(_ image: UIImage) -> String? {
guard let data = image.pngData() else {
return nil
}
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
do {
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true
)
removeStaleTemporaryImages(in: directory)
let url = directory.appendingPathComponent("\(UUID().uuidString).png")
try data.write(to: url, options: .atomic)
return url.absoluteString
} catch {
return nil
}
}
private static func removeStaleTemporaryImages(in directory: URL) {
let cutoff = Date().addingTimeInterval(-stalePastedImageAge)
guard let urls = try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],
options: [.skipsHiddenFiles]
) else {
return
}
for url in urls {
guard
let values = try? url.resourceValues(
forKeys: [.contentModificationDateKey, .isRegularFileKey]
),
values.isRegularFile == true,
let modifiedAt = values.contentModificationDate,
modifiedAt < cutoff
else {
continue
}
try? FileManager.default.removeItem(at: url)
}
}
}
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
private let textView = ComposerTextView()
private let placeholderLabel = UILabel()
private var value = ""
private var tokensJson = "[]"
private var tokens: [ComposerTokenPayload] = []
private var requestedSelection: ComposerSelectionPayload?
private var theme = ComposerThemePayload(
text: "#262626",
placeholder: "#8e8e93",
chipBackground: "#f2f2f7",
chipBorder: "#dedee3",
chipText: "#262626",
skillBackground: "#f9e8fb",
skillBorder: "#e5a6eb",
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontSize: CGFloat = 15
private var lineHeight: CGFloat = 22
private var contentInsetVertical: CGFloat = 0
private var shouldAutoFocus = false
private var didAutoFocus = false
private var isApplyingControlledValue = false
private var lastContentSize = CGSize.zero
private var iconImages: [String: UIImage] = [:]
private var pendingIconUris = Set<String>()
private var tokensNeedRebuild = false
let onComposerChange = EventDispatcher()
let onComposerSelectionChange = EventDispatcher()
let onComposerFocus = EventDispatcher()
let onComposerBlur = EventDispatcher()
let onComposerPasteImages = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
clipsToBounds = false
textView.delegate = self
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.keyboardDismissMode = .interactive
textView.alwaysBounceVertical = false
textView.showsVerticalScrollIndicator = true
textView.adjustsFontForContentSizeCategory = true
textView.onPasteImages = { [weak self] urls in
self?.onComposerPasteImages(["uris": urls])
}
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
}
addSubview(textView)
placeholderLabel.numberOfLines = 0
placeholderLabel.adjustsFontForContentSizeCategory = true
addSubview(placeholderLabel)
applyTypography()
applyTheme()
}
public override func layoutSubviews() {
super.layoutSubviews()
textView.frame = bounds
let placeholderX = textView.textContainerInset.left + textView.textContainer.lineFragmentPadding
let placeholderY = textView.textContainerInset.top
let placeholderWidth = max(
0,
bounds.width - placeholderX - textView.textContainerInset.right -
textView.textContainer.lineFragmentPadding
)
placeholderLabel.frame = CGRect(
x: placeholderX,
y: placeholderY,
width: placeholderWidth,
height: max(lineHeight, placeholderLabel.font.lineHeight)
)
emitContentSizeIfNeeded()
}
public override func didMoveToWindow() {
super.didMoveToWindow()
guard window != nil, shouldAutoFocus, !didAutoFocus else {
return
}
didAutoFocus = true
DispatchQueue.main.async { [weak self] in
self?.textView.becomeFirstResponder()
}
}
func setValue(_ value: String) {
self.value = value
applyControlledDocument(force: tokensNeedRebuild)
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setTokensJson(_ tokensJson: String) {
guard self.tokensJson != tokensJson else {
return
}
self.tokensJson = tokensJson
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
tokensNeedRebuild = true
applyControlledDocument(force: true)
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setSelectionJson(_ selectionJson: String) {
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
applyRequestedSelection()
}
func setThemeJson(_ themeJson: String) {
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
return
}
theme = nextTheme
applyTheme()
applyControlledDocument(force: true)
}
func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
setNeedsLayout()
}
func setFontFamily(_ fontFamily: String) {
self.fontFamily = fontFamily
applyTypography()
applyControlledDocument(force: true)
}
func setFontSize(_ fontSize: CGFloat) {
self.fontSize = fontSize
applyTypography()
applyControlledDocument(force: true)
}
func setLineHeight(_ lineHeight: CGFloat) {
self.lineHeight = lineHeight
applyTypography()
applyControlledDocument(force: true)
}
func setContentInsetVertical(_ contentInsetVertical: CGFloat) {
self.contentInsetVertical = contentInsetVertical
textView.textContainerInset = UIEdgeInsets(
top: contentInsetVertical,
left: 0,
bottom: contentInsetVertical,
right: 0
)
setNeedsLayout()
}
func setEditable(_ editable: Bool) {
textView.isEditable = editable
}
func setScrollEnabled(_ scrollEnabled: Bool) {
textView.isScrollEnabled = scrollEnabled
}
func setAutoFocus(_ autoFocus: Bool) {
shouldAutoFocus = autoFocus
}
func setAutoCorrect(_ autoCorrect: Bool) {
textView.autocorrectionType = autoCorrect ? .yes : .no
}
func setSpellCheck(_ spellCheck: Bool) {
textView.spellCheckingType = spellCheck ? .yes : .no
}
func focusEditor() {
textView.becomeFirstResponder()
}
func blurEditor() {
textView.resignFirstResponder()
}
func setSelection(start: Int, end: Int) {
requestedSelection = ComposerSelectionPayload(start: start, end: end)
applyRequestedSelection()
}
public func textViewDidChange(_ textView: UITextView) {
emitTextChange()
}
public func textViewDidChangeSelection(_ textView: UITextView) {
guard !isApplyingControlledValue else {
return
}
emitSelection()
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
public func textViewDidEndEditing(_ textView: UITextView) {
onComposerBlur()
}
private func applyControlledDocument(force: Bool = false) {
let currentSource = textView.serializedText()
guard force || currentSource != value || !documentMatchesExpectedTokens() else {
updatePlaceholderVisibility()
return
}
let previousSelection = sourceSelection()
isApplyingControlledValue = true
textView.attributedText = makeAttributedDocument()
let targetSelection = requestedSelection ?? previousSelection
requestedSelection = nil
textView.selectedRange = displayRange(for: targetSelection)
isApplyingControlledValue = false
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
}
private func makeAttributedDocument() -> NSAttributedString {
let result = NSMutableAttributedString()
let source = value as NSString
var cursor = 0
let validTokens = tokens.filter {
$0.start >= cursor &&
$0.end > $0.start &&
$0.end <= source.length &&
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
}
for token in validTokens {
if token.start < cursor {
continue
}
if token.start > cursor {
appendPlainText(
source.substring(with: NSRange(location: cursor, length: token.start - cursor)),
to: result
)
}
result.append(makeAttachmentString(token))
cursor = token.end
}
if cursor < source.length {
appendPlainText(
source.substring(with: NSRange(location: cursor, length: source.length - cursor)),
to: result
)
}
return result
}
private func appendPlainText(_ text: String, to result: NSMutableAttributedString) {
result.append(NSAttributedString(string: text, attributes: baseAttributes()))
}
private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
let isSkill = token.type == "skill"
let tint = UIColor(composerHex: isSkill ? theme.skillText : theme.fileTint) ?? .secondaryLabel
let iconName = isSkill ? "cube" : "doc"
let iconImage = token.iconUri.flatMap(iconImage(for:))
let style = ComposerChipStyle(
tint: tint,
backgroundColor: UIColor(
composerHex: isSkill ? theme.skillBackground : theme.chipBackground
) ?? .secondarySystemFill,
borderColor: UIColor(
composerHex: isSkill ? theme.skillBorder : theme.chipBorder
) ?? .separator,
textColor: UIColor(composerHex: isSkill ? theme.skillText : theme.chipText) ?? .label
)
let image = renderChip(
label: token.label,
iconName: iconName,
iconImage: iconImage,
style: style
)
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
let baselineOffset = floor((font.capHeight - image.size.height) / 2)
let attachment = ComposerTextAttachment(
source: token.source,
image: image,
size: image.size,
baselineOffset: baselineOffset
)
return NSAttributedString(attachment: attachment)
}
private func renderChip(
label: String,
iconName: String,
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .medium)
)
let icon = iconImage ?? fallbackIcon
let textSize = (label as NSString).size(withAttributes: [.font: font])
let iconWidth = icon == nil ? 0 : 14
let iconGap = icon == nil ? 0 : 5
let height: CGFloat = 24
let width = ceil(9 + CGFloat(iconWidth + iconGap) + textSize.width + 9)
let format = UIGraphicsImageRendererFormat.preferred()
format.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
return renderer.image { context in
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
let path = UIBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), cornerRadius: 7)
style.backgroundColor.setFill()
path.fill()
style.borderColor.setStroke()
path.lineWidth = 1
path.stroke()
var x: CGFloat = 9
if let icon {
let renderedIcon = iconImage == nil
? icon.withTintColor(style.tint, renderingMode: .alwaysOriginal)
: icon
renderedIcon.draw(
in: CGRect(x: x, y: 5, width: 14, height: 14)
)
x += 19
}
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .left
(label as NSString).draw(
in: CGRect(x: x, y: 3, width: textSize.width + 1, height: 18),
withAttributes: [
.font: font,
.foregroundColor: style.textColor,
.paragraphStyle: paragraph,
]
)
context.cgContext.setAllowsAntialiasing(true)
}
}
private func iconImage(for uri: String) -> UIImage? {
if let image = iconImages[uri] {
return image
}
guard !pendingIconUris.contains(uri), let url = URL(string: uri) else {
return nil
}
if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {
iconImages[uri] = image
return image
}
pendingIconUris.insert(uri)
URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
guard let self, let data, let image = UIImage(data: data) else {
DispatchQueue.main.async {
self?.pendingIconUris.remove(uri)
}
return
}
DispatchQueue.main.async {
self.pendingIconUris.remove(uri)
self.iconImages[uri] = image
self.applyControlledDocument(force: true)
}
}.resume()
return nil
}
private func baseAttributes() -> [NSAttributedString.Key: Any] {
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = lineHeight
paragraph.maximumLineHeight = lineHeight
return [
.font: font,
.foregroundColor: UIColor(composerHex: theme.text) ?? .label,
.paragraphStyle: paragraph,
]
}
private func applyTypography() {
let font = UIFont(name: fontFamily, size: fontSize)
?? UIFont.systemFont(ofSize: fontSize)
textView.font = font
textView.typingAttributes = baseAttributes()
placeholderLabel.font = font
setNeedsLayout()
}
private func applyTheme() {
textView.textColor = UIColor(composerHex: theme.text) ?? .label
placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
tintColor = UIColor.systemBlue
}
private func emitTextChange() {
guard !isApplyingControlledValue else {
return
}
value = textView.serializedText()
let selection = sourceSelection()
onComposerChange([
"value": value,
"selection": ["start": selection.start, "end": selection.end],
])
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
}
private func emitSelection() {
let selection = sourceSelection()
onComposerSelectionChange([
"selection": ["start": selection.start, "end": selection.end],
])
}
private func sourceSelection() -> ComposerSelectionPayload {
ComposerSelectionPayload(
start: textView.sourceOffset(forDisplayOffset: textView.selectedRange.location),
end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))
)
}
private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {
let start = displayOffset(forSourceOffset: selection.start)
let end = displayOffset(forSourceOffset: selection.end)
return NSRange(location: start, length: max(0, end - start))
}
private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
var collapsedLength = 0
for token in tokens where token.end <= boundedOffset {
collapsedLength += max(0, token.end - token.start - 1)
}
if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
return token.start - collapsedLength + 1
}
return boundedOffset - collapsedLength
}
private func applyRequestedSelection() {
guard let requestedSelection else {
return
}
let nextRange = displayRange(for: requestedSelection)
guard nextRange.location <= textView.attributedText.length,
NSMaxRange(nextRange) <= textView.attributedText.length else {
return
}
isApplyingControlledValue = true
textView.selectedRange = nextRange
isApplyingControlledValue = false
}
private func updatePlaceholderVisibility() {
placeholderLabel.isHidden = !value.isEmpty
}
private func emitContentSizeIfNeeded() {
let nextSize = textView.contentSize
guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
abs(nextSize.height - lastContentSize.height) > 0.5 else {
return
}
lastContentSize = nextSize
onComposerContentSizeChange(["width": nextSize.width, "height": nextSize.height])
}
private func decode<T: Decodable>(_ type: T.Type, from json: String) -> T? {
guard let data = json.data(using: .utf8) else {
return nil
}
return try? JSONDecoder().decode(type, from: data)
}
private func tokensMatchCurrentValue() -> Bool {
let source = value as NSString
return tokens.allSatisfy {
$0.start >= 0 &&
$0.end > $0.start &&
$0.end <= source.length &&
source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
}
}
private func documentMatchesExpectedTokens() -> Bool {
let source = value as NSString
let expectedSources = tokens.compactMap { token -> String? in
guard token.start >= 0,
token.end > token.start,
token.end <= source.length,
source.substring(
with: NSRange(location: token.start, length: token.end - token.start)
) == token.source else {
return nil
}
return token.source
}
var renderedSources: [String] = []
textView.attributedText.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: textView.attributedText.length)
) { value, _, _ in
if let attachment = value as? ComposerTextAttachment {
renderedSources.append(attachment.source)
}
}
return renderedSources == expectedSources
}
}
private extension UIColor {
convenience init?(composerHex hex: String?) {
guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
return nil
}
if value.hasPrefix("#") {
value.removeFirst()
}
guard value.count == 6 || value.count == 8,
let raw = UInt64(value, radix: 16) else {
return nil
}
if value.count == 8 {
self.init(
red: CGFloat((raw >> 24) & 0xff) / 255,
green: CGFloat((raw >> 16) & 0xff) / 255,
blue: CGFloat((raw >> 8) & 0xff) / 255,
alpha: CGFloat(raw & 0xff) / 255
)
} else {
self.init(
red: CGFloat((raw >> 16) & 0xff) / 255,
green: CGFloat((raw >> 8) & 0xff) / 255,
blue: CGFloat(raw & 0xff) / 255,
alpha: 1
)
}
}
}
@@ -1,20 +0,0 @@
MIT License
Copyright (c) 2024-25 Bluesky PBC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,25 +0,0 @@
require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
Pod::Spec.new do |s|
s.name = "T3MarkdownText"
s.version = package["version"]
s.summary = "Native selectable markdown renderer for T3 Code mobile."
s.description = "Fabric-backed attributed text and markdown rendering primitives owned by T3 Code."
s.homepage = "https://t3tools.com"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "T3 Tools" => "[email protected]" }
s.platforms = { :ios => min_ios_version_supported }
s.source = { :path => "." }
s.source_files = "ios/**/*.{h,m,mm,cpp}"
install_modules_dependencies(s)
if ENV["USE_FRAMEWORKS"] != nil && new_arch_enabled
add_dependency(s, "React-FabricComponents", :additional_framework_paths => [
"react/renderer/textlayoutmanager/platform/ios",
])
end
end
@@ -1,12 +0,0 @@
# Upstream Attribution
The Fabric attributed-text component in this module originated from
[`bluesky-social/react-native-uitextview`](https://github.com/bluesky-social/react-native-uitextview),
version `2.2.0`, commit `addc08fea303608f070fe1eeba4bc075f181c4af`.
The upstream project is Copyright (c) 2024-25 Bluesky PBC and licensed under
the MIT License included in this directory.
T3 Code has substantially modified and renamed the implementation, integrated
its markdown renderer, and owns the resulting module going forward. This is not
an upstream package dependency or a compatibility fork.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 870 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 534 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 472 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 620 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

@@ -1,27 +0,0 @@
export { markdownFileIconSource } from "./src/markdownFileIcons";
export {
resolveMarkdownFileIcon,
resolveMarkdownLinkPresentation,
type MarkdownFileIcon,
type MarkdownLinkPresentation,
} from "./src/markdownLinks";
export {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
type NativeMarkdownDocumentChunk,
type NativeMarkdownTextRun,
} from "./src/nativeMarkdownText";
export { MarkdownTextPrimitive } from "./src/MarkdownTextPrimitive";
export {
SelectableMarkdownText,
type MarkdownCodeHighlighter,
type MarkdownHighlightedToken,
} from "./src/SelectableMarkdownText";
export type {
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
SelectableMarkdownTextProps,
} from "./src/SelectableMarkdownText.types";
@@ -1,13 +0,0 @@
#import <React/RCTViewComponentView.h>
#import <UIKit/UIKit.h>
#ifndef T3MarkdownTextNativeComponent_h
#define T3MarkdownTextNativeComponent_h
NS_ASSUME_NONNULL_BEGIN
@interface T3MarkdownText : RCTViewComponentView
@end
NS_ASSUME_NONNULL_END
#endif /* UitextviewViewNativeComponent_h */
@@ -1,592 +0,0 @@
#import "T3MarkdownText.h"
#import "T3MarkdownTextShadowNode.h"
#import "T3MarkdownTextComponentDescriptor.h"
#import "T3MarkdownTextRun.h"
#import <React/RCTConversions.h>
#import <objc/runtime.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
#import "RCTFabricComponentsPlugins.h"
using namespace facebook::react;
static void T3MarkdownTextApplyParagraphStyles(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
{
for (const auto &styleRange : styleRanges) {
if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
continue;
}
const NSRange markerRange = NSMakeRange(
styleRange.location,
MIN(styleRange.length, attributedString.length - styleRange.location));
const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
const NSParagraphStyle *existingStyle =
[attributedString attribute:NSParagraphStyleAttributeName
atIndex:paragraphRange.location
effectiveRange:nil];
NSMutableParagraphStyle *paragraphStyle =
existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
paragraphStyle.headIndent = styleRange.headIndent;
paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
paragraphStyle.tabStops = @[
[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
location:styleRange.headIndent
options:@{}]
];
paragraphStyle.defaultTabInterval = styleRange.headIndent;
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:paragraphRange];
}
}
static void T3MarkdownTextApplyAttachments(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges,
NSDictionary<NSString *, UIImage *> *images)
{
for (const auto &attachmentRange : attachmentRanges) {
if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
continue;
}
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *image = images[imageUri];
if ([imageUri hasPrefix:@"sf:"]) {
NSString *symbolName = [imageUri substringFromIndex:3];
UIColor *foregroundColor =
[attributedString attribute:NSForegroundColorAttributeName
atIndex:attachmentRange.location
effectiveRange:nil] ?: UIColor.labelColor;
image = [[UIImage systemImageNamed:symbolName] imageWithTintColor:foregroundColor
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
NSAttributedString *attachmentString =
[NSAttributedString attributedStringWithAttachment:attachment];
[attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
}
}
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@interface T3MarkdownOutsideTapCoordinator : NSObject <UIGestureRecognizerDelegate>
- (instancetype)initWithWindow:(UIWindow *)window;
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target;
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target;
@end
static const void *T3MarkdownOutsideTapCoordinatorKey =
&T3MarkdownOutsideTapCoordinatorKey;
@implementation T3MarkdownOutsideTapCoordinator {
__weak UIWindow *_window;
UITapGestureRecognizer *_recognizer;
NSHashTable<id<T3MarkdownOutsideTapTarget>> *_targets;
}
- (instancetype)initWithWindow:(UIWindow *)window
{
if (self = [super init]) {
_window = window;
_targets = [NSHashTable weakObjectsHashTable];
_recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
_recognizer.cancelsTouchesInView = NO;
_recognizer.delegate = self;
[window addGestureRecognizer:_recognizer];
}
return self;
}
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target
{
[_targets addObject:target];
}
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target
{
[_targets removeObject:target];
if (_targets.count > 0) {
return;
}
UIWindow *window = _window;
[window removeGestureRecognizer:_recognizer];
if (objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey) == self) {
objc_setAssociatedObject(
window,
T3MarkdownOutsideTapCoordinatorKey,
nil,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
- (void)handleTap:(UITapGestureRecognizer *)sender
{
UIWindow *window = _window;
if (window == nil) {
return;
}
UIView *hitView = [window hitTest:[sender locationInView:window] withEvent:nil];
if (hitView == nil) {
return;
}
for (id<T3MarkdownOutsideTapTarget> target in _targets.allObjects) {
[target clearSelectionForOutsideTapWithHitView:hitView];
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
@end
static T3MarkdownOutsideTapCoordinator *
T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
{
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey);
if (coordinator == nil) {
coordinator = [[T3MarkdownOutsideTapCoordinator alloc] initWithWindow:window];
objc_setAssociatedObject(
window,
T3MarkdownOutsideTapCoordinatorKey,
coordinator,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return coordinator;
}
@interface T3MarkdownText () <RCTT3MarkdownTextViewProtocol, UIGestureRecognizerDelegate, UITextViewDelegate>
@end
@interface T3MarkdownText () <T3MarkdownOutsideTapTarget>
@end
@implementation T3MarkdownText {
UIView * _view;
UITextView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
NSMutableDictionary<NSString *, UIImage *> * _attachmentImages;
NSMutableSet<NSString *> * _pendingAttachmentUris;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
_props = defaultProps;
_view = [[UIView alloc] init];
self.contentView = _view;
self.clipsToBounds = true;
_textView = [[UITextView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
_textView.editable = false;
_textView.textContainerInset = UIEdgeInsetsZero;
_textView.textContainer.lineFragmentPadding = 0;
_textView.delegate = self;
// Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
_textView.layoutManager.usesFontLeading = NO;
[self addSubview:_textView];
const auto longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(handleLongPressIfNecessary:)];
longPressGestureRecognizer.delegate = self;
const auto pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handlePressIfNecessary:)];
pressGestureRecognizer.delegate = self;
[pressGestureRecognizer requireGestureRecognizerToFail:longPressGestureRecognizer];
[_textView addGestureRecognizer:pressGestureRecognizer];
[_textView addGestureRecognizer:longPressGestureRecognizer];
}
return self;
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (_outsideTapWindow == self.window) {
return;
}
if (_outsideTapWindow != nil) {
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
}
_outsideTapWindow = self.window;
if (_outsideTapWindow != nil) {
[T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
}
}
- (void)dealloc
{
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
}
// See RCTParagraphComponentView
- (void)prepareForRecycle
{
[super prepareForRecycle];
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
_outsideTapWindow = nil;
_state.reset();
// Reset the frame to zero so that when it properly lays out on the next use
_textView.frame = CGRectZero;
_textView.attributedText = nil;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// _textView's frame is assigned inside drawRect, which only fires when
// state changes. Trigger a redraw whenever the host frame moves out from
// under it (rotation, parent relayout) so the text view resizes and
// onTextLayout re-fires with the new line wrapping.
if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
[self setNeedsDisplay];
}
}
- (void)drawRect:(CGRect)rect
{
if (!_state) {
return;
}
const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
const auto attrString = _state->getData().attributedString;
NSMutableAttributedString *convertedAttrString =
[RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
T3MarkdownTextApplyParagraphStyles(
convertedAttrString,
_state->getData().paragraphStyleRanges);
T3MarkdownTextApplyAttachments(
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
// the frame triggers a layout flush that has the same effect. Bail out
// entirely when nothing actually changed so a JS-side state update made in
// response to onSelectionChange doesn't deselect what the user is selecting.
const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
if (!textChanged && !frameChanged) {
return;
}
if (textChanged) {
// Reassigning attributedText clears any active selection. Save it and
// restore after, while suppressing the synthetic textViewDidChangeSelection
// events the clear-then-restore would otherwise produce — those would
// round-trip to JS and re-trigger this same path, causing a loop.
const NSRange savedRange = _textView.selectedRange;
_suppressSelectionChange = YES;
_textView.attributedText = convertedAttrString;
if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
_textView.selectedRange = savedRange;
}
_suppressSelectionChange = NO;
}
if (frameChanged) {
_textView.frame = _view.frame;
}
__block std::vector<std::string> lines;
const int maxLines = props.numberOfLines;
[_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
CGRect usedRect,
NSTextContainer * _Nonnull textContainer,
NSRange glyphRange,
BOOL * _Nonnull stop) {
const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
const auto line = [self->_textView.text substringWithRange:charRange];
lines.push_back(line.UTF8String);
// enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
// 18, so cap explicitly.
if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
*stop = YES;
}
}];
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
};
}
- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
{
for (const auto &attachmentRange : attachmentRanges) {
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
if ([imageUri hasPrefix:@"sf:"]) {
continue;
}
if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
continue;
}
NSURL *url = [NSURL URLWithString:imageUri];
if (url == nil) {
continue;
}
if (url.isFileURL) {
UIImage *image = [UIImage imageWithContentsOfFile:url.path];
if (image != nil) {
_attachmentImages[imageUri] = image;
dispatch_async(dispatch_get_main_queue(), ^{
[self refreshDisplayedAttachments];
});
}
continue;
}
[_pendingAttachmentUris addObject:imageUri];
[[[NSURLSession sharedSession] dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[self->_pendingAttachmentUris removeObject:imageUri];
if (image != nil) {
self->_attachmentImages[imageUri] = image;
[self refreshDisplayedAttachments];
}
});
}] resume];
}
}
- (void)refreshDisplayedAttachments
{
if (!_state || _textView.attributedText == nil) {
return;
}
NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
T3MarkdownTextApplyAttachments(
attributedText,
_state->getData().attachmentRanges,
_attachmentImages);
const NSRange savedRange = _textView.selectedRange;
_suppressSelectionChange = YES;
_textView.attributedText = attributedText;
if (savedRange.location != NSNotFound &&
NSMaxRange(savedRange) <= _textView.attributedText.length) {
_textView.selectedRange = savedRange;
}
_suppressSelectionChange = NO;
[_textView setNeedsDisplay];
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
_textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
}
if (oldViewProps.selectable != newViewProps.selectable) {
_textView.selectable = newViewProps.selectable;
}
if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
if (@available(iOS 11.0, *)) {
_textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
}
}
if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
}
}
// I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
// is in will have this background color applied. To apply it just to a particular part of a string, you'd need
// to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
// This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
_textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
}
[super updateProps:props oldProps:oldProps];
}
// See RCTParagraphComponentView
- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
{
_state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
[self setNeedsDisplay];
}
// MARK: - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
return YES;
}
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
{
if ([hitView isDescendantOfView:self]) {
return;
}
// Defer past the current event loop turn so any in-flight edit-menu action
// (Copy / Define / Look Up / …) reads the live selection before we clear it.
UITextView *textView = _textView;
dispatch_async(dispatch_get_main_queue(), ^{
UITextRange *range = textView.selectedTextRange;
if (range != nil && !range.isEmpty) {
textView.selectedTextRange = nil;
}
});
}
// MARK: - Touch handling
- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
{
return [sender locationInView:_textView];
}
- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
{
const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
inTextContainer:_textView.textContainer
fractionOfDistanceBetweenInsertionPoints:nil
];
int currIndex = -1;
for (UIView* child in self.subviews) {
if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
continue;
}
T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
// This is UTF16 code units!!
currIndex += textChild.text.length;
if (charIndex <= currIndex) {
return textChild;
}
}
return nil;
}
- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
{
const auto location = [self getLocationOfPress:sender];
const auto child = [self getTouchChild:location];
if (child) {
[child onPress];
}
}
- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
{
const auto location = [self getLocationOfPress:sender];
const auto child = [self getTouchChild:location];
if (child) {
[child onLongPress];
}
}
// MARK: - UITextViewDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView
{
if (_suppressSelectionChange) {
return;
}
if (_eventEmitter == nullptr) {
return;
}
const NSRange selectedRange = textView.selectedRange;
if (selectedRange.location == NSNotFound) {
return;
}
// Fires on programmatic selection changes too (e.g. the outside-tap clear
// in handleOutsideTap:), so JS will see a synthetic empty-range event then.
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
static_cast<int>(self.tag),
static_cast<int>(selectedRange.location),
static_cast<int>(selectedRange.location + selectedRange.length),
});
}
Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
{
return T3MarkdownText.class;
}
@end
@@ -1,13 +0,0 @@
#pragma once
#include "T3MarkdownTextShadowNode.h"
#include <react/renderer/core/ConcreteComponentDescriptor.h>
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
namespace facebook::react {
using T3MarkdownTextComponentDescriptor = ConcreteComponentDescriptor<T3MarkdownTextShadowNode>;
void T3MarkdownTextSpec_registerComponentDescriptorsFromCodegen(
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
}
@@ -1,36 +0,0 @@
#import <React/RCTViewManager.h>
#import <React/RCTUIManager.h>
#import "RCTBridge.h"
#import "Utils.h"
@interface T3MarkdownTextManager : RCTViewManager
@end
@implementation T3MarkdownTextManager
RCT_EXPORT_MODULE(T3MarkdownText)
- (UIView *)view
{
return [[UIView alloc] init];
}
RCT_CUSTOM_VIEW_PROPERTY(color, NSString, UIView)
{
}
@end
@interface T3MarkdownTextRunManager : RCTViewManager
@end
@implementation T3MarkdownTextRunManager
RCT_EXPORT_MODULE(T3MarkdownTextRun)
- (UIView *)view
{
return nil;
}
@end
@@ -1,24 +0,0 @@
// This guard prevent this file to be compiled in the old architecture.
#ifdef RCT_NEW_ARCH_ENABLED
#import <React/RCTViewComponentView.h>
#import <React/RCTComponent.h>
#import <UIKit/UIKit.h>
#ifndef T3MarkdownTextRunNativeComponent_h
#define T3MarkdownTextRunNativeComponent_h
NS_ASSUME_NONNULL_BEGIN
@interface T3MarkdownTextRun : RCTViewComponentView
@property (nonatomic, copy, nullable) NSString *text;
- (void)onPress;
- (void)onLongPress;
@end
NS_ASSUME_NONNULL_END
#endif /* UitextviewViewNativeComponent_h */
#endif /* RCT_NEW_ARCH_ENABLED */
@@ -1,72 +0,0 @@
#import "T3MarkdownTextRun.h"
#import "T3MarkdownText.h"
#import "T3MarkdownTextRunComponentDescriptor.h"
#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
#import "RCTFabricComponentsPlugins.h"
#import "Utils.h"
using namespace facebook::react;
@interface T3MarkdownTextRun () <RCTT3MarkdownTextRunViewProtocol>
@end
@implementation T3MarkdownTextRun {
NSString * _text;
RCTBubblingEventBlock _onPress;
RCTBubblingEventBlock _onLongPress;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<T3MarkdownTextRunComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const T3MarkdownTextRunProps>();
_props = defaultProps;
}
return self;
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextRunProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextRunProps const>(props);
if (newViewProps.text != oldViewProps.text) {
NSString *text = [NSString stringWithUTF8String:newViewProps.text.c_str()];
_text = text;
}
[super updateProps:props oldProps:oldProps];
}
- (void)onPress {
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextRunEventEmitter>(_eventEmitter)
->onPress(facebook::react::T3MarkdownTextRunEventEmitter::OnPress{});
}
}
- (void)onLongPress {
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextRunEventEmitter>(_eventEmitter)
->onLongPress(facebook::react::T3MarkdownTextRunEventEmitter::OnLongPress{});
}
}
+ (BOOL)shouldBeRecycled {
return NO;
}
Class<RCTComponentViewProtocol> T3MarkdownTextRunCls(void)
{
return T3MarkdownTextRun.class;
}
@end
Loaded 100 of 890 files, more files were not shown because too many files have changed in this diff. Show more