Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
487295d5bf | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 |
No files matched your search
@@ -180,12 +180,46 @@ 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
|
||||
@@ -272,6 +306,20 @@ 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 }}"
|
||||
|
||||
@@ -508,6 +556,20 @@ 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 }}"
|
||||
|
||||
@@ -670,6 +732,20 @@ 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 }}"
|
||||
|
||||
@@ -716,6 +792,9 @@ 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,5 +1,6 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
@@ -33,6 +34,8 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -57,7 +60,7 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -65,7 +68,7 @@ function killChildTreeByPid(pid, signal) {
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -194,7 +197,7 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
@@ -30,9 +31,11 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 10;
|
||||
const LAUNCHER_VERSION = 11;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function resolveDevelopmentProtocolCallbackPort() {
|
||||
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
|
||||
@@ -295,7 +298,11 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
@@ -308,7 +315,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (process.platform !== "linux") {
|
||||
if (hostPlatform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -338,7 +345,7 @@ export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
@@ -354,7 +361,7 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (process.platform !== "darwin" || !isDevelopment) {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { arch, platform, tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (process.platform) {
|
||||
switch (hostPlatform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -17,12 +21,12 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (process.platform !== "win32") {
|
||||
if (hostPlatform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +43,7 @@ function repairPathFile(electronDir, platformPath) {
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
@@ -58,7 +62,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -76,7 +80,7 @@ function missingRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -111,16 +115,16 @@ function runChecked(command, args) {
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
|
||||
@@ -49,7 +49,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export interface ElectronMenuPosition {
|
||||
readonly x: number;
|
||||
@@ -79,109 +80,113 @@ const normalizePosition = (
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const layer = Layer.sync(ElectronMenu, () => {
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
export const layer = Layer.effect(
|
||||
ElectronMenu,
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
});
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -6,6 +6,7 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -37,6 +38,7 @@ export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWind
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
@@ -98,7 +100,7 @@ const make = Effect.gen(function* () {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
@@ -53,11 +54,13 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
|
||||
Effect.flatMap((app) => app.metadata),
|
||||
);
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const processArch = yield* HostProcessArchitecture;
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: __dirname,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
platform,
|
||||
processArch,
|
||||
...metadata,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -189,6 +189,55 @@ 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* () {
|
||||
|
||||
@@ -1344,7 +1344,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
};
|
||||
const onDestroyed = () => settle(null);
|
||||
const onNavigated = () => settle(null);
|
||||
const onNavigated = (
|
||||
_event: Electron.Event,
|
||||
_url: string,
|
||||
_isInPlace: boolean,
|
||||
isMainFrame: boolean,
|
||||
) => {
|
||||
if (isMainFrame) settle(null);
|
||||
};
|
||||
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
|
||||
yield* attempt("pickElement.register", () => {
|
||||
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
|
||||
|
||||
@@ -68,6 +68,7 @@ function makeFakeBrowserWindow() {
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setAutoHideCursor: vi.fn(),
|
||||
setTitle: vi.fn(),
|
||||
setTitleBarOverlay: vi.fn(),
|
||||
show: vi.fn(),
|
||||
@@ -78,6 +79,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
}
|
||||
@@ -134,10 +136,17 @@ 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: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
|
||||
create: (options) =>
|
||||
Effect.sync(() => {
|
||||
input.createdWindowOptions?.push(options);
|
||||
}).pipe(
|
||||
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
|
||||
Effect.as(input.window),
|
||||
),
|
||||
main: Ref.get(input.mainWindow),
|
||||
currentMainOrFirst: Ref.get(input.mainWindow),
|
||||
focusedMainOrFirst: Ref.get(input.mainWindow),
|
||||
@@ -205,10 +214,12 @@ 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* () {
|
||||
@@ -218,6 +229,8 @@ 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));
|
||||
|
||||
@@ -82,9 +82,10 @@ function resolveDesktopDevServerUrl(
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
platform: NodeJS.Platform,
|
||||
): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = platform === "win32" ? "ico" : "png";
|
||||
return Option.match(iconPaths[ext], {
|
||||
onNone: () => ({}),
|
||||
onSome: (icon) => ({ icon }),
|
||||
@@ -106,8 +107,11 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): WindowTitleBarOptions {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
@@ -127,6 +131,7 @@ function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarO
|
||||
function syncWindowAppearance(
|
||||
window: Electron.BrowserWindow,
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
@@ -134,7 +139,7 @@ function syncWindowAppearance(
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
@@ -179,7 +184,7 @@ const make = Effect.gen(function* () {
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths);
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const window = yield* electronWindow.create({
|
||||
width: 1100,
|
||||
@@ -188,10 +193,11 @@ const make = Effect.gen(function* () {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
...iconOption,
|
||||
title: environment.displayName,
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors),
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
|
||||
webPreferences: {
|
||||
preload: environment.preloadPath,
|
||||
contextIsolation: true,
|
||||
@@ -201,6 +207,10 @@ 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 (
|
||||
@@ -318,7 +328,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (process.platform === "linux") {
|
||||
if (environment.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
@@ -408,7 +418,7 @@ const make = Effect.gen(function* () {
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
yield* electronWindow.syncAllAppearance((window) =>
|
||||
syncWindowAppearance(window, shouldUseDarkColors),
|
||||
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"neutral": "#F5F5F5",
|
||||
"border": "#E5E5EA",
|
||||
"ring": "#A3A3A3",
|
||||
"muted": "#F5F5F5",
|
||||
"muted": "#F2F2F7",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"darkColors": {
|
||||
@@ -30,7 +30,7 @@
|
||||
"neutral": "#1C1C1C",
|
||||
"border": "#2A2A2A",
|
||||
"ring": "#525252",
|
||||
"muted": "#1C1C1C",
|
||||
"muted": "#0E0E0E",
|
||||
"shadow": "#000000"
|
||||
},
|
||||
"design": {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
--color-foreground: #262626;
|
||||
--color-foreground-secondary: #525252;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #a3a3a3;
|
||||
--color-foreground-tertiary: #8e8e93;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(0, 0, 0, 0.08);
|
||||
@@ -28,6 +28,9 @@
|
||||
/* 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;
|
||||
@@ -58,6 +61,8 @@
|
||||
/* 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;
|
||||
@@ -105,8 +110,8 @@
|
||||
/* Text */
|
||||
--color-foreground: #f5f5f5;
|
||||
--color-foreground-secondary: #a3a3a3;
|
||||
--color-foreground-muted: #737373;
|
||||
--color-foreground-tertiary: #525252;
|
||||
--color-foreground-muted: #8e8e93;
|
||||
--color-foreground-tertiary: #636366;
|
||||
|
||||
/* Borders & separators */
|
||||
--color-border: rgba(255, 255, 255, 0.06);
|
||||
@@ -116,6 +121,9 @@
|
||||
/* 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;
|
||||
@@ -136,16 +144,18 @@
|
||||
/* Inputs */
|
||||
--color-input: #141414;
|
||||
--color-input-border: rgba(255, 255, 255, 0.08);
|
||||
--color-placeholder: #737373;
|
||||
--color-placeholder: #8e8e93;
|
||||
|
||||
/* Icons */
|
||||
--color-icon: #f5f5f5;
|
||||
--color-icon-muted: #a3a3a3;
|
||||
--color-icon-subtle: #737373;
|
||||
--color-icon-subtle: #8e8e93;
|
||||
|
||||
/* 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;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ComposerEditorModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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
|
||||
@@ -0,0 +1,71 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,819 @@
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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.
|
||||
@@ -0,0 +1,25 @@
|
||||
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
|
||||
@@ -0,0 +1,12 @@
|
||||
# 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.
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 870 B |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 534 B |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 472 B |
|
After Width: | Height: | Size: 620 B |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 497 B |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,27 @@
|
||||
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";
|
||||
@@ -0,0 +1,13 @@
|
||||
#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 */
|
||||
@@ -0,0 +1,688 @@
|
||||
#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];
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
NSAttributedString *attachmentString =
|
||||
[NSAttributedString attributedStringWithAttachment:attachment];
|
||||
[attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
|
||||
}
|
||||
}
|
||||
|
||||
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextChipRange> &chipRanges)
|
||||
{
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
|
||||
for (const auto &chipRange : chipRanges) {
|
||||
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange range = NSMakeRange(
|
||||
chipRange.location,
|
||||
MIN(chipRange.length, attributedString.length - chipRange.location));
|
||||
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
if (color == nil) {
|
||||
continue;
|
||||
}
|
||||
[backgrounds addObject:@{
|
||||
@"range": [NSValue valueWithRange:range],
|
||||
@"color": color,
|
||||
@"strokeColor": [foregroundColor
|
||||
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
|
||||
}];
|
||||
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
|
||||
}
|
||||
return backgrounds;
|
||||
}
|
||||
|
||||
@interface T3MarkdownTextBackingView : UITextView
|
||||
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownTextBackingView
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
if (context != nil) {
|
||||
CGContextSaveGState(context);
|
||||
CGContextResetClip(context);
|
||||
CGContextClipToRect(context, self.bounds);
|
||||
}
|
||||
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
|
||||
const NSRange characterRange = [background[@"range"] rangeValue];
|
||||
UIColor *color = background[@"color"];
|
||||
UIColor *strokeColor = background[@"strokeColor"];
|
||||
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange glyphRange =
|
||||
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
|
||||
[color setFill];
|
||||
[self.layoutManager
|
||||
enumerateEnclosingRectsForGlyphRange:glyphRange
|
||||
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
|
||||
inTextContainer:self.textContainer
|
||||
usingBlock:^(CGRect glyphRect, BOOL *stop) {
|
||||
const CGFloat chipHeight = 22;
|
||||
CGRect chipRect = CGRectMake(
|
||||
glyphRect.origin.x - 4,
|
||||
CGRectGetMidY(glyphRect) - chipHeight / 2,
|
||||
glyphRect.size.width + 8,
|
||||
chipHeight);
|
||||
chipRect.origin.x += self.textContainerInset.left;
|
||||
chipRect.origin.y += self.textContainerInset.top;
|
||||
const CGFloat minimumX = self.textContainerInset.left + 0.5;
|
||||
const CGFloat maximumX =
|
||||
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
|
||||
if (chipRect.origin.x < minimumX) {
|
||||
chipRect.size.width -= minimumX - chipRect.origin.x;
|
||||
chipRect.origin.x = minimumX;
|
||||
}
|
||||
if (CGRectGetMaxX(chipRect) > maximumX) {
|
||||
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
|
||||
}
|
||||
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
|
||||
[path fill];
|
||||
[strokeColor setStroke];
|
||||
path.lineWidth = 1;
|
||||
[path stroke];
|
||||
}];
|
||||
}
|
||||
if (context != nil) {
|
||||
CGContextRestoreGState(context);
|
||||
}
|
||||
|
||||
[super drawRect:rect];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@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;
|
||||
T3MarkdownTextBackingView * _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 = [[T3MarkdownTextBackingView 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);
|
||||
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
|
||||
convertedAttrString,
|
||||
_state->getData().chipRanges);
|
||||
[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
|
||||
@@ -0,0 +1,13 @@
|
||||
#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);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#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
|
||||
@@ -0,0 +1,24 @@
|
||||
// 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 */
|
||||
@@ -0,0 +1,72 @@
|
||||
#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
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include "T3MarkdownTextRunShadowNode.h"
|
||||
|
||||
#include <react/renderer/core/ConcreteComponentDescriptor.h>
|
||||
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
|
||||
|
||||
namespace facebook::react {
|
||||
using T3MarkdownTextRunComponentDescriptor = ConcreteComponentDescriptor<T3MarkdownTextRunShadowNode>;
|
||||
|
||||
void T3MarkdownTextRunSpec_registerComponentDescriptorsFromCodegen(
|
||||
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#include "T3MarkdownTextRunShadowNode.h"
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
extern const char T3MarkdownTextRunComponentName[] = "T3MarkdownTextRun";
|
||||
} // namespace facebook::react
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
|
||||
#include <react/renderer/components/T3MarkdownTextSpec/Props.h>
|
||||
#include <react/renderer/components/T3MarkdownTextSpec/States.h>
|
||||
#include <react/renderer/components/view/ConcreteViewShadowNode.h>
|
||||
|
||||
namespace facebook::react {
|
||||
extern const char T3MarkdownTextRunComponentName[];
|
||||
|
||||
using T3MarkdownTextRunShadowNode = ConcreteViewShadowNode<
|
||||
T3MarkdownTextRunComponentName,
|
||||
T3MarkdownTextRunProps,
|
||||
T3MarkdownTextRunEventEmitter,
|
||||
T3MarkdownTextRunState>;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
|
||||
#include <react/renderer/components/T3MarkdownTextSpec/Props.h>
|
||||
#include <react/renderer/components/view/ConcreteViewShadowNode.h>
|
||||
#include <react/renderer/textlayoutmanager/TextLayoutManager.h>
|
||||
#include <react/renderer/core/LayoutContext.h>
|
||||
#include <react/renderer/core/ShadowNode.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
extern const char T3MarkdownTextComponentName[];
|
||||
|
||||
struct T3MarkdownTextParagraphStyleRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
Float firstLineHeadIndent;
|
||||
Float headIndent;
|
||||
Float paragraphSpacing;
|
||||
};
|
||||
|
||||
struct T3MarkdownTextAttachmentRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
std::string imageUri;
|
||||
};
|
||||
|
||||
struct T3MarkdownTextChipRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
bool isSkill;
|
||||
};
|
||||
|
||||
class T3MarkdownTextStateReal final {
|
||||
public:
|
||||
AttributedString attributedString;
|
||||
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
|
||||
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
|
||||
std::vector<T3MarkdownTextChipRange> chipRanges;
|
||||
};
|
||||
|
||||
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
|
||||
T3MarkdownTextComponentName,
|
||||
T3MarkdownTextProps,
|
||||
T3MarkdownTextEventEmitter,
|
||||
T3MarkdownTextStateReal> {
|
||||
public:
|
||||
using ConcreteViewShadowNode::ConcreteViewShadowNode;
|
||||
|
||||
T3MarkdownTextShadowNode(
|
||||
const ShadowNode& sourceShadowNode,
|
||||
const ShadowNodeFragment& fragment
|
||||
);
|
||||
|
||||
static ShadowNodeTraits BaseTraits() {
|
||||
auto traits = ConcreteViewShadowNode::BaseTraits();
|
||||
traits.set(ShadowNodeTraits::Trait::LeafYogaNode);
|
||||
traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode);
|
||||
return traits;
|
||||
}
|
||||
|
||||
void layout(LayoutContext layoutContext) override;
|
||||
|
||||
Size measureContent(
|
||||
const LayoutContext& layoutContext,
|
||||
const LayoutConstraints& layoutConstraints) const override;
|
||||
|
||||
private:
|
||||
mutable AttributedString _attributedString;
|
||||
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
|
||||
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
|
||||
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
|
||||
};
|
||||
} // namespace facebook::React
|
||||
@@ -0,0 +1,269 @@
|
||||
#include "T3MarkdownTextShadowNode.h"
|
||||
#include "T3MarkdownTextRunShadowNode.h"
|
||||
#include <react/renderer/components/view/ViewShadowNode.h>
|
||||
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
static constexpr Float ParagraphStyleEncodingOffset = 1000;
|
||||
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
|
||||
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
|
||||
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
|
||||
|
||||
static void applyParagraphStyles(
|
||||
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 applyAttachments(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges)
|
||||
{
|
||||
for (const auto &attachmentRange : attachmentRanges) {
|
||||
if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
attachment.image = [[UIImage alloc] init];
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
NSAttributedString *attachmentString =
|
||||
[NSAttributedString attributedStringWithAttachment:attachment];
|
||||
[attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
|
||||
}
|
||||
}
|
||||
|
||||
T3MarkdownTextShadowNode::T3MarkdownTextShadowNode(
|
||||
const ShadowNode& sourceShadowNode,
|
||||
const ShadowNodeFragment& fragment
|
||||
) : ConcreteViewShadowNode(sourceShadowNode, fragment) {
|
||||
};
|
||||
|
||||
Size T3MarkdownTextShadowNode::measureContent(
|
||||
const LayoutContext& layoutContext,
|
||||
const LayoutConstraints& layoutConstraints) const {
|
||||
const auto &baseProps = getConcreteProps();
|
||||
|
||||
auto baseTextAttributes = TextAttributes::defaultTextAttributes();
|
||||
baseTextAttributes.backgroundColor = baseProps.backgroundColor;
|
||||
baseTextAttributes.allowFontScaling = baseProps.allowFontScaling;
|
||||
|
||||
Float fontSizeMultiplier = 1.0;
|
||||
if (baseTextAttributes.allowFontScaling) {
|
||||
fontSizeMultiplier = layoutContext.fontSizeMultiplier;
|
||||
}
|
||||
|
||||
auto baseAttributedString = AttributedString{};
|
||||
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
|
||||
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
|
||||
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
|
||||
size_t utf16Offset = 0;
|
||||
const auto &children = getChildren();
|
||||
for (size_t i = 0; i < children.size(); i++) {
|
||||
const auto child = children[i].get();
|
||||
if (auto textViewChild = dynamic_cast<const T3MarkdownTextRunShadowNode *>(child)) {
|
||||
auto &props = textViewChild->getConcreteProps();
|
||||
auto fragment = AttributedString::Fragment{};
|
||||
auto textAttributes = TextAttributes::defaultTextAttributes();
|
||||
|
||||
textAttributes.allowFontScaling = baseProps.allowFontScaling;
|
||||
textAttributes.backgroundColor = props.backgroundColor;
|
||||
textAttributes.fontSize = props.fontSize * fontSizeMultiplier;
|
||||
textAttributes.lineHeight = props.lineHeight * fontSizeMultiplier;
|
||||
textAttributes.foregroundColor = props.color;
|
||||
const bool hasParagraphStyle = props.shadowRadius >= ParagraphStyleEncodingOffset;
|
||||
if (!hasParagraphStyle) {
|
||||
textAttributes.textShadowColor = props.shadowColor;
|
||||
textAttributes.textShadowOffset = props.shadowOffset;
|
||||
textAttributes.textShadowRadius = props.shadowRadius;
|
||||
}
|
||||
textAttributes.letterSpacing = props.letterSpacing;
|
||||
textAttributes.textDecorationColor = props.textDecorationColor;
|
||||
textAttributes.fontFamily = props.fontFamily;
|
||||
|
||||
if (props.fontStyle == T3MarkdownTextRunFontStyle::Italic) {
|
||||
textAttributes.fontStyle = FontStyle::Italic;
|
||||
} else {
|
||||
textAttributes.fontStyle = FontStyle::Normal;
|
||||
}
|
||||
|
||||
if (props.fontWeight == T3MarkdownTextRunFontWeight::Bold) {
|
||||
textAttributes.fontWeight = FontWeight::Bold;
|
||||
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::UltraLight) {
|
||||
textAttributes.fontWeight = FontWeight::UltraLight;
|
||||
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Light) {
|
||||
textAttributes.fontWeight = FontWeight::Light;
|
||||
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Medium) {
|
||||
textAttributes.fontWeight = FontWeight::Medium;
|
||||
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Semibold) {
|
||||
textAttributes.fontWeight = FontWeight::Semibold;
|
||||
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Heavy) {
|
||||
textAttributes.fontWeight = FontWeight::Heavy;
|
||||
} else {
|
||||
textAttributes.fontWeight = FontWeight::Regular;
|
||||
}
|
||||
|
||||
if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::LineThrough) {
|
||||
textAttributes.textDecorationLineType = TextDecorationLineType::Strikethrough;
|
||||
} else if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::Underline) {
|
||||
textAttributes.textDecorationLineType = TextDecorationLineType::Underline;
|
||||
} else {
|
||||
textAttributes.textDecorationLineType = TextDecorationLineType::None;
|
||||
}
|
||||
|
||||
if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Solid) {
|
||||
textAttributes.textDecorationStyle = TextDecorationStyle::Solid;
|
||||
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dotted) {
|
||||
textAttributes.textDecorationStyle = TextDecorationStyle::Dotted;
|
||||
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dashed) {
|
||||
textAttributes.textDecorationStyle = TextDecorationStyle::Dashed;
|
||||
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Double) {
|
||||
textAttributes.textDecorationStyle = TextDecorationStyle::Double;
|
||||
}
|
||||
|
||||
if (props.textAlign == T3MarkdownTextRunTextAlign::Left) {
|
||||
textAttributes.alignment = TextAlignment::Left;
|
||||
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Right) {
|
||||
textAttributes.alignment = TextAlignment::Right;
|
||||
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Center) {
|
||||
textAttributes.alignment = TextAlignment::Center;
|
||||
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Justify) {
|
||||
textAttributes.alignment = TextAlignment::Justified;
|
||||
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Auto) {
|
||||
textAttributes.alignment = TextAlignment::Natural;
|
||||
}
|
||||
|
||||
textAttributes.backgroundColor = props.backgroundColor;
|
||||
|
||||
fragment.string = props.text;
|
||||
fragment.textAttributes = textAttributes;
|
||||
|
||||
NSString *fragmentText = [NSString stringWithUTF8String:props.text.c_str()];
|
||||
const size_t fragmentLength = fragmentText.length;
|
||||
if (hasParagraphStyle) {
|
||||
paragraphStyleRanges.push_back(T3MarkdownTextParagraphStyleRange{
|
||||
utf16Offset,
|
||||
fragmentLength,
|
||||
props.shadowOffset.width,
|
||||
props.shadowOffset.height,
|
||||
props.shadowRadius - ParagraphStyleEncodingOffset,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
chipRanges.push_back(T3MarkdownTextChipRange{
|
||||
utf16Offset,
|
||||
fragmentLength,
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
|
||||
});
|
||||
}
|
||||
utf16Offset += fragmentLength;
|
||||
baseAttributedString.appendFragment(std::move(fragment));
|
||||
}
|
||||
}
|
||||
|
||||
_attributedString = baseAttributedString;
|
||||
_paragraphStyleRanges = paragraphStyleRanges;
|
||||
_attachmentRanges = attachmentRanges;
|
||||
_chipRanges = chipRanges;
|
||||
|
||||
NSMutableAttributedString *convertedAttributedString =
|
||||
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
|
||||
applyParagraphStyles(convertedAttributedString, paragraphStyleRanges);
|
||||
applyAttachments(convertedAttributedString, attachmentRanges);
|
||||
|
||||
const CGFloat maximumWidth = std::isfinite(layoutConstraints.maximumSize.width)
|
||||
? layoutConstraints.maximumSize.width
|
||||
: CGFLOAT_MAX;
|
||||
NSTextStorage *textStorage =
|
||||
[[NSTextStorage alloc] initWithAttributedString:convertedAttributedString];
|
||||
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
|
||||
layoutManager.usesFontLeading = NO;
|
||||
NSTextContainer *textContainer =
|
||||
[[NSTextContainer alloc] initWithSize:CGSizeMake(maximumWidth, CGFLOAT_MAX)];
|
||||
textContainer.lineFragmentPadding = 0;
|
||||
textContainer.maximumNumberOfLines = baseProps.numberOfLines;
|
||||
if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
|
||||
textContainer.lineBreakMode = NSLineBreakByTruncatingHead;
|
||||
} else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
|
||||
textContainer.lineBreakMode = NSLineBreakByTruncatingMiddle;
|
||||
} else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
|
||||
textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
|
||||
} else {
|
||||
textContainer.lineBreakMode = NSLineBreakByClipping;
|
||||
}
|
||||
[layoutManager addTextContainer:textContainer];
|
||||
[textStorage addLayoutManager:layoutManager];
|
||||
[layoutManager ensureLayoutForTextContainer:textContainer];
|
||||
const CGRect usedRect = [layoutManager usedRectForTextContainer:textContainer];
|
||||
|
||||
return {
|
||||
std::clamp(
|
||||
static_cast<Float>(std::ceil(usedRect.size.width)),
|
||||
layoutConstraints.minimumSize.width,
|
||||
layoutConstraints.maximumSize.width),
|
||||
std::clamp(
|
||||
static_cast<Float>(std::ceil(usedRect.size.height)),
|
||||
layoutConstraints.minimumSize.height,
|
||||
layoutConstraints.maximumSize.height),
|
||||
};
|
||||
}
|
||||
|
||||
void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
|
||||
ensureUnsealed();
|
||||
setStateData(T3MarkdownTextStateReal{
|
||||
_attributedString,
|
||||
_paragraphStyleRanges,
|
||||
_attachmentRanges,
|
||||
_chipRanges,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@t3tools/mobile-markdown-text",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"source": "./index.ts",
|
||||
"files": [
|
||||
"assets",
|
||||
"ios",
|
||||
"src",
|
||||
"index.ts",
|
||||
"LICENSE",
|
||||
"UPSTREAM.md",
|
||||
"T3MarkdownText.podspec",
|
||||
"react-native.config.js"
|
||||
],
|
||||
"main": "./index.ts",
|
||||
"types": "./index.ts",
|
||||
"react-native": "./index.ts",
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./file-icons": "./src/markdownFileIcons.ts",
|
||||
"./links": "./src/markdownLinks.ts",
|
||||
"./markdown": "./src/nativeMarkdownText.ts",
|
||||
"./primitive": "./src/MarkdownTextPrimitive.tsx",
|
||||
"./renderer": "./src/SelectableMarkdownText.ios.tsx",
|
||||
"./types": "./src/SelectableMarkdownText.types.ts"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo-asset": "*",
|
||||
"expo-clipboard": "*",
|
||||
"expo-haptics": "*",
|
||||
"expo-symbols": "*",
|
||||
"react": "*",
|
||||
"react-native": "*",
|
||||
"react-native-nitro-markdown": "*"
|
||||
},
|
||||
"codegenConfig": {
|
||||
"name": "T3MarkdownTextSpec",
|
||||
"type": "all",
|
||||
"jsSrcsDir": "src",
|
||||
"ios": {
|
||||
"componentProvider": {
|
||||
"T3MarkdownText": "T3MarkdownText",
|
||||
"T3MarkdownTextRun": "T3MarkdownTextRun"
|
||||
}
|
||||
},
|
||||
"outputDir": {
|
||||
"ios": "ios/generated"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
module.exports = {
|
||||
dependency: {
|
||||
platforms: {
|
||||
ios: {
|
||||
podspecPath: "T3MarkdownText.podspec",
|
||||
},
|
||||
android: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { getBuiltInSpriteSheet } from "@pierre/trees";
|
||||
|
||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||
const moduleDirectory = resolve(scriptDirectory, "..");
|
||||
const repositoryRoot = resolve(moduleDirectory, "../../../..");
|
||||
const outputDirectory = join(moduleDirectory, "assets/file-icons");
|
||||
const generatedModulePath = join(moduleDirectory, "src/markdownFileIcons.generated.ts");
|
||||
const webIconSource = readFileSync(join(repositoryRoot, "apps/web/src/pierre-icons.ts"), "utf8");
|
||||
const customSprite = webIconSource.match(/const T3_FILE_ICON_SPRITE = `([\s\S]*?)`;/)?.[1];
|
||||
|
||||
if (!customSprite) {
|
||||
throw new Error("Could not read the T3 Pierre icon sprite from apps/web/src/pierre-icons.ts");
|
||||
}
|
||||
|
||||
const colors = {
|
||||
astro: "#a631be",
|
||||
babel: "#d5a910",
|
||||
bash: "#199f43",
|
||||
biome: "#1a85d4",
|
||||
bootstrap: "#693acf",
|
||||
browserslist: "#d5a910",
|
||||
bun: "#594c5b",
|
||||
c: "#1a85d4",
|
||||
claude: "#d47628",
|
||||
cpp: "#1a85d4",
|
||||
css: "#693acf",
|
||||
database: "#a631be",
|
||||
default: "#84848a",
|
||||
docker: "#1a85d4",
|
||||
eslint: "#693acf",
|
||||
font: "#84848a",
|
||||
git: "#ff8c5b",
|
||||
go: "#1ca1c7",
|
||||
graphql: "#d32a61",
|
||||
html: "#d47628",
|
||||
image: "#d32a61",
|
||||
javascript: "#d5a910",
|
||||
json: "#d47628",
|
||||
markdown: "#199f43",
|
||||
mcp: "#17a5af",
|
||||
nextjs: "#84848a",
|
||||
npm: "#d52c36",
|
||||
oxc: "#1ca1c7",
|
||||
postcss: "#d52c36",
|
||||
prettier: "#17a5af",
|
||||
python: "#1a85d4",
|
||||
react: "#1ca1c7",
|
||||
ruby: "#d52c36",
|
||||
rust: "#d47628",
|
||||
sass: "#d32a61",
|
||||
stylelint: "#84848a",
|
||||
svelte: "#d52c36",
|
||||
svg: "#d47628",
|
||||
svgo: "#199f43",
|
||||
swift: "#d47628",
|
||||
table: "#17a5af",
|
||||
tailwind: "#1ca1c7",
|
||||
terraform: "#693acf",
|
||||
text: "#84848a",
|
||||
typescript: "#1a85d4",
|
||||
vite: "#a631be",
|
||||
vscode: "#1a85d4",
|
||||
vue: "#199f43",
|
||||
wasm: "#693acf",
|
||||
webpack: "#1a85d4",
|
||||
yml: "#d52c36",
|
||||
zig: "#d47628",
|
||||
zip: "#d47628",
|
||||
};
|
||||
|
||||
const customIcons = {
|
||||
agents: "t3-file-icon-agents",
|
||||
claude: "t3-file-icon-claude",
|
||||
package: "t3-file-icon-package-json",
|
||||
pnpm: "t3-file-icon-pnpm",
|
||||
readme: "t3-file-icon-readme",
|
||||
tsconfig: "t3-file-icon-tsconfig",
|
||||
};
|
||||
|
||||
function symbolFromSprite(sprite, id) {
|
||||
const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const match = sprite.match(
|
||||
new RegExp(`<symbol id="${escapedId}"([^>]*)>([\\s\\S]*?)<\\/symbol>`),
|
||||
);
|
||||
if (!match) throw new Error(`Missing Pierre icon symbol: ${id}`);
|
||||
return {
|
||||
body: match[2],
|
||||
viewBox: match[1].match(/viewBox="([^"]+)"/)?.[1] ?? "0 0 16 16",
|
||||
};
|
||||
}
|
||||
|
||||
function renderIcon(token, symbol, color) {
|
||||
const svgPath = join(outputDirectory, `.pierre-${token}.svg`);
|
||||
const pngPath = join(outputDirectory, `pierre_${token}.png`);
|
||||
writeFileSync(
|
||||
svgPath,
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="${symbol.viewBox}" style="color:${color}">${symbol.body}</svg>`,
|
||||
);
|
||||
execFileSync("sips", ["-s", "format", "png", svgPath, "--out", pngPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
rmSync(svgPath);
|
||||
}
|
||||
|
||||
rmSync(outputDirectory, { recursive: true, force: true });
|
||||
mkdirSync(outputDirectory, { recursive: true });
|
||||
|
||||
const builtInSprite = getBuiltInSpriteSheet("complete");
|
||||
const builtInTokens = [...builtInSprite.matchAll(/<symbol id="file-tree-builtin-([^"]+)"/g)]
|
||||
.map((match) => match[1])
|
||||
.sort();
|
||||
|
||||
for (const token of builtInTokens) {
|
||||
renderIcon(
|
||||
token,
|
||||
symbolFromSprite(builtInSprite, `file-tree-builtin-${token}`),
|
||||
colors[token] ?? colors.default,
|
||||
);
|
||||
}
|
||||
for (const [token, symbolId] of Object.entries(customIcons)) {
|
||||
renderIcon(token, symbolFromSprite(customSprite, symbolId), colors[token] ?? colors.default);
|
||||
}
|
||||
|
||||
const tokens = [...new Set([...builtInTokens, ...Object.keys(customIcons)])].sort();
|
||||
const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const MARKDOWN_FILE_ICON_SOURCES = {\n${tokens
|
||||
.map((token) => ` ${token}: require("../assets/file-icons/pierre_${token}.png"),`)
|
||||
.join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
|
||||
writeFileSync(generatedModulePath, generatedSource);
|
||||
@@ -0,0 +1,73 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import { Pressable, type ColorValue } from "react-native";
|
||||
|
||||
const COPY_FEEDBACK_DURATION_MS = 1200;
|
||||
|
||||
function copyTextWithHaptic(value: string): void {
|
||||
void Clipboard.setStringAsync(value);
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
|
||||
export const CopyTextButton = memo(function CopyTextButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly text: string;
|
||||
readonly tintColor: ColorValue;
|
||||
readonly copiedTintColor?: ColorValue;
|
||||
readonly backgroundColor?: ColorValue;
|
||||
readonly borderColor?: ColorValue;
|
||||
readonly iconSize?: number;
|
||||
readonly buttonSize?: number;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetTimeoutRef.current) {
|
||||
clearTimeout(resetTimeoutRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={copied ? "Copied" : props.accessibilityLabel}
|
||||
disabled={props.text.length === 0}
|
||||
hitSlop={8}
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.text);
|
||||
setCopied(true);
|
||||
if (resetTimeoutRef.current) {
|
||||
clearTimeout(resetTimeoutRef.current);
|
||||
}
|
||||
resetTimeoutRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
resetTimeoutRef.current = null;
|
||||
}, COPY_FEEDBACK_DURATION_MS);
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
width: props.buttonSize ?? 30,
|
||||
height: props.buttonSize ?? 30,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: 9,
|
||||
borderWidth: props.borderColor ? 1 : 0,
|
||||
borderColor: props.borderColor,
|
||||
backgroundColor: props.backgroundColor,
|
||||
opacity: pressed ? 0.52 : 1,
|
||||
})}
|
||||
>
|
||||
<SymbolView
|
||||
name={copied ? "checkmark" : "doc.on.doc"}
|
||||
size={props.iconSize ?? 13}
|
||||
tintColor={copied ? (props.copiedTintColor ?? props.tintColor) : props.tintColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import React from "react";
|
||||
import { Platform, StyleSheet, Text as RNText, type TextProps, type ViewStyle } from "react-native";
|
||||
import T3MarkdownTextRunNativeComponent from "./T3MarkdownTextRunNativeComponent";
|
||||
import T3MarkdownTextNativeComponent from "./T3MarkdownTextNativeComponent";
|
||||
import { flattenStyles } from "./util";
|
||||
|
||||
const TextAncestorContext = React.createContext<[boolean, ViewStyle]>([
|
||||
false,
|
||||
StyleSheet.create({}),
|
||||
]);
|
||||
|
||||
const textDefaults: TextProps = {
|
||||
allowFontScaling: true,
|
||||
selectable: true,
|
||||
};
|
||||
|
||||
const useTextAncestorContext = () => React.useContext(TextAncestorContext);
|
||||
|
||||
/**
|
||||
* Event fired by `onSelectionChange`. `start`/`end` are 0-based UTF-16 indices
|
||||
* into the rendered string. `start === end` means the selection was cleared.
|
||||
*/
|
||||
export type SelectionChangeEvent = {
|
||||
nativeEvent: { target: number; start: number; end: number };
|
||||
};
|
||||
|
||||
export type MarkdownTextPrimitiveProps = TextProps & {
|
||||
uiTextView?: boolean;
|
||||
/**
|
||||
* Fired when the native text selection changes. Only fires on iOS when
|
||||
* `uiTextView` is true. Note: fires on every selection-edge adjustment
|
||||
* (e.g. dragging a selection handle), so consumers driving expensive work
|
||||
* off this event should debounce.
|
||||
*/
|
||||
onSelectionChange?: (event: SelectionChangeEvent) => void;
|
||||
};
|
||||
|
||||
function MarkdownTextPrimitiveChild({ style, children, ...rest }: MarkdownTextPrimitiveProps) {
|
||||
const [isAncestor, rootStyle] = useTextAncestorContext();
|
||||
|
||||
// Flatten the styles, and apply the root styles when needed
|
||||
const flattenedStyle = React.useMemo(() => flattenStyles(rootStyle, style), [rootStyle, style]);
|
||||
const contextValue = React.useMemo<[boolean, ViewStyle]>(
|
||||
() => [true, flattenedStyle],
|
||||
[flattenedStyle],
|
||||
);
|
||||
let childPosition = 0;
|
||||
const nativeChildren = React.Children.toArray(children).map((child) => {
|
||||
const position = childPosition;
|
||||
childPosition += 1;
|
||||
|
||||
if (React.isValidElement(child)) {
|
||||
return child;
|
||||
}
|
||||
if (typeof child !== "string" && typeof child !== "number") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const text = child.toString();
|
||||
return (
|
||||
// @ts-expect-error The generated run props do not include inherited Text props.
|
||||
<T3MarkdownTextRunNativeComponent
|
||||
key={`text-${position}-${text.length}-${text}`}
|
||||
style={flattenedStyle}
|
||||
text={text}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
if (!isAncestor) {
|
||||
return (
|
||||
<TextAncestorContext.Provider value={contextValue}>
|
||||
<T3MarkdownTextNativeComponent
|
||||
{...textDefaults}
|
||||
{...rest}
|
||||
// ellipsizeMode={rest.ellipsizeMode ?? rest.lineBreakMode ?? 'tail'}
|
||||
style={[flattenedStyle]}
|
||||
// @ts-expect-error Weirdness
|
||||
onPress={undefined}
|
||||
onLongPress={undefined}
|
||||
>
|
||||
{nativeChildren}
|
||||
</T3MarkdownTextNativeComponent>
|
||||
</TextAncestorContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{nativeChildren}</>;
|
||||
}
|
||||
|
||||
function MarkdownTextPrimitiveInner(props: MarkdownTextPrimitiveProps) {
|
||||
const [isAncestor] = useTextAncestorContext();
|
||||
|
||||
// Even if the uiTextView prop is set, we can still default to using
|
||||
// normal selection (i.e. base RN text) if the text doesn't need to be
|
||||
// selectable
|
||||
if ((!props.selectable || !props.uiTextView) && !isAncestor) {
|
||||
return <RNText {...props} />;
|
||||
}
|
||||
return <MarkdownTextPrimitiveChild {...props} />;
|
||||
}
|
||||
|
||||
export function MarkdownTextPrimitive(props: MarkdownTextPrimitiveProps) {
|
||||
if (Platform.OS !== "ios") {
|
||||
return <RNText {...props} />;
|
||||
}
|
||||
return <MarkdownTextPrimitiveInner {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,647 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Image, ScrollView, Text, useColorScheme, View } from "react-native";
|
||||
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import { CopyTextButton } from "./CopyTextButton";
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
|
||||
const highlightedCodeCache = new Map<string, HighlightedCode>();
|
||||
const highlightedCodePromiseCache = new Map<string, Promise<HighlightedCode>>();
|
||||
const HIGHLIGHTED_CODE_CACHE_LIMIT = 64;
|
||||
|
||||
function nodeKey(node: MarkdownNode, index: number): string {
|
||||
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
|
||||
}
|
||||
|
||||
function nodeText(node: MarkdownNode): string {
|
||||
if (node.content !== undefined) {
|
||||
return node.content;
|
||||
}
|
||||
return (node.children ?? []).map(nodeText).join("");
|
||||
}
|
||||
|
||||
function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
return node.type === "document" ? node : { type: "document", children: [node] };
|
||||
}
|
||||
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
textStyle={props.textStyle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function codeHighlightCacheKey(
|
||||
code: string,
|
||||
language: string | undefined,
|
||||
theme: "light" | "dark",
|
||||
): string {
|
||||
return `${theme}:${language ?? "text"}:${code}`;
|
||||
}
|
||||
|
||||
function cacheHighlightedCode(key: string, tokens: HighlightedCode): void {
|
||||
highlightedCodeCache.delete(key);
|
||||
highlightedCodeCache.set(key, tokens);
|
||||
|
||||
while (highlightedCodeCache.size > HIGHLIGHTED_CODE_CACHE_LIMIT) {
|
||||
const oldestKey = highlightedCodeCache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
highlightedCodeCache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
function loadHighlightedCode(
|
||||
code: string,
|
||||
language: string | undefined,
|
||||
theme: "light" | "dark",
|
||||
highlightCode: MarkdownCodeHighlighter,
|
||||
): Promise<HighlightedCode> {
|
||||
const key = codeHighlightCacheKey(code, language, theme);
|
||||
const cached = highlightedCodeCache.get(key);
|
||||
if (cached) {
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
|
||||
const pending = highlightedCodePromiseCache.get(key);
|
||||
if (pending) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
const promise = highlightCode({ code, language, theme })
|
||||
.then((tokens) => {
|
||||
cacheHighlightedCode(key, tokens);
|
||||
highlightedCodePromiseCache.delete(key);
|
||||
return tokens;
|
||||
})
|
||||
.catch((error) => {
|
||||
highlightedCodePromiseCache.delete(key);
|
||||
throw error;
|
||||
});
|
||||
highlightedCodePromiseCache.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function useHighlightedCode(
|
||||
code: string,
|
||||
language: string | undefined,
|
||||
theme: "light" | "dark",
|
||||
highlightCode: MarkdownCodeHighlighter,
|
||||
): HighlightedCode | null {
|
||||
const key = codeHighlightCacheKey(code, language, theme);
|
||||
const [highlighted, setHighlighted] = useState<{
|
||||
readonly key: string;
|
||||
readonly tokens: HighlightedCode | null;
|
||||
}>(() => ({
|
||||
key,
|
||||
tokens: highlightedCodeCache.get(key) ?? null,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const cached = highlightedCodeCache.get(key);
|
||||
if (cached) {
|
||||
cacheHighlightedCode(key, cached);
|
||||
setHighlighted({ key, tokens: cached });
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}
|
||||
|
||||
void loadHighlightedCode(code, language, theme, highlightCode)
|
||||
.then((tokens) => {
|
||||
if (active) {
|
||||
setHighlighted({ key, tokens });
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setHighlighted({ key, tokens: null });
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [code, highlightCode, key, language, theme]);
|
||||
|
||||
return highlighted.key === key ? highlighted.tokens : null;
|
||||
}
|
||||
|
||||
function HighlightedCodeText(props: {
|
||||
readonly content: string;
|
||||
readonly highlighted: HighlightedCode | null;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
if (!props.highlighted) {
|
||||
return (
|
||||
<MarkdownTextPrimitive
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
}}
|
||||
>
|
||||
{props.content}
|
||||
</MarkdownTextPrimitive>
|
||||
);
|
||||
}
|
||||
const highlighted = props.highlighted;
|
||||
let sourceOffset = 0;
|
||||
const keyOccurrences = new Map<string, number>();
|
||||
const keyedLines = highlighted.map((line) => {
|
||||
const lineStart = sourceOffset;
|
||||
const tokens = line.map((token) => {
|
||||
const start = sourceOffset;
|
||||
sourceOffset += token.content.length;
|
||||
const signature = `${start}:${token.content}:${token.color ?? ""}:${token.fontStyle ?? ""}`;
|
||||
const occurrence = keyOccurrences.get(signature) ?? 0;
|
||||
keyOccurrences.set(signature, occurrence + 1);
|
||||
return { key: `${signature}:${occurrence}`, token };
|
||||
});
|
||||
sourceOffset += 1;
|
||||
return {
|
||||
key: `line:${lineStart}:${line.map((token) => token.content).join("")}`,
|
||||
tokens,
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<MarkdownTextPrimitive
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
}}
|
||||
>
|
||||
{keyedLines.map((line, lineIndex) => (
|
||||
<MarkdownTextPrimitive key={line.key}>
|
||||
{line.tokens.map(({ key, token }) => (
|
||||
<MarkdownTextPrimitive
|
||||
key={key}
|
||||
style={{
|
||||
color: token.color ?? props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontStyle:
|
||||
token.fontStyle !== null && (token.fontStyle & 1) === 1 ? "italic" : "normal",
|
||||
fontWeight: token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
|
||||
}}
|
||||
>
|
||||
{token.content}
|
||||
</MarkdownTextPrimitive>
|
||||
))}
|
||||
{lineIndex + 1 < keyedLines.length ? "\n" : ""}
|
||||
</MarkdownTextPrimitive>
|
||||
))}
|
||||
</MarkdownTextPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeCodeBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly compact?: boolean;
|
||||
}) {
|
||||
const content = nodeText(props.node).replace(/\n$/, "");
|
||||
const colorScheme = useColorScheme();
|
||||
const theme = colorScheme === "dark" ? "dark" : "light";
|
||||
const highlighted = useHighlightedCode(content, props.node.language, theme, props.highlightCode);
|
||||
const languageLabel = props.node.language?.toUpperCase() ?? "CODE";
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: props.textStyle.codeBlockBackgroundColor,
|
||||
borderColor: props.textStyle.dividerColor,
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 10,
|
||||
borderWidth: 1,
|
||||
marginVertical: props.compact ? 7 : 0,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
minHeight: 42,
|
||||
borderBottomColor: props.textStyle.dividerColor,
|
||||
borderBottomWidth: 1,
|
||||
paddingLeft: 14,
|
||||
paddingRight: 6,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
style={{
|
||||
flex: 1,
|
||||
color: props.textStyle.mutedColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
{languageLabel}
|
||||
</Text>
|
||||
<CopyTextButton
|
||||
accessibilityLabel={`Copy ${languageLabel.toLowerCase()} code`}
|
||||
text={content}
|
||||
tintColor={props.textStyle.mutedColor}
|
||||
copiedTintColor={props.textStyle.linkColor}
|
||||
backgroundColor={props.textStyle.codeBackgroundColor}
|
||||
borderColor={props.textStyle.dividerColor}
|
||||
buttonSize={34}
|
||||
iconSize={14}
|
||||
/>
|
||||
</View>
|
||||
<ScrollView
|
||||
horizontal
|
||||
bounces={false}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
|
||||
>
|
||||
<HighlightedCodeText
|
||||
content={content}
|
||||
highlighted={highlighted}
|
||||
textStyle={props.textStyle}
|
||||
/>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
const rows: MarkdownNode[] = [];
|
||||
const visit = (child: MarkdownNode) => {
|
||||
if (child.type === "table_row") {
|
||||
rows.push(child);
|
||||
return;
|
||||
}
|
||||
for (const nested of child.children ?? []) {
|
||||
visit(nested);
|
||||
}
|
||||
};
|
||||
visit(node);
|
||||
return rows;
|
||||
}
|
||||
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
const rows = collectTableRows(props.node);
|
||||
return (
|
||||
<ScrollView horizontal bounces={false} showsHorizontalScrollIndicator={false}>
|
||||
<View
|
||||
style={{
|
||||
borderColor: props.textStyle.dividerColor,
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 8,
|
||||
borderWidth: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<View
|
||||
key={nodeKey(row, rowIndex)}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
backgroundColor: rowIndex === 0 ? props.textStyle.codeBackgroundColor : "transparent",
|
||||
borderTopColor: props.textStyle.dividerColor,
|
||||
borderTopWidth: rowIndex === 0 ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
{(row.children ?? []).map((cell, cellIndex) => (
|
||||
<View
|
||||
key={nodeKey(cell, cellIndex)}
|
||||
style={{
|
||||
width: 160,
|
||||
borderLeftColor: props.textStyle.dividerColor,
|
||||
borderLeftWidth: cellIndex === 0 ? 0 : 1,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 8,
|
||||
}}
|
||||
>
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownTextRuns(cell).map((run) =>
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
const href = props.node.href;
|
||||
if (!href) {
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={{ gap: 6 }}>
|
||||
<Image
|
||||
source={{ uri: href }}
|
||||
resizeMode="contain"
|
||||
accessibilityLabel={props.node.alt ?? props.node.title}
|
||||
style={{
|
||||
width: "100%",
|
||||
aspectRatio: 16 / 9,
|
||||
backgroundColor: props.textStyle.codeBackgroundColor,
|
||||
borderRadius: 10,
|
||||
}}
|
||||
/>
|
||||
{props.node.alt ? (
|
||||
<Text
|
||||
selectable
|
||||
style={{
|
||||
color: props.textStyle.mutedColor,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: 12,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
{props.node.alt}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
const groups: MarkdownNode[] = [];
|
||||
let inline: MarkdownNode[] = [];
|
||||
const flush = () => {
|
||||
if (inline.length === 0) {
|
||||
return;
|
||||
}
|
||||
groups.push({ type: "paragraph", children: inline });
|
||||
inline = [];
|
||||
};
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.type === "image") {
|
||||
flush();
|
||||
groups.push(node);
|
||||
} else {
|
||||
inline.push(node);
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return groups;
|
||||
}
|
||||
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
{inlineGroups(props.node.children ?? []).map((child, index) =>
|
||||
child.type === "image" ? (
|
||||
<NativeMarkdownImage
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly depth: number;
|
||||
}) {
|
||||
const ordered = props.node.ordered ?? false;
|
||||
const start = props.node.start ?? 1;
|
||||
const nested = props.depth > 0;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
gap: nested ? 3 : 5,
|
||||
}}
|
||||
>
|
||||
{(props.node.children ?? []).map((item, index) => {
|
||||
const taskMarker = item.type === "task_list_item";
|
||||
const marker = taskMarker
|
||||
? item.checked
|
||||
? "☑︎"
|
||||
: "☐︎"
|
||||
: ordered
|
||||
? `${start + index}.`
|
||||
: props.depth % 3 === 1
|
||||
? "◦"
|
||||
: props.depth % 3 === 2
|
||||
? "▪︎"
|
||||
: "•";
|
||||
const markerWidth = ordered ? 28 : taskMarker ? 20 : 18;
|
||||
const markerOffset = taskMarker ? 3 : ordered ? 0 : 2;
|
||||
return (
|
||||
<View
|
||||
key={nodeKey(item, index)}
|
||||
style={{ alignItems: "flex-start", flexDirection: "row" }}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
width: markerWidth,
|
||||
height: props.textStyle.lineHeight,
|
||||
marginRight: 6,
|
||||
alignItems: ordered ? "flex-end" : "center",
|
||||
justifyContent: "flex-start",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: props.textStyle.color,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: taskMarker ? 14 : props.textStyle.fontSize,
|
||||
lineHeight: props.textStyle.lineHeight,
|
||||
fontVariant: ordered ? ["tabular-nums"] : undefined,
|
||||
transform: [{ translateY: markerOffset }],
|
||||
}}
|
||||
>
|
||||
{marker}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
|
||||
{nativeMarkdownListItemBlocks(item).map((child, childIndex) => (
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, childIndex)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
depth={props.depth + 1}
|
||||
compact
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly depth?: number;
|
||||
readonly compact?: boolean;
|
||||
}) {
|
||||
const depth = props.depth ?? 0;
|
||||
switch (props.node.type) {
|
||||
case "document":
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
{(props.node.children ?? []).map((child, index) => (
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
depth={depth}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
case "code_block":
|
||||
return (
|
||||
<NativeCodeBlock
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
compact={props.compact}
|
||||
/>
|
||||
);
|
||||
case "table":
|
||||
return <NativeTable node={props.node} textStyle={props.textStyle} />;
|
||||
case "image":
|
||||
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
|
||||
case "horizontal_rule":
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
height: 1,
|
||||
backgroundColor: props.textStyle.dividerColor,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
case "blockquote":
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
borderLeftColor: props.textStyle.quoteMarkerColor,
|
||||
borderLeftWidth: 2,
|
||||
marginVertical: props.compact ? 4 : 0,
|
||||
paddingLeft: 11,
|
||||
paddingVertical: 2,
|
||||
gap: 6,
|
||||
}}
|
||||
>
|
||||
{(props.node.children ?? []).map((child, index) => (
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
case "list":
|
||||
return (
|
||||
<NativeList
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
depth={depth}
|
||||
/>
|
||||
);
|
||||
case "paragraph":
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
|
||||
) : (
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
);
|
||||
case "html_block":
|
||||
case "math_block":
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
marginVertical: props.compact ? 2 : 0,
|
||||
paddingHorizontal: props.node.type === "math_block" ? 10 : 0,
|
||||
paddingVertical: props.node.type === "math_block" ? 8 : 0,
|
||||
backgroundColor:
|
||||
props.node.type === "math_block"
|
||||
? props.textStyle.codeBackgroundColor
|
||||
: "transparent",
|
||||
}}
|
||||
>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
</View>
|
||||
);
|
||||
case "table_head":
|
||||
case "table_body":
|
||||
case "table_row":
|
||||
case "table_cell":
|
||||
case "list_item":
|
||||
case "task_list_item":
|
||||
return (
|
||||
<View style={{ gap: 4 }}>
|
||||
{(props.node.children ?? []).map((child, index) => (
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
default:
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Asset } from "expo-asset";
|
||||
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
|
||||
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import { markdownFileIconSource } from "./markdownFileIcons";
|
||||
import type { MarkdownFileIcon } from "./markdownLinks";
|
||||
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
|
||||
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
|
||||
|
||||
const EXTERNAL_LINK_PREFIX = "◉ ";
|
||||
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
|
||||
const CHIP_SUFFIX = "\u00A0";
|
||||
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
|
||||
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
|
||||
|
||||
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
|
||||
const iconSignature = JSON.stringify(
|
||||
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
|
||||
);
|
||||
const icons = useMemo(
|
||||
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
|
||||
[iconSignature],
|
||||
);
|
||||
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void Promise.all(
|
||||
icons.map(async (icon) => {
|
||||
const source = markdownFileIconSource(icon);
|
||||
const fallbackUri = Image.resolveAssetSource(source).uri;
|
||||
if (typeof source !== "number" && typeof source !== "string") {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
try {
|
||||
const asset = Asset.fromModule(source);
|
||||
await asset.downloadAsync();
|
||||
return [icon, asset.localUri ?? fallbackUri] as const;
|
||||
} catch {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
}),
|
||||
).then((entries) => {
|
||||
if (!cancelled) {
|
||||
setUris(new Map(entries));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [icons]);
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
return [
|
||||
run.text,
|
||||
run.bold,
|
||||
run.italic,
|
||||
run.strikethrough,
|
||||
run.code,
|
||||
run.href,
|
||||
run.externalHost,
|
||||
run.fileIcon,
|
||||
run.skillName,
|
||||
run.skillLabel,
|
||||
run.role,
|
||||
run.headingLevel,
|
||||
run.depth,
|
||||
run.spacing,
|
||||
run.firstLineHeadIndent,
|
||||
run.headIndent,
|
||||
run.paragraphSpacing,
|
||||
].join(":");
|
||||
}
|
||||
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const isChip = isFile || isSkill;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
|
||||
|
||||
return {
|
||||
color: isFile
|
||||
? textStyle.fileTextColor
|
||||
: isSkill
|
||||
? textStyle.skillTextColor
|
||||
: run.href
|
||||
? textStyle.linkColor
|
||||
: isHeading
|
||||
? textStyle.strongColor
|
||||
: run.role === "quote-marker"
|
||||
? textStyle.quoteMarkerColor
|
||||
: run.role === "divider"
|
||||
? textStyle.dividerColor
|
||||
: run.role === "code-language"
|
||||
? textStyle.mutedColor
|
||||
: run.role === "list-marker"
|
||||
? textStyle.mutedColor
|
||||
: run.code || isFile
|
||||
? textStyle.codeColor
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily: isChip
|
||||
? "DMSans_500Medium"
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
fontSize:
|
||||
run.role === "spacer"
|
||||
? (run.spacing ?? 10)
|
||||
: run.role === "list-break"
|
||||
? textStyle.fontSize
|
||||
: isHeading
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
: run.code || isChip || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
lineHeight:
|
||||
run.role === "spacer"
|
||||
? (run.spacing ?? 10)
|
||||
: run.role === "list-break"
|
||||
? textStyle.lineHeight + (run.spacing ?? 0)
|
||||
: isHeading
|
||||
? Math.max(headingFontSize + 6, 20)
|
||||
: isCodeBlock
|
||||
? 18
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
|
||||
textDecorationLine,
|
||||
backgroundColor: isCodeBlock
|
||||
? textStyle.codeBlockBackgroundColor
|
||||
: isSkill
|
||||
? textStyle.skillBackgroundColor
|
||||
: run.code
|
||||
? textStyle.codeBackgroundColor
|
||||
: isFile
|
||||
? textStyle.fileBackgroundColor
|
||||
: undefined,
|
||||
...(hasParagraphStyle
|
||||
? {
|
||||
shadowColor: "transparent",
|
||||
shadowOffset: {
|
||||
width: run.firstLineHeadIndent ?? 0,
|
||||
height: run.headIndent,
|
||||
},
|
||||
shadowRadius: PARAGRAPH_STYLE_ENCODING_OFFSET + (run.paragraphSpacing ?? 0),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function NativeMarkdownSelectableText(props: {
|
||||
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const fileIconUris = useFileIconUris(props.runs);
|
||||
const occurrences = new Map<string, number>();
|
||||
const prefixedExternalLinks = new Set<string>();
|
||||
const keyedRuns = props.runs.map((run) => {
|
||||
const signature = runKeySignature(run);
|
||||
const occurrence = occurrences.get(signature) ?? 0;
|
||||
occurrences.set(signature, occurrence + 1);
|
||||
|
||||
let text = run.text;
|
||||
if (run.fileIcon) {
|
||||
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
|
||||
} else if (run.skillName && run.skillLabel) {
|
||||
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
|
||||
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
|
||||
prefixedExternalLinks.add(run.href);
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
}
|
||||
|
||||
return { key: `${signature}:${occurrence}`, run, text };
|
||||
});
|
||||
// T3MarkdownText only rebuilds its attributed string during native layout. A
|
||||
// color-only child update can otherwise leave the previous appearance cached.
|
||||
const appearanceKey = [
|
||||
colorScheme ?? "unspecified",
|
||||
props.textStyle.color,
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
props.textStyle.linkColor,
|
||||
props.textStyle.codeColor,
|
||||
props.textStyle.codeBackgroundColor,
|
||||
props.textStyle.codeBlockBackgroundColor,
|
||||
props.textStyle.fileBackgroundColor,
|
||||
props.textStyle.fileTextColor,
|
||||
props.textStyle.skillBackgroundColor,
|
||||
props.textStyle.skillTextColor,
|
||||
props.textStyle.quoteMarkerColor,
|
||||
props.textStyle.dividerColor,
|
||||
].join(":");
|
||||
|
||||
return (
|
||||
<MarkdownTextPrimitive
|
||||
key={appearanceKey}
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
width: "100%",
|
||||
color: props.textStyle.color,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: props.textStyle.fontSize,
|
||||
lineHeight: props.textStyle.lineHeight,
|
||||
}}
|
||||
>
|
||||
{keyedRuns.map(({ key, run, text }) => {
|
||||
const href = run.href;
|
||||
return (
|
||||
<MarkdownTextPrimitive
|
||||
key={key}
|
||||
nativeID={
|
||||
run.fileIcon
|
||||
? `t3-chip-file:${
|
||||
fileIconUris.get(run.fileIcon) ??
|
||||
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
|
||||
}`
|
||||
: run.skillName
|
||||
? "t3-chip-skill:sf:cube"
|
||||
: undefined
|
||||
}
|
||||
style={runStyle(run, props.textStyle)}
|
||||
onPress={
|
||||
href
|
||||
? () => {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{text}
|
||||
</MarkdownTextPrimitive>
|
||||
);
|
||||
})}
|
||||
</MarkdownTextPrimitive>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { parseMarkdownWithOptions } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import {
|
||||
nativeMarkdownChunkSpacing,
|
||||
nativeMarkdownDocumentChunks,
|
||||
nativeMarkdownDocumentRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
SelectableMarkdownSkill,
|
||||
SelectableMarkdownTextProps,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
const EMPTY_SKILLS: ReadonlyArray<SelectableMarkdownSkill> = [];
|
||||
|
||||
export type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
SelectableMarkdownTextProps,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
export function hasNativeSelectableMarkdownText(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function SelectableMarkdownText({
|
||||
markdown,
|
||||
skills = EMPTY_SKILLS,
|
||||
textStyle,
|
||||
highlightCode,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
const chunks = useMemo(() => {
|
||||
const document = parseMarkdownWithOptions(markdown, {
|
||||
gfm: true,
|
||||
html: true,
|
||||
math: false,
|
||||
});
|
||||
return nativeMarkdownDocumentChunks(document).map((chunk) =>
|
||||
chunk.kind === "selectable"
|
||||
? {
|
||||
...chunk,
|
||||
runs: nativeMarkdownDocumentRuns(chunk.node, skills),
|
||||
}
|
||||
: chunk,
|
||||
);
|
||||
}, [markdown, skills]);
|
||||
|
||||
return (
|
||||
<View style={{ width: "100%", marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
key={chunk.key}
|
||||
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
|
||||
>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||