From 4929ed5a0f18d12e2bb4108ddca109e92ce4a84f Mon Sep 17 00:00:00 2001 From: Matt Pilsbury <88013057+AnalyticETH@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:07:48 -0500 Subject: [PATCH 001/109] fix(codex): restore subagent status after reopen and rewind (#10171) * fix(codex): settle historical collaboration subagents * fix(codex): reconcile replayed collaboration with child turns --- .../agent/providers/codex-app-server-agent.ts | 265 ++++++- .../providers/codex/collab-replay.test.ts | 692 ++++++++++++++++++ .../agent/providers/codex/thread-history.ts | 131 +++- .../providers/codex/tool-call-mapper.test.ts | 14 + .../agent/providers/codex/tool-call-mapper.ts | 19 +- 5 files changed, 1055 insertions(+), 66 deletions(-) create mode 100644 packages/server/src/server/agent/providers/codex/collab-replay.test.ts diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 62b8ffc564f4..66f9dd198a10 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -64,6 +64,7 @@ import { mapCodexToolCallEnvelope, mapCodexToolCallFromThreadItem, normalizeCommandExecutionCommand, + normalizeCollabAgentChildStatus, splitCodexMcpToolResultImages, } from "./codex/tool-call-mapper.js"; import { normalizeCodexFilePath } from "./codex/tool-call-detail-parser.js"; @@ -103,6 +104,7 @@ import { codexAppServerStartup } from "./codex/app-server-startup.js"; import { type CodexUserMessageTurnIndex, revertCodexConversation } from "./codex/rewind.js"; import { type CodexHistoryRow, + type CodexHistoryStatus, CodexThreadHistoryTooLargeError, readCodexThreadHistory, } from "./codex/thread-history.js"; @@ -557,12 +559,14 @@ interface CodexThreadHistory { interface PersistedSubAgentRoute { childThreadId: string; - toolCall: ToolCallTimelineItem; + entry: PersistedTimelineEntry; + legacyCollaboration: boolean; } interface CodexThreadHistoryProjection { timeline: PersistedTimelineEntry[]; subAgentRoutes: PersistedSubAgentRoute[]; + status: CodexHistoryStatus | null; } function mergeCodexConfiguredDefaults( @@ -1976,6 +1980,94 @@ function readCodexSubAgentActivity(item: unknown): CodexSubAgentActivity | null }; } +interface CodexCollabAgentUpdate { + threadId: string; + status: ToolCallTimelineItem["status"]; + preservesTerminal: boolean; +} + +type CodexCollabAgentControl = + | { kind: "submission"; childThreadIds: string[] } + | { kind: "outcome"; childThreadIds: string[]; updates: CodexCollabAgentUpdate[] }; + +interface HistoricalCodexSubAgent { + timelineIndex: number; + pendingFollowUp: boolean; + legacyCollaboration: boolean; +} + +function readCodexCollabAgentControl(item: unknown): CodexCollabAgentControl | null { + const record = toObjectRecord(item); + if ( + !record || + normalizeCodexThreadItemType(typeof record.type === "string" ? record.type : undefined) !== + "collabAgentToolCall" || + record.tool === "spawnAgent" + ) { + return null; + } + const tool = typeof record.tool === "string" ? record.tool : undefined; + const receivers = Array.isArray(record.receiverThreadIds) + ? record.receiverThreadIds.filter((id): id is string => typeof id === "string") + : []; + if (tool === "sendInput") { + return record.status === "completed" && record.error == null + ? { kind: "submission", childThreadIds: receivers } + : null; + } + if (tool !== "wait" && tool !== "closeAgent") return null; + const outcomeStates = toObjectRecord(record.agentsStates); + const updates = Object.entries(outcomeStates ?? {}).flatMap( + ([threadId, value]): CodexCollabAgentUpdate[] => { + const state = toObjectRecord(value); + if (typeof state?.status !== "string") return []; + // Unlike a spawn snapshot, a control result can report the child's final error. + const status = normalizeCollabAgentChildStatus(state.status, tool); + return [ + { + threadId, + status, + preservesTerminal: state.status === "shutdown" || record.tool === "closeAgent", + }, + ]; + }, + ); + return { + kind: "outcome", + childThreadIds: [...new Set([...receivers, ...updates.map((update) => update.threadId)])], + updates, + }; +} + +function resolveCodexCollabAgentUpdate( + previous: ToolCallTimelineItem["status"], + update: CodexCollabAgentUpdate, +): ToolCallTimelineItem["status"] { + if ( + isTerminalSubAgentStatus(previous) && + (update.preservesTerminal || update.status === "running") + ) { + return previous; + } + return update.status; +} + +function restoreCollabAgentCallFromChildHistory( + state: CodexSubAgentCallState, + recorded: ToolCallTimelineItem, + status: CodexHistoryStatus | null, +): void { + // A live event received during the read is newer than the history snapshot. + if (state.toolCall !== recorded || status === null) return; + // A stored child turn can predate a terminal parent outcome, such as a close. + // A currently active child is direct evidence that it is working again. + if (status !== "running" && isTerminalSubAgentStatus(recorded.status)) return; + state.toolCall = + status === "failed" + ? { ...recorded, status, error: { message: "Sub-agent failed" } } + : { ...recorded, status, error: null }; +} + function shouldIgnoreMirroredLifecycleItem(source: "item" | "codex_event", item: unknown): boolean { return source === "codex_event" && !readCodexSubAgentActivity(item); } @@ -2016,7 +2108,7 @@ function updateHistoricalSubAgentActivity( }; } -function readCodexHistoricalSubAgentThreadIds(item: unknown): string[] { +function readCodexSpawnedSubAgentThreadIds(item: unknown): string[] { const activity = readCodexSubAgentActivity(item); if (activity) { return activity.kind === "started" ? [activity.agentThreadId] : []; @@ -2179,46 +2271,95 @@ async function threadItemToTimelineEntries( return [timelineItem, ...(await mcpToolResultImagesToTimeline(item))]; } +function updateHistoricalCollabAgentCalls( + timeline: PersistedTimelineEntry[], + subAgentsByThreadId: Map, + item: unknown, +): boolean { + const control = readCodexCollabAgentControl(item); + if (!control) return false; + if (control.kind === "submission") { + for (const threadId of control.childThreadIds) { + const child = subAgentsByThreadId.get(threadId); + if (child) child.pendingFollowUp = true; + } + return false; + } + for (const update of control.updates) { + const child = subAgentsByThreadId.get(update.threadId); + const existing = child === undefined ? undefined : timeline[child.timelineIndex]; + if (!child || existing?.item.type !== "tool_call") continue; + const status = child.pendingFollowUp + ? update.status + : resolveCodexCollabAgentUpdate(existing.item.status, update); + child.pendingFollowUp = false; + const toolCall: ToolCallTimelineItem = + status === "failed" + ? { ...existing.item, status, error: { message: "Sub-agent failed" } } + : { ...existing.item, status, error: null }; + timeline[child.timelineIndex] = { ...existing, item: toolCall }; + } + return ( + control.childThreadIds.length > 0 && + control.childThreadIds.every((id) => subAgentsByThreadId.has(id)) + ); +} + async function loadCodexThreadHistoryTimeline(params: { client: CodexAppServerClientLike; threadId: string; cwd: string | null; + readLatestTurn?: boolean; }): Promise { const timeline: PersistedTimelineEntry[] = []; - const subAgentTimelineIndexByThreadId = new Map(); + const subAgentsByThreadId = new Map(); + let status: CodexHistoryStatus | null = null; try { - await projectCodexThreadHistory(params, { timeline, subAgentTimelineIndexByThreadId }); + const history = await readCodexThreadHistory(params.client, params.threadId, { + readLatestTurn: params.readLatestTurn, + }); + status = history.status; + await projectCodexThreadHistory( + { cwd: params.cwd, rows: history.rows }, + { + timeline, + subAgentsByThreadId, + }, + ); } catch (error) { if (!(error instanceof CodexThreadHistoryTooLargeError)) throw error; // The session stays usable; the row says why the history stops here. timeline.push({ item: { type: "notification", level: "warning", message: error.message } }); } - const subAgentRoutes = Array.from(subAgentTimelineIndexByThreadId.entries()).flatMap( - ([childThreadId, timelineIndex]): PersistedSubAgentRoute[] => { - const item = timeline[timelineIndex]?.item; - return item?.type === "tool_call" && item.detail.type === "sub_agent" - ? [{ childThreadId, toolCall: item }] + const subAgentRoutes = Array.from(subAgentsByThreadId.entries()).flatMap( + ([childThreadId, child]): PersistedSubAgentRoute[] => { + const entry = timeline[child.timelineIndex]; + return entry?.item.type === "tool_call" && entry.item.detail.type === "sub_agent" + ? [{ childThreadId, entry, legacyCollaboration: child.legacyCollaboration }] : []; }, ); - return { timeline, subAgentRoutes }; + return { timeline, subAgentRoutes, status }; } async function projectCodexThreadHistory( - params: { client: CodexAppServerClientLike; threadId: string; cwd: string | null }, + params: { rows: Iterable | AsyncIterable; cwd: string | null }, projection: { timeline: PersistedTimelineEntry[]; - subAgentTimelineIndexByThreadId: Map; + subAgentsByThreadId: Map; }, ): Promise { - const { timeline, subAgentTimelineIndexByThreadId } = projection; - for await (const row of readCodexThreadHistory(params.client, params.threadId)) { + const { timeline, subAgentsByThreadId } = projection; + for await (const row of params.rows) { const { item } = row; + if (updateHistoricalCollabAgentCalls(timeline, subAgentsByThreadId, item)) { + continue; + } const historicalSubAgentActivity = readCodexSubAgentActivity(item); if (historicalSubAgentActivity) { - const existingIndex = subAgentTimelineIndexByThreadId.get( + const existingIndex = subAgentsByThreadId.get( historicalSubAgentActivity.agentThreadId, - ); + )?.timelineIndex; if (existingIndex !== undefined) { const activityTimelineItem = await threadItemToTimeline(item, { cwd: params.cwd }); updateHistoricalSubAgentActivity( @@ -2248,8 +2389,12 @@ async function projectCodexThreadHistory( ? { providerTurnId: row.turnId } : {}), }); - for (const childThreadId of readCodexHistoricalSubAgentThreadIds(item)) { - subAgentTimelineIndexByThreadId.set(childThreadId, timeline.length - 1); + for (const childThreadId of readCodexSpawnedSubAgentThreadIds(item)) { + subAgentsByThreadId.set(childThreadId, { + timelineIndex: timeline.length - 1, + pendingFollowUp: false, + legacyCollaboration: historicalSubAgentActivity === null, + }); } } } @@ -4299,31 +4444,46 @@ export class CodexAppServerAgentSession implements AgentSession { parentSubagentId: null as string | null, })); const visitedThreadIds = new Set(this.currentThreadId ? [this.currentThreadId] : []); + const replayed: { + route: PersistedSubAgentRoute; + state: CodexSubAgentCallState; + timeline: readonly PersistedTimelineEntry[]; + }[] = []; while (queue.length > 0 && visitedThreadIds.size < 100) { const next = queue.shift(); if (!next || visitedThreadIds.has(next.route.childThreadId)) { continue; } visitedThreadIds.add(next.route.childThreadId); + const toolCall = next.route.entry.item; + if (toolCall.type !== "tool_call") continue; this.registerSubAgentToolCall({ - timelineItem: next.route.toolCall, + timelineItem: toolCall, rawItem: { agentThreadId: next.route.childThreadId }, + childThreadIds: [next.route.childThreadId], parentCallId: next.parentCallId, parentSubagentId: next.parentSubagentId, + deferUpsert: true, }); + const state = this.subAgentCallsByCallId.get(toolCall.callId); + if (!state?.childThreadIds.has(next.route.childThreadId)) continue; + let timeline: readonly PersistedTimelineEntry[] = []; try { const childHistory = await loadCodexThreadHistoryTimeline({ client, threadId: next.route.childThreadId, cwd: this.config.cwd ?? null, + readLatestTurn: + next.route.legacyCollaboration && !isTerminalSubAgentStatus(toolCall.status), }); - for (const entry of childHistory.timeline) { - this.emitProviderSubagentTimeline(next.route.childThreadId, entry.item, entry.timestamp); + if (next.route.legacyCollaboration) { + restoreCollabAgentCallFromChildHistory(state, toolCall, childHistory.status); } + timeline = childHistory.timeline; for (const route of childHistory.subAgentRoutes) { queue.push({ route, - parentCallId: next.route.toolCall.callId, + parentCallId: toolCall.callId, parentSubagentId: next.route.childThreadId, }); } @@ -4333,6 +4493,17 @@ export class CodexAppServerAgentSession implements AgentSession { "Failed to load persisted Codex child history", ); } + replayed.push({ route: next.route, state, timeline }); + } + // Settle nested cards before emitting the parent timelines that contain them. + for (const { route, state } of replayed) { + if (route.legacyCollaboration) route.entry.item = state.toolCall; + } + for (const { route, state, timeline } of replayed) { + this.emitProviderSubagentUpsert(route.childThreadId, state, state.toolCall.status); + for (const entry of timeline) { + this.emitProviderSubagentTimeline(route.childThreadId, entry.item, entry.timestamp); + } } } @@ -6235,8 +6406,10 @@ export class CodexAppServerAgentSession implements AgentSession { private registerSubAgentToolCall(params: { timelineItem: ToolCallTimelineItem; rawItem: { [key: string]: unknown }; + childThreadIds: readonly string[]; parentCallId: string | null; parentSubagentId: string | null; + deferUpsert?: boolean; }): string[] { const { timelineItem, rawItem, parentCallId, parentSubagentId } = params; if (timelineItem.detail.type !== "sub_agent") { @@ -6266,16 +6439,9 @@ export class CodexAppServerAgentSession implements AgentSession { } this.subAgentCallsByCallId.set(timelineItem.callId, state); - const receiverThreadIds = Array.isArray(rawItem.receiverThreadIds) - ? rawItem.receiverThreadIds.filter((value): value is string => typeof value === "string") - : []; - const agentThreadId = - typeof rawItem.agentThreadId === "string" && rawItem.agentThreadId.length > 0 - ? rawItem.agentThreadId - : null; - const childThreadIds = Array.from( - new Set(agentThreadId ? [...receiverThreadIds, agentThreadId] : receiverThreadIds), - ).filter((threadId) => threadId !== this.currentThreadId); + const childThreadIds = Array.from(new Set(params.childThreadIds)).filter( + (threadId) => threadId !== this.currentThreadId, + ); for (const receiverThreadId of childThreadIds) { const owningCallId = this.subAgentCallIdByChildThreadId.get(receiverThreadId); if (owningCallId && owningCallId !== timelineItem.callId) { @@ -6283,12 +6449,43 @@ export class CodexAppServerAgentSession implements AgentSession { } this.subAgentCallIdByChildThreadId.set(receiverThreadId, timelineItem.callId); state.childThreadIds.add(receiverThreadId); - this.emitProviderSubagentUpsert(receiverThreadId, state, timelineItem.status); + if (!params.deferUpsert) { + this.emitProviderSubagentUpsert(receiverThreadId, state, timelineItem.status); + } } return childThreadIds; } + private handleRegisteredCollabAgentControl( + rawItem: { [key: string]: unknown }, + control: CodexCollabAgentControl, + ): boolean { + if (control.kind === "submission") return false; + for (const update of control.updates) { + const callId = this.subAgentCallIdByChildThreadId.get(update.threadId); + if (!callId) continue; + const state = this.subAgentCallsByCallId.get(callId); + if (!state) continue; + const status = resolveCodexCollabAgentUpdate(state.toolCall.status, update); + if (status !== state.toolCall.status) { + this.emitSubAgentActivityUpdate(callId, status); + } + } + // A control rendered at start must also render its completion, even if + // Codex's final result lists fewer receivers than its started record. + const hasOwnCard = typeof rawItem.id === "string" && this.subAgentCallsByCallId.has(rawItem.id); + return ( + !hasOwnCard && + control.childThreadIds.length > 0 && + control.childThreadIds.every((id) => this.subAgentCallIdByChildThreadId.has(id)) + ); + } + private handleRegisteredSubAgentActivity(rawItem: { [key: string]: unknown }): boolean { + const control = readCodexCollabAgentControl(rawItem); + if (control) { + return this.handleRegisteredCollabAgentControl(rawItem, control); + } const activity = readCodexSubAgentActivity(rawItem); if (!activity) { return false; @@ -7228,6 +7425,7 @@ export class CodexAppServerAgentSession implements AgentSession { ? this.registerSubAgentToolCall({ timelineItem, rawItem: parsed.item, + childThreadIds: readCodexSpawnedSubAgentThreadIds(parsed.item), parentCallId: childSubAgentCallId, parentSubagentId: resolveCodexParentSubagentId(childSubAgentCallId, parsed.threadId), }) @@ -7401,6 +7599,7 @@ export class CodexAppServerAgentSession implements AgentSession { const registeredChildThreadIds = this.registerSubAgentToolCall({ timelineItem, rawItem: parsed.item, + childThreadIds: readCodexSpawnedSubAgentThreadIds(parsed.item), parentCallId: childSubAgentCallId, parentSubagentId: resolveCodexParentSubagentId(childSubAgentCallId, parsed.threadId), }); diff --git a/packages/server/src/server/agent/providers/codex/collab-replay.test.ts b/packages/server/src/server/agent/providers/codex/collab-replay.test.ts new file mode 100644 index 000000000000..737a27476c77 --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/collab-replay.test.ts @@ -0,0 +1,692 @@ +import { describe, expect, test, vi } from "vitest"; +import { CodexAppServerAgentSession } from "../codex-app-server-agent.js"; +import { createTestLogger } from "../../../../test-utils/test-logger.js"; +import { createFakeCodexAppServer } from "./test-utils/fake-app-server.js"; + +function collab(tool: string, states: Record, id = tool) { + return { + type: "collabAgentToolCall", + id, + tool, + status: "completed", + prompt: tool === "spawnAgent" ? "Reply with a short result." : null, + receiverThreadIds: Object.keys(states), + agentsStates: Object.fromEntries( + Object.entries(states).map(([threadId, status]) => [threadId, { status }]), + ), + }; +} + +interface ChildHistory { + status?: { type: string }; + turns: { status: string; items?: unknown[] }[]; + historyMode?: "paginated"; + turnProbe?: "supported" | "unsupported"; +} + +async function replay(items: unknown[], children: Record = {}) { + const appServer = createFakeCodexAppServer({ + "thread/read": (params) => { + const { threadId, includeTurns } = params as { threadId: string; includeTurns: boolean }; + const child = children[threadId]; + const turns = threadId === "parent" ? [{ items }] : (child?.turns ?? []); + return { + thread: { + status: child?.status, + historyMode: child?.historyMode, + turns: includeTurns ? turns : [], + }, + }; + }, + "thread/items/list": () => ({ data: [], nextCursor: null }), + "thread/turns/list": (params) => { + const child = children[(params as { threadId: string }).threadId]; + if (child?.turnProbe !== "supported") throw new Error("method not supported"); + return { data: child.turns.slice(-1) }; + }, + }); + const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: process.cwd(), modeId: "full-access" }, + { sessionId: "parent" }, + createTestLogger(), + async () => appServer.child, + {}, + false, + false, + false, + undefined, + "history", + ); + try { + await session.connect(); + const history = await Array.fromAsync(session.streamHistory()); + for (const [threadId, child] of Object.entries(children)) { + // Status is recovered from the history we already read for this child. + expect( + appServer + .requests() + .flatMap(({ method, params }) => + method === "thread/read" && (params as { threadId: string }).threadId === threadId + ? [(params as { includeTurns: boolean }).includeTurns] + : [], + ), + ).toEqual(child.historyMode === "paginated" ? [false] : [false, true]); + expect( + appServer + .requests() + .filter( + ({ method, params }) => + method === "thread/turns/list" && + (params as { threadId: string }).threadId === threadId, + ), + ).toMatchObject( + child.turnProbe + ? [{ params: { threadId, limit: 1, itemsView: "notLoaded", sortDirection: "desc" } }] + : [], + ); + } + return history; + } finally { + await session.close(); + appServer.assertNoErrors(); + } +} + +describe("Codex collaboration history", () => { + test.each([ + { turn: "completed", expected: "completed" }, + { turn: "failed", expected: "failed" }, + { turn: "interrupted", expected: "canceled" }, + ])( + "recovers a $turn child even when the parent did not wait or close it", + async ({ turn, expected }) => { + const history = await replay( + [collab("spawnAgent", { first: "pendingInit" }, "spawn-first")], + { + first: { + status: { type: "notLoaded" }, + turns: [{ status: "completed" }, { status: turn }], + }, + }, + ); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ), + ).toEqual([expected]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" ? [event.item.status] : [], + ), + ).toEqual([expected]); + }, + ); + + test("keeps a live child running when the rewound parent only has its earlier wait", async () => { + const history = await replay( + [ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("wait", { first: "completed" }), + ], + { first: { status: { type: "active" }, turns: [{ status: "completed" }] } }, + ); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ), + ).toEqual(["running"]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" ? [event.item.status] : [], + ), + ).toEqual(["running"]); + }); + + test("keeps a live completion received while the child history is loading", async () => { + const reading = Promise.withResolvers(); + const childReply = Promise.withResolvers(); + const appServer = createFakeCodexAppServer({ + "thread/read": (params) => { + const { threadId, includeTurns } = params as { threadId: string; includeTurns: boolean }; + if (!includeTurns) return { thread: {} }; + if (threadId === "parent") { + return { + thread: { + turns: [{ items: [collab("spawnAgent", { first: "pendingInit" }, "spawn-first")] }], + }, + }; + } + reading.resolve(); + return childReply.promise; + }, + }); + const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: process.cwd(), modeId: "full-access" }, + { sessionId: "parent" }, + createTestLogger(), + async () => appServer.child, + ); + const completed = Promise.withResolvers(); + session.subscribe((event) => { + if ( + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.callId === "spawn-first" && + event.item.status === "completed" + ) { + completed.resolve(); + } + }); + try { + await session.connect(); + const restoring = Array.fromAsync(session.streamHistory()); + await reading.promise; + appServer.completeTurn({ threadId: "first" }); + await completed.promise; + childReply.resolve({ thread: { status: { type: "active" }, turns: [] } }); + const history = await restoring; + expect( + history + .flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ) + .at(-1), + ).toBe("completed"); + expect(history.filter((event) => event.type === "timeline")).toMatchObject([ + { item: { callId: "spawn-first", status: "completed" } }, + ]); + } finally { + await session.close(); + appServer.assertNoErrors(); + } + }); + + test("does not let an older child turn override an explicit close", async () => { + const history = await replay( + [ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("closeAgent", { first: "running" }), + ], + { first: { status: { type: "notLoaded" }, turns: [{ status: "completed" }] } }, + ); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ), + ).toEqual(["canceled"]); + }); + + test("reads one turn without items for an unresolved paginated child", async () => { + const history = await replay( + [ + collab("spawnAgent", { migrated: "pendingInit" }, "spawn-migrated"), + collab("spawnAgent", { settled: "pendingInit" }, "spawn-settled"), + collab("wait", { settled: "completed" }), + collab("spawnAgent", { unsupported: "pendingInit" }, "spawn-unsupported"), + ], + { + migrated: { + historyMode: "paginated", + turns: [{ status: "failed" }], + turnProbe: "supported", + }, + settled: { historyMode: "paginated", turns: [{ status: "completed" }] }, + unsupported: { historyMode: "paginated", turns: [], turnProbe: "unsupported" }, + }, + ); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [[event.event.id, event.event.status]] + : [], + ), + ).toEqual([ + ["migrated", "failed"], + ["settled", "completed"], + ["unsupported", "running"], + ]); + }); + + test("settles a nested child's own card and descriptor", async () => { + const history = await replay([collab("spawnAgent", { first: "pendingInit" }, "spawn-first")], { + first: { + turns: [ + { + status: "completed", + items: [collab("spawnAgent", { nested: "pendingInit" }, "spawn-nested")], + }, + ], + }, + nested: { turns: [{ status: "interrupted" }] }, + }); + expect(history.filter((event) => event.type === "provider_subagent")).toMatchObject([ + { event: { type: "upsert", id: "first", status: "completed" } }, + { + event: { + type: "timeline", + id: "first", + item: { callId: "spawn-nested", status: "canceled" }, + }, + }, + { event: { type: "upsert", id: "nested", parentSubagentId: "first", status: "canceled" } }, + ]); + }); + + test("restores completed children from nullable wait and close results", async () => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("spawnAgent", { second: "pendingInit" }, "spawn-second"), + collab("wait", { first: "completed" }, "wait-first"), + collab("wait", { second: "completed" }, "wait-second"), + collab("closeAgent", { first: "completed" }, "close-first"), + collab("closeAgent", { second: "completed" }, "close-second"), + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([ + { id: "first", status: "completed" }, + { id: "second", status: "completed" }, + ]); + }); + + test.each(["completed", "interrupted", "running"])( + "keeps follow-up instructions in replay without applying the %s submission snapshot", + async (submissionStatus) => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("wait", { first: "completed" }), + { ...collab("sendInput", { first: submissionStatus }), prompt: "Now add tests" }, + ]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" + ? [{ id: event.item.callId, status: event.item.status, detail: event.item.detail }] + : [], + ), + ).toEqual([ + { id: "spawn-first", status: "completed", detail: expect.anything() }, + { + id: "sendInput", + status: "completed", + detail: expect.objectContaining({ description: "Now add tests" }), + }, + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([{ id: "first", status: "completed" }]); + }, + ); + + test.each([ + ["completed", "closeAgent", "errored", "failed"], + ["errored", "closeAgent", "completed", "completed"], + ["completed", "wait", "running", "running"], + ["completed", "closeAgent", "running", "canceled"], + ])( + "replaces the earlier %s outcome after a follow-up and %s result %s", + async (initialStatus, tool, resultStatus, expected) => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("spawnAgent", { second: "pendingInit" }, "spawn-second"), + { + ...collab("wait", { first: initialStatus, second: "completed" }), + status: initialStatus === "errored" ? "failed" : "completed", + }, + { ...collab("sendInput", { first: "running" }), prompt: "Do more work" }, + { + ...collab(tool, { first: resultStatus }), + status: resultStatus === "errored" ? "failed" : "completed", + }, + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([ + { id: "first", status: expected }, + { id: "second", status: "completed" }, + ]); + expect( + history.flatMap((event) => + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.callId === "spawn-first" + ? [event.item.status] + : [], + ), + ).toEqual([expected]); + }, + ); + + test("keeps the prior outcome when a follow-up submission fails", async () => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("wait", { first: "completed" }), + { ...collab("sendInput", { first: "running" }), status: "failed", prompt: "Do more work" }, + collab("wait", { first: "running" }, "stale-wait"), + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ), + ).toEqual(["completed"]); + }); + + test("settles a close card without a registered spawn", async () => { + const history = await replay([collab("closeAgent", { external: "running" })]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" + ? [{ id: event.item.callId, status: event.item.status }] + : [], + ), + ).toEqual([{ id: "closeAgent", status: "canceled" }]); + }); + + test.each(["notFound", "errored"])( + "preserves completion and shows a failed resume reporting %s", + async (status) => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("wait", { first: "completed" }), + collab("closeAgent", { first: "completed" }), + { ...collab("resumeAgent", { first: status }), status: "failed" }, + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [event.event.status] + : [], + ), + ).toEqual(["completed"]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" + ? [{ id: event.item.callId, status: event.item.status }] + : [], + ), + ).toEqual([ + { id: "spawn-first", status: "completed" }, + { id: "resumeAgent", status: "failed" }, + ]); + }, + ); + + test("stops counting a child closed while running", async () => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("closeAgent", { first: "running" }), + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([{ id: "first", status: "canceled" }]); + }); + + test.each(["wait", "closeAgent"])( + "restores an errored child as failed after %s", + async (tool) => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + { ...collab(tool, { first: "errored" }), status: "failed" }, + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([{ id: "first", status: "failed" }]); + expect( + history.flatMap((event) => + event.type === "timeline" && event.item.type === "tool_call" + ? [{ id: event.item.callId, status: event.item.status, error: event.item.error }] + : [], + ), + ).toEqual([{ id: "spawn-first", status: "failed", error: { message: "Sub-agent failed" } }]); + }, + ); + + test.each(["wait", "closeAgent"])( + "settles a live errored child as failed after %s", + async (tool) => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: process.cwd(), modeId: "full-access" }, + null, + createTestLogger(), + async () => appServer.child, + ); + const statuses = new Map(); + const cards = new Map(); + session.subscribe((event) => { + if (event.type === "provider_subagent" && event.event.type === "upsert") { + statuses.set(event.event.id, event.event.status); + } + if (event.type === "timeline" && event.item.type === "tool_call") { + cards.set(event.item.callId, { status: event.item.status, error: event.item.error }); + } + }); + function notify(method: string, item: ReturnType) { + appServer.child.stdout.write( + `${JSON.stringify({ method, params: { threadId: "thread-1", item } })}\n`, + ); + } + try { + const result = session.run("Delegate the work."); + await appServer.waitForTurnStart(); + notify("item/completed", collab("spawnAgent", { first: "pendingInit" }, "spawn-first")); + notify("item/started", { + ...collab(tool, { first: "errored" }), + status: "inProgress", + agentsStates: {}, + }); + notify("item/completed", { ...collab(tool, { first: "errored" }), status: "failed" }); + appServer.completeTurn(); + await result; + expect([...statuses]).toEqual([["first", "failed"]]); + expect([...cards]).toEqual([ + ["spawn-first", { status: "failed", error: { message: "Sub-agent failed" } }], + ]); + } finally { + await session.close(); + appServer.assertNoErrors(); + } + }, + ); + + test("preserves completion when a close carries an older running snapshot", async () => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("wait", { first: "completed" }), + collab("closeAgent", { first: "running" }), + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([{ id: "first", status: "completed" }]); + }); + + test.each([ + ["shutdown", "canceled"], + ["notFound", "failed"], + ])("restores a %s child as %s and preserves its running sibling", async (status, expected) => { + const history = await replay([ + collab("spawnAgent", { first: "pendingInit" }, "spawn-first"), + collab("spawnAgent", { second: "pendingInit" }, "spawn-second"), + collab("closeAgent", { first: status }), + ]); + expect( + history.flatMap((event) => + event.type === "provider_subagent" && event.event.type === "upsert" + ? [{ id: event.event.id, status: event.event.status }] + : [], + ), + ).toEqual([ + { id: "first", status: expected }, + { id: "second", status: "running" }, + ]); + }); + + test("settles a rendered live wait when its completion lists only the finished receiver", async () => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: process.cwd(), modeId: "full-access" }, + null, + createTestLogger(), + async () => appServer.child, + ); + const cards = new Map(); + const statuses = new Map(); + session.subscribe((event) => { + if (event.type === "timeline" && event.item.type === "tool_call") { + cards.set(event.item.callId, event.item.status); + } + if (event.type === "provider_subagent" && event.event.type === "upsert") { + statuses.set(event.event.id, event.event.status); + } + }); + function notify(method: string, item: ReturnType) { + appServer.child.stdout.write( + `${JSON.stringify({ method, params: { threadId: "thread-1", item } })}\n`, + ); + } + try { + const result = session.run("Wait for the children."); + await appServer.waitForTurnStart(); + notify("item/completed", collab("spawnAgent", { first: "pendingInit" }, "spawn-first")); + notify("item/started", { + ...collab("wait", { first: "running", second: "running" }, "mixed-wait"), + status: "inProgress", + agentsStates: {}, + }); + await vi.waitFor(() => expect(cards.get("mixed-wait")).toBe("running")); + notify("item/completed", collab("wait", { first: "completed" }, "mixed-wait")); + notify("item/completed", collab("wait", { second: "completed" }, "wait-second")); + appServer.completeTurn(); + await result; + expect([...statuses]).toEqual([["first", "completed"]]); + expect([...cards]).toEqual([ + ["spawn-first", "completed"], + ["mixed-wait", "completed"], + ["wait-second", "completed"], + ]); + } finally { + await session.close(); + appServer.assertNoErrors(); + } + }); + + test.each(["completed", "interrupted", "running"])( + "keeps a live follow-up running despite a late %s sendInput snapshot", + async (submissionStatus) => { + const appServer = createFakeCodexAppServer(); + const session = new CodexAppServerAgentSession( + { provider: "codex", cwd: process.cwd(), modeId: "full-access" }, + null, + createTestLogger(), + async () => appServer.child, + ); + const statuses = new Map(); + const timelineCards = new Map(); + let parentMessage = ""; + session.subscribe((event) => { + if (event.type === "provider_subagent" && event.event.type === "upsert") { + statuses.set(event.event.id, event.event.status); + } + if (event.type === "timeline" && event.item.type === "tool_call") { + timelineCards.set(event.item.callId, { + status: event.item.status, + detail: event.item.detail, + }); + } + if (event.type === "timeline" && event.item.type === "assistant_message") { + parentMessage = event.item.text; + } + }); + function complete(tool: string, states: Record, id = tool) { + const item = { + ...collab(tool, states, id), + ...(tool === "sendInput" ? { prompt: "Now add tests" } : {}), + }; + if (tool !== "spawnAgent") { + appServer.child.stdout.write( + `${JSON.stringify({ + method: "item/started", + params: { + threadId: "thread-1", + item: { ...item, status: "inProgress", agentsStates: {} }, + }, + })}\n`, + ); + } + appServer.child.stdout.write( + `${JSON.stringify({ + method: "item/completed", + params: { threadId: "thread-1", item }, + })}\n`, + ); + } + try { + const result = session.run("Delegate the work."); + await appServer.waitForTurnStart(); + complete("spawnAgent", { first: "pendingInit" }, "spawn-first"); + complete("spawnAgent", { second: "pendingInit" }, "spawn-second"); + complete("wait", { first: "completed", second: "running" }); + await vi.waitFor(() => { + expect(statuses.get("first")).toBe("completed"); + expect(statuses.get("second")).toBe("running"); + }); + complete("closeAgent", { first: "shutdown" }); + complete("wait", { first: "running" }, "stale-wait"); + appServer.says({ threadId: "thread-1", text: "Still waiting." }); + appServer.completeTurn(); + await result; + expect(statuses.get("first")).toBe("completed"); + appServer.startsTurn({ threadId: "first", turnId: "follow-up" }); + await vi.waitFor(() => expect(statuses.get("first")).toBe("running")); + complete("sendInput", { first: submissionStatus }); + appServer.says({ threadId: "thread-1", text: "Follow-up submitted." }); + await vi.waitFor(() => expect(parentMessage).toBe("Follow-up submitted.")); + expect(statuses.get("first")).toBe("running"); + expect([...timelineCards.keys()]).toEqual(["spawn-first", "spawn-second", "sendInput"]); + expect(timelineCards.get("sendInput")).toEqual({ + status: "completed", + detail: expect.objectContaining({ description: "Now add tests" }), + }); + // Only the child's completion settles the follow-up. + appServer.completeTurn({ threadId: "first" }); + await vi.waitFor(() => expect(statuses.get("first")).toBe("completed")); + } finally { + await session.close(); + appServer.assertNoErrors(); + } + }, + ); +}); diff --git a/packages/server/src/server/agent/providers/codex/thread-history.ts b/packages/server/src/server/agent/providers/codex/thread-history.ts index 557d92150be9..1dda8eae714b 100644 --- a/packages/server/src/server/agent/providers/codex/thread-history.ts +++ b/packages/server/src/server/agent/providers/codex/thread-history.ts @@ -10,6 +10,7 @@ export interface CodexThreadHistoryClient { } export type CodexThreadHistoryMode = "legacy" | "paginated"; +export type CodexHistoryStatus = "running" | "completed" | "failed" | "canceled"; export interface CodexHistoryRow { item: unknown; @@ -19,6 +20,11 @@ export interface CodexHistoryRow { completedAt: unknown; } +interface CodexThreadHistoryRead { + rows: Iterable | AsyncIterable; + status: CodexHistoryStatus | null; +} + /** A history reply over the line cap; the rows before it were already read. */ export class CodexThreadHistoryTooLargeError extends Error { constructor(message: string) { @@ -29,7 +35,22 @@ export class CodexThreadHistoryTooLargeError extends Error { const CodexThreadMetadataSchema = z .object({ - thread: z.object({ historyMode: z.enum(["legacy", "paginated"]).optional() }).passthrough(), + thread: z + .object({ + historyMode: z.enum(["legacy", "paginated"]).optional(), + status: z.unknown().optional(), + }) + .passthrough(), + }) + .passthrough(); + +const CodexLegacyTurnSchema = z + .object({ + id: z.string().optional(), + startedAt: z.unknown().optional(), + completedAt: z.unknown().optional(), + status: z.unknown().optional(), + items: z.array(z.unknown()).default([]), }) .passthrough(); @@ -37,18 +58,8 @@ const CodexLegacyThreadReadSchema = z .object({ thread: z .object({ - turns: z - .array( - z - .object({ - id: z.string().optional(), - startedAt: z.unknown().optional(), - completedAt: z.unknown().optional(), - items: z.array(z.unknown()).default([]), - }) - .passthrough(), - ) - .default([]), + status: z.unknown().optional(), + turns: z.array(CodexLegacyTurnSchema).default([]), }) .passthrough() .default({ turns: [] }), @@ -71,15 +82,48 @@ const CodexItemsPageSchema = z }) .passthrough(); +const CodexLatestTurnPageSchema = z.object({ + data: z.array(z.object({ status: z.unknown().optional() })), +}); + /** Codex builds before 0.143 report no history mode; their threads are legacy. */ export async function readCodexThreadHistoryMode( client: CodexThreadHistoryClient, threadId: string, ): Promise { - const response = CodexThreadMetadataSchema.parse( + return (await readThreadMetadata(client, threadId)).historyMode ?? "legacy"; +} + +async function readThreadMetadata(client: CodexThreadHistoryClient, threadId: string) { + return CodexThreadMetadataSchema.parse( await client.request("thread/read", { threadId, includeTurns: false }), - ); - return response.thread.historyMode ?? "legacy"; + ).thread; +} + +function readHistoryStatus( + threadStatus: unknown, + latestTurnStatus?: unknown, +): CodexHistoryStatus | null { + if ( + typeof threadStatus === "object" && + threadStatus !== null && + "type" in threadStatus && + threadStatus.type === "active" + ) { + return "running"; + } + // An unloaded thread can contain an unfinished rollout. Only the runtime + // status proves that it is still working. + switch (latestTurnStatus) { + case "completed": + return "completed"; + case "failed": + return "failed"; + case "interrupted": + return "canceled"; + default: + return null; + } } /** @@ -87,21 +131,20 @@ export async function readCodexThreadHistoryMode( * pages; a legacy thread arrives in one `thread/read` reply, as Codex offers * no pages for it. */ -export async function* readCodexThreadHistory( +export async function readCodexThreadHistory( client: CodexThreadHistoryClient, threadId: string, -): AsyncGenerator { - if ((await readCodexThreadHistoryMode(client, threadId)) === "paginated") { - yield* readPaginatedHistory(client, threadId); - } else { - yield* readLegacyHistory(client, threadId); + options?: { readLatestTurn?: boolean }, +): Promise { + const metadata = await readThreadMetadata(client, threadId); + if (metadata.historyMode === "paginated") { + const active = readHistoryStatus(metadata.status); + return { + rows: readPaginatedHistory(client, threadId), + status: + active ?? (options?.readLatestTurn ? await readLatestTurnStatus(client, threadId) : null), + }; } -} - -async function* readLegacyHistory( - client: CodexThreadHistoryClient, - threadId: string, -): AsyncGenerator { const response = await requestHistory( client, "thread/read", @@ -111,7 +154,37 @@ async function* readLegacyHistory( `run \`codex migrate-rollouts --apply --thread ${threadId}\` (Codex 0.148 or newer), ` + `then unarchive the agent.`, ); - for (const turn of CodexLegacyThreadReadSchema.parse(response).thread.turns) { + const { thread } = CodexLegacyThreadReadSchema.parse(response); + return { + rows: readLegacyRows(thread.turns), + status: readHistoryStatus(thread.status, thread.turns.at(-1)?.status), + }; +} + +async function readLatestTurnStatus( + client: CodexThreadHistoryClient, + threadId: string, +): Promise { + try { + const response = await client.request("thread/turns/list", { + threadId, + limit: 1, + sortDirection: "desc", + itemsView: "notLoaded", + }); + const page = CodexLatestTurnPageSchema.parse(response); + return readHistoryStatus(undefined, page.data[0]?.status); + } catch { + // Older Codex builds and stores can reject this optional probe. The + // recorded parent outcome and the child's timeline still load normally. + return null; + } +} + +function* readLegacyRows( + turns: z.infer[], +): Generator { + for (const turn of turns) { for (const item of turn.items) { yield { item, turnId: turn.id, startedAt: turn.startedAt, completedAt: turn.completedAt }; } diff --git a/packages/server/src/server/agent/providers/codex/tool-call-mapper.test.ts b/packages/server/src/server/agent/providers/codex/tool-call-mapper.test.ts index 423aa08c76f7..01f8f24afaf2 100644 --- a/packages/server/src/server/agent/providers/codex/tool-call-mapper.test.ts +++ b/packages/server/src/server/agent/providers/codex/tool-call-mapper.test.ts @@ -213,6 +213,20 @@ describe("codex tool-call mapper", () => { }); }); + it("accepts a nullable prompt in completed collaboration control items", () => { + expect( + mapCodexToolCallFromThreadItem({ + type: "collabAgentToolCall", + id: "wait-child", + tool: "wait", + prompt: null, + status: "completed", + receiverThreadIds: ["child"], + agentsStates: { child: { status: "completed" } }, + }), + ).toMatchObject({ callId: "wait-child", status: "completed" }); + }); + it("maps collabAgentToolCall into canonical sub-agent detail", () => { const item = mapCodexToolCallFromThreadItem({ type: "collabAgentToolCall", diff --git a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts index 8c0f8b955855..8e335de76bd7 100644 --- a/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/codex/tool-call-mapper.ts @@ -187,7 +187,7 @@ const CodexCollabAgentToolCallItemSchema = z id: z.string().min(1), status: z.string().optional(), error: z.unknown().optional(), - prompt: z.string().optional(), + prompt: z.string().nullish(), tool: z.string().optional(), receiverThreadIds: z.array(z.string()).optional(), agentsStates: z.record(z.string(), z.unknown()).optional(), @@ -546,12 +546,18 @@ function readStatus(value: unknown): string | undefined { return typeof value.status === "string" ? value.status : undefined; } -function normalizeCollabAgentChildStatus(status: string): ToolCallTimelineItem["status"] { +export function normalizeCollabAgentChildStatus( + status: string, + tool?: string, +): ToolCallTimelineItem["status"] { const normalized = status.trim().toLowerCase(); switch (normalized) { case "error": case "errored": - return "running"; + return tool === "wait" || tool === "closeAgent" ? "failed" : "running"; + case "running": + case "pendinginit": + return tool === "closeAgent" ? "canceled" : "running"; case "shutdown": return "canceled"; case "notfound": @@ -573,10 +579,15 @@ function resolveCollabAgentStatus( return "failed"; } + // Sending input completes the submission, not the child's new turn. + if (item.tool === "sendInput") { + return parentStatus; + } + const childStatuses = Object.values(item.agentsStates ?? {}) .map(readStatus) .filter((status): status is string => typeof status === "string" && status.trim().length > 0) - .map(normalizeCollabAgentChildStatus); + .map((status) => normalizeCollabAgentChildStatus(status, item.tool)); if (childStatuses.some((status) => status === "failed")) { return "failed"; From 32218adfecf3807416d9dc7a3149002e78b85e1d Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:48:36 +0000 Subject: [PATCH 002/109] Read a restored worktree again instead of serving its not-git snapshot (#10224) When a worktree folder disappears, the workspace git service can cache a not-git snapshot before it notices and suspends the workspace. After the folder comes back, a plain getSnapshot returned that cached snapshot before it tried to resume, so checkout status said "not a git repository" until the 60 s missing-folder probe. The Changes panel of a just-restored worktree had no repository header during that time. Resume a suspended workspace first, then serve the cached snapshot. This made e2e worktree-restore.spec.ts:167 flaky in CI. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/workspace-git-service.test.ts | 23 +++++++++++++++++++ .../src/server/workspace-git-service.ts | 8 ++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index 509b20193857..d99ee80f4981 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -2381,6 +2381,29 @@ describe("WorkspaceGitServiceImpl with workspace folders that no longer exist", await service.dispose(); }); + test("a plain snapshot read resumes a suspended workspace whose folder is back, instead of returning the non-git snapshot cached while it was gone", async () => { + const workspace = await createTemporaryFolder(); + const git = createFolderBackedGit(); + const service = createService(git.deps); + const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn()); + await waitForObservationToSettle(service, 1); + await rm(workspace, { recursive: true, force: true }); + service.onWorkspaceStateMayHaveChanged(workspace); + await vi.advanceTimersByTimeAsync(1_000); + await waitForRefreshesToSettle(service); + expect((await service.getSnapshot(workspace)).git.isGit).toBe(false); + await advanceThroughDegradedPolls(service); + await waitForObservationToSettle(service, 0); + + await mkdir(workspace); + const snapshot = await service.getSnapshot(workspace); + + expect(snapshot.git.isGit).toBe(true); + + subscription.unsubscribe(); + await service.dispose(); + }); + test("a resumed workspace rebuilds observation from fresh facts, not the non-git facts cached while its folder was gone", async () => { const workspace = await createTemporaryFolder(); const git = createFolderBackedGit(); diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 847e0c5927f2..8e50a7cffb6e 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -834,12 +834,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { cwd = resolve(cwd); const request = this.normalizeRefreshRequest(options, "getSnapshot"); const target = this.ensureWorkspaceTarget(cwd); - if (!request.force && target.latestSnapshot) { - return target.latestSnapshot; - } + // The snapshot cached while the folder was gone can say "not git". Resume + // first, so a restored folder is read again instead of served from it. if (target.folderMissing) { await this.resumeWorkspaceIfFolderRestored(target); } + if (!request.force && target.latestSnapshot) { + return target.latestSnapshot; + } return this.requestWorkspaceSnapshot(target, request); } From 4d29ee415a939117da5d27b6ad888a31d57322b3 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 19 Nov 2026 20:56:00 +0700 Subject: [PATCH 003/109] Show provider versions and run provider updates from provider settings (#9568) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(providers): show installed version and install link in provider settings Providers can now declare `installation`: install and update links plus an `inspect` callback that reports installed state and an opaque version string. Built-in clients and plugin providers share one contract; plugins receive the daemon-resolved launch with `resolved: false` when the executable is missing, so they can report not installed instead of failing. The daemon calls `inspect` only on the new `provider.installation.inspect.request` RPC, never from availability probing, discovery or session creation, so a slow version probe cannot delay agents. Results are cached per client for 30s, deadlined at 20s, and links survive a failed probe. The app gates the provider sheet's Installation row on `server_info.features.providerInstallation`, so older hosts show nothing new. * feat(providers): show available updates in provider settings Providers can now declare `installation.checkForUpdates`, returning `current`, `available` with opaque `versions` and `message`, or `unknown`. The provider decides what counts as newer; Paseo shows its answer as written and never parses or compares versions. The check is its own RPC, `provider.installation.check_updates`, so the installed version never waits on a network lookup. The daemon caches a conclusive answer for an hour and an inconclusive one for 30s, shares in-flight calls, and deadlines the call at 25s, below the plugin RPC timeout. A throw or timeout comes back as `error`, which the app shows as inconclusive, never as up to date. The sheet's Refresh bypasses the cache. Codex and Claude Code read the release source their own updaters use: the Homebrew cask for cask installs, otherwise the GitHub latest release for Codex and the configured `autoUpdatesChannel` for Claude Code. `codex doctor --json` reports the same answer but scans local state and took close to a minute, so it is not used. Muse compares its build with the launcher's channel manifest, the same rule the launcher updates by. The install link now shows whenever the provider declares `installUrl` and is not reported installed: the Install button for `not_installed`, a quieter "Install instructions" link when the check failed or the provider only links to a guide. * feat(providers): run provider updates from provider settings Providers can declare `update(context)`, and the Installation section shows an Update button when an update is available. The daemon owns the operation: one per provider, joined by later requests, kept in memory past client disconnects, streamed to subscribers through an owned subscription, and aborted only when the daemon stops. The provider's answer is the outcome; the daemon adds no verification. After success it drops the cached inspection and update check and refreshes discovery, without restarting agents. Codex and Claude run their own `update` subcommand and pass the output through. Muse has no update subcommand, so it does not declare one. Updater output is capped at 64 KiB per update so a chatty updater cannot grow daemon memory. Starting an update requires daemon.manage because it runs commands on the host. * feat(providers): report installation for the remaining providers Copilot, OpenCode, Pi, Oh My Pi, Antigravity and Hoplite now show an install link and the installed version in provider settings. Each one declares only what its CLI offers: - Update checks ask the source the CLI's own updater reads: Pi's latest-version endpoint, `omp update --check`, and Hoplite's latest.json. Copilot and OpenCode resolve their release inside the binary, so they declare no check. - Updates run the CLI's own command: `copilot update`, `opencode upgrade`, `pi update --self` (leaves Pi packages alone), `omp update`. Antigravity and Hoplite document no self-update. OpenCode's success message asks for a daemon restart, because all OpenCode agents share one server that keeps running the old version. * docs(providers): document the provider installation contract Plugin authors get the contract in the provider guide, with a worked example that reports a version, checks for an update and runs the CLI's own updater, and every field, deadline and cache in the reference. The internal provider and plugin docs record why the three callbacks are separate, that versions are opaque, that Paseo adds no verification to an update, and how the plugin bridge carries and cancels each request. * chore(protocol): mark provider installation as shipping in v0.17.0 main is on the 0.16 beta series, and a promotion ships the tested beta's content without pulling from main, so this lands in the next minor. * fix(app): bound update output and show refresh failures in provider settings The screen appended every progress chunk with no limit while open, so a noisy updater grew memory and never showed the truncation note that a reopened screen shows. Progress now folds with the daemon's 64 KiB limit. A manual refresh stored its result and failure outside the queries the screen reads, so a failed refresh brought back the old answer with no warning. Refresh now runs through those queries. It passes staleTime 0 because the app's default staleTime of Infinity would otherwise answer from the cache. The not-connected error uses the translated string the i18n check requires. * fix(providers): keep update checks in step with the installed version A conclusive check is cached for an hour and was not tied to the version it answered for. After a CLI updated outside Paseo, settings showed the new version and still offered Update to it. When an inspection reports a different version, the cached check is dropped. Versions are compared for equality, so they stay opaque. The release comparison dropped prerelease suffixes, so Codex 0.200.0-alpha.1 looked current against 0.200.0. A prerelease now comes before the release with the same numbers. Two different prereleases of the same release are reported as unknown. * docs(providers): say when Update instructions shows * fix(providers): reuse a cached update check only for the version it answered The previous fix dropped the cached check after an inspection settled with a new version. On reopen the app sends inspect and check together, so the check answered from the stale entry before the inspection settled. A cached check now records the installed version it was computed against and is reused only when the current inspection, shared if in flight, reports the same version. * fix(app): refresh provider version after an update settles while disconnected The installation and update queries were invalidated only by a live succeeded progress event. A connection dropped mid-update delivered the settled operation as a snapshot on reconnect, which left the old version and Update on screen. A success the view saw running now rereads them whether it arrives as progress or as a snapshot. * fix(providers): keep update checks within their own deadline Tying a cached check to its version made every check wait for a fresh inspection, which could add the 20 s inspect deadline to the 25 s check deadline. A check now never starts an inspection. It waits on one only when the inspection is cached or already running and the check would reuse a cached answer. When it asks the provider, it records the version afterwards. * test(app): assert provider installation states are visible * fix(providers): share one update check when two clients reopen after a version change * fix(muse): report the build the update check compares Paseo reuses a cached update check while inspect reports the same version string. Muse reported 1.4.18 but compared its build (1.4.18-R8600.1), so a new build of the same release kept the stale "Update available" for up to an hour. The contract docs now say to include everything the check compares in the reported version. * test(app): scroll custom model rows into view before checking them The provider sheet now shows an Installation section above the model lists. At 390x1000 the custom model row sits under the sheet footer until scrolled. The spec checks that a long model id leaves its Remove button reachable. It had assumed the row needed no vertical scroll. * test(app): keep the custom model check sensitive to a Remove button pushed off the sheet scrollIntoViewIfNeeded on the Remove button scrolled the overflow-hidden model card sideways too, so the check passed with the long-id layout fix undone. Scroll only the Custom models heading into view, which moves the sheet vertically and leaves the card at scrollLeft 0. With the layout fix undone the spec now fails at 1200px and 390px again. * feat(app): offer provider updates whether or not an update check answers Update and Update instructions lived inside the row that appeared only after checkForUpdates answered, so Copilot and OpenCode, which declare update but no check, never offered either. A check is a convenience: the Updates row now shows for an installed provider that offers an update, keeps Update or Update instructions in place in every check state (none, checking, up to date, available, couldn't check), and shows what the check knows as a hint beside it. A provider that offers no update still shows the check's answer once it has one. The daemon already ran update without a check; a test now says so. * fix(app): let update output scroll inside the provider sheet on Android The output box is a ScrollView nested in the sheet's scrolling body. Android hands the drag to the outer ScrollView unless the inner one sets nestedScrollEnabled, so only the last 240px of a long update's output was readable. The tool-call detail views set the same flag. * fix(app): show one progress indicator per provider update and refresh While an update ran, the Update button and the update's row each showed a spinner. The button's spinner also widened it, and the row's leading spinner shifted the title when the update settled. The update's row now owns progress from the tap until the update settles: it shows the update starting before the host answers, so the indicator never moves, and the Update button only disables. Refresh blanked the Installation rows while the provider was asked again, then moved "Checking…" from the Version row to the Updates row. The rows now keep their last answers until the new ones arrive, and the Refresh button shows the refresh until both the models and the installation are read again. * fix(app): show a provider update's progress on its Update button The pressed button carries an action's progress everywhere else in Settings: Button's own loading state with a present-participle label, as Browser data's Clear and Project settings' Save do. Update now does the same, reading "Updating..." from the tap until the update settles, and the update's row holds only the output while it runs, then the result. This replaces the row-owned spinner from the previous commit, which no other surface uses. The installation's in-flight labels use three dots like their siblings. * fix(app): keep a running update's progress visible whatever the inspection reads Update carries the update's progress, but its row rendered only while the inspection read "installed". An inspection that ran during the update (on reopen or Refresh) could read loading, not installed or failed while the binary was replaced, and the sheet then showed nothing about the running update. The Updates row now stays while an update runs. * fix(server): show and update the provider CLI its agents launch The installation contract found the CLI on the daemon's PATH, while agents spawn the bare command with the provider's environment. A provider whose env sets PATH could launch one copy and show and update another, so an update succeeded while new agents kept the old version. The CLI is now resolved with the provider's environment. The section test's check-state table now always names the text it expects, so no case can skip its assertion. * test(server): name the provider PATH test for what it shows The availability check that gates a Copilot spawn still looks on the daemon's PATH, so the copy on the provider's PATH is not always the one agents launch. * test(antigravity-provider): read the version from the CLI, not its acp subcommand Antigravity now launches `agy acp --disable-telemetry`, so the launch the installation receives ends with the ACP subcommand. The version read drops it, since `agy acp --version` starts the ACP server. * feat(plugin): pass the inspected version to checkForUpdates checkForUpdates now receives installedVersion, the version inspect reported, and the daemon keys the cached answer on it. Before, each provider read its version a second time and the daemon recorded which version a cached check answered for, so a check could compare a different version than the one shown, and a plugin had to put everything its check compared into the reported version. An update check now waits for the provider's inspection (shared with a concurrent inspect, refreshed with it), answers Not installed or the inspection's error without asking the provider, and is asked again once the inspection reports a different version. * fix(server): clear a failed provider update when the provider is refreshed The daemon kept a provider's last update for its whole lifetime, so a failed update stayed the current update until a later update succeeded or the daemon restarted, and the provider looked broken after the user fixed it. A refresh of the provider's installation or update check now drops a failed result. A running update is never dropped. * docs(server): say which agents look up the provider CLI on its PATH * fix(server): tell open provider views when a refresh drops a failed update A refresh deleted the failed update on the daemon but sent nothing, so a view already observing the provider's updates, in this client or another one, kept showing the failure until it observed again. The daemon now pushes provider.installation.update.cleared with the dropped operation's id to every subscriber, and the app clears the update it shows when the ids match. --- docs/plugins.md | 12 + docs/providers.md | 46 + .../browser/provider-update-failure.spec.ts | 26 + .../app/e2e/support/helpers/custom-models.ts | 16 +- .../helpers/provider-update-failure.ts | 118 +++ .../components/provider-diagnostic-sheet.tsx | 25 +- ...ider-installation-section.browser.test.tsx | 480 +++++++++ .../provider-installation-section.tsx | 448 +++++++++ .../src/components/provider-installation.tsx | 195 ++++ .../provider-update-progress.test.ts | 48 + .../components/provider-update-progress.ts | 38 + packages/app/src/i18n/resources/ar.ts | 20 + packages/app/src/i18n/resources/en.ts | 20 + packages/app/src/i18n/resources/es.ts | 20 + packages/app/src/i18n/resources/fr.ts | 20 + packages/app/src/i18n/resources/ja.ts | 20 + packages/app/src/i18n/resources/ko.ts | 20 + packages/app/src/i18n/resources/pt-BR.ts | 20 + packages/app/src/i18n/resources/ru.ts | 20 + packages/app/src/i18n/resources/zh-CN.ts | 20 + packages/client/src/daemon-client.ts | 73 ++ packages/plugin/src/server/provider.ts | 87 ++ packages/protocol/src/messages.ts | 200 ++++ .../src/server/agent/agent-sdk-types.ts | 36 + .../src/server/agent/plugin-provider.ts | 65 +- .../provider-installations.test.ts | 934 ++++++++++++++++++ .../provider-installations.ts | 377 +++++++ .../provider-update-operation.ts | 80 ++ .../src/server/agent/provider-registry.ts | 1 + .../server/agent/provider-snapshot-manager.ts | 13 + .../server/agent/providers/claude/agent.ts | 140 ++- .../agent/providers/cli-installation.ts | 120 +++ .../agent/providers/codex-app-server-agent.ts | 109 ++ .../agent/providers/copilot-acp-agent.ts | 32 +- .../agent/providers/diagnostic-utils.ts | 18 +- .../src/server/agent/providers/omp/agent.ts | 4 + .../agent/providers/omp/installation.ts | 62 ++ .../providers/opencode/runtime-client.ts | 23 + .../src/server/agent/providers/pi/agent.ts | 31 + .../providers/provider-update-checks.test.ts | 380 +++++++ .../server/agent/providers/release-check.ts | 108 ++ .../server/agent/providers/update-command.ts | 52 + .../authorization/operation-permissions.ts | 11 + .../src/server/daemon-e2e/models.e2e.test.ts | 186 ++++ .../src/server/plugins/index.posix.test.ts | 168 ++++ packages/server/src/server/plugins/index.ts | 45 +- .../server/plugins/plugin-process-protocol.ts | 69 ++ .../src/server/plugins/plugin-process.ts | 180 +++- packages/server/src/server/plugins/runtime.ts | 151 ++- packages/server/src/server/session.ts | 33 + .../provider/provider-catalog-session.ts | 71 ++ .../server/src/server/websocket-server.ts | 1 + .../server/provider.test.ts | 31 +- .../antigravity-provider/server/provider.ts | 29 + .../server/installation.test.ts | 106 ++ .../hoplite-provider/server/installation.ts | 83 ++ plugins/hoplite-provider/server/provider.ts | 2 + plugins/muse-provider/server/provider.ts | 79 +- plugins/muse-provider/server/updates.ts | 56 ++ plugins/muse-provider/test/provider.test.ts | 62 ++ public-docs/plugins/providers.md | 121 +++ public-docs/plugins/providers.zh-CN.md | 98 ++ public-docs/plugins/reference.md | 58 ++ public-docs/plugins/reference.zh-CN.md | 45 + 64 files changed, 6170 insertions(+), 92 deletions(-) create mode 100644 packages/app/e2e/browser/provider-update-failure.spec.ts create mode 100644 packages/app/e2e/support/helpers/provider-update-failure.ts create mode 100644 packages/app/src/components/provider-installation-section.browser.test.tsx create mode 100644 packages/app/src/components/provider-installation-section.tsx create mode 100644 packages/app/src/components/provider-installation.tsx create mode 100644 packages/app/src/components/provider-update-progress.test.ts create mode 100644 packages/app/src/components/provider-update-progress.ts create mode 100644 packages/server/src/server/agent/provider-installation/provider-installations.test.ts create mode 100644 packages/server/src/server/agent/provider-installation/provider-installations.ts create mode 100644 packages/server/src/server/agent/provider-installation/provider-update-operation.ts create mode 100644 packages/server/src/server/agent/providers/cli-installation.ts create mode 100644 packages/server/src/server/agent/providers/omp/installation.ts create mode 100644 packages/server/src/server/agent/providers/provider-update-checks.test.ts create mode 100644 packages/server/src/server/agent/providers/release-check.ts create mode 100644 packages/server/src/server/agent/providers/update-command.ts create mode 100644 plugins/hoplite-provider/server/installation.test.ts create mode 100644 plugins/hoplite-provider/server/installation.ts create mode 100644 plugins/muse-provider/server/updates.ts diff --git a/docs/plugins.md b/docs/plugins.md index 30757c1f93b2..e177d438f3c9 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -510,6 +510,18 @@ before calling status; it exposes your diagnostic through the normal provider di A command-backed provider without status is available when its executable resolves. Providers with neither command nor status retain connection-based availability. +Implement optional `installation` to fill the **Installation** section of provider settings. The +bridge sends each callback as a `provider.installation.*` request carrying the launch `status` +receives plus `resolved`. `resolved: false` means the executable was not found and `command` is +the configured name, so answer `not_installed` instead of spawning it. Inspect and update-check +requests use the 30 s plugin request timeout; the daemon's 25 s update-check deadline sits below +it, so a slow check reports that deadline. `update` has no request timeout and streams output +through `provider.installation.report`. When the daemon stops waiting on any of the three, it +sends `provider.installation.cancel`, which aborts the callback's `signal`. +The rules shared with built-ins are in [providers.md](providers.md#installation-and-updates); the +author contract is in the +[public provider guide](../public-docs/plugins/providers.md#report-installation-and-updates). + A same-ID config entry without `extends` overrides the plugin's `enabled`, `command`, `env`, label, description, and model configuration through the normal provider registry. `enabled: false` disables selection and discovery. An entry with `extends` defines the user's own provider, shadows the plugin, diff --git a/docs/providers.md b/docs/providers.md index f9dc73c4963d..34a078f88481 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -263,6 +263,52 @@ promise for completion: equal results, including equal discovery timestamps, emi --- +## Installation and updates + +The **Installation** section of provider settings reads `AgentClient.installation`. Built-ins set +it on the client; plugins set `ProviderRegistration.installation`, which the plugin bridge maps to +the same interface. `ProviderInstallations` in `packages/server/src/server/agent/provider-installation/` +owns deadlines, caching and the one running update per provider, so a provider only answers. + +Declare only what the vendor offers: + +- `installUrl` and `updateUrl` link the vendor's own install and update docs. +- `inspect` reports the version the CLI prints. Versions are opaque: Paseo shows them as written + and never parses them. +- `checkForUpdates` receives the version `inspect` reported as `installedVersion` and asks the + source the CLI's own updater reads, such as the vendor's release endpoint or the CLI's + `update --check`. Do not read the version again. Leave it out when that source is inside the binary or + depends on how the CLI was installed, which is why Copilot and OpenCode have no check. Do not + build a release lookup of your own. +- `update` runs the CLI's own update command and passes its output through, using + `runUpdateCommand`. Paseo adds no verification, signature check or rollback, so the update does + exactly what the same command does in a terminal. + +The three calls are separate because they cost differently. `inspect` runs whenever someone opens +provider settings, with a 20 s deadline and a 30 s cache. `checkForUpdates` usually reaches the +network. Paseo calls it only after `inspect` reports the CLI installed, and keeps a conclusive +answer for an hour while `inspect` reports the same version, so a CLI updated outside Paseo is +checked again once the 30 s inspection expires. `update` runs for minutes, streams output, and is +aborted only when the daemon stops. A failed update stays on the provider until the next refresh +of its installation, which tells every client observing the provider's updates that it is gone; a +running one is never dropped. + +The update check only informs. Once `inspect` reports the CLI installed, the app offers **Update** +for a provider that declares `update`, or **Update instructions** for one that declares only +`updateUrl`, whatever the check answers and whether the provider has one. The check's answer shows +beside the action when it has one. Copilot and OpenCode have no check, so they show **Update** alone. + +Write the success message for the provider's process model. A CLI that Paseo starts once per agent +uses `updatedForNewAgents()`. OpenCode agents share one server that keeps the old binary running, +so its message asks the user to restart the daemon. + +`createCliInstallation()` covers a CLI that prints `--version` and updates with a subcommand. It +resolves the configured command, so a profile that extends a built-in reports and updates the CLI +that profile launches. Clients for `extends: "acp"` providers declare no installation. + +Test with fake executables, as `providers/provider-update-checks.test.ts` does. Running a real +updater during development replaces the CLI on your machine. + ## Usage sources See the [public usage source reference](../public-docs/plugins/reference.md#usage-sources) for the diff --git a/packages/app/e2e/browser/provider-update-failure.spec.ts b/packages/app/e2e/browser/provider-update-failure.spec.ts new file mode 100644 index 000000000000..1613720dd398 --- /dev/null +++ b/packages/app/e2e/browser/provider-update-failure.spec.ts @@ -0,0 +1,26 @@ +import { + expectNoUpdateFailure, + openProviderInstallation, + refreshFromOtherClient, + refreshProviderDetails, + runFailingUpdate, + test, +} from "../support/helpers/provider-update-failure"; + +test("a refresh clears a failed update from the open Installation section", async ({ + providerUpdateFailure: { page, otherClient }, +}) => { + await openProviderInstallation(page); + + await test.step("Refresh in this view clears the failure", async () => { + await runFailingUpdate(page); + await refreshProviderDetails(page); + await expectNoUpdateFailure(page); + }); + + await test.step("a refresh from another client clears it too", async () => { + await runFailingUpdate(page); + await refreshFromOtherClient(otherClient); + await expectNoUpdateFailure(page); + }); +}); diff --git a/packages/app/e2e/support/helpers/custom-models.ts b/packages/app/e2e/support/helpers/custom-models.ts index aff79965ea55..7b078c1334e7 100644 --- a/packages/app/e2e/support/helpers/custom-models.ts +++ b/packages/app/e2e/support/helpers/custom-models.ts @@ -25,7 +25,7 @@ export async function addCustomModel(page: Page, id: string): Promise { } export async function removeCustomModel(page: Page, id: string): Promise { - await page.getByRole("textbox", { name: "Search models" }).fill(id); + await searchModels(page, id); const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true }); await expect(remove).toBeInViewport({ ratio: 1 }); await remove.click(); @@ -33,8 +33,20 @@ export async function removeCustomModel(page: Page, id: string): Promise { } export async function expectCustomModelRetained(page: Page, id: string): Promise { - await page.getByRole("textbox", { name: "Search models" }).fill(id); + await searchModels(page, id); await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toBeInViewport({ ratio: 1, }); } + +/** + * Filters the model list and scrolls the sheet down to the custom models, since other sections push + * them below the fold at phone width. Only the section heading is scrolled into view: scrolling the + * row itself would also slide its card sideways and hide a Remove button pushed past the right edge. + */ +async function searchModels(page: Page, id: string): Promise { + await page.getByRole("textbox", { name: "Search models" }).fill(id); + await page + .getByText("Custom models", { exact: true }) + .evaluate((heading) => heading.scrollIntoView({ block: "start" })); +} diff --git a/packages/app/e2e/support/helpers/provider-update-failure.ts b/packages/app/e2e/support/helpers/provider-update-failure.ts new file mode 100644 index 000000000000..420e05df2eab --- /dev/null +++ b/packages/app/e2e/support/helpers/provider-update-failure.ts @@ -0,0 +1,118 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client"; +import { expect, test as base, type Page } from "../fixtures"; +import { gotoAppShell, openSettings } from "./app"; +import { connectDaemonClient } from "./daemon-client-loader"; +import { copyPluginExample, pluginRequirements } from "./plugin-fixture"; +import { getServerId } from "./server-id"; +import { openSettingsHostSection } from "./settings"; + +const PLUGIN_ID = "provider-update-failure"; +const PROVIDER_ID = "update-failure"; +const PROVIDER_NAME = "Update failure"; +const FAILURE = "The updater could not write to the install directory"; + +/** The direct provider example with an installation whose updater always fails. */ +const SERVER_SOURCE = `import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { createDirectExampleProvider } from "./server/provider"; + +export default function contribute(server: PluginServerContext) { + server.registerProvider({ + ...createDirectExampleProvider(), + id: ${JSON.stringify(PROVIDER_ID)}, + label: ${JSON.stringify(PROVIDER_NAME)}, + installation: { + async inspect() { + return { status: "installed", version: "1.0.0" }; + }, + async update({ report }) { + report({ type: "stderr", text: "EACCES\\n" }); + return { status: "failed", message: ${JSON.stringify(FAILURE)} }; + }, + }, + }); + return () => {}; +} +`; + +type ObserverClient = Pick< + InternalDaemonClient, + | "close" + | "connect" + | "getDaemonConfig" + | "inspectProviderInstallation" + | "installDirectoryPlugin" + | "patchDaemonConfig" + | "removePlugin" +>; + +interface ProviderUpdateFailure { + page: Page; + /** A second client of the same host. */ + otherClient: ObserverClient; +} + +export const test = base.extend<{ providerUpdateFailure: ProviderUpdateFailure }>({ + providerUpdateFailure: async ({ page }, provide) => { + const client = await connectDaemonClient({ + clientIdPrefix: "app-e2e-provider-update-failure", + }); + const plugin = await copyPluginExample("provider-direct"); + try { + const previous = await client.getDaemonConfig(); + await writeFile( + path.join(plugin.directory, "paseo-plugin.json"), + JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }), + ); + await writeFile(path.join(plugin.directory, "index.server.ts"), SERVER_SOURCE); + try { + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(plugin.directory); + await provide({ page, otherClient: client }); + } finally { + try { + await client.removePlugin(PLUGIN_ID); + } finally { + await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled }); + } + } + } finally { + await plugin.cleanup(); + await client.close(); + } + }, +}); + +export async function openProviderInstallation(page: Page): Promise { + await gotoAppShell(page); + await openSettings(page); + await openSettingsHostSection(page, getServerId(), "providers"); + await page + .getByRole("button", { name: `${PROVIDER_NAME} provider details`, exact: true }) + .click(); + await expect(page.getByTestId("provider-installation-version")).toHaveText("1.0.0"); +} + +export async function runFailingUpdate(page: Page): Promise { + await page.getByTestId("provider-update-start").click(); + await expect(page.getByTestId("provider-update-status")).toHaveText("Update failed"); + await expect(page.getByTestId("provider-update-message")).toHaveText(FAILURE); +} + +export async function refreshProviderDetails(page: Page): Promise { + await page + .getByTestId("provider-settings-sheet") + .getByRole("button", { name: "Refresh", exact: true }) + .click(); +} + +export async function refreshFromOtherClient(client: ObserverClient): Promise { + const result = await client.inspectProviderInstallation(PROVIDER_ID, { refresh: true }); + expect(result.error).toBeNull(); +} + +export async function expectNoUpdateFailure(page: Page): Promise { + await expect(page.getByTestId("provider-update-run")).toHaveCount(0); + await expect(page.getByTestId("provider-installation-version")).toHaveText("1.0.0"); +} diff --git a/packages/app/src/components/provider-diagnostic-sheet.tsx b/packages/app/src/components/provider-diagnostic-sheet.tsx index 904ba17e8bf8..2426088e9dfa 100644 --- a/packages/app/src/components/provider-diagnostic-sheet.tsx +++ b/packages/app/src/components/provider-diagnostic-sheet.tsx @@ -27,6 +27,8 @@ import { resolveProviderLabel } from "@/utils/provider-definitions"; import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types"; import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config"; +import { ProviderInstallationSection } from "./provider-installation-section"; +import { useProviderInstallation } from "./provider-installation"; import { resolveProviderDiscoveredModels, type ProviderDiscoveredModelsCache, @@ -372,7 +374,8 @@ interface ProviderModalBodyProps { interface ProviderSheetFooterInput { fetchedAt: string | null; isCompact: boolean; - modelsRefreshing: boolean; + /** Models or the installation are being read again. */ + refreshing: boolean; t: TFunction; onOpenAddSheet: () => void; onOpenDiagSheet: () => void; @@ -382,7 +385,7 @@ interface ProviderSheetFooterInput { function renderProviderSheetFooter({ fetchedAt, isCompact, - modelsRefreshing, + refreshing, t, onOpenAddSheet, onOpenDiagSheet, @@ -410,12 +413,12 @@ function renderProviderSheetFooter({ @@ -593,9 +596,12 @@ export function ProviderDiagnosticSheet({ [additionalModels, q], ); + const installation = useProviderInstallation({ serverId, provider, visible }); + const refreshInstallation = installation.refresh; const handleRefreshModels = useCallback(() => { void refresh([provider]); - }, [provider, refresh]); + refreshInstallation(); + }, [provider, refresh, refreshInstallation]); const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []); const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []); @@ -642,7 +648,7 @@ export function ProviderDiagnosticSheet({ footer={renderProviderSheetFooter({ fetchedAt: providerEntry?.fetchedAt ?? null, isCompact, - modelsRefreshing, + refreshing: modelsRefreshing || installation.refreshing, t, onOpenAddSheet: handleOpenAddSheet, onOpenDiagSheet: handleOpenDiagSheet, @@ -650,6 +656,11 @@ export function ProviderDiagnosticSheet({ })} snapPoints={MAIN_SNAP_POINTS} > + vi.stubGlobal("React", React)); + +const mounted: { root: Root; container: HTMLDivElement }[] = []; +afterEach(() => { + for (const entry of mounted.splice(0)) { + act(() => entry.root.unmount()); + entry.container.remove(); + } +}); + +const INSTALL_URL = "https://example.com/install"; +const UPDATE_URL = "https://example.com/update"; + +function mount( + state: ProviderInstallationState, + updates: ProviderUpdatesState = { status: "hidden" }, + action?: ProviderUpdateAction, +) { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => + root.render(), + ); + mounted.push({ root, container }); + const view = within(container); + return { + view, + rerender: (nextUpdates: ProviderUpdatesState, nextAction?: ProviderUpdateAction) => + act(() => + root.render( + , + ), + ), + installButton: () => view.queryByRole("button", { name: "Install" }), + installLink: () => view.queryByRole("link", { name: "Install instructions" }), + }; +} + +function ready(installation: ProviderInstallationState & { status: "ready" }) { + return installation; +} + +describe("install link visibility", () => { + it("offers the Install button when the provider reports it is not installed", () => { + const section = mount( + ready({ + status: "ready", + installation: { installUrl: INSTALL_URL, inspection: { status: "not_installed" } }, + }), + ); + expect(section.installButton()).not.toBeNull(); + expect(section.installLink()).toBeNull(); + }); + + it("offers a quiet install link when the installation check failed", async () => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "error", message: "version probe exploded" }, + }, + }), + ); + await expect.element(section.view.getByText("version probe exploded")).toBeVisible(); + expect(section.installLink()).not.toBeNull(); + expect(section.installButton()).toBeNull(); + }); + + it("offers a quiet install link for a provider that only declares where to install it", () => { + const section = mount(ready({ status: "ready", installation: { installUrl: INSTALL_URL } })); + expect(section.installLink()).not.toBeNull(); + expect(section.installButton()).toBeNull(); + }); + + it("offers no install link once the provider reports it is installed", () => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "installed", version: "1" }, + }, + }), + ); + expect(section.installLink()).toBeNull(); + expect(section.installButton()).toBeNull(); + }); +}); + +describe("update check", () => { + const installed = ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + updateUrl: UPDATE_URL, + inspection: { status: "installed", version: "0.165.0" }, + }, + }); + + it("shows the reported versions and message as written, with Update instructions", async () => { + const section = mount(installed, { + status: "ready", + updateCheck: { + status: "available", + versions: ["0.168.0", "nightly (unstable)"], + message: "Restart to finish", + }, + }); + await expect.element(section.view.getByText("Update available")).toBeVisible(); + expect( + section.view.getAllByTestId("provider-updates-version").map((node) => node.textContent), + ).toEqual(["0.168.0", "nightly (unstable)"]); + await expect.element(section.view.getByText("Restart to finish")).toBeVisible(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }); + + const inconclusive = [ + { + name: "unknown", + updates: { status: "ready", updateCheck: { status: "unknown", message: "Offline" } }, + }, + { + name: "a thrown or timed-out check", + updates: { status: "ready", updateCheck: { status: "error", message: "Offline" } }, + }, + { name: "a failed request", updates: { status: "error", message: "Offline" } }, + ] as const; + + it.each(inconclusive)("shows $name as inconclusive, never up to date", async ({ updates }) => { + const section = mount(installed, updates); + await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible(); + await expect.element(section.view.getByText("Offline")).toBeVisible(); + expect(section.view.queryByText("Up to date")).toBeNull(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }); + + it.each(inconclusive)( + "still says $name when the provider offers no update", + async ({ updates }) => { + const section = mount( + ready({ + status: "ready", + installation: { inspection: { status: "installed", version: "0.165.0" } }, + }), + updates, + ); + await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible(); + expect(section.view.queryByRole("button")).toBeNull(); + }, + ); + + it("shows up to date only when the provider says so", async () => { + const section = mount(installed, { status: "ready", updateCheck: { status: "current" } }); + await expect.element(section.view.getByText("Up to date")).toBeVisible(); + }); + + it("shows the check's answer for a provider that offers no update", async () => { + const section = mount( + ready({ + status: "ready", + installation: { inspection: { status: "installed", version: "1.4.18" } }, + }), + { status: "ready", updateCheck: { status: "current" } }, + ); + await expect.element(section.view.getByText("Up to date")).toBeVisible(); + expect(section.view.queryByRole("button")).toBeNull(); + }); + + it.each([ + { name: "cannot check", updates: { status: "ready", updateCheck: null } }, + { name: "is still checking", updates: { status: "loading" } }, + ] as const)( + "shows no Updates row while a provider that offers no update $name", + ({ updates }) => { + const section = mount( + ready({ + status: "ready", + installation: { + installUrl: INSTALL_URL, + inspection: { status: "installed", version: "1.0.0" }, + }, + }), + updates, + ); + expect(section.view.queryByTestId("provider-updates")).toBeNull(); + expect(section.view.getByTestId("provider-installation-version").textContent).toBe("1.0.0"); + }, + ); +}); + +describe("update action", () => { + const installed = (canUpdate: boolean) => + ready({ + status: "ready", + installation: { + updateUrl: UPDATE_URL, + inspection: { status: "installed", version: "1.0.0" }, + ...(canUpdate ? { canUpdate: true } : {}), + }, + }); + const available: ProviderUpdatesState = { + status: "ready", + updateCheck: { status: "available", versions: ["2.0.0"] }, + }; + function action(overrides: Partial = {}) { + let starts = 0; + const value: ProviderUpdateAction = { + current: null, + starting: false, + startError: null, + start: () => { + starts += 1; + }, + ...overrides, + }; + return { value, starts: () => starts }; + } + const operation = { id: "op", startedAt: "2026-11-13T00:00:00.000Z" }; + const finishedAt = "2026-11-13T00:01:00.000Z"; + + // The check only informs: Update and the update instructions never wait on it. + const checkStates = [ + { name: "an update is available", updates: available, says: "Update available" }, + // No check answer: the row shows only its title (asserted whole below). + { + name: "the provider cannot check", + updates: { status: "ready", updateCheck: null }, + says: "Updates", + }, + { name: "the check is running", updates: { status: "loading" }, says: "Checking..." }, + { + name: "the check could not tell", + updates: { status: "ready", updateCheck: { status: "unknown" } }, + says: "Couldn't check for updates", + }, + { + name: "the check failed", + updates: { status: "error", message: "Offline" }, + says: "Couldn't check for updates", + }, + { + name: "the provider is up to date", + updates: { status: "ready", updateCheck: { status: "current" } }, + says: "Up to date", + }, + ] satisfies { name: string; updates: ProviderUpdatesState; says: string }[]; + + it.each(checkStates)( + "offers Update when $name and the provider runs its own", + async ({ updates, says }) => { + const control = action(); + const section = mount(installed(true), updates, control.value); + const button = section.view.getByRole("button", { name: "Update" }); + act(() => button.click()); + expect(control.starts()).toBe(1); + expect(section.view.queryByRole("button", { name: "Update instructions" })).toBeNull(); + await expect.element(section.view.getByText(says, { exact: true })).toBeVisible(); + }, + ); + + it.each(checkStates)( + "offers Update instructions when $name and the provider only links its guide", + async ({ updates }) => { + const section = mount(installed(false), updates, action().value); + expect(section.view.queryByRole("button", { name: "Update" })).toBeNull(); + await expect + .element(section.view.getByRole("button", { name: "Update instructions" })) + .toBeVisible(); + }, + ); + + it("shows no update status beside Update when the provider cannot check", () => { + const section = mount(installed(true), { status: "ready", updateCheck: null }, action().value); + expect(section.view.getByTestId("provider-updates").textContent).toBe("UpdatesUpdate"); + }); + + it("shows a running update with its output so far", () => { + const section = mount( + installed(true), + available, + action({ + current: { + operation: { ...operation, status: "running" }, + output: [ + { type: "message", text: "Running codex update\n" }, + { type: "stdout", text: "added 1 package\n" }, + ], + }, + }).value, + ); + expect(section.view.queryByTestId("provider-update-status")).toBeNull(); + expect(section.view.getByTestId("provider-update-output").textContent).toBe( + "Running codex update\nadded 1 package\n", + ); + }); + + it("shows the provider's success message as written", () => { + const section = mount( + installed(true), + { status: "ready", updateCheck: { status: "current" } }, + action({ + current: { + operation: { + ...operation, + status: "succeeded", + finishedAt, + message: " Restart agents \n", + }, + output: [], + }, + }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated"); + expect(section.view.getByTestId("provider-update-message").textContent).toBe( + " Restart agents \n", + ); + expect(section.view.queryByTestId("provider-update-output")).toBeNull(); + }); + + it("shows a failure with its message, its output and the update instructions", async () => { + const section = mount( + installed(true), + available, + action({ + current: { + operation: { ...operation, status: "failed", finishedAt, message: "exited with code 1" }, + output: [{ type: "stderr", text: "npm error EACCES\n" }], + truncated: true, + }, + }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + await expect.element(section.view.getByText("exited with code 1")).toBeVisible(); + expect(section.view.getByTestId("provider-update-output").textContent).toBe( + "npm error EACCES\n", + ); + await expect.element(section.view.getByText("Earlier output was dropped.")).toBeVisible(); + await expect + .element(section.view.getByRole("link", { name: "Update instructions" })) + .toBeVisible(); + await expect.element(section.view.getByRole("button", { name: "Update" })).toBeVisible(); + }); + + // Update carries the update's progress from the tap until it settles, like every in-flight + // button in Settings. The update's row shows only its output meanwhile. + describe("progress", () => { + const runningUpdate = (output: string[] = []) => ({ + operation: { ...operation, status: "running" as const }, + output: output.map((text) => ({ type: "stdout" as const, text })), + }); + function progress(section: ReturnType) { + const indicators = section.view.queryAllByRole("progressbar"); + const button = section.view.queryByTestId("provider-update-start"); + return { + count: indicators.length, + inButton: indicators.every((indicator) => button?.contains(indicator) ?? false), + label: button?.textContent, + pressable: button?.getAttribute("aria-disabled") !== "true", + }; + } + const updating = { count: 1, inButton: true, label: "Updating...", pressable: false }; + const idle = { count: 0, inButton: true, label: "Update", pressable: true }; + + it("shows progress on Update alone from tap to settle", () => { + const previous = { + operation: { ...operation, status: "failed" as const, finishedAt, message: "exit 1" }, + output: [{ type: "stderr" as const, text: "old failure\n" }], + }; + const section = mount(installed(true), available, action({ current: previous }).value); + expect(progress(section)).toEqual(idle); + + // Tapped, the host has not answered yet: the previous result gives way to the new update. + section.rerender(available, action({ current: previous, starting: true }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-run")).toBeNull(); + + // Running before any output arrives. + section.rerender(available, action({ current: runningUpdate() }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-run")).toBeNull(); + + section.rerender(available, action({ current: runningUpdate(["downloading\n"]) }).value); + expect(progress(section)).toEqual(updating); + expect(section.view.getByTestId("provider-update-run").textContent).toBe("downloading\n"); + + section.rerender( + { status: "ready", updateCheck: { status: "current" } }, + action({ + current: { + ...runningUpdate(["downloading\n"]), + operation: { ...operation, status: "succeeded", finishedAt }, + }, + }).value, + ); + expect(progress(section)).toEqual(idle); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated"); + }); + + it("shows progress on Update when the sheet reopens mid-update", () => { + const section = mount( + installed(true), + available, + action({ current: runningUpdate(["downloading\n"]) }).value, + ); + expect(progress(section)).toEqual(updating); + expect(section.view.queryByTestId("provider-update-status")).toBeNull(); + }); + + it.each([ + { name: "still loading", state: { status: "loading" } }, + { + name: "not installed", + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }, + { + name: "failing", + state: { + status: "ready", + installation: { inspection: { status: "error", message: "--version timed out" } }, + }, + }, + { name: "unreachable", state: { status: "error", message: "Host disconnected" } }, + ] satisfies { name: string; state: ProviderInstallationState }[])( + "shows progress on Update while the installation reads as $name", + ({ state }) => { + const section = mount( + state, + { status: "hidden" }, + action({ current: runningUpdate() }).value, + ); + // The inspection may show its own progress beside the Version row. + const button = section.view.getByRole("button", { name: "Updating..." }); + expect(button.getAttribute("aria-disabled")).toBe("true"); + expect(within(button).queryAllByRole("progressbar")).toHaveLength(1); + }, + ); + + it("returns Update to rest when the host refuses the start", () => { + const section = mount(installed(true), available, action({ starting: true }).value); + expect(progress(section)).toEqual(updating); + section.rerender(available, action({ startError: "Busy" }).value); + expect(progress(section)).toEqual(idle); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + }); + }); + + it("shows why the host refused to start the update", async () => { + const section = mount( + installed(true), + available, + action({ startError: "Provider codex cannot update itself" }).value, + ); + expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed"); + await expect + .element(section.view.getByText("Provider codex cannot update itself")) + .toBeVisible(); + }); +}); diff --git a/packages/app/src/components/provider-installation-section.tsx b/packages/app/src/components/provider-installation-section.tsx new file mode 100644 index 000000000000..59373d9af5a1 --- /dev/null +++ b/packages/app/src/components/provider-installation-section.tsx @@ -0,0 +1,448 @@ +import { useCallback, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { ScrollView, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import type { + ProviderInstallation, + ProviderInstallationUpdate, + ProviderInstallationUpdateCheck, +} from "@getpaseo/protocol/messages"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; +import { settingsStyles } from "@/styles/settings"; +import type { Theme } from "@/styles/theme"; +import { openExternalUrl } from "@/utils/open-external-url"; + +const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); +const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + +export type ProviderInstallationState = + | { status: "unsupported" } + | { status: "loading" } + | { status: "ready"; installation: ProviderInstallation | null } + | { status: "error"; message: string }; + +/** + * What the provider's update check knows. `hidden` until the provider is installed. A null + * `updateCheck` means the provider cannot check; the check only informs, and never gates Update. + */ +export type ProviderUpdatesState = + | { status: "hidden" } + | { status: "loading" } + | { status: "ready"; updateCheck: ProviderInstallationUpdateCheck | null } + | { status: "error"; message: string }; + +/** Running the provider's own update. Absent when the host cannot report updates. */ +export interface ProviderUpdateAction { + /** The provider's latest update since the host started, or null. */ + current: ProviderInstallationUpdate | null; + /** The request to start an update is in flight. */ + starting: boolean; + /** Why the host did not start the update. */ + startError: string | null; + start(): void; +} + +export function ProviderInstallationSection({ + state, + updates, + action, +}: { + state: ProviderInstallationState; + updates: ProviderUpdatesState; + action?: ProviderUpdateAction; +}) { + const { t } = useTranslation(); + if (state.status === "unsupported") return null; + if ( + state.status === "ready" && + !state.installation?.inspection && + !state.installation?.installUrl + ) + return null; + const installation = state.status === "ready" ? state.installation : null; + const run = action ? readUpdateRun(action) : null; + // A running update keeps its row, so Update shows its progress whatever the inspection reads + // meanwhile; the binary may be mid-replacement. + const updating = action ? isUpdating(action) : false; + + return ( + + + + {t("settings.providers.installation.title")} + + + + + {installation?.inspection?.status === "installed" || updating ? ( + + ) : null} + {run ? : null} + + + ); +} + +function InstallInstructionsLink({ installUrl }: { installUrl: string }) { + const { t } = useTranslation(); + return ( + + ); +} + +function InstallationRow({ state }: { state: ProviderInstallationState }) { + const { t } = useTranslation(); + const installation = state.status === "ready" ? state.installation : null; + const installUrl = installation?.installUrl; + const handleInstall = useCallback(() => { + if (installUrl) void openExternalUrl(installUrl); + }, [installUrl]); + + if (state.status === "loading") { + return ( + + {t("settings.providers.installation.version")} + + + {t("settings.providers.installation.checking")} + + + ); + } + const inspection = installation?.inspection; + if (inspection?.status === "not_installed") { + return ( + + + {t("settings.providers.installation.notInstalled")} + + {installUrl ? ( + + ) : null} + + ); + } + if (inspection?.status === "installed") { + return ( + + {t("settings.providers.installation.version")} + {inspection.version ? ( + + {inspection.version} + + ) : ( + {t("settings.providers.installation.installed")} + )} + + ); + } + // The installed state is unknown: the check failed, or the provider only links to a guide. + let message: string | null = null; + if (state.status === "error") message = state.message; + else if (inspection?.status === "error") message = inspection.message; + if (!message) { + return installUrl ? ( + + + + ) : null; + } + return ( + + + {t("settings.providers.installation.failed")} + {message} + {installUrl ? ( + + + + ) : null} + + + ); +} + +/** + * The update the provider offers, with what its check knows beside it. Update, or the update + * instructions, stay in place whatever the check says: an answer can be an hour old, and the + * provider's own updater reports when there is nothing newer. + */ +function UpdatesRow({ + updates, + updateUrl, + action, +}: { + updates: ProviderUpdatesState; + updateUrl: string | undefined; + /** Present when the provider runs its own update. */ + action: ProviderUpdateAction | undefined; +}) { + const { t } = useTranslation(); + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + const offersUpdate = Boolean(action || updateUrl); + // With nothing to offer, the row waits until the check has something to say. + if (!offersUpdate && !updateCheck && updates.status !== "error") return null; + + return ( + + + + {updateCheck?.status === "available" + ? t("settings.providers.installation.updateAvailable") + : t("settings.providers.installation.updates")} + + + + + + ); +} + +function UpdateCheckSummary({ updates }: { updates: ProviderUpdatesState }) { + const { t } = useTranslation(); + if (updates.status === "loading") { + return ( + + + {t("settings.providers.installation.checking")} + + ); + } + if (updates.status === "hidden") return null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + if (updates.status === "ready" && !updateCheck) return null; + if (updateCheck?.status === "current") { + return ( + + {t("settings.providers.installation.upToDate")} + + ); + } + if (updateCheck?.status === "available") { + // Versions are opaque; drop repeats so each one keys its own line. + const versions = [...new Set(updateCheck.versions ?? [])]; + return ( + <> + {versions.map((version) => ( + + {version} + + ))} + {updateCheck.message ? ( + {updateCheck.message} + ) : null} + + ); + } + // A check that threw, timed out or could not tell is never shown as up to date. + const message = updates.status === "error" ? updates.message : updateCheck?.message; + return ( + <> + + {t("settings.providers.installation.updatesFailed")} + + {message ? {message} : null} + + ); +} + +function isUpdating(action: ProviderUpdateAction): boolean { + return action.starting || action.current?.operation.status === "running"; +} + +/** + * Update runs the provider's updater; without one, the provider's update guide opens. The button + * carries the update's progress from the tap until it settles. + */ +function UpdateButton({ + action, + updateUrl, +}: { + action: ProviderUpdateAction | undefined; + updateUrl: string | undefined; +}) { + const { t } = useTranslation(); + const handleOpenInstructions = useCallback(() => { + if (updateUrl) void openExternalUrl(updateUrl); + }, [updateUrl]); + if (action) + return ( + + ); + if (!updateUrl) return null; + return ( + + ); +} + +type UpdateRun = + | { status: "running"; update: ProviderInstallationUpdate } + | { status: "succeeded" | "failed"; update: ProviderInstallationUpdate } + | { status: "refused"; message: string }; + +/** + * What the update's row shows, or null for nothing. While the update starts or runs, Update shows + * its progress and the row holds only the output so far. A new start clears the previous result. + */ +function readUpdateRun(action: ProviderUpdateAction): UpdateRun | null { + const update = action.current; + if (isUpdating(action)) { + return update?.operation.status === "running" && update.output.length > 0 + ? { status: "running", update } + : null; + } + if (action.startError) return { status: "refused", message: action.startError }; + if (!update || update.operation.status === "running") return null; + return { status: update.operation.status, update }; +} + +function UpdateRunRow({ run, updateUrl }: { run: UpdateRun; updateUrl: string | undefined }) { + const { t } = useTranslation(); + const scroll = useRef(null); + const followOutput = useCallback(() => scroll.current?.scrollToEnd({ animated: false }), []); + const update = run.status === "refused" ? null : run.update; + const output = update?.output.map((entry) => entry.text).join("") ?? ""; + let message: string | undefined; + if (run.status === "refused") message = run.message; + else if (run.update.operation.status !== "running") message = run.update.operation.message; + + return ( + + + {run.status === "running" ? null : ( + + {run.status === "succeeded" + ? t("settings.providers.installation.updated") + : t("settings.providers.installation.updateFailed")} + + )} + {message ? ( + + {message} + + ) : null} + {output ? ( + + {update?.truncated ? ( + + {t("settings.providers.installation.outputTruncated")} + + ) : null} + + {output} + + + ) : null} + {(run.status === "failed" || run.status === "refused") && updateUrl ? ( + + + + ) : null} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + output: { + maxHeight: 240, + borderRadius: theme.borderRadius.md, + backgroundColor: theme.colors.surface0, + }, + outputAfterResult: { + marginTop: theme.spacing[2], + }, + outputContent: { + padding: theme.spacing[3], + }, + outputText: { + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + lineHeight: 20, + color: theme.colors.foreground, + }, + outputNote: { + marginBottom: theme.spacing[1], + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + value: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, + version: { + flexShrink: 1, + marginLeft: theme.spacing[3], + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + }, + availableVersion: { + marginTop: theme.spacing[1], + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + }, + link: { + flexDirection: "row", + marginTop: theme.spacing[1], + }, +})); diff --git a/packages/app/src/components/provider-installation.tsx b/packages/app/src/components/provider-installation.tsx new file mode 100644 index 000000000000..957301a7d24d --- /dev/null +++ b/packages/app/src/components/provider-installation.tsx @@ -0,0 +1,195 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useCallback, useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import type { ProviderInstallationUpdate } from "@getpaseo/protocol/messages"; +import { useFetchQuery } from "@/data/query"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import type { + ProviderInstallationState, + ProviderUpdateAction, + ProviderUpdatesState, +} from "./provider-installation-section"; +import { applyProviderUpdateProgress } from "./provider-update-progress"; + +export interface ProviderInstallationRead { + state: ProviderInstallationState; + updates: ProviderUpdatesState; + /** Absent when the host cannot report provider installations. */ + action: ProviderUpdateAction | undefined; + /** Ask the provider again, skipping the host's caches. */ + refresh: () => void; + /** A refresh is in flight. The last answers stay on screen until the new ones arrive. */ + refreshing: boolean; +} + +/** + * Reads a provider's installation from hosts that advertise `providerInstallation`. The update + * check is a separate request that starts once the provider reports itself installed, so the + * installed version never waits on it. + */ +export function useProviderInstallation(input: { + serverId: string; + provider: string; + visible: boolean; +}): ProviderInstallationRead { + const { serverId, provider, visible } = input; + const supported = useHostFeature(serverId, "providerInstallation"); + const client = useHostRuntimeClient(serverId); + const queryClient = useQueryClient(); + const { t } = useTranslation(); + const enabled = supported && visible && Boolean(client); + const installationKey = ["provider-installation", serverId, provider] as const; + const updatesKey = ["provider-updates", serverId, provider] as const; + + const inspect = useCallback( + async (refresh: boolean) => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.inspectProviderInstallation(provider, { refresh }); + if (result.error) throw new Error(result.error); + return result.installation; + }, + [client, provider, t], + ); + const checkForUpdates = useCallback( + async (refresh: boolean) => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.checkProviderUpdates(provider, { refresh }); + if (result.error) throw new Error(result.error); + return result.updateCheck; + }, + [client, provider, t], + ); + + // The host caches both answers, so reading on every open is cheap. + const installationQuery = useFetchQuery({ + queryKey: installationKey, + queryFn: () => inspect(false), + enabled, + dataShape: "value", + staleTimeMs: 0, + }); + const installed = installationQuery.data?.inspection?.status === "installed"; + const updatesQuery = useFetchQuery({ + queryKey: updatesKey, + queryFn: () => checkForUpdates(false), + enabled: enabled && installed, + dataShape: "value", + staleTimeMs: 0, + }); + + // A refresh runs through the queries so its answer or its failure is what the screen shows. + // `staleTime: 0` overrides the app default so the request always goes out. + const refreshInstallation = useMutation({ + mutationFn: () => + queryClient.fetchQuery({ + queryKey: installationKey, + queryFn: () => inspect(true), + staleTime: 0, + }), + }); + const refreshUpdates = useMutation({ + mutationFn: () => + queryClient.fetchQuery({ + queryKey: updatesKey, + queryFn: () => checkForUpdates(true), + staleTime: 0, + }), + }); + // The host owns the update; this view follows it while open and catches up on reopen. + const [currentUpdate, setCurrentUpdate] = useState(null); + useEffect(() => { + if (!enabled || !client) return; + const subscription = client.observeProviderUpdates(provider); + // The update this view saw running. Its success arrives as live progress, or as the snapshot + // a reconnect delivers when the progress was missed; either way the host dropped its cached + // answers, so read the new version and update state. + let runningId: string | null = null; + const follow = (operation: ProviderInstallationUpdate["operation"] | undefined) => { + if (!operation) return; + if (operation.status === "running") { + runningId = operation.id; + return; + } + if (operation.id !== runningId) return; + runningId = null; + if (operation.status !== "succeeded") return; + void queryClient.invalidateQueries({ + queryKey: ["provider-installation", serverId, provider], + }); + void queryClient.invalidateQueries({ queryKey: ["provider-updates", serverId, provider] }); + }; + const detach = subscription.subscribe({ + snapshot: (response) => { + setCurrentUpdate(response.update); + follow(response.update?.operation); + }, + update: (message) => { + if (message.type === "provider.installation.update.cleared") { + const { operationId } = message.payload; + setCurrentUpdate((current) => (current?.operation.id === operationId ? null : current)); + return; + } + if (message.type !== "provider.installation.update.progress") return; + setCurrentUpdate((current) => applyProviderUpdateProgress(current, message.payload)); + follow(message.payload.operation); + }, + error: (failure) => console.warn("Failed to observe provider updates", failure), + }); + return () => { + detach(); + void subscription + .release() + .catch((failure) => console.warn("Failed to release provider update observation", failure)); + }; + }, [client, enabled, provider, queryClient, serverId]); + const startUpdate = useMutation({ + mutationFn: async () => { + if (!client) throw new Error(t("workspace.terminal.hostDisconnected")); + const result = await client.updateProvider(provider); + if (result.error) throw new Error(result.error); + return result.update; + }, + onSuccess: (update) => { + if (!update) return; + // Progress for this operation may already have arrived; keep the further-along copy. + setCurrentUpdate((current) => + current?.operation.id === update.operation.id ? current : update, + ); + }, + }); + const { mutate: mutateStartUpdate } = startUpdate; + const start = useCallback(() => mutateStartUpdate(), [mutateStartUpdate]); + const action: ProviderUpdateAction | undefined = supported + ? { + current: currentUpdate, + starting: startUpdate.isPending, + startError: startUpdate.error?.message ?? null, + start, + } + : undefined; + + const { mutate: mutateInstallation } = refreshInstallation; + const { mutate: mutateUpdates } = refreshUpdates; + const refresh = useCallback(() => { + if (!supported || !client) return; + mutateInstallation(); + if (installed) mutateUpdates(); + }, [client, installed, mutateInstallation, mutateUpdates, supported]); + + let state: ProviderInstallationState; + if (!supported) state = { status: "unsupported" }; + else if (installationQuery.isPending) state = { status: "loading" }; + else if (installationQuery.isError) + state = { status: "error", message: installationQuery.error.message }; + else state = { status: "ready", installation: installationQuery.data ?? null }; + + let updates: ProviderUpdatesState; + if (!supported || !installed) updates = { status: "hidden" }; + else if (updatesQuery.isPending) updates = { status: "loading" }; + else if (updatesQuery.isError) updates = { status: "error", message: updatesQuery.error.message }; + else updates = { status: "ready", updateCheck: updatesQuery.data ?? null }; + + const refreshing = refreshInstallation.isPending || refreshUpdates.isPending; + return { state, updates, action, refresh, refreshing }; +} diff --git a/packages/app/src/components/provider-update-progress.test.ts b/packages/app/src/components/provider-update-progress.test.ts new file mode 100644 index 000000000000..db6a53aa3b80 --- /dev/null +++ b/packages/app/src/components/provider-update-progress.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderInstallationUpdateProgress } from "@getpaseo/protocol/messages"; +import { applyProviderUpdateProgress } from "./provider-update-progress"; + +const running = { + status: "running", + id: "update-1", + startedAt: "2026-11-13T00:00:00.000Z", +} as const; + +function progress(...texts: string[]): ProviderInstallationUpdateProgress { + return { + provider: "codex", + operation: running, + output: texts.map((text) => ({ type: "stdout", text })), + }; +} + +describe("applyProviderUpdateProgress", () => { + it("appends output for the same update", () => { + const first = applyProviderUpdateProgress(null, progress("a"), { outputLimit: 10 }); + const second = applyProviderUpdateProgress(first, progress("b"), { outputLimit: 10 }); + expect(second.output.map((entry) => entry.text)).toEqual(["a", "b"]); + expect(second.truncated).toBeUndefined(); + }); + + it("drops the oldest output beyond the limit and marks the update truncated", () => { + let update = applyProviderUpdateProgress(null, progress("12345"), { outputLimit: 8 }); + update = applyProviderUpdateProgress(update, progress("6789"), { outputLimit: 8 }); + expect(update.output.map((entry) => entry.text)).toEqual(["6789"]); + expect(update.truncated).toBe(true); + + update = applyProviderUpdateProgress(update, progress("abcdefghij"), { outputLimit: 8 }); + expect(update.output.map((entry) => entry.text)).toEqual(["cdefghij"]); + expect(update.truncated).toBe(true); + }); + + it("starts a new update empty", () => { + const first = applyProviderUpdateProgress(null, progress("123456789"), { outputLimit: 4 }); + const next = applyProviderUpdateProgress( + first, + { ...progress("x"), operation: { ...running, id: "update-2" } }, + { outputLimit: 4 }, + ); + expect(next.output.map((entry) => entry.text)).toEqual(["x"]); + expect(next.truncated).toBeUndefined(); + }); +}); diff --git a/packages/app/src/components/provider-update-progress.ts b/packages/app/src/components/provider-update-progress.ts new file mode 100644 index 000000000000..ad72471d4ccc --- /dev/null +++ b/packages/app/src/components/provider-update-progress.ts @@ -0,0 +1,38 @@ +import type { + ProviderInstallationUpdate, + ProviderInstallationUpdateOutput, + ProviderInstallationUpdateProgress, +} from "@getpaseo/protocol/messages"; + +/** Characters of update output the app keeps, matching what the daemon retains. */ +export const PROVIDER_UPDATE_OUTPUT_LIMIT = 64 * 1024; + +/** + * Folds a progress message into the update it belongs to; a new operation starts empty. Output + * beyond `outputLimit` characters drops oldest first and marks the update truncated, so a noisy + * updater cannot grow the screen's memory while it stays open. + */ +export function applyProviderUpdateProgress( + current: ProviderInstallationUpdate | null, + progress: ProviderInstallationUpdateProgress, + options: { outputLimit: number } = { outputLimit: PROVIDER_UPDATE_OUTPUT_LIMIT }, +): ProviderInstallationUpdate { + const previous = current?.operation.id === progress.operation.id ? current : null; + const limit = options.outputLimit; + const output: ProviderInstallationUpdateOutput[] = [ + ...(previous?.output ?? []), + ...progress.output, + ]; + let length = output.reduce((total, entry) => total + entry.text.length, 0); + let truncated = previous?.truncated ?? false; + while (length > limit && output.length > 1) { + length -= output.shift()!.text.length; + truncated = true; + } + const last = output.at(-1); + if (last && last.text.length > limit) { + output[output.length - 1] = { type: last.type, text: last.text.slice(-limit) }; + truncated = true; + } + return { operation: progress.operation, output, ...(truncated ? { truncated: true } : {}) }; +} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 483b09ce4f20..8050a802edd9 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -3142,6 +3142,26 @@ export const ar: TranslationResources = { custom: "نماذج مخصصة", updated: "تم تحديث{{time}}", }, + installation: { + title: "التثبيت", + version: "الإصدار", + installed: "مثبّت", + notInstalled: "غير مثبّت", + install: "تثبيت", + checking: "جارٍ التحقق...", + failed: "تعذّر التحقق من التثبيت", + updates: "التحديثات", + upToDate: "محدّث", + updateAvailable: "يتوفر تحديث", + updateInstructions: "تعليمات التحديث", + update: "تحديث", + updating: "جارٍ التحديث...", + updated: "تم التحديث", + updateFailed: "فشل التحديث", + outputTruncated: "تم حذف المخرجات السابقة.", + updatesFailed: "تعذّر التحقق من التحديثات", + installInstructions: "تعليمات التثبيت", + }, diagnostic: { title: "التشخيص", button: "التشخيص", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 7fcd230092b9..5f916373d49b 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -3241,6 +3241,26 @@ export const en = { custom: "Custom models", updated: "Updated {{time}}", }, + installation: { + title: "Installation", + version: "Version", + installed: "Installed", + notInstalled: "Not installed", + install: "Install", + checking: "Checking...", + failed: "Couldn't check this installation", + updates: "Updates", + upToDate: "Up to date", + updateAvailable: "Update available", + updateInstructions: "Update instructions", + update: "Update", + updating: "Updating...", + updated: "Updated", + updateFailed: "Update failed", + outputTruncated: "Earlier output was dropped.", + updatesFailed: "Couldn't check for updates", + installInstructions: "Install instructions", + }, diagnostic: { title: "Diagnostic", button: "Diagnostic", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index b7bf6c6ebab7..23fea2743a3f 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -3171,6 +3171,26 @@ export const es: TranslationResources = { custom: "Modelos personalizados", updated: "{{time}}actualizado", }, + installation: { + title: "Instalación", + version: "Versión", + installed: "Instalado", + notInstalled: "No instalado", + install: "Instalar", + checking: "Comprobando...", + failed: "No se pudo comprobar la instalación", + updates: "Actualizaciones", + upToDate: "Actualizado", + updateAvailable: "Actualización disponible", + updateInstructions: "Instrucciones de actualización", + update: "Actualizar", + updating: "Actualizando...", + updated: "Actualizado", + updateFailed: "No se pudo actualizar", + outputTruncated: "Se descartó la salida anterior.", + updatesFailed: "No se pudo comprobar si hay actualizaciones", + installInstructions: "Instrucciones de instalación", + }, diagnostic: { title: "Diagnóstico", button: "Diagnóstico", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index b223321b84fb..2d451eed8824 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -3179,6 +3179,26 @@ export const fr: TranslationResources = { custom: "Modèles personnalisés", updated: "Mis à jour {{time}}", }, + installation: { + title: "Installation", + version: "Version", + installed: "Installé", + notInstalled: "Non installé", + install: "Installer", + checking: "Vérification...", + failed: "Impossible de vérifier l'installation", + updates: "Mises à jour", + upToDate: "À jour", + updateAvailable: "Mise à jour disponible", + updateInstructions: "Instructions de mise à jour", + update: "Mettre à jour", + updating: "Mise à jour...", + updated: "Mis à jour", + updateFailed: "Échec de la mise à jour", + outputTruncated: "La sortie précédente a été supprimée.", + updatesFailed: "Impossible de vérifier les mises à jour", + installInstructions: "Instructions d'installation", + }, diagnostic: { title: "Diagnostic", button: "Diagnostic", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 1aa50bbfa37c..2ba764a894fa 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -3139,6 +3139,26 @@ export const ja: TranslationResources = { custom: "カスタムモデル", updated: "{{time}}に更新", }, + installation: { + title: "インストール", + version: "バージョン", + installed: "インストール済み", + notInstalled: "未インストール", + install: "インストール", + checking: "確認中...", + failed: "インストールを確認できませんでした", + updates: "アップデート", + upToDate: "最新です", + updateAvailable: "アップデートがあります", + updateInstructions: "アップデート手順", + update: "アップデート", + updating: "アップデート中...", + updated: "アップデート済み", + updateFailed: "アップデートに失敗しました", + outputTruncated: "以前の出力は破棄されました。", + updatesFailed: "アップデートを確認できませんでした", + installInstructions: "インストール手順", + }, diagnostic: { title: "診断", button: "診断", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 27ae440dbef4..e4988e9a19f8 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -3125,6 +3125,26 @@ export const ko: TranslationResources = { custom: "사용자 지정 모델", updated: "{{time}} 업데이트됨", }, + installation: { + title: "설치", + version: "버전", + installed: "설치됨", + notInstalled: "설치되지 않음", + install: "설치", + checking: "확인 중...", + failed: "설치를 확인할 수 없습니다", + updates: "업데이트", + upToDate: "최신 상태", + updateAvailable: "업데이트 가능", + updateInstructions: "업데이트 안내", + update: "업데이트", + updating: "업데이트 중...", + updated: "업데이트됨", + updateFailed: "업데이트 실패", + outputTruncated: "이전 출력이 삭제되었습니다.", + updatesFailed: "업데이트를 확인할 수 없습니다", + installInstructions: "설치 안내", + }, diagnostic: { title: "진단", button: "진단", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index c07d1479b00a..d92dffa1b67a 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -3152,6 +3152,26 @@ export const ptBR: TranslationResources = { custom: "Modelos personalizados", updated: "Atualizado {{time}}", }, + installation: { + title: "Instalação", + version: "Versão", + installed: "Instalado", + notInstalled: "Não instalado", + install: "Instalar", + checking: "Verificando...", + failed: "Não foi possível verificar a instalação", + updates: "Atualizações", + upToDate: "Atualizado", + updateAvailable: "Atualização disponível", + updateInstructions: "Instruções de atualização", + update: "Atualizar", + updating: "Atualizando...", + updated: "Atualizado", + updateFailed: "Falha na atualização", + outputTruncated: "A saída anterior foi descartada.", + updatesFailed: "Não foi possível verificar atualizações", + installInstructions: "Instruções de instalação", + }, diagnostic: { title: "Diagnóstico", button: "Diagnóstico", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 263e4e4f2968..cda5ba01215c 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -3164,6 +3164,26 @@ export const ru: TranslationResources = { custom: "Пользовательские модели", updated: "Обновлено {{time}}", }, + installation: { + title: "Установка", + version: "Версия", + installed: "Установлено", + notInstalled: "Не установлено", + install: "Установить", + checking: "Проверка...", + failed: "Не удалось проверить установку", + updates: "Обновления", + upToDate: "Актуальная версия", + updateAvailable: "Доступно обновление", + updateInstructions: "Инструкции по обновлению", + update: "Обновить", + updating: "Обновление...", + updated: "Обновлено", + updateFailed: "Не удалось обновить", + outputTruncated: "Более ранний вывод был отброшен.", + updatesFailed: "Не удалось проверить обновления", + installInstructions: "Инструкции по установке", + }, diagnostic: { title: "Диагностика", button: "Диагностика", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 2440c00f0cc7..e8e59a127e64 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -3071,6 +3071,26 @@ export const zhCN: TranslationResources = { custom: "自定义 Models", updated: "已更新 {{time}}", }, + installation: { + title: "安装", + version: "版本", + installed: "已安装", + notInstalled: "未安装", + install: "安装", + checking: "正在检查...", + failed: "无法检查安装状态", + updates: "更新", + upToDate: "已是最新", + updateAvailable: "有可用更新", + updateInstructions: "更新说明", + update: "更新", + updating: "正在更新...", + updated: "已更新", + updateFailed: "更新失败", + outputTruncated: "较早的输出已被丢弃。", + updatesFailed: "无法检查更新", + installInstructions: "安装说明", + }, diagnostic: { title: "诊断", button: "诊断", diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 04af82f6044c..8bc2baa8efd1 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -119,6 +119,8 @@ import type { RefreshProvidersSnapshotResponseMessage, ProviderDiagnosticResponseMessage, ProviderUsageListResponseMessage, + ProviderInstallationInspectResponseMessage, + ProviderInstallationCheckUpdatesResponseMessage, UsageReportEntry, DaemonGetStatusResponse, DaemonGetPairingOfferResponse, @@ -631,6 +633,13 @@ type GetProvidersSnapshotPayload = GetProvidersSnapshotResponseMessage["payload" type RefreshProvidersSnapshotPayload = RefreshProvidersSnapshotResponseMessage["payload"]; type ProviderDiagnosticPayload = ProviderDiagnosticResponseMessage["payload"]; type ProviderUsageListPayload = ProviderUsageListResponseMessage["payload"]; +type ProviderInstallationInspectPayload = ProviderInstallationInspectResponseMessage["payload"]; +type ProviderInstallationCheckUpdatesPayload = + ProviderInstallationCheckUpdatesResponseMessage["payload"]; +type ProviderInstallationUpdatePayload = Extract< + SessionOutboundMessage, + { type: "provider.installation.update.response" } +>["payload"]; interface UsageListReportsPayload { requestId: string; reports: UsageReportEntry[]; @@ -6244,6 +6253,70 @@ export class DaemonClient { }); } + /** Install and update links plus installed state. Requires `features.providerInstallation`. */ + async inspectProviderInstallation( + provider: AgentProvider, + options?: { refresh?: boolean; requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.inspect.response">({ + requestId: options?.requestId, + message: { + type: "provider.installation.inspect.request", + provider, + ...(options?.refresh ? { refresh: true } : {}), + }, + timeout: 60_000, + }); + } + + /** Whether the provider reports a newer version. Requires `features.providerInstallation`. */ + async checkProviderUpdates( + provider: AgentProvider, + options?: { refresh?: boolean; requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.check_updates.response">( + { + requestId: options?.requestId, + message: { + type: "provider.installation.check_updates.request", + provider, + ...(options?.refresh ? { refresh: true } : {}), + }, + timeout: 60_000, + }, + ); + } + + /** Starts the provider's update, or joins the running one. Follow it with `observeProviderUpdates`. */ + async updateProvider( + provider: AgentProvider, + options?: { requestId?: string }, + ): Promise { + return this.sendNamespacedCorrelatedSessionRequest<"provider.installation.update.response">({ + requestId: options?.requestId, + message: { type: "provider.installation.update.request", provider }, + timeout: 60_000, + }); + } + + /** + * The provider's latest update, then `provider.installation.update.progress` as updates start, + * report output and settle, and `provider.installation.update.cleared` when a refresh drops a + * failed update. Survives reconnects: each new snapshot replaces the previous one. + */ + observeProviderUpdates( + provider: AgentProvider, + options?: { signal?: AbortSignal }, + ): OwnedSubscription< + CorrelatedResponsePayload<"provider.installation.update.subscribe.response"> + > { + return this.observe( + "provider.installation.update.subscribe.response", + { type: "provider.installation.update.subscribe.request", provider }, + options, + ); + } + async listProviderUsage(options?: { requestId?: string }): Promise { return this.sendNamespacedCorrelatedSessionRequest({ requestId: options?.requestId, diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index b928f5d168d9..622a20d68de5 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -39,9 +39,96 @@ export interface ProviderRegistration { description?: string; /** Plugin-directory-relative path to a self-contained SVG file. */ icon?: string; + /** How users install the provider's CLI and which version they run. Every member is optional. */ + installation?: ProviderInstallation; connect(request: ProviderConnectRequest): Promise; } +export interface ProviderInstallation { + /** http(s) page that explains how to install the provider. Paseo opens it; it never installs. */ + installUrl?: string; + /** http(s) page that explains how to update the provider. */ + updateUrl?: string; + /** Report whether the provider is installed and which version. Runs only when a user asks. */ + inspect?(context: ProviderInstallationContext): Promise; + /** + * Report whether a newer version than `installedVersion` is available. The provider decides how + * to find out and what counts as newer; Paseo shows the result as written. Return `unknown` when + * it cannot tell. Runs only when a user asks, never before a session, and only after `inspect` + * reports the provider installed. Paseo reuses the answer while `inspect` reports the same + * version. + */ + checkForUpdates?(context: ProviderUpdateCheckContext): Promise; + /** + * Update the provider, usually by running its CLI's own updater. Paseo shows everything passed + * to `report` while it runs, then the returned message. A throw is a failure with its message. + * Runs only when a user asks. Paseo sets no deadline; `signal` aborts when the daemon stops. + */ + update?(context: ProviderUpdateContext): Promise; +} + +export interface ProviderUpdateCheckContext extends ProviderInstallationContext { + /** + * The version `inspect` reported, as written. Absent when `inspect` reported none or the + * provider declares no `inspect`. + */ + installedVersion?: string; +} + +export interface ProviderUpdateContext extends ProviderInstallationContext { + /** Shows output to the user as it happens, unchanged and in order. */ + report(event: ProviderUpdateReport): void; +} + +export const ProviderUpdateReportSchema = z + .object({ type: z.enum(["stdout", "stderr", "message"]), text: z.string() }) + .strip(); + +export type ProviderUpdateReport = z.infer; + +export const ProviderUpdateResultSchema = z.discriminatedUnion("status", [ + /** `message` is shown as written, such as which version is now installed. */ + z.object({ status: z.literal("succeeded"), message: z.string().optional() }).strip(), + z.object({ status: z.literal("failed"), message: z.string() }).strip(), +]); + +export type ProviderUpdateResult = z.infer; + +export interface ProviderInstallationContext { + /** The launch a session would use. Absent when the provider declares no `command`. */ + launch?: ProviderInstallationLaunch; + /** Aborted when Paseo stops waiting for the result. */ + signal: AbortSignal; +} + +export interface ProviderInstallationLaunch extends ProviderLaunch { + /** False when the executable was not found; `command` is then the configured command as written. */ + resolved: boolean; +} + +export const ProviderInspectionSchema = z.discriminatedUnion("status", [ + /** `version` is shown as written and passed to `checkForUpdates`; Paseo does not parse it. */ + z.object({ status: z.literal("installed"), version: z.string().optional() }).strip(), + z.object({ status: z.literal("not_installed") }).strip(), +]); + +export type ProviderInspection = z.infer; + +export const ProviderUpdateCheckSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("current") }).strip(), + /** `versions` and `message` are shown as written; Paseo does not parse, sort or compare them. */ + z + .object({ + status: z.literal("available"), + versions: z.array(z.string()).optional(), + message: z.string().optional(), + }) + .strip(), + z.object({ status: z.literal("unknown"), message: z.string().optional() }).strip(), +]); + +export type ProviderUpdateCheck = z.infer; + export type ProviderCatalogOptions = | { scope: "global"; force?: boolean; launch?: ProviderLaunch } | { scope: "workspace"; cwd: string; force?: boolean; launch?: ProviderLaunch }; diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 8f935bdaf164..f7dca4bf7a93 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1982,6 +1982,34 @@ export const ProviderDiagnosticRequestMessageSchema = z.object({ requestId: z.string(), }); +export const ProviderInstallationInspectRequestMessageSchema = z.object({ + type: z.literal("provider.installation.inspect.request"), + provider: AgentProviderSchema, + /** Skip the daemon's short result cache and ask the provider again. */ + refresh: z.boolean().optional(), + requestId: z.string(), +}); + +export const ProviderInstallationCheckUpdatesRequestMessageSchema = z.object({ + type: z.literal("provider.installation.check_updates.request"), + provider: AgentProviderSchema, + /** Skip the daemon's update-check cache and ask the provider again. */ + refresh: z.boolean().optional(), + requestId: z.string(), +}); + +export const ProviderInstallationUpdateRequestMessageSchema = z.object({ + type: z.literal("provider.installation.update.request"), + provider: AgentProviderSchema, + requestId: z.string(), +}); + +export const ProviderInstallationUpdateSubscribeRequestMessageSchema = z.object({ + type: z.literal("provider.installation.update.subscribe.request"), + provider: AgentProviderSchema, + requestId: z.string(), +}); + export const ProviderUsageListRequestMessageSchema = z.object({ type: z.literal("provider.usage.list.request"), requestId: z.string(), @@ -3626,6 +3654,10 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ GetProvidersSnapshotRequestMessageSchema, RefreshProvidersSnapshotRequestMessageSchema, ProviderDiagnosticRequestMessageSchema, + ProviderInstallationInspectRequestMessageSchema, + ProviderInstallationCheckUpdatesRequestMessageSchema, + ProviderInstallationUpdateRequestMessageSchema, + ProviderInstallationUpdateSubscribeRequestMessageSchema, ProviderUsageListRequestMessageSchema, UsageListReportsRequestMessageSchema, ResumeAgentRequestMessageSchema, @@ -3953,6 +3985,8 @@ export const ServerInfoStatusPayloadSchema = z // COMPAT(usageSetting): added in v0.14, remove after 2027-05-01. usageSetting: z.boolean().optional(), usageSources: z.boolean().optional(), + // COMPAT(providerInstallation): added in v0.17.0, remove gate after 2027-05-13. + providerInstallation: z.boolean().optional(), // COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10. providersSnapshotCwd: z.boolean().optional(), // COMPAT(directorySync): added in v0.3.x, remove gate after 2027-02-12. @@ -6804,6 +6838,142 @@ export const ProviderDiagnosticResponseMessageSchema = z.object({ }), }); +/** Provider-owned facts; `version` is an opaque string the app shows as written. */ +export const ProviderInstallationInspectionSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("installed"), version: z.string().optional() }), + z.object({ status: z.literal("not_installed") }), + z.object({ status: z.literal("error"), message: z.string() }), +]); + +export const ProviderInstallationSchema = z.object({ + installUrl: z.string().optional(), + updateUrl: z.string().optional(), + /** Absent when the provider does not report its installation. */ + inspection: ProviderInstallationInspectionSchema.optional(), + /** True when the provider can run its own update through `provider.installation.update`. */ + canUpdate: z.boolean().optional(), +}); + +export const ProviderInstallationInspectResponseMessageSchema = z.object({ + type: z.literal("provider.installation.inspect.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** Null when the provider declares no installation contract. */ + installation: ProviderInstallationSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** + * The provider's answer to "is a newer version available". `versions` and `message` are opaque + * strings the app shows as written. `error` means the check threw or missed its deadline. + */ +export const ProviderInstallationUpdateCheckSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("current") }), + z.object({ + status: z.literal("available"), + versions: z.array(z.string()).optional(), + message: z.string().optional(), + }), + z.object({ status: z.literal("unknown"), message: z.string().optional() }), + z.object({ status: z.literal("error"), message: z.string() }), +]); + +export const ProviderInstallationCheckUpdatesResponseMessageSchema = z.object({ + type: z.literal("provider.installation.check_updates.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** Null when the provider cannot check for updates. */ + updateCheck: ProviderInstallationUpdateCheckSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** One piece of updater output, shown unchanged and in order. */ +export const ProviderInstallationUpdateOutputSchema = z.object({ + type: z.enum(["stdout", "stderr", "message"]), + text: z.string(), +}); + +/** The state of one provider update. Messages are the provider's, shown as written. */ +export const ProviderInstallationUpdateOperationSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("running"), id: z.string(), startedAt: z.string() }), + z.object({ + status: z.literal("succeeded"), + id: z.string(), + startedAt: z.string(), + finishedAt: z.string(), + message: z.string().optional(), + }), + z.object({ + status: z.literal("failed"), + id: z.string(), + startedAt: z.string(), + finishedAt: z.string(), + message: z.string(), + }), +]); + +/** The latest update of a provider since the daemon started, with its retained output. */ +export const ProviderInstallationUpdateSchema = z.object({ + operation: ProviderInstallationUpdateOperationSchema, + output: z.array(ProviderInstallationUpdateOutputSchema), + /** True when the oldest output was dropped to stay within the daemon's output limit. */ + truncated: z.boolean().optional(), +}); + +export const ProviderInstallationUpdateResponseMessageSchema = z.object({ + type: z.literal("provider.installation.update.response"), + payload: z.object({ + provider: AgentProviderSchema, + /** The update this request started, or the one already running. */ + update: ProviderInstallationUpdateSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +export const ProviderInstallationUpdateSubscribeResponseMessageSchema = z.object({ + type: z.literal("provider.installation.update.subscribe.response"), + payload: z.object({ + provider: AgentProviderSchema, + subscriptionId: z.string().optional(), + /** Null when the provider has not been updated since the daemon started. */ + update: ProviderInstallationUpdateSchema.nullable(), + error: z.string().nullable(), + requestId: z.string(), + }), +}); + +/** + * Sent to `provider.installation.update.subscribe` owners when an update starts, reports output + * or finishes. `output` holds only the entries new since the previous progress for `operation.id`. + */ +export const ProviderInstallationUpdateProgressMessageSchema = z.object({ + type: z.literal("provider.installation.update.progress"), + payload: z.object({ + subscriptionId: z.string().optional(), + provider: AgentProviderSchema, + operation: ProviderInstallationUpdateOperationSchema, + output: z.array(ProviderInstallationUpdateOutputSchema), + }), +}); + +/** + * Sent to `provider.installation.update.subscribe` owners when a refresh of the provider drops + * the failed update `operationId`, so the provider has no current update. + */ +export const ProviderInstallationUpdateClearedMessageSchema = z.object({ + type: z.literal("provider.installation.update.cleared"), + payload: z.object({ + subscriptionId: z.string().optional(), + provider: AgentProviderSchema, + operationId: z.string(), + }), +}); + export const ProviderUsageToneSchema = z.enum(["default", "ok", "warning", "danger"]); export const ProviderUsageStatusSchema = z.enum(["available", "unavailable", "error"]); @@ -7671,6 +7841,12 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ ProvidersSnapshotUpdateMessageSchema, RefreshProvidersSnapshotResponseMessageSchema, ProviderDiagnosticResponseMessageSchema, + ProviderInstallationInspectResponseMessageSchema, + ProviderInstallationCheckUpdatesResponseMessageSchema, + ProviderInstallationUpdateResponseMessageSchema, + ProviderInstallationUpdateSubscribeResponseMessageSchema, + ProviderInstallationUpdateProgressMessageSchema, + ProviderInstallationUpdateClearedMessageSchema, ProviderUsageListResponseMessageSchema, UsageListReportsUpdateMessageSchema, UsageListReportsResponseMessageSchema, @@ -7855,6 +8031,30 @@ export type RefreshProvidersSnapshotResponseMessage = z.infer< export type ProviderDiagnosticResponseMessage = z.infer< typeof ProviderDiagnosticResponseMessageSchema >; +export type ProviderInstallation = z.infer; +export type ProviderInstallationInspection = z.infer; +export type ProviderInstallationInspectResponseMessage = z.infer< + typeof ProviderInstallationInspectResponseMessageSchema +>; +export type ProviderInstallationUpdateCheck = z.infer; +export type ProviderInstallationCheckUpdatesResponseMessage = z.infer< + typeof ProviderInstallationCheckUpdatesResponseMessageSchema +>; +export type ProviderInstallationUpdateOutput = z.infer< + typeof ProviderInstallationUpdateOutputSchema +>; +export type ProviderInstallationUpdateOperation = z.infer< + typeof ProviderInstallationUpdateOperationSchema +>; +export type ProviderInstallationUpdate = z.infer; +export type ProviderInstallationUpdateProgress = Omit< + z.infer["payload"], + "subscriptionId" +>; +export type ProviderInstallationUpdateCleared = Omit< + z.infer["payload"], + "subscriptionId" +>; export type ProviderUsageTone = z.infer; export type UsageProblem = z.infer; export type UsageReport = z.infer; diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index ad7f97b834e0..aa2a21dda556 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -10,6 +10,12 @@ import type { } from "@getpaseo/protocol/agent-types"; import type { AgentMessage } from "@getpaseo/protocol/agent-message"; import type { AgentAttachment } from "@getpaseo/protocol/messages"; +import type { + ProviderInspection, + ProviderUpdateCheck, + ProviderUpdateReport, + ProviderUpdateResult, +} from "@getpaseo/plugin/server/provider"; import type { PaseoToolCatalog } from "./tools/types.js"; export type { @@ -818,6 +824,30 @@ export interface AgentDraftControls { options: ProviderOptions; } +export interface AgentClientInstallationContext { + /** Aborted when Paseo stops waiting for the result. */ + signal: AbortSignal; +} + +export interface AgentClientInstallation { + installUrl?: string; + updateUrl?: string; + inspect?(context: AgentClientInstallationContext): Promise; + /** See `ProviderInstallation.checkForUpdates` in the plugin contract. */ + checkForUpdates?(context: AgentClientUpdateCheckContext): Promise; + /** Runs the provider's updater. See `ProviderInstallation.update` in the plugin contract. */ + update?(context: AgentClientUpdateContext): Promise; +} + +export interface AgentClientUpdateCheckContext extends AgentClientInstallationContext { + /** The version `inspect` reported, as written. Absent when it reported none or there is no `inspect`. */ + installedVersion?: string; +} + +export interface AgentClientUpdateContext extends AgentClientInstallationContext { + report(event: ProviderUpdateReport): void; +} + export interface AgentClient { readonly provider: AgentProvider; readonly capabilities: AgentCapabilityFlags; @@ -881,6 +911,12 @@ export interface AgentClient { */ isAvailable(signal?: AbortSignal, options?: FetchCatalogOptions): Promise; getDiagnostic?(): Promise<{ diagnostic: string }>; + /** + * Installation links and the installed version. The same contract as plugin providers' + * `ProviderRegistration.installation`; built-ins resolve their own launch inside `inspect`. + * Never consulted by availability, discovery, or session creation. + */ + readonly installation?: AgentClientInstallation; /** * Archive a durable native session (best-effort). Runtime release belongs to AgentSession.close(). * Called when Paseo archives an agent so the provider's own UI reflects the same state. diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 6a61b1b067b9..4090467f61d5 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -12,6 +12,10 @@ import { ProviderInputSchema, ProviderStatusSchema, type ProviderStatus, + type ProviderInspection, + type ProviderUpdateCheck, + type ProviderUpdateResult, + type ProviderInstallationLaunch, type ProviderLaunch, requireProviderCapabilities, type ProviderCapability, @@ -31,6 +35,9 @@ import { import type { AgentCapabilityFlags, AgentClient, + AgentClientInstallation, + AgentClientUpdateCheckContext, + AgentClientUpdateContext, AgentCreateSessionOptions, AgentLaunchContext, AgentMode, @@ -156,7 +163,8 @@ class ProviderRuntime { private readonly runtimeSettings?: ProviderRuntimeSettings, ) {} - private async resolveLaunch(): Promise { + /** The effective launch, including when its executable does not resolve. */ + private async resolveEffectiveLaunch(): Promise { const command = this.registration.command; if (!command) return undefined; const launch = await resolveProviderLaunch({ @@ -167,8 +175,45 @@ class ProviderRuntime { const env = createProviderEnv({ runtimeSettings: this.runtimeSettings }); launch.env = env; const availability = await checkProviderLaunchAvailable(launch); - if (!availability.resolvedPath) throw new Error(`${launch.command} not found on PATH`); - return { command: resolvePath(availability.resolvedPath), args: launch.args, env }; + if (!availability.resolvedPath) + return { command: launch.command, args: launch.args, env, resolved: false }; + return { + command: resolvePath(availability.resolvedPath), + args: launch.args, + env, + resolved: true, + }; + } + + private async resolveLaunch(): Promise { + const launch = await this.resolveEffectiveLaunch(); + if (!launch) return undefined; + if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`); + return { command: launch.command, args: launch.args, env: launch.env }; + } + + async inspectInstallation(signal: AbortSignal): Promise { + const inspect = this.registration.installation?.inspect; + if (!inspect) throw new Error("Provider does not report its installation"); + const launch = await this.resolveEffectiveLaunch(); + signal.throwIfAborted(); + return await inspect.call(this.registration.installation, { launch, signal }); + } + + async checkForUpdates(context: AgentClientUpdateCheckContext): Promise { + const checkForUpdates = this.registration.installation?.checkForUpdates; + if (!checkForUpdates) throw new Error("Provider does not check for updates"); + const launch = await this.resolveEffectiveLaunch(); + context.signal.throwIfAborted(); + return await checkForUpdates.call(this.registration.installation, { ...context, launch }); + } + + async update(context: AgentClientUpdateContext): Promise { + const update = this.registration.installation?.update; + if (!update) throw new Error("Provider does not update itself"); + const launch = await this.resolveEffectiveLaunch(); + context.signal.throwIfAborted(); + return await update.call(this.registration.installation, { ...context, launch }); } async status(): Promise { @@ -964,12 +1009,26 @@ class PluginAgentClient implements AgentClient { private readonly pendingChildren: PendingChild[] = []; readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"]; + readonly installation?: AgentClientInstallation; constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) { this.provider = registration.id; this.runtime = new ProviderRuntime(registration, runtimeSettings); if (registration.getCatalogCacheKey) this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options); + const installation = registration.installation; + if (installation) + this.installation = { + installUrl: installation.installUrl, + updateUrl: installation.updateUrl, + inspect: installation.inspect + ? ({ signal }) => this.runtime.inspectInstallation(signal) + : undefined, + checkForUpdates: installation.checkForUpdates + ? (context) => this.runtime.checkForUpdates(context) + : undefined, + update: installation.update ? (context) => this.runtime.update(context) : undefined, + }; this.runtime.onSessionOpened((session, opened) => this.acceptChild(session, opened)); } diff --git a/packages/server/src/server/agent/provider-installation/provider-installations.test.ts b/packages/server/src/server/agent/provider-installation/provider-installations.test.ts new file mode 100644 index 000000000000..9bf04add83c1 --- /dev/null +++ b/packages/server/src/server/agent/provider-installation/provider-installations.test.ts @@ -0,0 +1,934 @@ +import type { + ProviderEvent, + ProviderInstallation, + ProviderInstallationContext, + ProviderRegistration, + ProviderUpdateResult, +} from "@getpaseo/plugin/server/provider"; +import type { + ProviderInstallationUpdate, + ProviderInstallationUpdateProgress, +} from "@getpaseo/protocol/messages"; +import { describe, expect, test } from "vitest"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import type { AgentClient, AgentClientInstallation } from "../agent-sdk-types.js"; +import { ProviderSnapshotManager } from "../provider-snapshot-manager.js"; +import { ProviderInstallations, type ProviderUpdateEvent } from "./provider-installations.js"; + +const OPAQUE_VERSION = " v1.2.3-beta+weird (build 7)\n"; +const MISSING_COMMAND = "paseo-provider-installation-missing-binary"; +const OPAQUE_VERSIONS = ["v9-nightly+abc", " 2.0 (LTS)\n"]; +const OPAQUE_MESSAGE = " Restart to finish updating\n"; + +function pluginProvider( + installation: ProviderInstallation | undefined, + command: readonly [string, ...string[]] = [process.execPath], +): ProviderRegistration { + return { + id: "installation-plugin", + label: "Installation plugin", + command, + installation, + async connect() { + let listener: ((event: ProviderEvent) => void) | undefined; + return { + version: 1, + capabilities: [], + async send(input) { + if (input.type === "catalog") + listener?.({ + type: "catalog", + requestId: input.requestId, + catalog: { models: [{ id: "model", label: "Model" }], modes: [] }, + }); + }, + onEvent(next) { + listener = next; + return () => { + listener = undefined; + }; + }, + async close() {}, + }; + }, + }; +} + +function builtinClient(installation: AgentClientInstallation | undefined): AgentClient { + return { + provider: "codex", + capabilities: { + supportsStreaming: false, + supportsSessionPersistence: false, + supportsDynamicModes: false, + supportsMcpServers: false, + supportsReasoningStream: false, + supportsToolInvocations: false, + }, + installation, + async createSession() { + throw new Error("not opened by this test"); + }, + async resumeSession() { + throw new Error("not opened by this test"); + }, + async fetchCatalog() { + return { models: [], modes: [] }; + }, + async isAvailable() { + return true; + }, + }; +} + +function managerWith(input: { plugin?: ProviderRegistration; codex?: AgentClient }) { + const manager = new ProviderSnapshotManager({ + logger: createTestLogger(), + extraClients: input.codex ? { codex: input.codex } : {}, + }); + if (input.plugin) manager.replacePluginProviders([input.plugin]); + return manager; +} + +describe("provider installation", () => { + test("exposes links and lets the plugin report not installed when its executable is missing", async () => { + const contexts: ProviderInstallationContext[] = []; + const manager = managerWith({ + plugin: pluginProvider( + { + installUrl: "https://example.com/install", + updateUrl: "https://example.com/update", + async inspect(context) { + contexts.push(context); + return context.launch?.resolved ? { status: "installed" } : { status: "not_installed" }; + }, + }, + [MISSING_COMMAND, "serve"], + ), + }); + try { + await expect(manager.installations.inspect("installation-plugin")).resolves.toEqual({ + installUrl: "https://example.com/install", + updateUrl: "https://example.com/update", + inspection: { status: "not_installed" }, + }); + expect(contexts[0]?.launch).toEqual({ + command: MISSING_COMMAND, + args: ["serve"], + env: expect.objectContaining({ PATH: expect.any(String) }), + resolved: false, + }); + } finally { + manager.destroy(); + } + }); + + test.each([ + { + name: "plugin", + manager: () => + managerWith({ + plugin: pluginProvider({ + installUrl: "https://example.com/install", + async inspect({ launch }) { + if (!launch?.resolved || launch.command !== process.execPath) + throw new Error("Unexpected launch"); + return { status: "installed", version: OPAQUE_VERSION }; + }, + }), + }), + provider: "installation-plugin", + }, + { + name: "built-in", + manager: () => + managerWith({ + codex: builtinClient({ + installUrl: "https://example.com/install", + async inspect() { + return { status: "installed", version: OPAQUE_VERSION }; + }, + }), + }), + provider: "codex", + }, + ])("returns a $name provider's version string unchanged", async ({ manager, provider }) => { + const providers = manager(); + try { + await expect(providers.installations.inspect(provider)).resolves.toEqual({ + installUrl: "https://example.com/install", + inspection: { status: "installed", version: OPAQUE_VERSION }, + }); + } finally { + providers.destroy(); + } + }); + + test("keeps links and reports the failure when inspect throws", async () => { + const manager = managerWith({ + plugin: pluginProvider({ + installUrl: "https://example.com/install", + async inspect() { + throw new Error("version probe exploded"); + }, + }), + }); + try { + await expect(manager.installations.inspect("installation-plugin")).resolves.toEqual({ + installUrl: "https://example.com/install", + inspection: { status: "error", message: "version probe exploded" }, + }); + } finally { + manager.destroy(); + } + }); + + test("returns null for a provider without an installation contract", async () => { + const manager = managerWith({ plugin: pluginProvider(undefined) }); + try { + await expect(manager.installations.inspect("installation-plugin")).resolves.toBeNull(); + await expect(manager.installations.inspect("not-a-provider")).rejects.toThrow( + "Provider not-a-provider is not configured", + ); + } finally { + manager.destroy(); + } + }); + + test("availability and discovery never wait on inspect", async () => { + let inspectCalls = 0; + const manager = managerWith({ + plugin: pluginProvider({ + inspect() { + inspectCalls += 1; + return new Promise(() => {}); + }, + }), + }); + try { + void manager.installations.inspect("installation-plugin"); + const entry = await manager.getProvider({ provider: "installation-plugin", wait: true }); + expect(entry.status).toBe("ready"); + expect(inspectCalls).toBe(1); + } finally { + manager.destroy(); + } + }); + + test.each([ + { + name: "plugin", + manager: () => + managerWith({ + plugin: pluginProvider({ + async checkForUpdates({ launch }) { + if (!launch?.resolved) throw new Error("Unexpected launch"); + return { status: "available", versions: OPAQUE_VERSIONS, message: OPAQUE_MESSAGE }; + }, + }), + }), + provider: "installation-plugin", + }, + { + name: "built-in", + manager: () => + managerWith({ + codex: builtinClient({ + async checkForUpdates() { + return { status: "available", versions: OPAQUE_VERSIONS, message: OPAQUE_MESSAGE }; + }, + }), + }), + provider: "codex", + }, + ])("returns a $name provider's available versions unchanged", async ({ manager, provider }) => { + const providers = manager(); + try { + await expect(providers.installations.checkForUpdates(provider)).resolves.toEqual({ + status: "available", + versions: OPAQUE_VERSIONS, + message: OPAQUE_MESSAGE, + }); + } finally { + providers.destroy(); + } + }); + + test.each([ + { + name: "returns unknown", + checkForUpdates: async () => ({ status: "unknown" as const, message: "Offline" }), + expected: { status: "unknown", message: "Offline" }, + }, + { + name: "throws", + checkForUpdates: async (): Promise => { + throw new Error("release feed exploded"); + }, + expected: { status: "error", message: "release feed exploded" }, + }, + { + name: "breaks the contract", + checkForUpdates: async () => ({ status: "up_to_date" }) as never, + expected: { status: "error", message: expect.stringContaining("status") }, + }, + ])("reports an inconclusive check when the provider $name", async (input) => { + const manager = managerWith({ + plugin: pluginProvider({ checkForUpdates: input.checkForUpdates }), + }); + try { + await expect(manager.installations.checkForUpdates("installation-plugin")).resolves.toEqual( + input.expected, + ); + } finally { + manager.destroy(); + } + }); + + test("returns null when the provider cannot check for updates", async () => { + const manager = managerWith({ + plugin: pluginProvider({ installUrl: "https://example.com/install" }), + }); + try { + await expect( + manager.installations.checkForUpdates("installation-plugin"), + ).resolves.toBeNull(); + await expect(manager.installations.checkForUpdates("not-a-provider")).rejects.toThrow( + "Provider not-a-provider is not configured", + ); + } finally { + manager.destroy(); + } + }); + + test("availability, discovery and the installed version never wait on an update check", async () => { + let checks = 0; + const manager = managerWith({ + plugin: pluginProvider({ + async inspect() { + return { status: "installed", version: "1.0.0" }; + }, + checkForUpdates() { + checks += 1; + return new Promise(() => {}); + }, + }), + }); + try { + void manager.installations.checkForUpdates("installation-plugin"); + const entry = await manager.getProvider({ provider: "installation-plugin", wait: true }); + expect(entry.status).toBe("ready"); + await expect(manager.installations.inspect("installation-plugin")).resolves.toEqual({ + inspection: { status: "installed", version: "1.0.0" }, + }); + expect(checks).toBe(1); + } finally { + manager.destroy(); + } + }); +}); + +describe("ProviderInstallations", () => { + function counting( + inspect: NonNullable, + options: { now?: () => number; inspectTimeoutMs?: number } = {}, + ) { + let calls = 0; + const client = builtinClient({ + inspect(context) { + calls += 1; + return inspect(context); + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: (provider) => (provider === "codex" ? client : null), + ...options, + }); + return { installations, calls: () => calls }; + } + + test("shares concurrent reads, caches briefly, and refresh asks again", async () => { + let time = 0; + const { installations, calls } = counting( + async () => ({ status: "installed", version: `v${time}` }), + { now: () => time }, + ); + const [first, second] = await Promise.all([ + installations.inspect("codex"), + installations.inspect("codex"), + ]); + expect(first).toEqual(second); + expect(calls()).toBe(1); + + time = 1_000; + await expect(installations.inspect("codex")).resolves.toEqual({ + inspection: { status: "installed", version: "v0" }, + }); + expect(calls()).toBe(1); + + await expect(installations.inspect("codex", { refresh: true })).resolves.toEqual({ + inspection: { status: "installed", version: "v1000" }, + }); + expect(calls()).toBe(2); + + time = 1_000_000; + await installations.inspect("codex"); + expect(calls()).toBe(3); + }); + + function countingUpdates( + checkForUpdates: NonNullable, + options: { now?: () => number; updateCheckTimeoutMs?: number } = {}, + ) { + let calls = 0; + const client = builtinClient({ + checkForUpdates(context) { + calls += 1; + return checkForUpdates(context); + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: (provider) => (provider === "codex" ? client : null), + updateCheckCacheMs: 3_600_000, + inspectCacheMs: 30_000, + ...options, + }); + return { installations, calls: () => calls }; + } + + test("shares concurrent update checks, holds an answer for the long cache, and refresh asks again", async () => { + let time = 0; + const { installations, calls } = countingUpdates( + async () => ({ status: "available", versions: [`v${time}`] }), + { now: () => time }, + ); + const [first, second] = await Promise.all([ + installations.checkForUpdates("codex"), + installations.checkForUpdates("codex"), + ]); + expect(first).toEqual(second); + expect(calls()).toBe(1); + + time = 3_000_000; + await expect(installations.checkForUpdates("codex")).resolves.toEqual({ + status: "available", + versions: ["v0"], + }); + expect(calls()).toBe(1); + + await expect(installations.checkForUpdates("codex", { refresh: true })).resolves.toEqual({ + status: "available", + versions: ["v3000000"], + }); + expect(calls()).toBe(2); + + time = 3_000_000 + 3_600_000; + await installations.checkForUpdates("codex"); + expect(calls()).toBe(3); + }); + + test("retries an inconclusive update check after the short cache", async () => { + let time = 0; + const { installations, calls } = countingUpdates(async () => ({ status: "unknown" }), { + now: () => time, + }); + await installations.checkForUpdates("codex"); + time = 29_000; + await installations.checkForUpdates("codex"); + expect(calls()).toBe(1); + time = 31_000; + await installations.checkForUpdates("codex"); + expect(calls()).toBe(2); + }); + + test("an update check asks with the version the inspection reported, inspecting once", async () => { + let inspections = 0; + const versions: (string | undefined)[] = []; + const client = builtinClient({ + async inspect() { + inspections += 1; + return { status: "installed", version: OPAQUE_VERSION }; + }, + async checkForUpdates({ installedVersion }) { + versions.push(installedVersion); + return { status: "current" }; + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: () => client, + }); + // The app sends both together; the check joins the inspection instead of starting another. + await expect( + Promise.all([installations.inspect("codex"), installations.checkForUpdates("codex")]), + ).resolves.toEqual([ + { inspection: { status: "installed", version: OPAQUE_VERSION } }, + { status: "current" }, + ]); + expect(inspections).toBe(1); + expect(versions).toEqual([OPAQUE_VERSION]); + + await Promise.all([ + installations.inspect("codex", { refresh: true }), + installations.checkForUpdates("codex", { refresh: true }), + ]); + expect(inspections).toBe(2); + expect(versions).toEqual([OPAQUE_VERSION, OPAQUE_VERSION]); + }); + + test("asks for updates again once the installed version changes", async () => { + let time = 0; + let installed = "1.0.0"; + let checks = 0; + const client = builtinClient({ + async inspect() { + return { status: "installed", version: installed }; + }, + async checkForUpdates({ installedVersion }) { + checks += 1; + return installedVersion === "1.0.0" + ? { status: "available", versions: ["2.0.0"] } + : { status: "current" }; + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: () => client, + inspectCacheMs: 30_000, + updateCheckCacheMs: 3_600_000, + now: () => time, + }); + const check = () => installations.checkForUpdates("codex"); + await expect(check()).resolves.toEqual({ status: "available", versions: ["2.0.0"] }); + + // The CLI updated itself outside Paseo; the cached inspection still reports 1.0.0. + installed = "2.0.0"; + time = 29_000; + await expect(check()).resolves.toEqual({ status: "available", versions: ["2.0.0"] }); + expect(checks).toBe(1); + + // Once the inspection is read again, the check answers for the new version. + time = 31_000; + await expect(check()).resolves.toEqual({ status: "current" }); + expect(checks).toBe(2); + + // Two clients reopening together after another change share one new check. + installed = "3.0.0"; + time = 93_000; + await Promise.all([check(), check()]); + expect(checks).toBe(3); + + // The same version again keeps the long-cached answer. + time = 124_000; + await check(); + expect(checks).toBe(3); + }); + + test("an update check reports a missing or unreadable installation without asking", async () => { + let installed = false; + let checks = 0; + const client = builtinClient({ + async inspect() { + if (installed) throw new Error(OPAQUE_MESSAGE); + return { status: "not_installed" }; + }, + async checkForUpdates() { + checks += 1; + return { status: "current" }; + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: () => client, + }); + await expect(installations.checkForUpdates("codex")).resolves.toEqual({ + status: "unknown", + message: "Not installed", + }); + installed = true; + await expect(installations.checkForUpdates("codex", { refresh: true })).resolves.toEqual({ + status: "error", + message: OPAQUE_MESSAGE, + }); + expect(checks).toBe(0); + }); + + test("a provider without inspect is asked with no installed version", async () => { + const versions: (string | undefined)[] = []; + const { installations } = countingUpdates(async ({ installedVersion }) => { + versions.push(installedVersion); + return { status: "current" }; + }); + await installations.checkForUpdates("codex"); + expect(versions).toEqual([undefined]); + }); + + test("aborts a slow update check and reports it as an error", async () => { + let aborted = false; + function waitForAbort(signal: AbortSignal) { + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => { + aborted = true; + reject(new Error("aborted")); + }); + }); + } + const { installations } = countingUpdates(({ signal }) => waitForAbort(signal), { + updateCheckTimeoutMs: 10, + }); + await expect(installations.checkForUpdates("codex")).resolves.toEqual({ + status: "error", + message: "Timed out after 10ms", + }); + expect(aborted).toBe(true); + }); + + test("aborts a slow inspect and reports it as an error", async () => { + let aborted = false; + function waitForAbort(signal: AbortSignal) { + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => { + aborted = true; + reject(new Error("aborted")); + }); + }); + } + const { installations } = counting(({ signal }) => waitForAbort(signal), { + inspectTimeoutMs: 10, + }); + await expect(installations.inspect("codex")).resolves.toEqual({ + inspection: { status: "error", message: "Timed out after 10ms" }, + }); + expect(aborted).toBe(true); + }); +}); + +describe("provider updates", () => { + function updating( + update: NonNullable, + options: { + inspect?: AgentClientInstallation["inspect"]; + refreshProvider?: (provider: string) => Promise; + updateOutputLimit?: number; + } = {}, + ) { + let calls = 0; + const client = builtinClient({ + updateUrl: "https://example.com/update", + inspect: options.inspect, + update(context) { + calls += 1; + return update(context); + }, + }); + const installations = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: (provider) => (provider === "codex" ? client : null), + refreshProvider: options.refreshProvider, + updateOutputLimit: options.updateOutputLimit, + }); + const events: ProviderUpdateEvent[] = []; + const progress: ProviderInstallationUpdateProgress[] = []; + installations.observeUpdates("codex", (event) => { + events.push(event); + if (event.type === "provider.installation.update.progress") progress.push(event.payload); + }); + return { installations, events, progress, calls: () => calls }; + } + + function settled(installations: ProviderInstallations): Promise { + return new Promise((resolve) => { + const stop = installations.observeUpdates("codex", (event) => { + if (event.type !== "provider.installation.update.progress") return; + if (event.payload.operation.status === "running") return; + stop(); + resolve(installations.getUpdate("codex")!); + }); + }); + } + + test("passes output and the success message through unchanged, in order", async () => { + const { installations, progress } = updating(async ({ report }) => { + report({ type: "message", text: OPAQUE_MESSAGE }); + report({ type: "stdout", text: " added 1 package\r\n" }); + report({ type: "stderr", text: "npm warn \u001b[33mdeprecated\u001b[0m\n" }); + report({ type: "stdout", text: "" }); + return { status: "succeeded", message: OPAQUE_MESSAGE }; + }); + const done = settled(installations); + const started = installations.update("codex"); + expect(started.operation.status).toBe("running"); + + const update = await done; + const output = [ + { type: "message", text: OPAQUE_MESSAGE }, + { type: "stdout", text: " added 1 package\r\n" }, + { type: "stderr", text: "npm warn \u001b[33mdeprecated\u001b[0m\n" }, + { type: "stdout", text: "" }, + ]; + expect(update).toEqual({ + operation: { + status: "succeeded", + id: started.operation.id, + startedAt: expect.any(String), + finishedAt: expect.any(String), + message: OPAQUE_MESSAGE, + }, + output, + }); + expect(progress.map((event) => event.operation.status)).toEqual([ + "running", + "running", + "running", + "running", + "running", + "succeeded", + ]); + expect(progress.flatMap((event) => event.output)).toEqual(output); + }); + + test("reports a failure with the provider's message and keeps its output", async () => { + const { installations } = updating(async ({ report }) => { + report({ type: "stdout", text: "Updating Codex via `npm install -g @openai/codex`...\n" }); + report({ type: "stderr", text: "npm error code EACCES\n" }); + return { status: "failed", message: OPAQUE_MESSAGE }; + }); + const done = settled(installations); + installations.update("codex"); + await expect(done).resolves.toEqual({ + operation: expect.objectContaining({ status: "failed", message: OPAQUE_MESSAGE }), + output: [ + { type: "stdout", text: "Updating Codex via `npm install -g @openai/codex`...\n" }, + { type: "stderr", text: "npm error code EACCES\n" }, + ], + }); + }); + + test("turns a throw into a failure with its message and keeps earlier output", async () => { + const { installations } = updating(async ({ report }) => { + report({ type: "stdout", text: "step 1\n" }); + throw new Error(OPAQUE_MESSAGE); + }); + const done = settled(installations); + installations.update("codex"); + await expect(done).resolves.toEqual({ + operation: expect.objectContaining({ status: "failed", message: OPAQUE_MESSAGE }), + output: [{ type: "stdout", text: "step 1\n" }], + }); + }); + + test("a refresh drops a failed update and keeps a running one", async () => { + let finish!: () => void; + let attempt = 0; + const { installations } = updating( + async () => { + attempt += 1; + if (attempt === 1) return { status: "failed", message: "EACCES" }; + await new Promise((resolve) => { + finish = resolve; + }); + return { status: "succeeded" }; + }, + { inspect: async () => ({ status: "installed", version: "1.0.0" }) }, + ); + const failed = settled(installations); + installations.update("codex"); + await failed; + await installations.inspect("codex"); + expect(installations.getUpdate("codex")?.operation.status).toBe("failed"); + await installations.inspect("codex", { refresh: true }); + expect(installations.getUpdate("codex")).toBeNull(); + + const running = installations.update("codex"); + await installations.inspect("codex", { refresh: true }); + await installations.checkForUpdates("codex", { refresh: true }); + expect(installations.getUpdate("codex")?.operation.id).toBe(running.operation.id); + const done = settled(installations); + finish(); + await done; + }); + + test("tells observers when a refresh drops a failed update", async () => { + const { installations, events } = updating( + async () => ({ status: "failed", message: "EACCES" }), + { + inspect: async () => ({ status: "installed", version: "1.0.0" }), + }, + ); + const failed = settled(installations); + const started = installations.update("codex"); + await failed; + events.length = 0; + + await installations.inspect("codex", { refresh: true }); + await installations.inspect("codex", { refresh: true }); + expect(events).toEqual([ + { + type: "provider.installation.update.cleared", + payload: { provider: "codex", operationId: started.operation.id }, + }, + ]); + }); + + test("a second request while an update runs joins it instead of starting another", async () => { + let finish!: () => void; + const { installations, calls } = updating(async ({ report }) => { + report({ type: "stdout", text: "working\n" }); + await new Promise((resolve) => { + finish = resolve; + }); + return { status: "succeeded" }; + }); + const first = installations.update("codex"); + const second = installations.update("codex"); + expect(second.operation.id).toBe(first.operation.id); + expect(second.output).toEqual([{ type: "stdout", text: "working\n" }]); + expect(calls()).toBe(1); + + const done = settled(installations); + finish(); + await expect(done).resolves.toMatchObject({ operation: { status: "succeeded" } }); + const third = installations.update("codex"); + expect(third.operation.id).not.toBe(first.operation.id); + expect(calls()).toBe(2); + }); + + test("after success the next read asks the provider again and discovery refreshes", async () => { + let version = "1.0.0"; + const refreshed: string[] = []; + const { installations } = updating( + async () => { + version = "2.0.0"; + return { status: "succeeded" }; + }, + { + inspect: async () => ({ status: "installed", version }), + refreshProvider: async (provider) => { + refreshed.push(provider); + }, + }, + ); + await expect(installations.inspect("codex")).resolves.toMatchObject({ + inspection: { version: "1.0.0" }, + }); + const done = settled(installations); + installations.update("codex"); + await done; + await expect(installations.inspect("codex")).resolves.toMatchObject({ + inspection: { version: "2.0.0" }, + }); + expect(refreshed).toEqual(["codex"]); + }); + + test("a failed refresh after success still reports success; a failure keeps the caches", async () => { + let version = "1.0.0"; + let result: "succeeded" | "failed" = "failed"; + const { installations } = updating( + async () => { + version = "2.0.0"; + return result === "succeeded" ? { status: result } : { status: result, message: "no" }; + }, + { + inspect: async () => ({ status: "installed", version }), + refreshProvider: async () => { + throw new Error("discovery failed"); + }, + }, + ); + await installations.inspect("codex"); + let done = settled(installations); + installations.update("codex"); + await done; + await expect(installations.inspect("codex")).resolves.toMatchObject({ + inspection: { version: "1.0.0" }, + }); + + result = "succeeded"; + done = settled(installations); + installations.update("codex"); + await expect(done).resolves.toMatchObject({ operation: { status: "succeeded" } }); + }); + + test("retains the most recent output within the limit and marks the drop", async () => { + const { installations, progress } = updating( + async ({ report }) => { + report({ type: "stdout", text: "aaaa" }); + report({ type: "stdout", text: "bbbb" }); + report({ type: "stderr", text: "cccc" }); + report({ type: "stdout", text: "0123456789XYZ" }); + return { status: "succeeded" }; + }, + { updateOutputLimit: 10 }, + ); + const done = settled(installations); + installations.update("codex"); + const update = await done; + expect(update.output).toEqual([{ type: "stdout", text: "3456789XYZ" }]); + expect(update.truncated).toBe(true); + expect(progress.flatMap((event) => event.output).at(-1)).toEqual({ + type: "stdout", + text: "3456789XYZ", + }); + + const partial = updating( + async ({ report }) => { + report({ type: "stdout", text: "aaaa" }); + report({ type: "stdout", text: "bbbb" }); + report({ type: "stderr", text: "cccc" }); + return { status: "succeeded" }; + }, + { updateOutputLimit: 10 }, + ); + const partialDone = settled(partial.installations); + partial.installations.update("codex"); + await expect(partialDone).resolves.toMatchObject({ + output: [ + { type: "stdout", text: "bbbb" }, + { type: "stderr", text: "cccc" }, + ], + truncated: true, + }); + }); + + test("advertises the update only when the provider declares one", async () => { + const { installations } = updating(async () => ({ status: "succeeded" })); + await expect(installations.inspect("codex")).resolves.toEqual({ + updateUrl: "https://example.com/update", + canUpdate: true, + }); + // The update never depends on a check: this provider has none, and it still updates. + await expect(installations.checkForUpdates("codex")).resolves.toBeNull(); + const done = settled(installations); + installations.update("codex"); + await expect(done).resolves.toMatchObject({ operation: { status: "succeeded" } }); + + const plain = new ProviderInstallations({ + logger: createTestLogger(), + resolveClient: () => builtinClient({ updateUrl: "https://example.com/update" }), + }); + await expect(plain.inspect("codex")).resolves.toEqual({ + updateUrl: "https://example.com/update", + }); + expect(() => plain.update("codex")).toThrow("Provider codex cannot update itself"); + expect(plain.getUpdate("codex")).toBeNull(); + }); + + test("close aborts a running update, which settles with the provider's answer", async () => { + function failOnAbort(signal: AbortSignal): Promise { + return new Promise((resolve) => { + const stopped = () => + resolve({ status: "failed", message: `stopped: ${String(signal.reason)}` }); + signal.addEventListener("abort", stopped); + }); + } + const { installations } = updating(({ signal }) => failOnAbort(signal)); + const done = settled(installations); + installations.update("codex"); + installations.close(); + await expect(done).resolves.toMatchObject({ + operation: { status: "failed", message: "stopped: Error: The daemon is stopping" }, + }); + }); +}); diff --git a/packages/server/src/server/agent/provider-installation/provider-installations.ts b/packages/server/src/server/agent/provider-installation/provider-installations.ts new file mode 100644 index 000000000000..f48104807b53 --- /dev/null +++ b/packages/server/src/server/agent/provider-installation/provider-installations.ts @@ -0,0 +1,377 @@ +import { randomUUID } from "node:crypto"; +import type { Logger } from "pino"; +import type { + ProviderInstallation, + ProviderInstallationInspection, + ProviderInstallationUpdate, + ProviderInstallationUpdateCheck, + ProviderInstallationUpdateCleared, + ProviderInstallationUpdateProgress, +} from "@getpaseo/protocol/messages"; +import { + ProviderInspectionSchema, + ProviderUpdateCheckSchema, + ProviderUpdateReportSchema, + ProviderUpdateResultSchema, + type ProviderUpdateResult, +} from "@getpaseo/plugin/server/provider"; +import type { + AgentClient, + AgentClientInstallationContext, + AgentClientUpdateContext, + AgentProvider, +} from "../agent-sdk-types.js"; +import { ProviderUpdateOperation } from "./provider-update-operation.js"; + +const DEFAULT_INSPECT_TIMEOUT_MS = 20_000; +const DEFAULT_INSPECT_CACHE_MS = 30_000; +// Below the plugin RPC timeout, so a slow plugin check reports this deadline. +const DEFAULT_UPDATE_CHECK_TIMEOUT_MS = 25_000; +const DEFAULT_UPDATE_CHECK_CACHE_MS = 60 * 60_000; +/** Characters of updater output kept per update; older output is dropped first. */ +export const DEFAULT_UPDATE_OUTPUT_LIMIT = 64 * 1024; + +export interface ProviderInstallationsOptions { + logger: Logger; + /** The current client for a configured provider, or null when the provider is unknown. */ + resolveClient(provider: AgentProvider): AgentClient | null; + inspectTimeoutMs?: number; + inspectCacheMs?: number; + updateCheckTimeoutMs?: number; + /** How long a conclusive update check is reused. Failed checks use `inspectCacheMs`. */ + updateCheckCacheMs?: number; + /** Rediscovers the provider after a successful update. A failure is logged, not reported. */ + refreshProvider?(provider: AgentProvider): Promise; + updateOutputLimit?: number; + now?: () => number; +} + +/** What an update observer hears, shaped as the message the session forwards to its clients. */ +export type ProviderUpdateEvent = + | { type: "provider.installation.update.progress"; payload: ProviderInstallationUpdateProgress } + | { type: "provider.installation.update.cleared"; payload: ProviderInstallationUpdateCleared }; + +export type ProviderUpdateListener = (event: ProviderUpdateEvent) => void; + +export interface InspectProviderInstallationOptions { + /** Skip the settled-result cache. Joins a call that is already running. */ + refresh?: boolean; +} + +/** A wire result: the provider's answer, or the `failed` value when the call threw or timed out. */ +interface ProviderCallResult { + status: string; +} + +interface ProviderCall { + name: string; + /** A cached result is reused only for the same key. */ + key?: string; + /** Validates the provider's answer; throws when it breaks the contract. */ + parse(value: unknown): T; + timeoutMs: number; + /** How long a settled result is reused. */ + cacheMs(result: T): number; + run(context: AgentClientInstallationContext): Promise; + failed(message: string): T; +} + +interface CachedRead { + key: string | undefined; + promise: Promise; + settledAt: number | null; + cacheMs: number; +} + +/** + * Calls provider installation callbacks for every provider, built-in or plugin, through + * `AgentClient.installation`. Owns deadlines, in-flight sharing and result caching. Results are + * keyed by client, so a provider configuration change, which replaces the client, starts fresh. + * An update check first reads the inspection and passes its version to the provider, so the + * installed version never waits on an update check. + */ +export class ProviderInstallations { + private readonly logger: Logger; + private readonly resolveClient: ProviderInstallationsOptions["resolveClient"]; + private readonly inspectTimeoutMs: number; + private readonly inspectCacheMs: number; + private readonly updateCheckTimeoutMs: number; + private readonly updateCheckCacheMs: number; + private readonly refreshProvider: ProviderInstallationsOptions["refreshProvider"]; + private readonly updateOutputLimit: number; + private readonly now: () => number; + private readonly updates = new Map(); + private readonly updateListeners = new Map>(); + private readonly runningUpdates = new Set(); + private readonly inspections = new WeakMap< + AgentClient, + CachedRead + >(); + private readonly updateChecks = new WeakMap< + AgentClient, + CachedRead + >(); + + constructor(options: ProviderInstallationsOptions) { + this.logger = options.logger; + this.resolveClient = options.resolveClient; + this.inspectTimeoutMs = options.inspectTimeoutMs ?? DEFAULT_INSPECT_TIMEOUT_MS; + this.inspectCacheMs = options.inspectCacheMs ?? DEFAULT_INSPECT_CACHE_MS; + this.updateCheckTimeoutMs = options.updateCheckTimeoutMs ?? DEFAULT_UPDATE_CHECK_TIMEOUT_MS; + this.updateCheckCacheMs = options.updateCheckCacheMs ?? DEFAULT_UPDATE_CHECK_CACHE_MS; + this.refreshProvider = options.refreshProvider; + this.updateOutputLimit = options.updateOutputLimit ?? DEFAULT_UPDATE_OUTPUT_LIMIT; + this.now = options.now ?? Date.now; + } + + /** Links and installed state, or null when the provider declares no installation contract. */ + async inspect( + provider: AgentProvider, + options: InspectProviderInstallationOptions = {}, + ): Promise { + const client = this.requireClient(provider); + const installation = client.installation; + if (!installation) return null; + const result: ProviderInstallation = {}; + if (installation.installUrl) result.installUrl = installation.installUrl; + if (installation.updateUrl) result.updateUrl = installation.updateUrl; + if (installation.update) result.canUpdate = true; + const inspection = await this.readInspection(provider, client, options); + if (inspection) result.inspection = inspection; + return result; + } + + /** + * Whether a newer version is available, as the provider reports it, or null when the provider + * cannot check. A check that throws or misses its deadline is reported as `error`. + */ + async checkForUpdates( + provider: AgentProvider, + options: InspectProviderInstallationOptions = {}, + ): Promise { + const client = this.requireClient(provider); + const installation = client.installation; + const checkForUpdates = installation?.checkForUpdates; + if (!installation || !checkForUpdates) return null; + // The provider compares the version the inspection reported, so a cached answer holds only + // while the inspection still reports that version. + const inspection = await this.readInspection(provider, client, options); + if (inspection?.status === "not_installed") + return { status: "unknown", message: "Not installed" }; + if (inspection?.status === "error") return { status: "error", message: inspection.message }; + const installedVersion = inspection?.version; + return this.read(provider, client, this.updateChecks, options, { + name: "update check", + key: installedVersion, + parse: (value) => ProviderUpdateCheckSchema.parse(value), + timeoutMs: this.updateCheckTimeoutMs, + // Inconclusive answers are retried soon; a conclusive one holds for the long cache. + cacheMs: (result) => + result.status === "current" || result.status === "available" + ? this.updateCheckCacheMs + : this.inspectCacheMs, + run: (context) => checkForUpdates.call(installation, { ...context, installedVersion }), + failed: (message) => ({ status: "error" as const, message }), + }); + } + + /** + * Starts the provider's update, or returns the one already running. The update runs until the + * provider settles it, independent of any client; only `close` aborts it. Throws when the + * provider declares no `update`. + */ + update(provider: AgentProvider): ProviderInstallationUpdate { + const running = this.updates.get(provider); + if (running?.running) return running.snapshot(); + const client = this.requireClient(provider); + const installation = client.installation; + const update = installation?.update; + if (!installation || !update) throw new Error(`Provider ${provider} cannot update itself`); + const operation = new ProviderUpdateOperation({ + id: randomUUID(), + provider, + startedAt: this.timestamp(), + outputLimit: this.updateOutputLimit, + publish: (progress) => + this.publishUpdate(provider, { + type: "provider.installation.update.progress", + payload: progress, + }), + }); + this.updates.set(provider, operation); + void this.runUpdate(provider, client, operation, (context) => + update.call(installation, context), + ); + return operation.snapshot(); + } + + /** + * The latest update of the provider since the daemon started, or null. A failed update stays + * until the next refresh of the provider's installation or update check. + */ + getUpdate(provider: AgentProvider): ProviderInstallationUpdate | null { + return this.updates.get(provider)?.snapshot() ?? null; + } + + /** + * Calls `listener` when an update of the provider starts, reports output or settles, and when + * a refresh drops a failed update. + */ + observeUpdates(provider: AgentProvider, listener: ProviderUpdateListener): () => void { + let listeners = this.updateListeners.get(provider); + if (!listeners) { + listeners = new Set(); + this.updateListeners.set(provider, listeners); + } + listeners.add(listener); + return () => { + listeners.delete(listener); + if (listeners.size === 0) this.updateListeners.delete(provider); + }; + } + + private publishUpdate(provider: AgentProvider, event: ProviderUpdateEvent): void { + for (const listener of this.updateListeners.get(provider) ?? []) listener(event); + } + + /** Aborts running updates. Each settles as failed with the provider's answer to the abort. */ + close(): void { + for (const controller of this.runningUpdates) + controller.abort(new Error("The daemon is stopping")); + } + + /** + * The provider's inspection, or undefined when it declares no `inspect`. A refresh also drops + * a failed update, so the provider's own state replaces it; a running update is kept. + */ + private readInspection( + provider: AgentProvider, + client: AgentClient, + options: InspectProviderInstallationOptions, + ): Promise | undefined { + const failed = this.updates.get(provider)?.snapshot().operation; + if (options.refresh && failed?.status === "failed") { + this.updates.delete(provider); + this.publishUpdate(provider, { + type: "provider.installation.update.cleared", + payload: { provider, operationId: failed.id }, + }); + } + const installation = client.installation; + const inspect = installation?.inspect; + if (!installation || !inspect) return undefined; + return this.read(provider, client, this.inspections, options, { + name: "inspect", + parse: (value) => ProviderInspectionSchema.parse(value), + timeoutMs: this.inspectTimeoutMs, + cacheMs: () => this.inspectCacheMs, + run: (context) => inspect.call(installation, context), + failed: (message) => ({ status: "error" as const, message }), + }); + } + + private async runUpdate( + provider: AgentProvider, + client: AgentClient, + operation: ProviderUpdateOperation, + run: (context: AgentClientUpdateContext) => Promise, + ): Promise { + const controller = new AbortController(); + this.runningUpdates.add(controller); + let result: ProviderUpdateResult; + try { + const answer = await run({ + signal: controller.signal, + report: (event) => { + const parsed = ProviderUpdateReportSchema.safeParse(event); + if (parsed.success) operation.append(parsed.data); + else this.logger.warn({ provider }, "Ignored invalid provider update output"); + }, + }); + result = ProviderUpdateResultSchema.parse(answer); + } catch (error) { + this.logger.warn({ err: error, provider }, "Provider update failed"); + result = { + status: "failed", + message: error instanceof Error ? error.message : String(error), + }; + } finally { + this.runningUpdates.delete(controller); + } + if (result.status === "succeeded") { + // The installed version and update state are now stale; read them again on next request. + this.inspections.delete(client); + this.updateChecks.delete(client); + } + operation.settle(result, this.timestamp()); + if (result.status === "succeeded" && this.refreshProvider) { + await this.refreshProvider(provider).catch((error: unknown) => { + this.logger.warn({ err: error, provider }, "Provider refresh after update failed"); + }); + } + } + + private timestamp(): string { + return new Date(this.now()).toISOString(); + } + + private requireClient(provider: AgentProvider): AgentClient { + const client = this.resolveClient(provider); + if (!client) throw new Error(`Provider ${provider} is not configured`); + return client; + } + + private read( + provider: AgentProvider, + client: AgentClient, + cache: WeakMap>, + options: InspectProviderInstallationOptions, + call: ProviderCall, + ): Promise { + const existing = cache.get(client); + if ( + existing && + existing.key === call.key && + (existing.settledAt === null || (!options.refresh && this.isFresh(existing))) + ) { + return existing.promise; + } + // invoke settles asynchronously, after `read` is initialized. + const promise = this.invoke(provider, call).then((result) => { + read.settledAt = this.now(); + read.cacheMs = call.cacheMs(result); + return result; + }); + const read: CachedRead = { key: call.key, promise, settledAt: null, cacheMs: 0 }; + cache.set(client, read); + return read.promise; + } + + private isFresh(read: CachedRead): boolean { + return read.settledAt !== null && this.now() - read.settledAt < read.cacheMs; + } + + private async invoke( + provider: AgentProvider, + call: ProviderCall, + ): Promise { + const controller = new AbortController(); + let timer: ReturnType | undefined; + const deadline = new Promise((_resolve, reject) => { + timer = setTimeout(() => { + const error = new Error(`Timed out after ${call.timeoutMs}ms`); + reject(error); + controller.abort(error); + }, call.timeoutMs); + }); + try { + const result = await Promise.race([call.run({ signal: controller.signal }), deadline]); + return call.parse(result); + } catch (error) { + this.logger.warn({ err: error, provider }, `Provider installation ${call.name} failed`); + return call.failed(error instanceof Error ? error.message : String(error)); + } finally { + clearTimeout(timer); + } + } +} diff --git a/packages/server/src/server/agent/provider-installation/provider-update-operation.ts b/packages/server/src/server/agent/provider-installation/provider-update-operation.ts new file mode 100644 index 000000000000..239716684d3f --- /dev/null +++ b/packages/server/src/server/agent/provider-installation/provider-update-operation.ts @@ -0,0 +1,80 @@ +import type { + ProviderInstallationUpdate, + ProviderInstallationUpdateOperation, + ProviderInstallationUpdateOutput, + ProviderInstallationUpdateProgress, +} from "@getpaseo/protocol/messages"; +import type { ProviderUpdateResult } from "@getpaseo/plugin/server/provider"; + +interface ProviderUpdateOperationOptions { + id: string; + provider: string; + startedAt: string; + /** Characters of output text retained; the oldest output is dropped beyond it. */ + outputLimit: number; + publish(progress: ProviderInstallationUpdateProgress): void; +} + +/** + * One provider update: its state and the output it reported, bounded to `outputLimit` + * characters. Output reported after the update settles is ignored. + */ +export class ProviderUpdateOperation { + private state: ProviderInstallationUpdateOperation; + private readonly output: ProviderInstallationUpdateOutput[] = []; + private outputLength = 0; + private truncated = false; + + constructor(private readonly options: ProviderUpdateOperationOptions) { + this.state = { status: "running", id: options.id, startedAt: options.startedAt }; + this.publish([]); + } + + get running(): boolean { + return this.state.status === "running"; + } + + append(entry: ProviderInstallationUpdateOutput): void { + if (!this.running) return; + const limit = this.options.outputLimit; + const kept = + entry.text.length > limit ? { type: entry.type, text: entry.text.slice(-limit) } : entry; + if (kept !== entry) this.truncated = true; + this.output.push(kept); + this.outputLength += kept.text.length; + while (this.outputLength > limit) { + const dropped = this.output.shift()!; + this.outputLength -= dropped.text.length; + this.truncated = true; + } + this.publish([kept]); + } + + settle(result: ProviderUpdateResult, finishedAt: string): void { + if (!this.running) return; + const { id, startedAt } = this.state; + this.state = + result.status === "succeeded" + ? { + status: "succeeded", + id, + startedAt, + finishedAt, + ...(result.message === undefined ? {} : { message: result.message }), + } + : { status: "failed", id, startedAt, finishedAt, message: result.message }; + this.publish([]); + } + + snapshot(): ProviderInstallationUpdate { + return { + operation: this.state, + output: [...this.output], + ...(this.truncated ? { truncated: true } : {}), + }; + } + + private publish(output: ProviderInstallationUpdateOutput[]): void { + this.options.publish({ provider: this.options.provider, operation: this.state, output }); + } +} diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index b671eb0fab17..bba0b3d5e7bf 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -626,6 +626,7 @@ function wrapClientProvider( getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner), isAvailable: (signal, options) => inner.isAvailable(signal, options), getDiagnostic: inner.getDiagnostic?.bind(inner), + installation: inner.installation, }; } diff --git a/packages/server/src/server/agent/provider-snapshot-manager.ts b/packages/server/src/server/agent/provider-snapshot-manager.ts index 9dfd480f6d4d..f20844aff52e 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.ts @@ -52,6 +52,7 @@ import { import type { ProviderRegistration } from "@getpaseo/plugin/server/provider"; import { PluginAgentClientRegistry } from "./plugin-provider.js"; import { convertLegacyClaudeUltracode, resolveAdapter } from "./option-controls.js"; +import { ProviderInstallations } from "./provider-installation/provider-installations.js"; const DEFAULT_REFRESH_TIMEOUT_MS = 120_000; const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647; @@ -254,6 +255,8 @@ export class ProviderSnapshotManager { private providerClients: Record; private readonly ownedClients = new Set(); private readonly pluginProviders: PluginAgentClientRegistry; + /** Installation links and versions; separate from availability and discovery. */ + readonly installations: ProviderInstallations; private pluginProvidersSettled = false; constructor(options: ProviderSnapshotManagerOptions) { @@ -282,6 +285,14 @@ export class ProviderSnapshotManager { ...this.extraClients, } as Record; for (const client of Object.values(this.providerClients)) this.ownedClients.add(client); + this.installations = new ProviderInstallations({ + logger: options.logger.child({ module: "provider-installations" }), + resolveClient: (provider) => { + const definition = this.generation.definitions[provider]; + return definition ? this.ensureClient(provider, definition) : null; + }, + refreshProvider: (provider) => this.refreshSettingsSnapshot({ providers: [provider] }), + }); } getSnapshot(cwd?: string): ProviderSnapshot { @@ -695,6 +706,7 @@ export class ProviderSnapshotManager { async shutdown(): Promise { this.destroyed = true; + this.installations.close(); for (const state of this.generation.providerStates.values()) state.discoveryLimit.clearQueue(); // Materialize a client per enabled provider so provider-owned resources // (background processes, sockets, etc.) get a chance to release even when @@ -705,6 +717,7 @@ export class ProviderSnapshotManager { destroy(): void { this.destroyed = true; + this.installations.close(); for (const state of this.generation.providerStates.values()) state.discoveryLimit.clearQueue(); this.catalogs.clear(); this.targets.clear(); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 0f2fb5667279..3be67c57b154 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -97,6 +97,15 @@ import { } from "./rewind.js"; import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js"; import { claudeConfigDir, claudeProjectDirSync, claudeTranscriptPath } from "./project-dir.js"; +import { + compareWithLatestRelease, + fetchHomebrewCaskVersion, + fetchReleaseText, + homebrewCaskOf, + resolveExecutablePath, + type LatestReleaseLookup, +} from "../release-check.js"; +import { runUpdateCommand, updatedForNewAgents } from "../update-command.js"; import { THINKING_APPLIES_NEXT_TURN_NOTICE } from "../../provider-notices.js"; import { isProviderImageMarkdown, @@ -135,6 +144,7 @@ import { type AgentTimelineItem, type AgentUsage, type AgentRuntimeInfo, + type AgentClientInstallation, type FetchCatalogOptions, type ImportableProviderSession, type ImportProviderSessionContext, @@ -481,6 +491,8 @@ interface ClaudeAgentClientOptions { queryFactory?: ClaudeQueryFactory; resolveBinary?: () => Promise; resolveVersion?: (signal?: AbortSignal) => Promise; + /** Where update checks learn the newest release; defaults to Claude Code's release channel. */ + lookupLatestRelease?: LatestReleaseLookup; rewindSdk?: ClaudeRewindSdk; } @@ -1614,6 +1626,43 @@ export class ClaudeAgentClient implements AgentClient { private readonly discoverModels: typeof discoverClaudeModels; readonly provider = "claude" as const; readonly capabilities = CLAUDE_CAPABILITIES; + readonly installation: AgentClientInstallation = { + installUrl: CLAUDE_INSTALL_URL, + updateUrl: CLAUDE_UPDATE_URL, + inspect: async ({ signal }) => { + const probe = await readClaudeCodeVersion(this.runtimeSettings, signal); + if (probe.status === "not_installed") return probe; + return probe.version + ? { status: "installed", version: probe.version } + : { status: "installed" }; + }, + checkForUpdates: async ({ installedVersion, signal }) => { + if (!installedVersion) + return { status: "unknown", message: "The configured command does not report its version" }; + const installed = await resolveInstalledClaude(this.runtimeSettings); + if (!installed) return { status: "unknown", message: "Claude Code is not installed" }; + const latest = await this.lookupLatestRelease({ + executablePath: await resolveExecutablePath(installed.executable), + signal, + }); + return compareWithLatestRelease({ installed: installedVersion, latest }); + }, + // `claude update` updates native installs itself and package-manager installs through the + // package manager. + update: async (context) => { + const installed = await resolveInstalledClaude(this.runtimeSettings); + if (!installed) return { status: "failed", message: "Claude Code is not installed" }; + return runUpdateCommand( + { + command: installed.executable, + args: [...installed.args, "update"], + env: createProviderEnvSpec({ runtimeSettings: this.runtimeSettings }), + successMessage: updatedForNewAgents("Claude Code"), + }, + context, + ); + }, + }; private readonly defaults?: { agents?: Record }; private readonly logger: Logger; @@ -1622,6 +1671,7 @@ export class ClaudeAgentClient implements AgentClient { private readonly resolveBinary: () => Promise; private readonly resolveVersion: (signal?: AbortSignal) => Promise; private version: Promise | undefined; + private readonly lookupLatestRelease: LatestReleaseLookup; private readonly rewindSdk: ClaudeRewindSdk; private readonly scheduleImportDescriptors = createImportDescriptorScheduler( (candidate: ClaudeSessionCandidate, signal) => this.readImportDescriptor(candidate, signal), @@ -1643,6 +1693,13 @@ export class ClaudeAgentClient implements AgentClient { this.resolveVersion = options.resolveVersion ?? ((signal) => resolveClaudeCodeVersion(this.runtimeSettings, signal)); + this.lookupLatestRelease = + options.lookupLatestRelease ?? + ((input) => + lookupLatestClaudeRelease({ + ...input, + configDir: claudeConfigDir(this.buildProviderEnv()), + })); this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk; } @@ -1945,20 +2002,85 @@ async function resolveClaudeBinary(runtimeSettings?: ProviderRuntimeSettings): P ); } +const CLAUDE_INSTALL_URL = "https://code.claude.com/docs/en/setup#install-claude-code"; +const CLAUDE_UPDATE_URL = "https://code.claude.com/docs/en/setup#update-claude-code"; + +type ClaudeCodeVersionRead = + | { status: "not_installed" } + /** `version` is null when the configured command is a wrapper that does not report Claude Code's version. */ + | { status: "installed"; version: string | null }; + +const CLAUDE_UPDATE_CHANNELS = new Set(["latest", "stable", "rc"]); + +/** The `autoUpdatesChannel` Claude Code updates from, `latest` unless settings pick another. */ +async function readClaudeUpdateChannel(configDir: string): Promise { + try { + const settings: unknown = JSON.parse( + await promises.readFile(path.join(configDir, "settings.json"), "utf8"), + ); + const channel = + settings && typeof settings === "object" + ? (settings as Record).autoUpdatesChannel + : undefined; + return typeof channel === "string" && CLAUDE_UPDATE_CHANNELS.has(channel) ? channel : "latest"; + } catch { + return "latest"; + } +} + +/** + * The release Claude Code's own updater offers: the Homebrew cask for cask installs, otherwise + * the version published on the configured update channel. + */ +async function lookupLatestClaudeRelease(input: { + executablePath: string; + configDir: string; + signal: AbortSignal; +}): Promise { + const cask = homebrewCaskOf(input.executablePath); + if (cask) return fetchHomebrewCaskVersion(cask, input.signal); + const channel = await readClaudeUpdateChannel(input.configDir); + return fetchReleaseText( + `https://downloads.claude.ai/claude-code-releases/${channel}`, + input.signal, + ); +} + export async function resolveClaudeCodeVersion( runtimeSettings?: ProviderRuntimeSettings, signal?: AbortSignal, ): Promise { + const read = await readClaudeCodeVersion(runtimeSettings, signal); + if (read.status === "not_installed") { + throw new Error("Claude binary not found while resolving Claude Code version"); + } + if (!read.version) { + throw new Error("Unable to parse Claude Code version from --version output"); + } + return read.version; +} + +/** The executable and arguments a session would launch, or null when Claude Code is missing. */ +async function resolveInstalledClaude( + runtimeSettings: ProviderRuntimeSettings | undefined, +): Promise<{ executable: string; args: string[] } | null> { const launch = await resolveProviderLaunch({ commandConfig: runtimeSettings?.command, defaultBinary: "claude", }); const availability = await checkProviderLaunchAvailable(launch); - if (!availability.available) { - throw new Error("Claude binary not found while resolving Claude Code version"); - } - const executable = availability.resolvedPath ?? launch.command; - const { stdout, stderr } = await execCommand(executable, [...launch.args, "--version"], { + if (!availability.available) return null; + return { executable: availability.resolvedPath ?? launch.command, args: [...launch.args] }; +} + +async function readClaudeCodeVersion( + runtimeSettings: ProviderRuntimeSettings | undefined, + signal: AbortSignal | undefined, +): Promise { + const installed = await resolveInstalledClaude(runtimeSettings); + if (!installed) return { status: "not_installed" }; + const { executable } = installed; + const { stdout, stderr } = await execCommand(executable, [...installed.args, "--version"], { ...createProviderEnvSpec({ runtimeSettings }), timeout: 5_000, signal, @@ -1970,10 +2092,10 @@ export async function resolveClaudeCodeVersion( const version = /\d+\.\d+\.\d+\s+\(Claude Code\)/i.test(rawVersionOutput) ? parseClaudeCodeVersion(rawVersionOutput) : null; - if (!version) { - throw new Error("Unable to parse Claude Code version from --version output"); - } - return version.join("."); + return { + status: "installed", + version: version ? version.join(".") : null, + }; } async function resolveClaudeAuth( diff --git a/packages/server/src/server/agent/providers/cli-installation.ts b/packages/server/src/server/agent/providers/cli-installation.ts new file mode 100644 index 000000000000..f86f6f21b3c1 --- /dev/null +++ b/packages/server/src/server/agent/providers/cli-installation.ts @@ -0,0 +1,120 @@ +import type { ProviderUpdateCheck } from "@getpaseo/plugin/server/provider"; +import type { AgentClientInstallation } from "../agent-sdk-types.js"; +import { + checkProviderLaunchAvailable, + createProviderEnv, + createProviderEnvSpec, + resolveProviderLaunch, + type ProviderRuntimeSettings, +} from "../provider-launch-config.js"; +import { readCommandVersionOutput } from "./diagnostic-utils.js"; +import { runUpdateCommand } from "./update-command.js"; + +/** The provider's CLI as configured, found on the provider's PATH. */ +export interface InstalledCli { + /** The resolved executable. */ + command: string; + /** Arguments the configuration puts before any subcommand. */ + args: string[]; + env: Record | undefined; +} + +export interface CliInstallationOptions { + /** The product name used in messages, such as "Copilot". */ + name: string; + defaultBinary: string; + runtimeSettings: ProviderRuntimeSettings | undefined; + installUrl: string; + updateUrl?: string; + /** The version shown for the CLI's `--version` output. Defaults to its first line. */ + versionLabel?(output: string): string | undefined; + /** Asks the source the CLI's own updater asks. Left out when that source is not known. */ + checkForUpdates?(input: { + cli: InstalledCli; + /** The version `inspect` reported. */ + installedVersion: string | undefined; + signal: AbortSignal; + }): Promise; + /** The CLI's own update command. Left out when the CLI cannot update itself. */ + update?: { args: string[]; successMessage: string }; +} + +function firstLine(output: string): string | undefined { + return output.split("\n")[0]?.trim() || undefined; +} + +/** + * The installation contract for a provider whose CLI reports its version with `--version` and, + * where it can, updates itself with a subcommand. + */ +export function createCliInstallation(options: CliInstallationOptions): AgentClientInstallation { + const { name, runtimeSettings } = options; + const versionLabel = options.versionLabel ?? firstLine; + + async function resolveCli(): Promise { + const launch = await resolveProviderLaunch({ + commandConfig: runtimeSettings?.command, + defaultBinary: options.defaultBinary, + }); + // Agents spawn the bare command with the provider's environment, so look on its PATH. The + // OpenCode 1.x legacy server is the exception: it resolves on the daemon's PATH. + const availability = await checkProviderLaunchAvailable({ + ...launch, + env: createProviderEnv({ runtimeSettings }), + }); + if (!availability.available) return null; + return { + command: availability.resolvedPath ?? launch.command, + args: [...launch.args], + env: runtimeSettings?.env, + }; + } + + async function readVersion(cli: InstalledCli, signal: AbortSignal): Promise { + const output = await readCommandVersionOutput({ + command: cli.command, + args: [...cli.args, "--version"], + env: cli.env, + signal, + }); + return versionLabel(output); + } + + const installation: AgentClientInstallation = { + installUrl: options.installUrl, + async inspect({ signal }) { + const cli = await resolveCli(); + if (!cli) return { status: "not_installed" }; + const version = await readVersion(cli, signal); + return version ? { status: "installed", version } : { status: "installed" }; + }, + }; + if (options.updateUrl) installation.updateUrl = options.updateUrl; + + const checkForUpdates = options.checkForUpdates; + if (checkForUpdates) { + installation.checkForUpdates = async ({ installedVersion, signal }) => { + const cli = await resolveCli(); + if (!cli) return { status: "unknown", message: `${name} is not installed` }; + return checkForUpdates({ cli, installedVersion, signal }); + }; + } + + const update = options.update; + if (update) { + installation.update = async (context) => { + const cli = await resolveCli(); + if (!cli) return { status: "failed", message: `${name} is not installed` }; + return runUpdateCommand( + { + command: cli.command, + args: [...cli.args, ...update.args], + env: createProviderEnvSpec({ runtimeSettings }), + successMessage: update.successMessage, + }, + context, + ); + }; + } + return installation; +} diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 66f9dd198a10..0deef7db4445 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -25,6 +25,7 @@ import { type AgentRunOptions, type AgentRunResult, type AgentRuntimeInfo, + type AgentClientInstallation, type AgentSession, type AgentSessionConfig, type SteerActiveTurnOptions, @@ -71,6 +72,7 @@ import { normalizeCodexFilePath } from "./codex/tool-call-detail-parser.js"; import { checkProviderLaunchAvailable, createProviderEnv, + createProviderEnvSpec, resolveProviderLaunch, type ProviderRuntimeSettings, type ResolvedProviderLaunch, @@ -120,8 +122,18 @@ import { formatProviderDiagnosticError, buildBinaryDiagnosticRows, buildCommandResolutionDiagnosticRows, + readCommandVersionOutput, resolveBinaryVersion, } from "./diagnostic-utils.js"; +import { + compareWithLatestRelease, + fetchHomebrewCaskVersion, + fetchReleaseField, + homebrewCaskOf, + resolveExecutablePath, + type LatestReleaseLookup, +} from "./release-check.js"; +import { runUpdateCommand, updatedForNewAgents } from "./update-command.js"; import { appendOrReplaceGrowingAssistantMessage, runProviderTurn } from "./provider-runner.js"; import { MODE_APPLIES_NEXT_TURN_NOTICE, @@ -328,6 +340,8 @@ interface CodexAppServerProcessPort { interface CodexAppServerAgentDeps { appServerProcess?: CodexAppServerProcessPort; environment?: Record; + /** Where update checks learn the newest release; defaults to Codex's own release sources. */ + lookupLatestRelease?: LatestReleaseLookup; workspaceGitService?: Pick; customProvider?: { id: string; @@ -8009,9 +8023,71 @@ export class CodexAppServerAgentSession implements AgentSession { } } +const CODEX_INSTALL_URL = "https://developers.openai.com/codex/cli"; + +/** `codex --version` prints `codex-cli `; report the version part. */ +function readCodexVersionLabel(output: string): string | undefined { + const line = output.split("\n")[0]?.trim() ?? ""; + return line.replace(/^codex-cli\s+/i, "") || undefined; +} + +type InstalledCodex = + | { status: "not_installed" } + | { status: "installed"; version: string | undefined }; + +/** + * The release Codex's own updater offers: the Homebrew cask for cask installs, which lags + * upstream, otherwise the latest GitHub release, tagged `rust-v`. + */ +const lookupLatestCodexRelease: LatestReleaseLookup = async ({ executablePath, signal }) => { + const cask = homebrewCaskOf(executablePath); + if (cask) return fetchHomebrewCaskVersion(cask, signal); + const tag = await fetchReleaseField({ + url: "https://api.github.com/repos/openai/codex/releases/latest", + field: "tag_name", + signal, + }); + return tag.replace(/^rust-v/, ""); +}; + export class CodexAppServerAgentClient implements AgentClient { readonly provider = CODEX_PROVIDER; readonly capabilities = CODEX_APP_SERVER_CAPABILITIES; + readonly installation: AgentClientInstallation = { + installUrl: CODEX_INSTALL_URL, + updateUrl: CODEX_INSTALL_URL, + inspect: async ({ signal }) => { + const installed = await this.readInstalledCodex(signal); + return installed.status === "installed" + ? { status: "installed", version: installed.version } + : installed; + }, + checkForUpdates: async ({ installedVersion, signal }) => { + const installed = await this.resolveInstalledCommand(); + if (!installed) return { status: "unknown", message: "Codex is not installed" }; + const lookup = this.deps.lookupLatestRelease ?? lookupLatestCodexRelease; + const latest = await lookup({ + executablePath: await resolveExecutablePath(installed.executable), + signal, + }); + return compareWithLatestRelease({ installed: installedVersion, latest }); + }, + // `codex update` picks the updater for the install method: npm, bun, pnpm, Homebrew or the + // standalone installer, and exits non-zero with a reason when it cannot tell. + update: async (context) => { + const command = await this.resolveInstalledCommand(); + if (!command) return { status: "failed", message: "Codex is not installed" }; + return runUpdateCommand( + { + command: command.command, + args: [...command.args, "update"], + env: createProviderEnvSpec({ runtimeSettings: this.runtimeSettings }), + successMessage: updatedForNewAgents("Codex"), + }, + context, + ); + }, + }; private goalsEnabledPromise: Promise | null = null; private autoReviewEnabledPromise: Promise | null = null; @@ -8021,6 +8097,39 @@ export class CodexAppServerAgentClient implements AgentClient { private readonly deps: CodexAppServerAgentDeps = {}, ) {} + private async readInstalledCodex(signal: AbortSignal): Promise { + const installed = await this.resolveInstalledCommand(); + if (!installed) return { status: "not_installed" }; + const output = await readCommandVersionOutput({ + command: installed.command, + args: [...installed.args, "--version"], + env: this.runtimeSettings?.env, + signal, + }); + return { + status: "installed", + version: readCodexVersionLabel(output), + }; + } + + /** The command a session would launch, or null when Codex is not installed. */ + private async resolveInstalledCommand(): Promise<{ + command: string; + args: string[]; + executable: string; + } | null> { + const launch = await resolveCodexLaunch(this.runtimeSettings); + const availability = await checkCodexLaunchAvailable(launch); + if (!availability.available) return null; + const command = + launch.source === "override" ? launch.command : (availability.resolvedPath ?? launch.command); + return { + command, + args: [...launch.args], + executable: availability.resolvedPath ?? command, + }; + } + private sessionDeps(launchEnv: Record | undefined): CodexAppServerAgentDeps { return { ...this.deps, diff --git a/packages/server/src/server/agent/providers/copilot-acp-agent.ts b/packages/server/src/server/agent/providers/copilot-acp-agent.ts index 5307fe0d5e22..fc120a34c1d0 100644 --- a/packages/server/src/server/agent/providers/copilot-acp-agent.ts +++ b/packages/server/src/server/agent/providers/copilot-acp-agent.ts @@ -1,7 +1,11 @@ import type { Logger } from "pino"; import type { SessionConfigOption } from "@agentclientprotocol/sdk"; -import type { AgentCapabilityFlags, AgentMode } from "../agent-sdk-types.js"; +import type { + AgentCapabilityFlags, + AgentClientInstallation, + AgentMode, +} from "../agent-sdk-types.js"; import { checkProviderLaunchAvailable, resolveProviderLaunch, @@ -21,6 +25,14 @@ import { buildBinaryDiagnosticRows, buildCommandResolutionDiagnosticRows, } from "./diagnostic-utils.js"; +import { createCliInstallation } from "./cli-installation.js"; +import { updatedForNewAgents } from "./update-command.js"; + +const COPILOT_INSTALL_URL = + "https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli"; +// The command reference documents `copilot update`. +const COPILOT_UPDATE_URL = + "https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference"; const COPILOT_CAPABILITIES: AgentCapabilityFlags = { supportsStreaming: true, @@ -78,7 +90,15 @@ interface CopilotACPAgentClientOptions { runtimeSettings?: ProviderRuntimeSettings; } +/** `copilot --version` prints `GitHub Copilot CLI .` and a hint; report the version. */ +function readCopilotVersionLabel(output: string): string | undefined { + const line = output.split("\n")[0]?.trim() ?? ""; + return line.replace(/^GitHub Copilot CLI\s+/i, "").replace(/\.$/, "") || undefined; +} + export class CopilotACPAgentClient extends ACPAgentClient { + readonly installation: AgentClientInstallation; + constructor(options: CopilotACPAgentClientOptions) { super({ provider: "copilot", @@ -94,6 +114,16 @@ export class CopilotACPAgentClient extends ACPAgentClient { beforeModeWriter: beforeCopilotModeWriter, capabilities: COPILOT_CAPABILITIES, }); + // Copilot's updater lives in its native binary, so there is no known release source to check. + this.installation = createCliInstallation({ + name: "Copilot", + defaultBinary: "copilot", + runtimeSettings: options.runtimeSettings, + installUrl: COPILOT_INSTALL_URL, + updateUrl: COPILOT_UPDATE_URL, + versionLabel: readCopilotVersionLabel, + update: { args: ["update"], successMessage: updatedForNewAgents("Copilot") }, + }); } override async isAvailable(): Promise { diff --git a/packages/server/src/server/agent/providers/diagnostic-utils.ts b/packages/server/src/server/agent/providers/diagnostic-utils.ts index 670bd8075570..3b8753fd32a0 100644 --- a/packages/server/src/server/agent/providers/diagnostic-utils.ts +++ b/packages/server/src/server/agent/providers/diagnostic-utils.ts @@ -388,13 +388,21 @@ export async function buildCommandResolutionDiagnosticRows( ]; } +/** Run a version command and return its trimmed output, stdout first. Throws when it fails. */ +export async function readCommandVersionOutput( + invocation: BinaryDiagnosticVersionCommand & { signal?: AbortSignal }, +): Promise { + const { stdout, stderr } = await execCommand(invocation.command, invocation.args, { + ...createProviderEnvSpec({ runtimeSettings: { env: invocation.env } }), + timeout: 5_000, + signal: invocation.signal, + }); + return stdout.trim() || stderr.trim(); +} + async function resolveCommandVersion(invocation: BinaryDiagnosticVersionCommand): Promise { try { - const { stdout, stderr } = await execCommand(invocation.command, invocation.args, { - ...createProviderEnvSpec({ runtimeSettings: { env: invocation.env } }), - timeout: 5_000, - }); - return stdout.trim() || stderr.trim() || "unknown"; + return (await readCommandVersionOutput(invocation)) || "unknown"; } catch (error) { return `error: ${toDiagnosticErrorMessage(error)}`; } diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index 376274511e2f..48d3d28520de 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -12,6 +12,7 @@ import { type AgentClient, type AgentDraftControls, type AgentOptionControl, + type AgentClientInstallation, type AgentLaunchContext, type AgentMetadata, type AgentMode, @@ -79,6 +80,7 @@ import { getUserMessageText } from "./message-history.js"; import { mapOmpSystemNoticeToNotification } from "./system-notice.js"; import { materializeProviderImage } from "../provider-image-output.js"; import { OmpCliRuntime } from "./cli-runtime.js"; +import { createOmpInstallation } from "./installation.js"; import { listOmpImportableSessions, readOmpImportSessionConfig } from "./session-descriptor.js"; import type { OmpRuntime, OmpRuntimeSession, OmpStartSessionInput } from "./runtime.js"; import { OmpMcpBridge, type OmpBridgedToolIdentity } from "./mcp-bridge.js"; @@ -2285,6 +2287,7 @@ export class OmpAgentSession implements AgentSession { export class OmpAgentClient implements AgentClient { readonly provider: AgentProvider = OMP_PROVIDER; readonly capabilities: AgentCapabilityFlags = withOmpCapabilities(); + readonly installation: AgentClientInstallation; private readonly logger: Logger; private readonly runtimeSettings?: ProviderRuntimeSettings; @@ -2306,6 +2309,7 @@ export class OmpAgentClient implements AgentClient { ); this.logger = options.logger; this.runtimeSettings = runtimeSettings; + this.installation = createOmpInstallation(runtimeSettings); this.providerIdleScheduler = options.providerIdleScheduler; this.noTurnScheduler = options.noTurnScheduler; this.usagePollScheduler = options.usagePollScheduler; diff --git a/packages/server/src/server/agent/providers/omp/installation.ts b/packages/server/src/server/agent/providers/omp/installation.ts new file mode 100644 index 000000000000..211463d80877 --- /dev/null +++ b/packages/server/src/server/agent/providers/omp/installation.ts @@ -0,0 +1,62 @@ +import { stripVTControlCharacters } from "node:util"; +import type { ProviderUpdateCheck } from "@getpaseo/plugin/server/provider"; +import { execCommand } from "../../../../utils/spawn.js"; +import type { AgentClientInstallation } from "../../agent-sdk-types.js"; +import { + createProviderEnvSpec, + type ProviderRuntimeSettings, +} from "../../provider-launch-config.js"; +import { createCliInstallation, type InstalledCli } from "../cli-installation.js"; +import { updatedForNewAgents } from "../update-command.js"; + +const OMP_INSTALL_URL = "https://github.com/can1357/oh-my-pi#install"; + +/** + * Reads the answer of `omp update --check`, which asks the release source `omp update` installs + * from. Anything else it prints, such as an install that another tool keeps up to date, is + * reported as is. + */ +export function readOmpUpdateCheck(output: string): ProviderUpdateCheck { + const text = stripVTControlCharacters(output).trim(); + const available = /New version available:\s*(\S+)/.exec(text)?.[1]; + if (available) return { status: "available", versions: [available] }; + if (/Already up to date/i.test(text)) return { status: "current" }; + return { status: "unknown", message: text || "omp update --check printed nothing" }; +} + +async function checkOmpForUpdates(input: { + cli: InstalledCli; + runtimeSettings: ProviderRuntimeSettings | undefined; + signal: AbortSignal; +}): Promise { + const { stdout, stderr } = await execCommand( + input.cli.command, + [...input.cli.args, "update", "--check"], + { + ...createProviderEnvSpec({ runtimeSettings: input.runtimeSettings }), + timeout: 20_000, + signal: input.signal, + }, + ); + return readOmpUpdateCheck(`${stdout}\n${stderr}`); +} + +export function createOmpInstallation( + runtimeSettings: ProviderRuntimeSettings | undefined, +): AgentClientInstallation { + return createCliInstallation({ + name: "Oh My Pi", + defaultBinary: "omp", + runtimeSettings, + installUrl: OMP_INSTALL_URL, + updateUrl: OMP_INSTALL_URL, + // `omp --version` prints `omp/18.6.1`. + versionLabel: (output) => + output + .split("\n")[0] + ?.trim() + .replace(/^omp\//, "") || undefined, + checkForUpdates: ({ cli, signal }) => checkOmpForUpdates({ cli, runtimeSettings, signal }), + update: { args: ["update"], successMessage: updatedForNewAgents("Oh My Pi") }, + }); +} diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index 25447db71854..c7ece2820073 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -1,6 +1,7 @@ import type { Logger } from "pino"; import type { AgentClient, + AgentClientInstallation, AgentSessionConfig, AgentLaunchContext, AgentCreateSessionOptions, @@ -23,6 +24,13 @@ import type { OpenCodeV2AgentClient } from "./v2/agent.js"; import { resolveExternalOpenCodeServer } from "./v2/external-server.js"; import { withOpenCodeRuntimeNotice } from "./runtime-notice.js"; import { selectOpenCodeService } from "./v2/service-selection.js"; +import { createCliInstallation } from "../cli-installation.js"; + +const OPENCODE_INSTALL_URL = "https://opencode.ai/docs/"; +// Agents share a long-lived OpenCode server, and this client keeps the protocol it chose for the +// version it found. Neither changes until the daemon restarts. +const OPENCODE_UPDATED = + "OpenCode is updated. Restart the Paseo daemon to use the new version; agents keep the running OpenCode server until then."; // Keep the minimum aligned with the SDK and binary exercised by CI. const MINIMUM_V2: readonly [number, number] = [0, 10]; @@ -60,6 +68,7 @@ export class OpenCodeRuntimeClient implements AgentClient { private selected: Promise | null = null; private legacySelected = false; private readonly legacy: OpenCodeAgentClient; + readonly installation: AgentClientInstallation; constructor( private readonly logger: Logger, private readonly settings?: ProviderRuntimeSettings, @@ -69,6 +78,20 @@ export class OpenCodeRuntimeClient implements AgentClient { this.capabilities = this.legacy.capabilities; this.resolveCreateConfig = this.legacy.resolveCreateConfig; this.isCreateConfigUnattended = this.legacy.isCreateConfigUnattended; + // OpenCode's update source depends on its channel and install method, which only the binary + // knows, so it has no update check here. + this.installation = createCliInstallation({ + name: "OpenCode", + defaultBinary: "opencode", + runtimeSettings: settings, + installUrl: OPENCODE_INSTALL_URL, + versionLabel: (output) => + output + .split("\n")[0] + ?.trim() + .replace(/^opencode\s+/i, "") || undefined, + update: { args: ["upgrade"], successMessage: OPENCODE_UPDATED }, + }); } private selectService() { return selectOpenCodeService({ diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index ec3fd1e999fc..3a67400994ff 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -19,6 +19,7 @@ import { type AgentPermissionRequest, type AgentPermissionResponse, type AgentProviderNotice, + type AgentClientInstallation, type AgentPersistenceHandle, type AgentPromptInput, type AgentProvider, @@ -43,6 +44,13 @@ import { type ProviderRefreshContext, } from "../../agent-sdk-types.js"; import { importSessionFromPersistence } from "../../provider-session-import.js"; +import { createCliInstallation } from "../cli-installation.js"; +import { + compareWithLatestRelease, + fetchReleaseField, + type LatestReleaseLookup, +} from "../release-check.js"; +import { updatedForNewAgents } from "../update-command.js"; import { runProviderRefreshActivity } from "../../provider-refresh-deadline.js"; import { runProviderTurn } from "../provider-runner.js"; import { @@ -199,8 +207,15 @@ export interface PiRpcAgentClientOptions { runtimeSettings?: ProviderRuntimeSettings; runtime?: PiRuntime; usagePollScheduler?: PiUsagePollScheduler; + lookupLatestRelease?: LatestReleaseLookup; } +const PI_INSTALL_URL = "https://pi.dev/docs/latest/quickstart"; + +/** The release `pi update` installs, from the endpoint Pi's own version check reads. */ +const lookupLatestPiRelease: LatestReleaseLookup = ({ signal }) => + fetchReleaseField({ url: "https://pi.dev/api/latest-version", field: "version", signal }); + interface PiPromptPayload { text: string; images?: PiImageContent[]; @@ -2572,6 +2587,7 @@ export class PiRpcAgentSession implements AgentSession { export class PiRpcAgentClient implements AgentClient { readonly provider: AgentProvider; readonly capabilities: AgentCapabilityFlags; + readonly installation: AgentClientInstallation; private readonly logger: Logger; private readonly runtimeSettings?: ProviderRuntimeSettings; @@ -2585,6 +2601,21 @@ export class PiRpcAgentClient implements AgentClient { this.runtimeSettings = options.runtimeSettings; this.runtime = options.runtime; this.usagePollScheduler = options.usagePollScheduler; + const lookup = options.lookupLatestRelease ?? lookupLatestPiRelease; + this.installation = createCliInstallation({ + name: "Pi", + defaultBinary: PI_BINARY_COMMAND, + runtimeSettings: options.runtimeSettings, + installUrl: PI_INSTALL_URL, + updateUrl: PI_INSTALL_URL, + checkForUpdates: async ({ cli, installedVersion, signal }) => + compareWithLatestRelease({ + installed: installedVersion, + latest: await lookup({ executablePath: cli.command, signal }), + }), + // `--self` updates Pi itself and leaves installed Pi packages alone. + update: { args: ["update", "--self"], successMessage: updatedForNewAgents("Pi") }, + }); } async createSession( diff --git a/packages/server/src/server/agent/providers/provider-update-checks.test.ts b/packages/server/src/server/agent/providers/provider-update-checks.test.ts new file mode 100644 index 000000000000..7e56758d04b1 --- /dev/null +++ b/packages/server/src/server/agent/providers/provider-update-checks.test.ts @@ -0,0 +1,380 @@ +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import type { AgentClient } from "../agent-sdk-types.js"; +import { ClaudeAgentClient } from "./claude/agent.js"; +import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; +import { CopilotACPAgentClient } from "./copilot-acp-agent.js"; +import { OmpAgentClient } from "./omp/agent.js"; +import { OpenCodeRuntimeClient } from "./opencode/runtime-client.js"; +import { PiRpcAgentClient } from "./pi/agent.js"; +import type { LatestReleaseLookup } from "./release-check.js"; +import type { ProviderUpdateReport } from "@getpaseo/plugin/server/provider"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); +}); + +/** A command that prints `banner` for `--version`, the way the real CLI does. */ +async function versionCommand(banner: string): Promise<[string, string]> { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-update-check-")); + roots.push(root); + const script = path.join(root, "cli.mjs"); + await fs.writeFile(script, `console.log(${JSON.stringify(banner)});\n`); + return [process.execPath, script]; +} + +/** + * A command that, for `update`, writes `stdout` and `stderr` and exits with `exitCode`. Its + * arguments are recorded so the test can see which updater ran. + */ +async function updaterCommand(input: { + stdout: string; + stderr: string; + exitCode: number; +}): Promise<{ argv: [string, string]; recordedArgs: () => Promise }> { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-updater-")); + roots.push(root); + const script = path.join(root, "cli.mjs"); + const record = path.join(root, "args.json"); + await fs.writeFile( + script, + [ + `import { writeFileSync } from "node:fs";`, + `writeFileSync(${JSON.stringify(record)}, JSON.stringify(process.argv.slice(2)));`, + `process.stdout.write(${JSON.stringify(input.stdout)});`, + `process.stderr.write(${JSON.stringify(input.stderr)});`, + `process.exitCode = ${input.exitCode};`, + ].join("\n"), + ); + return { + argv: [process.execPath, script], + recordedArgs: async () => JSON.parse(await fs.readFile(record, "utf8")) as string[], + }; +} + +async function runUpdate(client: AgentClient) { + const output: ProviderUpdateReport[] = []; + const result = await client.installation?.update?.({ + signal: new AbortController().signal, + report: (event) => output.push(event), + }); + return { result, output }; +} + +function releases(latest: string) { + const lookups: string[] = []; + const lookup: LatestReleaseLookup = async ({ executablePath }) => { + lookups.push(executablePath); + return latest; + }; + return { lookup, lookups }; +} + +/** Checks the way the daemon does: with the version the inspection reported. */ +async function check(client: AgentClient) { + const signal = new AbortController().signal; + const inspection = await client.installation?.inspect?.({ signal }); + const installedVersion = inspection?.status === "installed" ? inspection.version : undefined; + return client.installation?.checkForUpdates?.({ installedVersion, signal }); +} + +const providers = [ + { + name: "Codex", + banner: (version: string) => `codex-cli ${version}`, + client: (argv: [string, string], lookupLatestRelease: LatestReleaseLookup) => + new CodexAppServerAgentClient( + createTestLogger(), + { command: { mode: "replace", argv } }, + { lookupLatestRelease }, + ), + }, + { + name: "Claude Code", + banner: (version: string) => `${version} (Claude Code)`, + client: (argv: [string, string], lookupLatestRelease: LatestReleaseLookup) => + new ClaudeAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + lookupLatestRelease, + }), + }, +]; + +describe.each(providers)("$name update", ({ client }) => { + test("runs the CLI's own update command and passes its output through", async () => { + const updater = await updaterCommand({ + stdout: "Updating via `npm install -g`...\nadded 1 package\n", + stderr: "npm warn deprecated\n", + exitCode: 0, + }); + const { result, output } = await runUpdate(client(updater.argv, releases("9.9.9").lookup)); + expect(await updater.recordedArgs()).toEqual(["update"]); + expect(result).toEqual({ status: "succeeded", message: expect.stringContaining("updated") }); + expect(output[0]).toEqual({ + type: "message", + text: `Running ${updater.argv.join(" ")} update\n`, + }); + expect( + output + .filter((event) => event.type === "stdout") + .map((event) => event.text) + .join(""), + ).toBe("Updating via `npm install -g`...\nadded 1 package\n"); + expect( + output + .filter((event) => event.type === "stderr") + .map((event) => event.text) + .join(""), + ).toBe("npm warn deprecated\n"); + }); + + test("fails with the exit code and keeps the updater's output", async () => { + const updater = await updaterCommand({ + stdout: "", + stderr: "Could not detect the installation method\n", + exitCode: 3, + }); + const { result, output } = await runUpdate(client(updater.argv, releases("9.9.9").lookup)); + expect(result).toEqual({ + status: "failed", + message: `${updater.argv.join(" ")} update exited with code 3`, + }); + expect(output).toContainEqual({ + type: "stderr", + text: "Could not detect the installation method\n", + }); + }); +}); + +describe.each(providers)("$name update check", ({ banner, client }) => { + test("reports the newer release as available, version as published", async () => { + const argv = await versionCommand(banner("0.165.0")); + const { lookup, lookups } = releases("0.168.0"); + await expect(check(client(argv, lookup))).resolves.toEqual({ + status: "available", + versions: ["0.168.0"], + }); + expect(lookups).toEqual([await fs.realpath(process.execPath)]); + }); + + test("reports current when the installed release is the latest or newer", async () => { + const argv = await versionCommand(banner("2.1.323")); + await expect(check(client(argv, releases("2.1.323").lookup))).resolves.toEqual({ + status: "current", + }); + await expect(check(client(argv, releases("2.1.311").lookup))).resolves.toEqual({ + status: "current", + }); + }); + + test("is inconclusive when the release channel answers something unreadable", async () => { + const argv = await versionCommand(banner("2.1.323")); + await expect(check(client(argv, releases("").lookup))).resolves.toEqual({ + status: "unknown", + message: "Unrecognized release ", + }); + }); +}); + +describe("Codex prerelease update check", () => { + const codex = providers[0]!; + const client = codex.client; + const banner = codex.banner; + + test("orders a prerelease before the release with the same numbers", async () => { + const prerelease = await versionCommand(banner("0.200.0-alpha.1")); + await expect(check(client(prerelease, releases("0.200.0").lookup))).resolves.toEqual({ + status: "available", + versions: ["0.200.0"], + }); + const release = await versionCommand(banner("0.200.0")); + await expect(check(client(release, releases("0.200.0-alpha.1").lookup))).resolves.toEqual({ + status: "current", + }); + }); + + test("is inconclusive between two prereleases of the same release", async () => { + const argv = await versionCommand(banner("0.200.0-alpha.1")); + await expect(check(client(argv, releases("0.200.0-alpha.2").lookup))).resolves.toEqual({ + status: "unknown", + message: "Cannot compare 0.200.0-alpha.1 with 0.200.0-alpha.2", + }); + }); +}); + +test("Claude Code is inconclusive when a wrapper command hides its version", async () => { + const argv = await versionCommand("cux 0.4.1"); + const { lookup, lookups } = releases("2.1.323"); + await expect(check(providers[1]!.client(argv, lookup))).resolves.toEqual({ + status: "unknown", + message: "The configured command does not report its version", + }); + expect(lookups).toEqual([]); +}); + +/** + * A command that answers `--version` with `banner` and any other invocation with `rest`, the way + * a CLI answers both its version and its update check. + */ +async function cliCommand(input: { banner: string; rest: string }): Promise<[string, string]> { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-cli-")); + roots.push(root); + const script = path.join(root, "cli.mjs"); + await fs.writeFile( + script, + [ + `const args = process.argv.slice(2);`, + `console.log(args.at(-1) === "--version" ? ${JSON.stringify(input.banner)} : ${JSON.stringify(input.rest)});`, + ].join("\n"), + ); + return [process.execPath, script]; +} + +function inspect(client: AgentClient) { + return client.installation?.inspect?.({ signal: new AbortController().signal }); +} + +const selfUpdatingClis = [ + { + name: "Copilot", + banner: "GitHub Copilot CLI 1.0.110.\nRun 'copilot update' to check for updates.", + version: "1.0.110", + updateArgs: ["update"], + successMessage: expect.stringContaining("New agents use the new version"), + client: (argv: [string, string]) => + new CopilotACPAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + }), + }, + { + name: "OpenCode", + banner: "1.19.5", + version: "1.19.5", + updateArgs: ["upgrade"], + // OpenCode runs one server for every agent, which keeps the old version until restarted. + successMessage: expect.stringContaining("Restart the Paseo daemon"), + client: (argv: [string, string]) => + new OpenCodeRuntimeClient(createTestLogger(), { command: { mode: "replace", argv } }), + }, + { + name: "Pi", + banner: "1.3.0", + version: "1.3.0", + updateArgs: ["update", "--self"], + successMessage: expect.stringContaining("New agents use the new version"), + client: (argv: [string, string]) => + new PiRpcAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + }), + }, + { + name: "Oh My Pi", + banner: "omp/18.6.1", + version: "18.6.1", + updateArgs: ["update"], + successMessage: expect.stringContaining("New agents use the new version"), + client: (argv: [string, string]) => + new OmpAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + }), + }, +]; + +describe.each(selfUpdatingClis)("$name installation", (cli) => { + test("reports the version the CLI prints", async () => { + const argv = await versionCommand(cli.banner); + await expect(inspect(cli.client(argv))).resolves.toEqual({ + status: "installed", + version: cli.version, + }); + }); + + test("updates with the CLI's own update command", async () => { + const updater = await updaterCommand({ stdout: "done\n", stderr: "", exitCode: 0 }); + const { result } = await runUpdate(cli.client(updater.argv)); + expect(await updater.recordedArgs()).toEqual(cli.updateArgs); + expect(result).toEqual({ status: "succeeded", message: cli.successMessage }); + }); + + test("is not installed when the command is missing", async () => { + const client = cli.client(["/nonexistent/paseo-cli", "--flag"]); + await expect(inspect(client)).resolves.toEqual({ status: "not_installed" }); + await expect(runUpdate(client)).resolves.toMatchObject({ + result: { status: "failed", message: `${cli.name} is not installed` }, + }); + }); +}); + +// The agent spawn looks the bare command up on the provider's PATH, so the installation does too. +test("Copilot reports the copy on the provider's PATH", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-provider-path-")); + roots.push(dir); + if (process.platform === "win32") { + await fs.writeFile( + path.join(dir, "copilot.cmd"), + "@echo off\r\necho GitHub Copilot CLI 9.9.9.\r\n", + ); + } else { + await fs.writeFile(path.join(dir, "copilot"), "#!/bin/sh\necho 'GitHub Copilot CLI 9.9.9.'\n", { + mode: 0o755, + }); + } + const client = new CopilotACPAgentClient({ + logger: createTestLogger(), + runtimeSettings: { env: { PATH: dir } }, + }); + await expect(inspect(client)).resolves.toEqual({ status: "installed", version: "9.9.9" }); +}); + +test("Pi checks the release its own update check reads", async () => { + const argv = await versionCommand("1.3.0"); + const { lookup, lookups } = releases("1.5.2"); + const client = new PiRpcAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + lookupLatestRelease: lookup, + }); + await expect(check(client)).resolves.toEqual({ status: "available", versions: ["1.5.2"] }); + expect(lookups).toEqual([await fs.realpath(process.execPath)]); +}); + +describe("Oh My Pi update check", () => { + async function ompCheck(answer: string) { + const argv = await cliCommand({ banner: "omp/18.6.1", rest: answer }); + return check( + new OmpAgentClient({ + logger: createTestLogger(), + runtimeSettings: { command: { mode: "replace", argv } }, + }), + ); + } + + test("reads the answer of `omp update --check`", async () => { + await expect(ompCheck("\u001b[32mNew version available: 18.7.0\u001b[0m")).resolves.toEqual({ + status: "available", + versions: ["18.7.0"], + }); + await expect(ompCheck("Already up to date")).resolves.toEqual({ status: "current" }); + }); + + test("passes through an install that another tool keeps up to date", async () => { + await expect(ompCheck("omp is kept up to date by mise")).resolves.toEqual({ + status: "unknown", + message: "omp is kept up to date by mise", + }); + }); +}); + +test("Copilot and OpenCode declare no update check", () => { + const argv: [string, string] = [process.execPath, "cli.mjs"]; + expect(selfUpdatingClis[0]!.client(argv).installation.checkForUpdates).toBeUndefined(); + expect(selfUpdatingClis[1]!.client(argv).installation.checkForUpdates).toBeUndefined(); +}); diff --git a/packages/server/src/server/agent/providers/release-check.ts b/packages/server/src/server/agent/providers/release-check.ts new file mode 100644 index 000000000000..4e54f6f10837 --- /dev/null +++ b/packages/server/src/server/agent/providers/release-check.ts @@ -0,0 +1,108 @@ +import { realpath } from "node:fs/promises"; +import type { ProviderUpdateCheck } from "@getpaseo/plugin/server/provider"; + +/** + * Returns the newest version a provider's release channel offers for the installed executable. + * Built-in providers inject this so tests can answer without the network. + */ +export type LatestReleaseLookup = (input: { + /** The executable the provider launches, symlinks resolved. */ + executablePath: string; + signal: AbortSignal; +}) => Promise; + +interface ReleaseVersion { + /** The version as written, such as `0.200.0-alpha.1`. */ + text: string; + numbers: [number, number, number]; + /** True for a prerelease such as `-alpha.1`, which comes before the release itself. */ + prerelease: boolean; +} + +function parseReleaseVersion(value: string): ReleaseVersion | null { + const match = value.match(/\b(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?/); + if (!match) return null; + return { + text: match[0], + numbers: [Number(match[1]), Number(match[2]), Number(match[3])], + prerelease: match[4] !== undefined, + }; +} + +/** Newer, older or the same release; `null` between two prereleases of one release. */ +function compareReleases(latest: ReleaseVersion, installed: ReleaseVersion): number | null { + for (let index = 0; index < 3; index += 1) { + const difference = latest.numbers[index] - installed.numbers[index]; + if (difference !== 0) return difference; + } + if (latest.prerelease && installed.prerelease) return latest.text === installed.text ? 0 : null; + if (installed.prerelease) return 1; + if (latest.prerelease) return -1; + return 0; +} + +/** + * Compares `major.minor.patch` releases, the scheme Claude Code, Codex and Pi publish. A + * prerelease comes before the release with the same numbers. + */ +export function compareWithLatestRelease(input: { + installed: string | null | undefined; + latest: string; +}): ProviderUpdateCheck { + const installed = input.installed ? parseReleaseVersion(input.installed) : null; + const latest = parseReleaseVersion(input.latest); + if (!installed) return { status: "unknown", message: "The installed version is not readable" }; + if (!latest) return { status: "unknown", message: `Unrecognized release ${input.latest}` }; + const order = compareReleases(latest, installed); + if (order === null) + return { status: "unknown", message: `Cannot compare ${installed.text} with ${latest.text}` }; + return order > 0 + ? { status: "available", versions: [input.latest.trim()] } + : { status: "current" }; +} + +/** Resolves symlinks so Homebrew and npm installs show their real location. */ +export async function resolveExecutablePath(executablePath: string): Promise { + try { + return await realpath(executablePath); + } catch { + return executablePath; + } +} + +/** The cask name when the executable lives in a Homebrew Caskroom, such as `codex`. */ +export function homebrewCaskOf(executablePath: string): string | null { + return executablePath.match(/\/Caskroom\/([^/]+)\//)?.[1] ?? null; +} + +async function fetchRelease(url: string, signal: AbortSignal): Promise { + const response = await fetch(url, { signal, headers: { "User-Agent": "paseo" } }); + if (!response.ok) throw new Error(`${url} returned ${response.status}`); + return response; +} + +export async function fetchReleaseText(url: string, signal: AbortSignal): Promise { + return (await (await fetchRelease(url, signal)).text()).trim(); +} + +/** Reads a string field from a JSON release document. */ +export async function fetchReleaseField(input: { + url: string; + field: string; + signal: AbortSignal; +}): Promise { + const body: unknown = await (await fetchRelease(input.url, input.signal)).json(); + const value = + body && typeof body === "object" ? (body as Record)[input.field] : undefined; + if (typeof value !== "string") throw new Error(`${input.url} has no ${input.field}`); + return value; +} + +/** The latest Homebrew cask version, which can lag the upstream release. */ +export function fetchHomebrewCaskVersion(cask: string, signal: AbortSignal): Promise { + return fetchReleaseField({ + url: `https://formulae.brew.sh/api/cask/${encodeURIComponent(cask)}.json`, + field: "version", + signal, + }); +} diff --git a/packages/server/src/server/agent/providers/update-command.ts b/packages/server/src/server/agent/providers/update-command.ts new file mode 100644 index 000000000000..6c7efc9c8c67 --- /dev/null +++ b/packages/server/src/server/agent/providers/update-command.ts @@ -0,0 +1,52 @@ +import type { ProviderUpdateResult } from "@getpaseo/plugin/server/provider"; +import { spawnProcess } from "../../../utils/spawn.js"; +import type { AgentClientUpdateContext } from "../agent-sdk-types.js"; +import type { ProviderEnvSpec } from "../provider-launch-config.js"; + +export interface UpdateCommand { + command: string; + args: string[]; + env: ProviderEnvSpec; + /** Shown when the command exits 0. */ + successMessage: string; +} + +/** The success message for a CLI that Paseo starts once per agent. */ +export function updatedForNewAgents(name: string): string { + return `${name} is updated. New agents use the new version; running agents keep theirs until restarted.`; +} + +/** + * Runs a CLI's own updater and passes its output through unchanged. Exit code 0 is success; + * anything else is a failure. Aborting the signal kills the command. + */ +export function runUpdateCommand( + update: UpdateCommand, + context: AgentClientUpdateContext, +): Promise { + const commandLine = [update.command, ...update.args].join(" "); + context.report({ type: "message", text: `Running ${commandLine}\n` }); + return new Promise((resolve, reject) => { + const child = spawnProcess(update.command, update.args, { + ...update.env, + stdio: ["ignore", "pipe", "pipe"], + signal: context.signal, + }); + child.stdout?.setEncoding("utf8"); + child.stderr?.setEncoding("utf8"); + child.stdout?.on("data", (text: string) => context.report({ type: "stdout", text })); + child.stderr?.on("data", (text: string) => context.report({ type: "stderr", text })); + child.once("error", reject); + child.once("close", (code, signal) => { + if (code === 0) resolve({ status: "succeeded", message: update.successMessage }); + else + resolve({ + status: "failed", + message: + code === null + ? `${commandLine} stopped by ${signal}` + : `${commandLine} exited with code ${code}`, + }); + }); + }); +} diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 2214f6bb5e1e..1199678c18d9 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -165,6 +165,11 @@ const INBOUND_PERMISSION = { "project.remove.request": "workspace.manage", "project.rename.request": "workspace.manage", project_icon_request: "workspace.read", + "provider.installation.inspect.request": "daemon.read", + "provider.installation.check_updates.request": "daemon.read", + // Runs the provider's updater on the host. + "provider.installation.update.request": "daemon.manage", + "provider.installation.update.subscribe.request": "daemon.read", "provider.usage.list.request": "daemon.read", "usage.list_reports.request": "daemon.read", provider_diagnostic_request: "daemon.read", @@ -420,6 +425,12 @@ const OUTBOUND_PERMISSION = { "project.rename.response": "workspace.manage", "project.update": "workspace.read", project_icon_response: "workspace.read", + "provider.installation.inspect.response": "daemon.read", + "provider.installation.check_updates.response": "daemon.read", + "provider.installation.update.response": "daemon.manage", + "provider.installation.update.subscribe.response": "daemon.read", + "provider.installation.update.progress": "daemon.read", + "provider.installation.update.cleared": "daemon.read", "provider.usage.list.response": "daemon.read", "usage.list_reports.update": "daemon.read", "usage.list_reports.response": "daemon.read", diff --git a/packages/server/src/server/daemon-e2e/models.e2e.test.ts b/packages/server/src/server/daemon-e2e/models.e2e.test.ts index a2064da0f1a1..124e42cd60a5 100644 --- a/packages/server/src/server/daemon-e2e/models.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/models.e2e.test.ts @@ -9,6 +9,7 @@ import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { execFileSync } from "node:child_process"; import { createDaemonTestContext } from "../test-utils/index.js"; +import { createTestAgentClient } from "../test-utils/fake-agent-client.js"; function isBinaryInstalled(binary: string): boolean { try { @@ -333,3 +334,188 @@ test("bundled Hoplite requires a config entry and removal survives restart", asy await rm(daemon.staticDir, { recursive: true, force: true }); } }, 60000); + +test("provider installation reaches the client: version unchanged, Install link when missing", async () => { + const version = " codex-cli 0.200.0-alpha+local (build 7)\n"; + const codex = Object.assign(createTestAgentClient("codex"), { + installation: { + installUrl: "https://example.com/codex/install", + async inspect() { + return { status: "installed" as const, version }; + }, + }, + }); + const daemon = await createTestPaseoDaemon({ + agentClients: { codex }, + mcpEnabled: false, + builtinPlugins: new BuiltinPluginLoader(undefined, ["muse-provider"]), + providerOverrides: { muse: { command: ["paseo-e2e-missing-muse"] } }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + expect(client.getLastServerInfoMessage()?.features?.providerInstallation).toBe(true); + await expect(client.inspectProviderInstallation("codex")).resolves.toMatchObject({ + provider: "codex", + error: null, + installation: { + installUrl: "https://example.com/codex/install", + inspection: { status: "installed", version }, + }, + }); + await expect(client.inspectProviderInstallation("muse")).resolves.toMatchObject({ + provider: "muse", + error: null, + installation: { + installUrl: "https://paseo.sh/docs/muse-code", + inspection: { status: "not_installed" }, + }, + }); + } finally { + await client.close(); + await daemon.close(); + } +}, 60000); + +test("provider update checks reach the client: versions unchanged, failures inconclusive", async () => { + const versions = [" 0.300.0-beta+x\n", "nightly (unstable)"]; + const message = " Restart Codex to finish\n"; + let codexChecks = 0; + const codex = Object.assign(createTestAgentClient("codex"), { + installation: { + async checkForUpdates() { + codexChecks += 1; + return { status: "available" as const, versions, message }; + }, + }, + }); + const claude = Object.assign(createTestAgentClient("claude"), { + installation: { + async checkForUpdates(): Promise { + throw new Error("release channel unreachable"); + }, + }, + }); + const daemon = await createTestPaseoDaemon({ + agentClients: { codex, claude }, + mcpEnabled: false, + builtinPlugins: new BuiltinPluginLoader(undefined, ["muse-provider"]), + providerOverrides: { muse: { command: ["paseo-e2e-missing-muse"] } }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await expect(client.checkProviderUpdates("codex")).resolves.toMatchObject({ + provider: "codex", + error: null, + updateCheck: { status: "available", versions, message }, + }); + await client.checkProviderUpdates("codex"); + expect(codexChecks).toBe(1); + await client.checkProviderUpdates("codex", { refresh: true }); + expect(codexChecks).toBe(2); + + await expect(client.checkProviderUpdates("claude")).resolves.toMatchObject({ + error: null, + updateCheck: { status: "error", message: "release channel unreachable" }, + }); + await expect(client.checkProviderUpdates("muse")).resolves.toMatchObject({ + error: null, + updateCheck: { status: "unknown", message: "Not installed" }, + }); + } finally { + await client.close(); + await daemon.close(); + } +}, 60000); + +test("a provider update outlives the client that started it and a new client reads it", async () => { + let version = "1.0.0"; + let updates = 0; + let finish!: () => void; + const finished = new Promise((resolve) => { + finish = resolve; + }); + const codex = Object.assign(createTestAgentClient("codex"), { + installation: { + async inspect() { + return { status: "installed" as const, version }; + }, + async update({ report }: { report: (event: { type: "stdout"; text: string }) => void }) { + updates += 1; + report({ type: "stdout", text: " step 1\r\n" }); + await finished; + report({ type: "stdout", text: " step 2\n" }); + version = "2.0.0"; + return { status: "succeeded" as const, message: " Restart agents \n" }; + }, + }, + }); + const daemon = await createTestPaseoDaemon({ + agentClients: { codex }, + mcpEnabled: false, + builtinPlugins: new BuiltinPluginLoader(undefined, []), + }); + const first = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + const second = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await first.connect(); + await expect(first.inspectProviderInstallation("codex")).resolves.toMatchObject({ + installation: { canUpdate: true, inspection: { version: "1.0.0" } }, + }); + const firstObservation = first.observeProviderUpdates("codex"); + const firstOutput: string[] = []; + firstObservation.subscribe({ + snapshot: () => {}, + update: (message) => { + if (message.type === "provider.installation.update.progress") + firstOutput.push(...message.payload.output.map((entry) => entry.text)); + }, + }); + await expect(firstObservation.ready).resolves.toMatchObject({ update: null }); + const started = await first.updateProvider("codex"); + expect(started).toMatchObject({ error: null, update: { operation: { status: "running" } } }); + await expect.poll(() => firstOutput).toEqual([" step 1\r\n"]); + await first.close(); + + await second.connect(); + const joined = await second.updateProvider("codex"); + expect(joined.update?.operation.id).toBe(started.update?.operation.id); + expect(updates).toBe(1); + + const observation = second.observeProviderUpdates("codex"); + let latest: { status: string; message?: string } | null = null; + const output: string[] = []; + observation.subscribe({ + snapshot: (snapshot) => { + latest = snapshot.update?.operation ?? null; + output.splice(0, output.length, ...(snapshot.update?.output ?? []).map((e) => e.text)); + }, + update: (message) => { + if (message.type !== "provider.installation.update.progress") return; + latest = message.payload.operation; + output.push(...message.payload.output.map((entry) => entry.text)); + }, + }); + await expect(observation.ready).resolves.toMatchObject({ + update: { + operation: { status: "running" }, + output: [{ type: "stdout", text: " step 1\r\n" }], + }, + }); + finish(); + await expect + .poll(() => latest) + .toMatchObject({ status: "succeeded", message: " Restart agents \n" }); + expect(output).toEqual([" step 1\r\n", " step 2\n"]); + await expect(second.inspectProviderInstallation("codex")).resolves.toMatchObject({ + installation: { inspection: { version: "2.0.0" } }, + }); + await observation.release(); + } finally { + finish(); + await first.close().catch(() => undefined); + await second.close(); + await daemon.close(); + } +}, 60000); diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 782bd59c58a7..59c75a97f4a7 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -308,6 +308,174 @@ describe("PluginService", () => { }, ); + it.each(["subprocess", "builtin"] as const)( + "carries a provider update's output and result through the %s plugin runtime", + async (runtime) => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const directory = await createPlugin( + "provider-update", + `export default function contribute(server) { + server.registerProvider({ id: "plugin-agent", label: "Plugin agent", command: ["agent"], + installation: { + async update({ launch, report }) { + report({ type: "message", text: "Running " + launch.command + " update\\n" }); + report({ type: "stdout", text: " added 1 package\\r\\n" }); + report({ type: "bogus", text: "dropped" }); + report({ type: "stderr", text: "warn \\u001b[33mold\\u001b[0m\\n" }); + if (launch.env.MODE === "throw") throw new Error(" updater crashed \\n"); + if (launch.env.MODE === "fail") return { status: "failed", message: " exit 3 \\n" }; + return { status: "succeeded", message: " Restart agents \\n" }; + }, + }, + async connect() { throw new Error("not connected by this test"); }, + }); + return () => {}; + }`, + ); + const store = createStore(home); + const builtinRoot = path.join(home, "builtins"); + if (runtime === "builtin") { + await mkdir(builtinRoot); + await cp(directory, path.join(builtinRoot, "provider-update"), { recursive: true }); + } + const builtinPlugins = new BuiltinPluginLoader( + builtinRoot, + runtime === "builtin" ? ["provider-update"] : [], + ); + const service = bindTestSessionHost( + new PluginService(pino({ level: "silent" }), store, "0.4.0", { builtinPlugins }), + ); + await service.start(); + try { + if (runtime === "subprocess") await service.installDirectory({ path: directory }); + const [registration] = service.getProviderRegistrations(); + const update = registration!.installation!.update!; + const run = async (env: Record) => { + const output: unknown[] = []; + const result = await update({ + launch: { command: "/bin/agent", args: [], env, resolved: true }, + signal: new AbortController().signal, + report: (event) => output.push(event), + }).catch((error: Error) => ({ thrown: error.message })); + return { result, output }; + }; + const output = [ + { type: "message", text: "Running /bin/agent update\n" }, + { type: "stdout", text: " added 1 package\r\n" }, + { type: "stderr", text: "warn \u001b[33mold\u001b[0m\n" }, + ]; + await expect(run({})).resolves.toEqual({ + result: { status: "succeeded", message: " Restart agents \n" }, + output, + }); + await expect(run({ MODE: "fail" })).resolves.toEqual({ + result: { status: "failed", message: " exit 3 \n" }, + output, + }); + await expect(run({ MODE: "throw" })).resolves.toEqual({ + result: { thrown: " updater crashed \n" }, + output, + }); + } finally { + await service.stopAllPlugins(); + } + }, + ); + + it.each(["subprocess", "builtin"] as const)( + "carries provider installation links, inspect and update checks through the %s plugin runtime", + async (runtime) => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const directory = await createPlugin( + "provider-installation", + `export default function contribute(server) { + server.registerProvider({ id: "plugin-agent", label: "Plugin agent", command: ["agent"], + installation: { + installUrl: "https://example.com/install", + updateUrl: "https://example.com/update", + async inspect({ launch, signal }) { + if (launch.env.HANG === "yes") + return await new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new Error("aborted")))); + if (!launch.resolved) return { status: "not_installed" }; + return { status: "installed", version: launch.command + " " + launch.env.VERSION }; + }, + async checkForUpdates({ launch, installedVersion, signal }) { + if (launch.env.HANG === "yes") + return await new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new Error("aborted")))); + if (launch.env.FEED === "down") throw new Error("feed down"); + return { status: "available", versions: [installedVersion, "nightly"], message: launch.env.NOTE }; + }, + }, + async connect() { throw new Error("not connected by this test"); }, + }); + return () => {}; + }`, + ); + const store = createStore(home); + const builtinRoot = path.join(home, "builtins"); + if (runtime === "builtin") { + await mkdir(builtinRoot); + await cp(directory, path.join(builtinRoot, "provider-installation"), { recursive: true }); + } + const builtinPlugins = new BuiltinPluginLoader( + builtinRoot, + runtime === "builtin" ? ["provider-installation"] : [], + ); + const service = bindTestSessionHost( + new PluginService(pino({ level: "silent" }), store, "0.4.0", { builtinPlugins }), + ); + await service.start(); + try { + if (runtime === "subprocess") await service.installDirectory({ path: directory }); + const [registration] = service.getProviderRegistrations(); + const installation = registration!.installation!; + expect(installation).toMatchObject({ + installUrl: "https://example.com/install", + updateUrl: "https://example.com/update", + }); + const signal = new AbortController().signal; + const launch = { command: "/bin/agent", args: [], env: { VERSION: " 1.0 (beta)\n" } }; + await expect( + installation.inspect!({ launch: { ...launch, resolved: true }, signal }), + ).resolves.toEqual({ status: "installed", version: "/bin/agent 1.0 (beta)\n" }); + await expect( + installation.inspect!({ launch: { ...launch, resolved: false }, signal }), + ).resolves.toEqual({ status: "not_installed" }); + await expect( + installation.checkForUpdates!({ + launch: { ...launch, env: { ...launch.env, NOTE: " Restart \n" }, resolved: true }, + installedVersion: " 1.0 (beta)\n", + signal, + }), + ).resolves.toEqual({ + status: "available", + versions: [" 1.0 (beta)\n", "nightly"], + message: " Restart \n", + }); + await expect( + installation.checkForUpdates!({ + launch: { ...launch, env: { FEED: "down" }, resolved: true }, + signal, + }), + ).rejects.toThrow("feed down"); + + for (const call of [installation.inspect!, installation.checkForUpdates!]) { + const abort = new AbortController(); + const hanging = call({ + launch: { ...launch, env: { HANG: "yes" }, resolved: true }, + signal: abort.signal, + }); + abort.abort(new Error("stop waiting")); + await expect(hanging).rejects.toThrow("stop waiting"); + } + } finally { + await service.stopAllPlugins(); + } + }, + ); + it("resolves a provider icon path to sanitized inline SVG", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); roots.push(home); diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 784acd523b94..b848b6130f32 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -3,7 +3,7 @@ import type { PluginLifecycle } from "./lifecycle/index.js"; import path from "node:path"; import { stat, rm } from "node:fs/promises"; import type pino from "pino"; -import type { ProviderRegistration } from "@getpaseo/plugin/server/provider"; +import type { ProviderInstallation, ProviderRegistration } from "@getpaseo/plugin/server/provider"; import { PluginIdSchema, type PluginLogEntry, @@ -27,7 +27,10 @@ import { runPluginBuild } from "./preparation.js"; import { PluginRuntime } from "./runtime.js"; import type { PluginRuntimeSubscription } from "./runtime-subscription.js"; import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js"; -import type { PluginProviderMetadata } from "./plugin-process-protocol.js"; +import type { + PluginProviderInstallationMetadata, + PluginProviderMetadata, +} from "./plugin-process-protocol.js"; import { readPluginProviderIcon } from "./provider-icon.js"; import { type AgentUsageLookup, @@ -59,6 +62,9 @@ interface PluginRuntimePort { connectProvider: PluginRuntime["connectProvider"]; getProviderCatalogCacheKey?: PluginRuntime["getProviderCatalogCacheKey"]; getProviderStatus?: PluginRuntime["getProviderStatus"]; + inspectProviderInstallation?: PluginRuntime["inspectProviderInstallation"]; + checkProviderUpdates?: PluginRuntime["checkProviderUpdates"]; + updateProvider?: PluginRuntime["updateProvider"]; validatePlugin?(path: string): Promise; startPlugin(pluginId: string, path: string, canPublish: () => boolean): Promise; startBuiltinPlugin?(plugin: BuiltinPlugin): Promise; @@ -727,6 +733,9 @@ export class PluginService { return this.runtime.getProviderCatalogCacheKey(pluginId, provider.id, options); } : undefined, + installation: provider.installation + ? this.providerInstallation(pluginId, provider.id, provider.installation) + : undefined, icon: provider.iconPath ? await readPluginProviderIcon(pluginDirectory, provider.iconPath) : undefined, @@ -746,6 +755,38 @@ export class PluginService { } } + private providerInstallation( + pluginId: string, + providerId: string, + metadata: PluginProviderInstallationMetadata, + ): ProviderInstallation { + return { + installUrl: metadata.installUrl, + updateUrl: metadata.updateUrl, + inspect: metadata.hasInspect + ? (context) => { + if (!this.runtime.inspectProviderInstallation) + throw new Error("Plugin runtime cannot inspect provider installations"); + return this.runtime.inspectProviderInstallation(pluginId, providerId, context); + } + : undefined, + checkForUpdates: metadata.hasCheckForUpdates + ? (context) => { + if (!this.runtime.checkProviderUpdates) + throw new Error("Plugin runtime cannot check provider updates"); + return this.runtime.checkProviderUpdates(pluginId, providerId, context); + } + : undefined, + update: metadata.hasUpdate + ? (context) => { + if (!this.runtime.updateProvider) + throw new Error("Plugin runtime cannot update providers"); + return this.runtime.updateProvider(pluginId, providerId, context); + } + : undefined, + }; + } + private removeProviderRegistrations(pluginId: string): void { const ids = this.providerIdsByPlugin.get(pluginId); if (!ids) return; diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index 2ddcc30457e6..b867d21e20af 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -6,9 +6,12 @@ import type { ProviderCatalogOptions, ProviderEvent, ProviderInput, + ProviderInstallationLaunch, ProviderStatusRequest, + ProviderUpdateReport, } from "@getpaseo/plugin/server/provider"; import { + ProviderUpdateReportSchema, ProviderEventSchema, ProviderInputSchema, ProviderLaunchSchema, @@ -19,6 +22,7 @@ export interface PluginProviderMetadata { requiresConfiguration?: boolean; hasCatalogCacheKey?: boolean; hasStatus?: boolean; + installation?: PluginProviderInstallationMetadata; command?: readonly [string, ...string[]]; id: string; label: string; @@ -26,6 +30,14 @@ export interface PluginProviderMetadata { iconPath?: string; } +export interface PluginProviderInstallationMetadata { + installUrl?: string; + updateUrl?: string; + hasInspect: boolean; + hasCheckForUpdates: boolean; + hasUpdate?: boolean; +} + export interface PluginUsageSourceMetadata { id: string; label: string; @@ -42,6 +54,19 @@ export type PluginProcessRequest = providerId: string; request: ProviderStatusRequest; } + | { + type: "provider.installation.inspect" | "provider.installation.update"; + requestId: string; + providerId: string; + request: { launch?: ProviderInstallationLaunch }; + } + | { + type: "provider.installation.check_updates"; + requestId: string; + providerId: string; + request: { launch?: ProviderInstallationLaunch; installedVersion?: string }; + } + | { type: "provider.installation.cancel"; requestId: string } | { type: "initialize"; pluginId: string; @@ -99,6 +124,7 @@ export type PluginProcessMessage = } | { type: "result"; requestId: string; output: unknown } | { type: "error"; requestId: string; error: string } + | { type: "provider.installation.report"; requestId: string; report: ProviderUpdateReport } | { type: "fatal"; error: string } | { type: "subscription.event"; subscriptionId: string; event: unknown } | { type: "subscription.closed"; subscriptionId: string; error?: string } @@ -132,6 +158,16 @@ const providerMetadataSchema = z requiresConfiguration: z.boolean().optional(), hasCatalogCacheKey: z.boolean().optional(), hasStatus: z.boolean().optional(), + installation: z + .object({ + installUrl: z.string().optional(), + updateUrl: z.string().optional(), + hasInspect: z.boolean(), + hasCheckForUpdates: z.boolean(), + hasUpdate: z.boolean().optional(), + }) + .strict() + .optional(), command: z.tuple([z.string().min(1)], z.string()).optional(), }) .strict(); @@ -142,6 +178,10 @@ const usageSourceMetadataSchema = z icon: z.string().optional(), }) .strict(); +const ProviderInstallationLaunchSchema = ProviderLaunchSchema.extend({ + resolved: z.boolean(), +}).strict(); + const providerConnectRequestSchema = z .object({ launch: ProviderLaunchSchema.optional(), @@ -187,6 +227,28 @@ export const PluginProcessRequestSchema: z.ZodType = z.dis request: z.object({ launch: ProviderLaunchSchema.optional() }).strict(), }) .strict(), + z + .object({ + type: z.enum(["provider.installation.inspect", "provider.installation.update"]), + requestId: z.string().min(1), + providerId: z.string().min(1), + request: z.object({ launch: ProviderInstallationLaunchSchema.optional() }).strict(), + }) + .strict(), + z + .object({ + type: z.literal("provider.installation.check_updates"), + requestId: z.string().min(1), + providerId: z.string().min(1), + request: z + .object({ + launch: ProviderInstallationLaunchSchema.optional(), + installedVersion: z.string().optional(), + }) + .strict(), + }) + .strict(), + z.object({ type: z.literal("provider.installation.cancel"), requestId: z.string() }).strict(), z .object({ type: z.literal("initialize"), @@ -308,6 +370,13 @@ export const PluginProcessMessageSchema: z.ZodType = z.dis z .object({ type: z.literal("error"), requestId: z.string().min(1), error: z.string() }) .strict(), + z + .object({ + type: z.literal("provider.installation.report"), + requestId: z.string().min(1), + report: ProviderUpdateReportSchema, + }) + .strict(), z.object({ type: z.literal("fatal"), error: z.string() }).strict(), z .object({ diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index 1c0d6bc4766e..5af2bab78579 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -29,6 +29,10 @@ import { type ProviderConnection, type ProviderRegistration, ProviderStatusSchema, + ProviderInspectionSchema, + ProviderUpdateCheckSchema, + ProviderUpdateReportSchema, + ProviderUpdateResultSchema, } from "@getpaseo/plugin/server/provider"; import { createPaseoApi, type PaseoApi } from "@getpaseo/client"; import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -42,6 +46,35 @@ function describeError(error: unknown): string { return error instanceof Error ? error.message : String(error); } +function isHttpUrl(value: string): boolean { + try { + const { protocol } = new URL(value); + return protocol === "https:" || protocol === "http:"; + } catch { + return false; + } +} + +function validateProviderInstallation( + id: string, + installation: ProviderRegistration["installation"], +): void { + if (installation === undefined) return; + for (const url of [installation.installUrl, installation.updateUrl]) { + if (url !== undefined && (typeof url !== "string" || !isHttpUrl(url))) + throw new Error(`Plugin provider ${id} installation links must be http(s) URLs`); + } + if (installation.inspect !== undefined && typeof installation.inspect !== "function") + throw new Error(`Invalid installation inspect callback for plugin provider ${id}`); + if ( + installation.checkForUpdates !== undefined && + typeof installation.checkForUpdates !== "function" + ) + throw new Error(`Invalid installation checkForUpdates callback for plugin provider ${id}`); + if (installation.update !== undefined && typeof installation.update !== "function") + throw new Error(`Invalid installation update callback for plugin provider ${id}`); +} + export interface PluginWorkerChannel { send(message: PluginProcessMessage, callback?: () => void): void; onMessage(handler: (message: PluginProcessRequest) => void): () => void; @@ -87,6 +120,7 @@ export function createPluginWorker(options: { { connection: ProviderConnection; unsubscribe: () => void; closing?: Promise } >(); const pendingProviderConnections = new Map(); + const installationRequests = new Map(); let cleanup: (() => void | Promise) | null = null; let daemonClient: DaemonClient | null = null; let paseo: PaseoApi | null = null; @@ -167,6 +201,7 @@ export function createPluginWorker(options: { } if (provider.status !== undefined && typeof provider.status !== "function") throw new Error(`Invalid status callback for plugin provider ${id}`); + validateProviderInstallation(id, provider.installation); if ( provider.command !== undefined && (provider.command.length === 0 || @@ -202,10 +237,83 @@ export function createPluginWorker(options: { requiresConfiguration: provider.requiresConfiguration, hasCatalogCacheKey: provider.getCatalogCacheKey !== undefined, hasStatus: provider.status !== undefined, + installation: provider.installation + ? { + installUrl: provider.installation.installUrl, + updateUrl: provider.installation.updateUrl, + hasInspect: provider.installation.inspect !== undefined, + hasCheckForUpdates: provider.installation.checkForUpdates !== undefined, + hasUpdate: provider.installation.update !== undefined, + } + : undefined, command: provider.command, }; } + /** Handles installation requests; returns false for any other message. */ + function handleInstallationMessage(message: PluginProcessRequest): boolean { + if (message.type === "provider.installation.cancel") { + installationRequests + .get(message.requestId) + ?.abort(new Error("Installation request canceled")); + return true; + } + if ( + message.type !== "provider.installation.inspect" && + message.type !== "provider.installation.check_updates" && + message.type !== "provider.installation.update" + ) + return false; + const controller = new AbortController(); + installationRequests.set(message.requestId, controller); + const context = { launch: message.request.launch, signal: controller.signal }; + const installedVersion = + message.type === "provider.installation.check_updates" + ? message.request.installedVersion + : undefined; + void (async () => { + const installation = providers.get(message.providerId)?.installation; + if (message.type === "provider.installation.update") { + if (!installation?.update) + throw new Error(`Provider has no update capability: ${message.providerId}`); + let settled = false; + const report = (event: unknown) => { + const parsed = ProviderUpdateReportSchema.safeParse(event); + if (settled || !parsed.success) return; + send({ + type: "provider.installation.report", + requestId: message.requestId, + report: parsed.data, + }); + }; + try { + return ProviderUpdateResultSchema.parse( + await installation.update({ ...context, report }), + ); + } finally { + settled = true; + } + } + if (message.type === "provider.installation.inspect") { + if (!installation?.inspect) + throw new Error(`Provider has no inspect capability: ${message.providerId}`); + return ProviderInspectionSchema.parse(await installation.inspect(context)); + } + if (!installation?.checkForUpdates) + throw new Error(`Provider has no checkForUpdates capability: ${message.providerId}`); + return ProviderUpdateCheckSchema.parse( + await installation.checkForUpdates({ ...context, installedVersion }), + ); + })() + .then( + (output) => send({ type: "result", requestId: message.requestId, output }), + (error) => + send({ type: "error", requestId: message.requestId, error: describeError(error) }), + ) + .finally(() => installationRequests.delete(message.requestId)); + return true; + } + async function connectProvider( message: Extract, ): Promise { @@ -367,6 +475,8 @@ export function createPluginWorker(options: { agentTools.close(); subscriptions.releaseAll(); for (const pending of pendingProviderConnections.values()) pending.tombstoned = true; + for (const request of installationRequests.values()) + request.abort(new Error("Plugin is stopping")); const currentCleanup = cleanup; cleanup = null; try { @@ -402,6 +512,9 @@ export function createPluginWorker(options: { function rejectWhileStopping(message: PluginProcessRequest): void { if ( message.type === "provider.status" || + message.type === "provider.installation.inspect" || + message.type === "provider.installation.check_updates" || + message.type === "provider.installation.update" || message.type === "provider.catalog_key" || message.type === "usage.fetch" || message.type === "usage.discover" || @@ -470,6 +583,47 @@ export function createPluginWorker(options: { else send({ type: "error", requestId: message.requestId, error: "Plugin API unavailable" }); } + /** Handles a provider's status, catalogue key and installation requests; false for others. */ + function handleProviderQueryMessage(message: PluginProcessRequest): message is Extract< + PluginProcessRequest, + { + type: + | "provider.status" + | "provider.catalog_key" + | "provider.installation.inspect" + | "provider.installation.check_updates" + | "provider.installation.update" + | "provider.installation.cancel"; + } + > { + if (message.type === "provider.status") { + void (async () => { + const provider = providers.get(message.providerId); + if (!provider || !provider.status) + throw new Error(`Provider has no status capability: ${message.providerId}`); + const output = ProviderStatusSchema.parse(await provider.status(message.request)); + send({ type: "result", requestId: message.requestId, output }); + })().catch((error) => + send({ type: "error", requestId: message.requestId, error: describeError(error) }), + ); + return true; + } + if (message.type === "provider.catalog_key") { + void (async () => { + const provider = providers.get(message.providerId); + if (!provider) throw new Error(`Unknown provider: ${message.providerId}`); + const output = await provider.getCatalogCacheKey?.(message.options); + if (output !== undefined && typeof output !== "string") + throw new Error("Invalid catalogue key"); + send({ type: "result", requestId: message.requestId, output }); + })().catch((error) => + send({ type: "error", requestId: message.requestId, error: describeError(error) }), + ); + return true; + } + return handleInstallationMessage(message); + } + function handleMessage(rawMessage: unknown): void { const parsed = PluginProcessRequestSchema.safeParse(rawMessage); if (!parsed.success) { @@ -512,31 +666,7 @@ export function createPluginWorker(options: { return; } if (handleToolMessage(message)) return; - if (message.type === "provider.status") { - void (async () => { - const provider = providers.get(message.providerId); - if (!provider || !provider.status) - throw new Error(`Provider has no status capability: ${message.providerId}`); - const output = ProviderStatusSchema.parse(await provider.status(message.request)); - send({ type: "result", requestId: message.requestId, output }); - })().catch((error) => - send({ type: "error", requestId: message.requestId, error: describeError(error) }), - ); - return; - } - if (message.type === "provider.catalog_key") { - void (async () => { - const provider = providers.get(message.providerId); - if (!provider) throw new Error(`Unknown provider: ${message.providerId}`); - const output = await provider.getCatalogCacheKey?.(message.options); - if (output !== undefined && typeof output !== "string") - throw new Error("Invalid catalogue key"); - send({ type: "result", requestId: message.requestId, output }); - })().catch((error) => - send({ type: "error", requestId: message.requestId, error: describeError(error) }), - ); - return; - } + if (handleProviderQueryMessage(message)) return; if (message.type === "usage.fetch" || message.type === "usage.discover") { handleUsageRequest(message); return; diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index fad1b78bd0d5..d4adb5a37403 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -4,7 +4,17 @@ import type { PluginWireBeforeRequests, PluginBeforeResults } from "./lifecycle/ import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js"; import type { UsageScope } from "@getpaseo/plugin/server/usage"; import { + ProviderInspectionSchema, + ProviderUpdateCheckSchema, + ProviderUpdateResultSchema, ProviderStatusSchema, + type ProviderInspection, + type ProviderUpdateCheck, + type ProviderUpdateContext, + type ProviderUpdateReport, + type ProviderUpdateResult, + type ProviderInstallationContext, + type ProviderUpdateCheckContext, type ProviderStatus, type ProviderStatusRequest, } from "@getpaseo/plugin/server/provider"; @@ -68,7 +78,15 @@ interface PluginChild { interface PendingInvocation { resolve: (output: unknown) => void; reject: (error: Error) => void; - timeout: ReturnType; + /** Absent for requests without a deadline. */ + timeout?: ReturnType; + report?: (report: ProviderUpdateReport) => void; +} + +interface PluginRequestOptions { + signal?: AbortSignal; + /** Receives `provider.installation.report` messages for the request. */ + report?: (report: ProviderUpdateReport) => void; } interface LoadedPlugin { @@ -267,6 +285,21 @@ function jsonTransportValue(value: Value): Value { return JSON.parse(encoded) as Value; } +function isInstallationRequest(message: PluginProcessRequest): boolean { + return ( + message.type === "provider.installation.inspect" || + message.type === "provider.installation.check_updates" || + message.type === "provider.installation.update" + ); +} + +function requestTimeoutMs(message: PluginProcessRequest): number | null { + if (message.type === "tool.call") return TOOL_CALL_TIMEOUT_MS; + // An updater runs as long as it needs; daemon shutdown aborts it. + if (message.type === "provider.installation.update") return null; + return REQUEST_TIMEOUT_MS; +} + function send(child: PluginChild, message: PluginProcessRequest): Promise { return new Promise((resolve, reject) => { child.send(message, (error) => { @@ -438,6 +471,69 @@ export class PluginRuntime { ); } + async inspectProviderInstallation( + pluginId: string, + providerId: string, + context: ProviderInstallationContext, + ): Promise { + const loaded = this.plugins.get(pluginId); + if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`); + return ProviderInspectionSchema.parse( + await this.request( + loaded, + { + type: "provider.installation.inspect", + requestId: randomUUID(), + providerId, + request: { launch: context.launch }, + }, + { signal: context.signal }, + ), + ); + } + + async checkProviderUpdates( + pluginId: string, + providerId: string, + context: ProviderUpdateCheckContext, + ): Promise { + const loaded = this.plugins.get(pluginId); + if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`); + return ProviderUpdateCheckSchema.parse( + await this.request( + loaded, + { + type: "provider.installation.check_updates", + requestId: randomUUID(), + providerId, + request: { launch: context.launch, installedVersion: context.installedVersion }, + }, + { signal: context.signal }, + ), + ); + } + + async updateProvider( + pluginId: string, + providerId: string, + context: ProviderUpdateContext, + ): Promise { + const loaded = this.plugins.get(pluginId); + if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`); + return ProviderUpdateResultSchema.parse( + await this.request( + loaded, + { + type: "provider.installation.update", + requestId: randomUUID(), + providerId, + request: { launch: context.launch }, + }, + { signal: context.signal, report: (report) => context.report(report) }, + ), + ); + } + async connectProvider( pluginId: string, providerId: string, @@ -732,7 +828,7 @@ export class PluginRuntime { return (await this.request( loaded, { type: "tool.call", requestId, agent, name, input }, - signal, + { signal }, )) as AgentToolResult; } catch (error) { if (signal?.aborted) throw error; @@ -743,8 +839,9 @@ export class PluginRuntime { private request( loaded: LoadedPlugin, message: Extract, - signal?: AbortSignal, + options: PluginRequestOptions = {}, ): Promise { + const { signal, report } = options; const child = loaded.child; const pluginId = loaded.id; if (!child) throw new Error(`Plugin ${pluginId} has no server entry`); @@ -756,27 +853,34 @@ export class PluginRuntime { loaded.pending.delete(requestId); if (message.type === "tool.call") void send(child, { type: "tool.cancel", requestId }).catch(() => {}); + if (isInstallationRequest(message)) + void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {}); signal?.removeEventListener("abort", cancel); reject(signal?.reason ?? new Error("Tool call canceled")); }; - const timeout = setTimeout( - () => { - loaded.pending.delete(requestId); - signal?.removeEventListener("abort", cancel); - if (message.type === "tool.call") - void send(child, { type: "tool.cancel", requestId }).catch(() => {}); - if (message.type === "hook") { - void send(child, { type: "hook.cancel", requestId }).catch(() => {}); - } - // The handler may still start after the daemon gave up on it. - if (message.type === "subscribe") { - const { subscriptionId } = message; - void send(child, { type: "unsubscribe", subscriptionId }).catch(() => {}); - } - reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`)); - }, - message.type === "tool.call" ? TOOL_CALL_TIMEOUT_MS : REQUEST_TIMEOUT_MS, - ); + const timeoutMs = requestTimeoutMs(message); + const timeout = + timeoutMs === null + ? undefined + : setTimeout(() => { + loaded.pending.delete(requestId); + signal?.removeEventListener("abort", cancel); + if (message.type === "tool.call") + void send(child, { type: "tool.cancel", requestId }).catch(() => {}); + if (message.type === "hook") { + void send(child, { type: "hook.cancel", requestId }).catch(() => {}); + } + // The handler may still start after the daemon gave up on it. + if (message.type === "subscribe") { + const { subscriptionId } = message; + void send(child, { type: "unsubscribe", subscriptionId }).catch(() => {}); + } + if (isInstallationRequest(message)) + void send(child, { type: "provider.installation.cancel", requestId }).catch( + () => {}, + ); + reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`)); + }, timeoutMs); signal?.addEventListener("abort", cancel, { once: true }); loaded.pending.set(requestId, { resolve: (value) => { @@ -788,6 +892,7 @@ export class PluginRuntime { reject(error); }, timeout, + report, }); void send(child, message).catch((error) => { clearTimeout(timeout); @@ -1055,6 +1160,10 @@ export class PluginRuntime { this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId); return; } + if (message.type === "provider.installation.report") { + loaded.pending.get(message.requestId)?.report?.(message.report); + return; + } if (message.type.startsWith("provider.")) { this.handleProviderMessage(loaded, message); return; diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index df317e94cfb6..020f9272701b 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -2628,12 +2628,39 @@ export class Session { }); } + private async subscribeProviderUpdates( + request: Extract< + SessionInboundMessage, + { type: "provider.installation.update.subscribe.request" } + >, + ): Promise { + if (!this.delivery.isModern(this.delivery.currentSource)) + throw new Error("Provider update observation requires owned subscriptions"); + const installations = this.providerSnapshotManager.installations; + let stop: (() => void) | undefined; + const owner = this.delivery.begin("provider-update", undefined, () => stop?.()); + // Register and read in one synchronous turn so no progress falls between them. + stop = installations.observeUpdates(request.provider, (event) => owner.emit(event)); + this.emit({ + type: "provider.installation.update.subscribe.response", + payload: { + requestId: request.requestId, + subscriptionId: owner.responseId, + provider: request.provider, + update: installations.getUpdate(request.provider), + error: null, + }, + }); + } + private dispatchSubscriptionMessage( msg: SessionInboundMessage, source?: object, ): Promise | undefined { if (msg.type === "workspace.setup.subscribe.request") return this.subscribeWorkspaceSetup(msg); if (msg.type === "browser.host.register.request") return this.registerBrowserHost(msg); + if (msg.type === "provider.installation.update.subscribe.request") + return this.subscribeProviderUpdates(msg); if (msg.type === "browser.automation.execute.response") { if (source) this.browserToolsBroker?.receiveResponse( @@ -3531,6 +3558,12 @@ export class Session { return this.providerCatalogSession.handleRefreshProvidersSnapshotRequest(msg); case "provider_diagnostic_request": return this.providerCatalogSession.handleProviderDiagnosticRequest(msg); + case "provider.installation.inspect.request": + return this.providerCatalogSession.handleInspectProviderInstallationRequest(msg); + case "provider.installation.check_updates.request": + return this.providerCatalogSession.handleCheckProviderUpdatesRequest(msg); + case "provider.installation.update.request": + return this.providerCatalogSession.handleUpdateProviderRequest(msg); case "provider.usage.list.request": return this.usageSession.handleLegacyList(msg); case "usage.list_reports.request": diff --git a/packages/server/src/server/session/provider/provider-catalog-session.ts b/packages/server/src/server/session/provider/provider-catalog-session.ts index ee9560f8127e..ed8c62254c57 100644 --- a/packages/server/src/server/session/provider/provider-catalog-session.ts +++ b/packages/server/src/server/session/provider/provider-catalog-session.ts @@ -517,6 +517,77 @@ export class ProviderCatalogSession { }); } } + + async handleInspectProviderInstallationRequest( + msg: Extract, + ): Promise { + const response = { provider: msg.provider, requestId: msg.requestId }; + try { + const installation = await this.providerSnapshotManager.installations.inspect(msg.provider, { + refresh: msg.refresh, + }); + this.host.emit({ + type: "provider.installation.inspect.response", + payload: { ...response, installation, error: null }, + }); + } catch (error) { + this.host.emit({ + type: "provider.installation.inspect.response", + payload: { + ...response, + installation: null, + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } + + async handleUpdateProviderRequest( + msg: Extract, + ): Promise { + const response = { provider: msg.provider, requestId: msg.requestId }; + try { + const update = this.providerSnapshotManager.installations.update(msg.provider); + this.host.emit({ + type: "provider.installation.update.response", + payload: { ...response, update, error: null }, + }); + } catch (error) { + this.host.emit({ + type: "provider.installation.update.response", + payload: { + ...response, + update: null, + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } + + async handleCheckProviderUpdatesRequest( + msg: Extract, + ): Promise { + const response = { provider: msg.provider, requestId: msg.requestId }; + try { + const updateCheck = await this.providerSnapshotManager.installations.checkForUpdates( + msg.provider, + { refresh: msg.refresh }, + ); + this.host.emit({ + type: "provider.installation.check_updates.response", + payload: { ...response, updateCheck, error: null }, + }); + } catch (error) { + this.host.emit({ + type: "provider.installation.check_updates.response", + payload: { + ...response, + updateCheck: null, + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } } function resolveCatalogRequestCwd(cwd?: string | null): string | undefined { diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 37e82203e8a1..ed24eaffeda6 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2048,6 +2048,7 @@ export class VoiceAssistantWebSocketServer { relayProtectedSecurity: true, usageSetting: true, usageSources: true, + providerInstallation: true, ownedSubscriptions: true, providerOptionControls: true, entityMetadata: true, diff --git a/plugins/antigravity-provider/server/provider.test.ts b/plugins/antigravity-provider/server/provider.test.ts index 351925c308d7..ca635794d896 100644 --- a/plugins/antigravity-provider/server/provider.test.ts +++ b/plugins/antigravity-provider/server/provider.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpdir } from "node:os"; import type { ProviderEvent } from "@getpaseo/plugin/server/provider"; -import { afterEach, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { createAntigravityProvider } from "./provider.js"; const directories: string[] = []; @@ -184,3 +184,32 @@ it.each([true, false])( } }, ); + +describe("installation", () => { + const signal = new AbortController().signal; + + it("reports the version agy prints and links its install docs", async () => { + // A real `agy acp --version` starts the ACP server, so the fake refuses it. + const { launch } = await launchAgent(` + const args = process.argv.slice(2); + if (args.includes("acp")) process.exit(1); + if (args[0] === "--version") console.log("Antigravity CLI 1.6.2"); + `); + const installation = createAntigravityProvider().installation!; + expect(installation.installUrl).toBe("https://antigravity.google/docs/getting-started?tab=cli"); + expect(installation.update).toBeUndefined(); + await expect( + installation.inspect!({ launch: { ...launch, resolved: true }, signal }), + ).resolves.toEqual({ + status: "installed", + version: "1.6.2", + }); + }); + + it("is not installed when the executable does not resolve", async () => { + const launch = { command: "agy", args: ["acp"], env: {}, resolved: false }; + await expect( + createAntigravityProvider().installation!.inspect!({ launch, signal }), + ).resolves.toEqual({ status: "not_installed" }); + }); +}); diff --git a/plugins/antigravity-provider/server/provider.ts b/plugins/antigravity-provider/server/provider.ts index 4b6c81d0c398..417a36d8864c 100644 --- a/plugins/antigravity-provider/server/provider.ts +++ b/plugins/antigravity-provider/server/provider.ts @@ -1,6 +1,8 @@ +import { execCommand } from "@getpaseo/plugin/server"; import { runAcpProvider, type AcpTransformer } from "@getpaseo/plugin/server/acp"; import { PROVIDER_PROTOCOL_VERSION, + type ProviderInstallationLaunch, type ProviderRegistration, } from "@getpaseo/plugin/server/provider"; import { z } from "zod"; @@ -65,6 +67,24 @@ const antigravity: AcpTransformer = { }, }; +/** The release `agy --version` reports, or its first line when it names no release. */ +async function readAgyVersion( + launch: ProviderInstallationLaunch, + signal: AbortSignal, +): Promise { + // The launch ends with the `acp` subcommand and its flags; the version comes from the CLI itself. + const acp = launch.args.indexOf("acp"); + const prefix = acp === -1 ? launch.args : launch.args.slice(0, acp); + const { stdout } = await execCommand(launch.command, [...prefix, "--version"], { + env: launch.env, + timeout: 5000, + maxBuffer: 8192, + signal, + }); + const firstLine = stdout.trim().split("\n")[0]?.trim(); + return /\b\d+\.\d+\.\d+\S*/.exec(stdout)?.[0] ?? (firstLine || undefined); +} + export function createAntigravityProvider(): ProviderRegistration { const provider = runAcpProvider({ id: "antigravity", @@ -91,6 +111,15 @@ export function createAntigravityProvider(): ProviderRegistration { }); return { ...provider, + // agy documents no update command and no release source, so there is nothing to check or run. + installation: { + installUrl: "https://antigravity.google/docs/getting-started?tab=cli", + async inspect({ launch, signal }) { + if (!launch?.resolved) return { status: "not_installed" }; + const version = await readAgyVersion(launch, signal); + return version ? { status: "installed", version } : { status: "installed" }; + }, + }, async status({ launch }) { if (!launch) return { available: false, diagnostic: "Install Antigravity 1.5.0 or later." }; try { diff --git a/plugins/hoplite-provider/server/installation.test.ts b/plugins/hoplite-provider/server/installation.test.ts new file mode 100644 index 000000000000..e44b4f2d4e74 --- /dev/null +++ b/plugins/hoplite-provider/server/installation.test.ts @@ -0,0 +1,106 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import type { ProviderInstallationLaunch } from "@getpaseo/plugin/server/provider"; +import { createHopliteInstallation } from "./installation.js"; + +const temporary: string[] = []; +const signal = new AbortController().signal; + +afterEach(async () => { + await Promise.all(temporary.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +/** A `hoplite` that records its arguments and prints `banner` for `--version`. */ +async function fakeHoplite(banner: string) { + const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-hoplite-")); + temporary.push(dir); + const script = path.join(dir, "hoplite.mjs"); + const record = path.join(dir, "args.json"); + await writeFile( + script, + [ + `import { writeFileSync } from "node:fs";`, + `writeFileSync(${JSON.stringify(record)}, JSON.stringify(process.argv.slice(2)));`, + `console.log(${JSON.stringify(banner)});`, + ].join("\n"), + ); + // Sessions launch `hoplite acp` plus any configured arguments. + const launch: ProviderInstallationLaunch = { + command: process.execPath, + args: [script, "acp", "--verbose"], + env: {}, + resolved: true, + }; + return { launch, args: async () => JSON.parse(await readFile(record, "utf8")) as string[] }; +} + +function latest(version: string) { + return async () => version; +} + +describe("Hoplite installation", () => { + it("reads the version from the launch without `acp`", async () => { + const hoplite = await fakeHoplite("3.4.0"); + const installation = createHopliteInstallation(latest("3.5.1")); + await expect(installation.inspect!({ launch: hoplite.launch, signal })).resolves.toEqual({ + status: "installed", + version: "3.4.0", + }); + expect(await hoplite.args()).toEqual(["--version"]); + }); + + it("compares the installed version with the release the installer reads", async () => { + const hoplite = await fakeHoplite("3.4.0"); + const check = (release: string) => + createHopliteInstallation(latest(release)).checkForUpdates!({ + launch: hoplite.launch, + installedVersion: "3.4.0", + signal, + }); + await expect(check("3.5.1")).resolves.toEqual({ status: "available", versions: ["3.5.1"] }); + await expect(check("3.4.0")).resolves.toEqual({ status: "current" }); + await expect(check("3.3.9")).resolves.toEqual({ status: "current" }); + await expect(check("")).resolves.toEqual({ + status: "unknown", + message: "Unrecognized release ", + }); + await expect( + createHopliteInstallation(latest("3.5.1")).checkForUpdates!({ + launch: hoplite.launch, + installedVersion: "hoplite (dev build)", + signal, + }), + ).resolves.toEqual({ status: "unknown", message: "The installed version is not readable" }); + }); + + it("does not check when the user turned Hoplite's update check off", async () => { + const hoplite = await fakeHoplite("3.4.0"); + const launch = { ...hoplite.launch, env: { HOPLITE_NO_UPDATE_CHECK: "1" } }; + await expect( + createHopliteInstallation(latest("3.5.1")).checkForUpdates!({ + launch, + installedVersion: "3.4.0", + signal, + }), + ).resolves.toEqual({ + status: "unknown", + message: "HOPLITE_NO_UPDATE_CHECK turns update checks off", + }); + }); + + it("links the upgrade docs and runs no updater, since the CLI does not update itself", () => { + const installation = createHopliteInstallation(); + expect(installation.updateUrl).toBe("https://hoplite.sh/docs/cli#upgrade"); + expect(installation.update).toBeUndefined(); + }); + + it("is not installed when the executable does not resolve", async () => { + const launch = { command: "hoplite", args: ["acp"], env: {}, resolved: false }; + const installation = createHopliteInstallation(latest("3.5.1")); + await expect(installation.inspect!({ launch, signal })).resolves.toEqual({ + status: "not_installed", + }); + }); +}); diff --git a/plugins/hoplite-provider/server/installation.ts b/plugins/hoplite-provider/server/installation.ts new file mode 100644 index 000000000000..0870cffc7268 --- /dev/null +++ b/plugins/hoplite-provider/server/installation.ts @@ -0,0 +1,83 @@ +import { execCommand } from "@getpaseo/plugin/server"; +import type { + ProviderInstallation, + ProviderInstallationLaunch, + ProviderUpdateCheck, +} from "@getpaseo/plugin/server/provider"; + +/** The file Hoplite's installer and its own update check read for the current release. */ +const LATEST_RELEASE_URL = "https://hoplite.sh/downloads/latest.json"; + +export type LatestHopliteRelease = (signal: AbortSignal) => Promise; + +type Release = [number, number, number]; + +function parseRelease(text: string): Release | null { + const match = /\b(\d+)\.(\d+)\.(\d+)\b/.exec(text); + return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null; +} + +function isNewer(latest: Release, installed: Release): boolean { + for (let index = 0; index < 3; index += 1) { + if (latest[index] !== installed[index]) return latest[index] > installed[index]; + } + return false; +} + +async function fetchLatestRelease(signal: AbortSignal): Promise { + const response = await fetch(LATEST_RELEASE_URL, { signal }); + if (!response.ok) throw new Error(`${LATEST_RELEASE_URL} returned ${response.status}`); + const body: unknown = await response.json(); + const version = + body && typeof body === "object" ? (body as Record).version : undefined; + if (typeof version !== "string") throw new Error(`${LATEST_RELEASE_URL} has no version`); + return version; +} + +/** + * Sessions run `hoplite acp` followed by any configured arguments. The version comes from the + * part of the launch before `acp`, so `npx hoplite acp` reads `npx hoplite --version`. + */ +async function readVersion( + launch: ProviderInstallationLaunch, + signal: AbortSignal, +): Promise { + const acp = launch.args.indexOf("acp"); + const args = acp === -1 ? launch.args : launch.args.slice(0, acp); + const { stdout } = await execCommand(launch.command, [...args, "--version"], { + env: launch.env, + timeout: 5000, + maxBuffer: 8192, + signal, + }); + const firstLine = stdout.trim().split("\n")[0]?.trim(); + return /\b\d+\.\d+\.\d+\S*/.exec(stdout)?.[0] ?? (firstLine || undefined); +} + +export function createHopliteInstallation( + latestRelease: LatestHopliteRelease = fetchLatestRelease, +): ProviderInstallation { + return { + installUrl: "https://hoplite.sh/docs/cli#install", + // The CLI does not update itself; its docs list the command for each install method. + updateUrl: "https://hoplite.sh/docs/cli#upgrade", + async inspect({ launch, signal }) { + if (!launch?.resolved) return { status: "not_installed" }; + const version = await readVersion(launch, signal); + return version ? { status: "installed", version } : { status: "installed" }; + }, + async checkForUpdates({ launch, installedVersion, signal }): Promise { + if (launch?.env.HOPLITE_NO_UPDATE_CHECK === "1") + return { status: "unknown", message: "HOPLITE_NO_UPDATE_CHECK turns update checks off" }; + const installed = parseRelease(installedVersion ?? ""); + if (!installed) + return { status: "unknown", message: "The installed version is not readable" }; + const latestText = (await latestRelease(signal)).trim(); + const latest = parseRelease(latestText); + if (!latest) return { status: "unknown", message: `Unrecognized release ${latestText}` }; + return isNewer(latest, installed) + ? { status: "available", versions: [latestText] } + : { status: "current" }; + }, + }; +} diff --git a/plugins/hoplite-provider/server/provider.ts b/plugins/hoplite-provider/server/provider.ts index cb362052eaec..74828eab7612 100644 --- a/plugins/hoplite-provider/server/provider.ts +++ b/plugins/hoplite-provider/server/provider.ts @@ -1,5 +1,6 @@ import { runAcpProvider } from "@getpaseo/plugin/server/acp"; import type { ProviderRegistration } from "@getpaseo/plugin/server/provider"; +import { createHopliteInstallation } from "./installation.js"; import { runPhaseTransformer } from "./run-phase.js"; export function createHopliteProvider(): ProviderRegistration { @@ -14,5 +15,6 @@ export function createHopliteProvider(): ProviderRegistration { acpOptions: { workspaceOnlyCatalog: true }, transformers: [runPhaseTransformer], }), + installation: createHopliteInstallation(), }; } diff --git a/plugins/muse-provider/server/provider.ts b/plugins/muse-provider/server/provider.ts index 8d9a3ddfea34..525d9b51e32a 100644 --- a/plugins/muse-provider/server/provider.ts +++ b/plugins/muse-provider/server/provider.ts @@ -17,6 +17,11 @@ import { MuseError, actionableError } from "./errors.js"; import { Sessions } from "./sessions.js"; import { Session } from "./session.js"; import { accountSchema } from "./wire.js"; +import { + checkMuseForUpdates, + readMuseChannelRelease, + type ReadMuseChannelRelease, +} from "./updates.js"; const capabilities = [ "prompt.message", @@ -29,12 +34,39 @@ const capabilities = [ "session.list", ] as const; -export function createMuseProvider(usage: Usage): ProviderRegistration { +export interface MuseProviderOptions { + /** Reads a Muse update channel; defaults to the channel the `muse` launcher updates from. */ + readChannelRelease?: ReadMuseChannelRelease; +} + +export function createMuseProvider( + usage: Usage, + museOptions: MuseProviderOptions = {}, +): ProviderRegistration { return { id: "muse", label: "Muse Code", icon: "icon.svg", command: ["muse"], + installation: { + installUrl: "https://paseo.sh/docs/muse-code", + async inspect({ launch, signal }) { + if (!launch?.resolved) return { status: "not_installed" }; + const version = await readVersion(launch, signal); + // The build identifies a release; several builds share one x.y.z. + return version + ? { status: "installed", version: version.build ?? version.text } + : { status: "installed" }; + }, + async checkForUpdates({ launch, installedVersion, signal }) { + return checkMuseForUpdates({ + installedVersion, + env: launch?.env, + readChannelRelease: museOptions.readChannelRelease ?? readMuseChannelRelease, + signal, + }); + }, + }, async getCatalogCacheKey(options) { return launchKey(requireLaunch(options.launch)); }, @@ -60,24 +92,39 @@ function requireLaunch(launch: ProviderLaunch | undefined): ProviderLaunch { if (!launch) throw new MuseError("missingLaunch", "Muse requires a daemon-resolved executable"); return launch; } +interface MuseVersion { + text: string; + major: number; + minor: number; + /** The build in parentheses, as in `Muse Code 1.4.18 (1.4.18-R8587.1)`. */ + build: string | null; +} +/** The `x.y.z` that `muse --version` prints, or null when the output has none. */ +async function readVersion( + launch: ProviderLaunch, + signal?: AbortSignal, +): Promise { + const { stdout } = await execCommand(launch.command, [...launch.args, "--version"], { + env: launch.env, + timeout: 3000, + maxBuffer: 8192, + signal, + }); + const match = /\b(\d+)\.(\d+)\.(\d+)\b/.exec(stdout); + if (!match) return null; + const build = /\(([^)\s]+)\)/.exec(stdout)?.[1] ?? null; + return { text: match[0], major: Number(match[1]), minor: Number(match[2]), build }; +} async function status(launch: ProviderLaunch): Promise { let host: MspConnection | undefined; try { - const { stdout: versionText } = await execCommand( - launch.command, - [...launch.args, "--version"], - { - env: launch.env, - timeout: 3000, - maxBuffer: 8192, - }, - ); - const match = /\b(\d+)\.(\d+)\.(\d+)\b/.exec(versionText); - if (!match) return { available: false, diagnostic: "Muse returned an unrecognized version." }; - const major = Number(match[1]); - const minor = Number(match[2]); - if (major < 1 || (major === 1 && minor < 3)) - return { available: false, diagnostic: `Update Muse Code: found ${match[0]}, need ≥1.3.0` }; + const version = await readVersion(launch); + if (!version) return { available: false, diagnostic: "Muse returned an unrecognized version." }; + if (version.major < 1 || (version.major === 1 && version.minor < 3)) + return { + available: false, + diagnostic: `Update Muse Code: found ${version.text}, need ≥1.3.0`, + }; // Leave room for the version probe, account read and cleanup within the status RPC deadline. host = new MspConnection({ launch, timeoutMs: 3000, startupTimeoutMs: 20000 }); await host.initialize(); diff --git a/plugins/muse-provider/server/updates.ts b/plugins/muse-provider/server/updates.ts new file mode 100644 index 000000000000..ba57e4a9406a --- /dev/null +++ b/plugins/muse-provider/server/updates.ts @@ -0,0 +1,56 @@ +import type { ProviderUpdateCheck } from "@getpaseo/plugin/server/provider"; +import { z } from "zod"; + +/** What a Muse update channel publishes; the launcher installs `version` when it differs. */ +export interface MuseChannelRelease { + version: string; + notificationText?: string; +} + +export type ReadMuseChannelRelease = (input: { + channel: string; + signal: AbortSignal; +}) => Promise; + +const DEFAULT_CHANNEL = "muse-stable"; + +const channelManifestSchema = z.object({ + version: z.string().min(1), + notification_text: z.string().optional(), +}); + +/** Reads the channel manifest the `muse` launcher updates from. */ +export const readMuseChannelRelease: ReadMuseChannelRelease = async ({ channel, signal }) => { + const url = `https://api.meta.ai/muse-code/channels/${encodeURIComponent(channel)}`; + const response = await fetch(url, { signal }); + if (!response.ok) throw new Error(`Muse update channel returned ${response.status}`); + const manifest = channelManifestSchema.parse(await response.json()); + return { version: manifest.version, notificationText: manifest.notification_text }; +}; + +/** + * Compares the installed build with the build the launcher's channel publishes. The launcher + * replaces any build that differs from the channel's, so a different build is an update. + */ +export async function checkMuseForUpdates(input: { + /** + * The version inspection reported: the build `muse --version` prints in parentheses, such as + * `1.4.18-R8587.1`, or its bare `x.y.z` when it prints no build. + */ + installedVersion: string | undefined; + env: Record | undefined; + readChannelRelease: ReadMuseChannelRelease; + signal: AbortSignal; +}): Promise { + const build = input.installedVersion; + if (!build || /^\d+\.\d+\.\d+$/.test(build)) + return { status: "unknown", message: "This Muse Code does not report its build" }; + const channel = input.env?.MUSE_CHANNEL || DEFAULT_CHANNEL; + const release = await input.readChannelRelease({ channel, signal: input.signal }); + if (release.version === build) return { status: "current" }; + return { + status: "available", + versions: [release.version], + ...(release.notificationText ? { message: release.notificationText } : {}), + }; +} diff --git a/plugins/muse-provider/test/provider.test.ts b/plugins/muse-provider/test/provider.test.ts index 4868634d7062..d88cd9d7de05 100644 --- a/plugins/muse-provider/test/provider.test.ts +++ b/plugins/muse-provider/test/provider.test.ts @@ -19,6 +19,7 @@ import { import type { UsageSourceRegistration } from "@getpaseo/plugin/server"; import { execCommand } from "@getpaseo/plugin/server"; import contribute from "../index.server.js"; +import { createMuseProvider } from "../server/provider.js"; const connections: ProviderConnection[] = []; const roots: string[] = []; @@ -161,6 +162,67 @@ test("registration exposes Muse with a daemon-resolved command", () => { icon: "icon.svg", }); }); +test("installation links to the Muse guide and reports the installed version", async () => { + const provider = registration(); + const launch = { + command: process.execPath, + args: [fileURLToPath(new URL("./fake-muse.mjs", import.meta.url))], + env: { MUSE_TEST_VERSION: "1.7.2" }, + }; + const signal = new AbortController().signal; + expect(provider.installation?.installUrl).toBe("https://paseo.sh/docs/muse-code"); + await expect( + provider.installation?.inspect?.({ launch: { ...launch, resolved: true }, signal }), + ).resolves.toEqual({ status: "installed", version: "1.7.2" }); + await expect( + provider.installation?.inspect?.({ + launch: { ...launch, command: "muse", resolved: false }, + signal, + }), + ).resolves.toEqual({ status: "not_installed" }); +}); +test("installation reports the build as the installed version", async () => { + const provider = registration(); + const launch = { + command: process.execPath, + args: [fileURLToPath(new URL("./fake-muse.mjs", import.meta.url))], + env: { MUSE_TEST_VERSION: "1.4.18 (1.4.18-R8600.1)" }, + resolved: true, + }; + await expect( + provider.installation?.inspect?.({ launch, signal: new AbortController().signal }), + ).resolves.toEqual({ status: "installed", version: "1.4.18-R8600.1" }); +}); +test("update check compares the installed build with the launcher's channel", async () => { + const channels: string[] = []; + const provider = createMuseProvider(new MuseUsage(), { + async readChannelRelease({ channel }) { + channels.push(channel); + return channel === "muse-beta" + ? { version: "1.5.0-R9000.2", notificationText: "Faster startup" } + : { version: "1.4.18-R8587.1", notificationText: "" }; + }, + }); + const signal = new AbortController().signal; + const check = (installedVersion: string, env: Record = {}) => + provider.installation?.checkForUpdates?.({ + launch: { command: "muse", args: [], env, resolved: true }, + installedVersion, + signal, + }); + + await expect(check("1.4.18-R8587.1")).resolves.toEqual({ status: "current" }); + await expect(check("1.4.18-R8587.1", { MUSE_CHANNEL: "muse-beta" })).resolves.toEqual({ + status: "available", + versions: ["1.5.0-R9000.2"], + message: "Faster startup", + }); + await expect(check("1.4.1")).resolves.toEqual({ + status: "unknown", + message: "This Muse Code does not report its build", + }); + expect(channels).toEqual(["muse-stable", "muse-beta"]); +}); test("catalog uses model effort variants, modes, and bounded cached discovery", async () => { const h = await harness("catalog-controls"); await h.send({ type: "catalog", requestId: "catalog-1" }); diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index 698b8a842633..83dcf782949f 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -427,6 +427,127 @@ export default function contribute(client: PluginClientContext) { The same renderer can display items emitted by a provider, a client timeline transformer, or a daemon timeline append. A renderer does not require a provider implementation. +## Report installation and updates + +Add `installation` to your registration and the provider's settings show an **Installation** +section. Users see whether your CLI is installed and which version, whether an update is +available, and an **Update** button that runs your updater and shows its output. Every member is +optional, so declare only what your CLI supports: + +| Member | Users see | Declare it when | +| ----------------- | ----------------------------------------------------------------------- | ------------------------------------------------------ | +| `installUrl` | **Install instructions**, and **Install** while not installed | Users install a CLI | +| `updateUrl` | **Update instructions** while installed, when you declare no `update` | Your docs say how to update | +| `inspect` | **Version**, or **Not installed** | The CLI reports its version | +| `checkForUpdates` | **Up to date**, **Update available**, or **Couldn't check for updates** | You can ask the release source your CLI's updater uses | +| `update` | **Update** while installed, then the updater's output | The CLI updates itself with a command | + +This `example-agent` prints its version, asks `self-update --check --json` for the release its +updater installs, and updates with `self-update`: + +```ts +import { execCommand, spawnProcess, terminateProcess } from "@getpaseo/plugin/server"; +import type { + ProviderInstallation, + ProviderInstallationLaunch, +} from "@getpaseo/plugin/server/provider"; + +async function run(launch: ProviderInstallationLaunch, args: string[], signal: AbortSignal) { + const { stdout } = await execCommand(launch.command, [...launch.args, ...args], { + env: launch.env, + timeout: 20_000, + signal, + }); + return stdout.trim(); +} + +export const installation: ProviderInstallation = { + installUrl: "https://example.com/docs/install", + updateUrl: "https://example.com/docs/update", + + async inspect({ launch, signal }) { + if (!launch?.resolved) return { status: "not_installed" }; + // `example-agent --version` prints `1.4.2`. + return { status: "installed", version: await run(launch, ["--version"], signal) }; + }, + + async checkForUpdates({ launch, installedVersion, signal }) { + if (!launch) return { status: "unknown" }; + // Prints `{"latest":"1.5.0"}`; `self-update` installs any release that differs. + const { latest } = JSON.parse( + await run(launch, ["self-update", "--check", "--json"], signal), + ) as { latest: string }; + return latest === installedVersion + ? { status: "current" } + : { status: "available", versions: [latest] }; + }, + + async update({ launch, signal, report }) { + if (!launch?.resolved) return { status: "failed", message: "example-agent is not installed" }; + const child = spawnProcess(launch.command, [...launch.args, "self-update"], { + env: launch.env, + stdio: "pipe", + }); + child.stdin.end(); + child.stdout.on("data", (chunk: Buffer) => report({ type: "stdout", text: chunk.toString() })); + child.stderr.on("data", (chunk: Buffer) => report({ type: "stderr", text: chunk.toString() })); + const stop = () => void terminateProcess(child); + signal.addEventListener("abort", stop, { once: true }); + const code = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", resolve); + }).finally(() => signal.removeEventListener("abort", stop)); + if (code !== 0) return { status: "failed", message: `self-update exited with code ${code}` }; + return { status: "succeeded", message: "New sessions use the new version." }; + }, +}; +``` + +Add it to the registration next to `command`: + +```ts +export function createProvider(): ProviderRegistration { + return { + id: "example-agent", + label: "Example Agent", + command: ["example-agent"], + installation, + async connect(request) { + // ... + }, + }; +} +``` + +Each callback receives the launch a session would use. When `launch.resolved` is `false`, Paseo did +not find the executable and `command` is the configured name, so report `not_installed` without +running it. `launch` is absent when the registration declares no `command`. `checkForUpdates` runs +only after `inspect` reports the CLI installed, and receives the `version` it reported as +`installedVersion`, so compare that instead of reading the version again. For an ACP provider, +spread `runAcpProvider()` into the registration and add `installation` beside it. Run version and +update probes with the launch's arguments before your session subcommand, such as `hoplite +--version` for a provider that runs `hoplite acp`. + +Paseo treats versions as text. It shows `version` and `versions` as written and never parses +them, so your check decides what counts as newer. Ask the source your CLI's own updater asks, and +leave `checkForUpdates` out when you cannot. A check that returns `unknown`, throws, or misses its +deadline shows **Couldn't check for updates** with your message and never shows **Up to date**. + +`update` runs only when a user selects **Update**, and Paseo runs one update per provider at a +time. Pass the updater's output to `report` unchanged; Paseo keeps the last 65,536 characters. Paseo adds no +verification of its own, so the update does what your command does in a terminal. Return +`succeeded` with a message that says when the new version takes effect, or `failed` with the reason. +A failed update shows until the user refreshes the provider. Without `update`, **Update instructions** opens `updateUrl` instead. + +**Update** and **Update instructions** appear whenever `inspect` reports the CLI installed. The +check only says what it knows beside them, so declare `update` even when you cannot check. + +Paseo calls `inspect` when the settings open and keeps the answer for 30 seconds. It keeps a +`current` or `available` answer from `checkForUpdates` for an hour while `inspect` reports the same +version, so a CLI updated outside Paseo is checked again once the inspection expires. `inspect` must answer within 20 seconds and `checkForUpdates` within 25. +`update` has no deadline. `signal` aborts when Paseo stops waiting or the daemon stops. +See the [`installation` reference](/docs/plugins/reference#provider-installation) for every field. + ## Adapt an ACP agent Use the ACP shim when the agent already speaks ACP: diff --git a/public-docs/plugins/providers.zh-CN.md b/public-docs/plugins/providers.zh-CN.md index e917ba0538fa..d1825d911d1c 100644 --- a/public-docs/plugins/providers.zh-CN.md +++ b/public-docs/plugins/providers.zh-CN.md @@ -351,6 +351,104 @@ export default function contribute(client: PluginClientContext) { 同一个渲染器可以显示由 Provider、客户端时间线转换器或 daemon 时间线追加发出的条目。渲染器并不需要 Provider 实现。 +## 报告安装与更新 {#report-installation-and-updates} + +在注册中添加 `installation`,Provider 的设置中就会出现 **安装** 部分。用户可以看到你的 CLI 是否已安装、是哪个版本、是否有可用更新,以及一个 **更新** 按钮,它会运行你的更新程序并显示其输出。每个成员都是可选的,只声明你的 CLI 支持的部分: + +| 成员 | 用户看到的内容 | 何时声明 | +| ----------------- | ------------------------------------------------ | --------------------------------------- | +| `installUrl` | **安装说明**,未安装时还有 **安装** | 用户需要安装 CLI | +| `updateUrl` | 已安装且未声明 `update` 时显示 **更新说明** | 你的文档说明了如何更新 | +| `inspect` | **版本**,或 **未安装** | CLI 会报告自己的版本 | +| `checkForUpdates` | **已是最新**、**有可用更新** 或 **无法检查更新** | 你能询问 CLI 自带更新程序所用的发布来源 | +| `update` | 已安装时显示 **更新**,随后显示更新程序的输出 | CLI 能用一条命令更新自己 | + +这个 `example-agent` 会打印自己的版本,用 `self-update --check --json` 查询其更新程序会安装的发布,并用 `self-update` 更新: + +```ts +import { execCommand, spawnProcess, terminateProcess } from "@getpaseo/plugin/server"; +import type { + ProviderInstallation, + ProviderInstallationLaunch, +} from "@getpaseo/plugin/server/provider"; + +async function run(launch: ProviderInstallationLaunch, args: string[], signal: AbortSignal) { + const { stdout } = await execCommand(launch.command, [...launch.args, ...args], { + env: launch.env, + timeout: 20_000, + signal, + }); + return stdout.trim(); +} + +export const installation: ProviderInstallation = { + installUrl: "https://example.com/docs/install", + updateUrl: "https://example.com/docs/update", + + async inspect({ launch, signal }) { + if (!launch?.resolved) return { status: "not_installed" }; + // `example-agent --version` prints `1.4.2`. + return { status: "installed", version: await run(launch, ["--version"], signal) }; + }, + + async checkForUpdates({ launch, installedVersion, signal }) { + if (!launch) return { status: "unknown" }; + // Prints `{"latest":"1.5.0"}`; `self-update` installs any release that differs. + const { latest } = JSON.parse( + await run(launch, ["self-update", "--check", "--json"], signal), + ) as { latest: string }; + return latest === installedVersion + ? { status: "current" } + : { status: "available", versions: [latest] }; + }, + + async update({ launch, signal, report }) { + if (!launch?.resolved) return { status: "failed", message: "example-agent is not installed" }; + const child = spawnProcess(launch.command, [...launch.args, "self-update"], { + env: launch.env, + stdio: "pipe", + }); + child.stdin.end(); + child.stdout.on("data", (chunk: Buffer) => report({ type: "stdout", text: chunk.toString() })); + child.stderr.on("data", (chunk: Buffer) => report({ type: "stderr", text: chunk.toString() })); + const stop = () => void terminateProcess(child); + signal.addEventListener("abort", stop, { once: true }); + const code = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", resolve); + }).finally(() => signal.removeEventListener("abort", stop)); + if (code !== 0) return { status: "failed", message: `self-update exited with code ${code}` }; + return { status: "succeeded", message: "New sessions use the new version." }; + }, +}; +``` + +把它添加到注册中 `command` 的旁边: + +```ts +export function createProvider(): ProviderRegistration { + return { + id: "example-agent", + label: "Example Agent", + command: ["example-agent"], + installation, + async connect(request) { + // ... + }, + }; +} +``` + +每个回调都会收到会话将使用的启动配置。当 `launch.resolved` 为 `false` 时,Paseo 没有找到可执行文件,`command` 是配置中写的名称,因此直接报告 `not_installed`,不要运行它。注册没有声明 `command` 时,`launch` 不存在。`checkForUpdates` 只在 `inspect` 报告 CLI 已安装后运行,并通过 `installedVersion` 收到 `inspect` 报告的 `version`,所以请比较它,不要再次读取版本。对于 ACP Provider,把 `runAcpProvider()` 展开到注册中,并在旁边添加 `installation`。版本和更新探测使用会话子命令之前的启动参数,例如对运行 `hoplite acp` 的 Provider 使用 `hoplite --version`。 + +Paseo 把版本当作文本。它按原样显示 `version` 和 `versions`,从不解析它们,因此由你的检查决定什么算更新。询问 CLI 自带更新程序所询问的来源;做不到时就不要声明 `checkForUpdates`。返回 `unknown`、抛出异常或超过期限的检查会显示 **无法检查更新** 和你的消息,绝不会显示 **已是最新**。 + +`update` 只在用户选择 **更新** 时运行,并且每个 Provider 同一时间只运行一个更新。把更新程序的输出原样传给 `report`;Paseo 保留最后 65,536 个字符。Paseo 不会额外做任何校验,所以更新的效果与在终端中运行你的命令相同。返回 `succeeded` 并用消息说明新版本何时生效,或返回 `failed` 并说明原因。失败的更新会一直显示,直到用户刷新该 Provider。没有 `update` 时,**更新说明** 会打开 `updateUrl`。 + +只要 `inspect` 报告 CLI 已安装,就会显示 **更新** 或 **更新说明**。检查只在旁边说明它知道的情况,所以即使无法检查,也要声明 `update`。 + +Paseo 在设置打开时调用 `inspect`,并把结果保留 30 秒。只要 `inspect` 报告的版本不变,它就把 `checkForUpdates` 的 `current` 或 `available` 结果保留一小时,所以在 Paseo 之外更新的 CLI 会在 `inspect` 的结果过期后重新检查。`inspect` 必须在 20 秒内回答,`checkForUpdates` 必须在 25 秒内回答。`update` 没有期限。当 Paseo 停止等待或 daemon 停止时,`signal` 会中止。每个字段见 [`installation` 参考](/docs/plugins/reference#provider-installation)。 + ## 适配 ACP Agent {#adapt-an-acp-agent} 当 Agent 已经支持 ACP 时,使用 ACP 适配层: diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index cefb4dabb70e..265b80b4bb1a 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -440,6 +440,64 @@ It must resolve inside that directory to a regular file that follows the [SVG icon rules](#svg-rules). Paseo reads and validates the file when the plugin starts; the string is never inline SVG or a URL. +#### Provider installation + +**Requires Paseo 0.17.** Older versions ignore `installation`. +`ProviderRegistration.installation` fills the **Installation** section of the provider's settings. +Every member is optional. Paseo hides the section when you declare neither `inspect` nor +`installUrl`. [Report installation and updates](/docs/plugins/providers#report-installation-and-updates) +has a complete example. Import the types from `@getpaseo/plugin/server/provider`. + +```ts +interface ProviderInstallation { + installUrl?: string; + updateUrl?: string; + inspect?(context: ProviderInstallationContext): Promise; + checkForUpdates?(context: ProviderUpdateCheckContext): Promise; + update?(context: ProviderUpdateContext): Promise; +} +``` + +| Member | Called | Deadline | Answer kept | +| ----------------- | ------------------------------------------------------------ | -------- | ------------------------------------------------ | +| `inspect` | When provider settings open | 20 s | 30 s | +| `checkForUpdates` | After `inspect` answers `installed`, or without `inspect` | 25 s | 1 hour for `current` or `available`, else 30 s | +| `update` | When the user selects **Update**, one at a time per provider | None | Paseo reads both answers again after `succeeded` | + +**Refresh** in the provider's settings skips the kept answers and clears a failed update. Paseo +never calls these members before a session or on a schedule. A deadline or a throw becomes an error that shows the message. + +`installUrl` and `updateUrl` are `http` or `https` pages that Paseo opens in the browser. The +plugin fails to start when either is another kind of URL. + +The context: + +| Field | Type | Meaning | +| ------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `launch` | `ProviderInstallationLaunch \| undefined` | The launch a session would use, with `resolved`. Absent when the registration declares no `command`. | +| `signal` | `AbortSignal` | Aborts when Paseo stops waiting or the daemon stops. | +| `installedVersion` | `string \| undefined` | `checkForUpdates` only. The `version` `inspect` reported, as written. Absent when it reported none or you declare no `inspect`. | +| `report` | `(event: ProviderUpdateReport) => void` | `update` only. Shows `{ type: "stdout" \| "stderr" \| "message", text }` to the user in order. | + +`ProviderInstallationLaunch` is `{ command, args, env, resolved }`. With `resolved: true`, `command` +is the executable's path. With `resolved: false`, Paseo did not find the executable and `command` +is the configured name. + +Answers: + +| Type | Values | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `ProviderInspection` | `{ status: "installed", version?: string }` or `{ status: "not_installed" }` | +| `ProviderUpdateCheck` | `{ status: "current" }`, `{ status: "available", versions?: string[], message?: string }`, or `{ status: "unknown", message?: string }` | +| `ProviderUpdateResult` | `{ status: "succeeded", message?: string }` or `{ status: "failed", message: string }` | + +Paseo shows `version`, `versions` and `message` as written and does not parse or sort them. It +reuses a `current` or `available` answer for up to an hour while `inspect` reports the same +`version`. It keeps the last 65,536 characters of `report` output. An answer that does not match these +shapes is an error. **Update** appears once `inspect` reports the CLI installed and you declare +`update`, whatever `checkForUpdates` answers and whether you declare it; without `update`, Paseo +offers `updateUrl` on the same terms. + ### Usage sources **Requires Paseo 0.11.** Register a source from your server entry with diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 4ccfa740eeb9..465cd70d8494 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -367,6 +367,51 @@ Paseo 刷新 Agent 的方式是关闭它当前的 Provider 会话,再用当前 `ProviderRegistration.icon` 是相对于插件目录的文件路径,例如 `icon.svg`。它必须解析到该目录内一个遵循 [SVG 图标规则](#svg-rules)的普通文件。Paseo 在插件启动时读取并校验该文件;这个字符串从不是内联 SVG 或 URL。 +#### Provider 安装 {#provider-installation} + +**需要 Paseo 0.17**。较旧的版本会忽略 `installation`。`ProviderRegistration.installation` 填充 Provider 设置中的 **安装** 部分。每个成员都是可选的。`inspect` 和 `installUrl` 都没有声明时,Paseo 会隐藏这个部分。完整示例见[报告安装与更新](/docs/plugins/providers#report-installation-and-updates)。类型从 `@getpaseo/plugin/server/provider` 导入。 + +```ts +interface ProviderInstallation { + installUrl?: string; + updateUrl?: string; + inspect?(context: ProviderInstallationContext): Promise; + checkForUpdates?(context: ProviderUpdateCheckContext): Promise; + update?(context: ProviderUpdateContext): Promise; +} +``` + +| 成员 | 调用时机 | 期限 | 结果保留时间 | +| ----------------- | ------------------------------------------------- | ----- | ----------------------------------------------- | +| `inspect` | 打开 Provider 设置时 | 20 秒 | 30 秒 | +| `checkForUpdates` | `inspect` 回答 `installed` 之后,或没有 `inspect` | 25 秒 | `current` 或 `available` 为一小时,其他为 30 秒 | +| `update` | 用户选择 **更新** 时,每个 Provider 同一时间一个 | 无 | `succeeded` 之后 Paseo 重新读取两个结果 | + +Provider 设置中的 **刷新** 会跳过保留的结果,并清除失败的更新。Paseo 从不在会话开始前或按计划调用这些成员。超过期限或抛出异常会变成显示该消息的错误。 + +`installUrl` 和 `updateUrl` 是 Paseo 在浏览器中打开的 `http` 或 `https` 页面。其中任何一个是其他类型的 URL 时,插件无法启动。 + +上下文: + +| 字段 | 类型 | 含义 | +| ------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `launch` | `ProviderInstallationLaunch \| undefined` | 会话将使用的启动配置,带有 `resolved`。注册没有声明 `command` 时不存在。 | +| `signal` | `AbortSignal` | 当 Paseo 停止等待或 daemon 停止时中止。 | +| `installedVersion` | `string \| undefined` | 仅用于 `checkForUpdates`。`inspect` 报告的 `version`,按原样传入。`inspect` 没有报告版本或你没有声明 `inspect` 时不存在。 | +| `report` | `(event: ProviderUpdateReport) => void` | 仅用于 `update`。按顺序向用户显示 `{ type: "stdout" \| "stderr" \| "message", text }`。 | + +`ProviderInstallationLaunch` 是 `{ command, args, env, resolved }`。`resolved: true` 时,`command` 是可执行文件的路径。`resolved: false` 时,Paseo 没有找到可执行文件,`command` 是配置中写的名称。 + +结果: + +| 类型 | 取值 | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `ProviderInspection` | `{ status: "installed", version?: string }` 或 `{ status: "not_installed" }` | +| `ProviderUpdateCheck` | `{ status: "current" }`、`{ status: "available", versions?: string[], message?: string }` 或 `{ status: "unknown", message?: string }` | +| `ProviderUpdateResult` | `{ status: "succeeded", message?: string }` 或 `{ status: "failed", message: string }` | + +Paseo 按原样显示 `version`、`versions` 和 `message`,不解析或排序它们。只要 `inspect` 报告的 `version` 不变,Paseo 会在最长一小时内复用 `current` 或 `available` 的结果。它保留 `report` 输出的最后 65,536 个字符。不符合这些结构的结果是错误。只要 `inspect` 报告 CLI 已安装且你声明了 `update`,就会出现 **更新**,与 `checkForUpdates` 的回答以及是否声明它无关;没有 `update` 时,Paseo 在同样条件下提供 `updateUrl`。 + ### 用量来源 {#usage-sources} **需要 Paseo 0.11**。在服务端入口中用 `server.registerUsageSource()` 注册一个来源。从 `@getpaseo/plugin/server/usage` 导入它的契约和辅助函数。 From 86ebdedcbecbf175764b105480a1cd738ab287e2 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 19 Nov 2026 21:12:36 +0700 Subject: [PATCH 004/109] Apply content width presets to open chats (#10231) * fix(app): apply content width presets to open chats Retained rows kept the numeric width in their generated web styles. Use a CSS variable so the timeline, composer, and Markdown previews follow the same preference while mounted. Reserve the outline gutter when the outline is enabled on a wide pane. * fix(app): keep capped chats centered beside the outline Reserve the left outline gutter and match it on the right when the selected column fits between both gutters. --- packages/app/e2e/browser/chat-outline.spec.ts | 6 +- .../app/e2e/browser/content-width.spec.ts | 98 +++++++++------- .../app/e2e/support/helpers/chat-outline.ts | 11 +- .../app/e2e/support/helpers/content-width.ts | 74 +++++------- .../src/agent-stream/chat-outline/rail.tsx | 4 + .../agent-stream/chat-outline/rail.web.tsx | 77 ++++++------- .../app/src/agent-stream/strategy-web.tsx | 32 ++++- packages/app/src/agent-stream/strategy.ts | 3 +- packages/app/src/agent-stream/view.tsx | 25 ++-- packages/app/src/appearance/apply.test.ts | 13 ++- packages/app/src/appearance/apply.ts | 8 +- packages/app/src/appearance/provider.tsx | 5 +- .../src/assistant-selection-copy/surface.tsx | 10 +- .../assistant-selection-copy/surface.web.tsx | 8 +- .../src/components/ui/segmented-control.tsx | 4 +- packages/app/src/hooks/use-settings/index.ts | 8 +- .../src/hooks/use-settings/storage.test.ts | 73 +++++++----- .../app/src/hooks/use-settings/storage.ts | 46 +++++--- packages/app/src/i18n/resources/ar.ts | 9 +- packages/app/src/i18n/resources/en.ts | 9 +- packages/app/src/i18n/resources/es.ts | 9 +- packages/app/src/i18n/resources/fr.ts | 10 +- packages/app/src/i18n/resources/ja.ts | 9 +- packages/app/src/i18n/resources/ko.ts | 9 +- packages/app/src/i18n/resources/pt-BR.ts | 9 +- packages/app/src/i18n/resources/ru.ts | 9 +- packages/app/src/i18n/resources/zh-CN.ts | 9 +- .../appearance/appearance-section.tsx | 109 +++++------------- packages/app/src/styles/theme.ts | 18 ++- 29 files changed, 383 insertions(+), 331 deletions(-) diff --git a/packages/app/e2e/browser/chat-outline.spec.ts b/packages/app/e2e/browser/chat-outline.spec.ts index 640b141f5350..26fc917dc22c 100644 --- a/packages/app/e2e/browser/chat-outline.spec.ts +++ b/packages/app/e2e/browser/chat-outline.spec.ts @@ -2,7 +2,7 @@ import { expect, test } from "../support/fixtures"; import { trackPromptJumpRequests } from "../support/helpers/agent-timeline-gate"; import { clickChatOutlineRowEdge, - disableChatOutlineFromAppearance, + disableChatOutline, expectActiveChatOutlinePrompt, expectActiveChatOutlinePromptMovedFrom, expectChatOutlinePreview, @@ -314,13 +314,13 @@ test.describe("desktop chat outline", () => { } }); - test("can be disabled from Appearance settings", async ({ page }) => { + test("can be disabled from Chat settings", async ({ page }) => { const agent = await seedLongMockAgentTimeline({ turns: 2 }); try { await page.setViewportSize(WIDE_VIEWPORT); await openAgentTimeline(page, agent); - await disableChatOutlineFromAppearance(page); + await disableChatOutline(page); await expectNoChatOutline(page); } finally { diff --git a/packages/app/e2e/browser/content-width.spec.ts b/packages/app/e2e/browser/content-width.spec.ts index bd3cc4394fa6..bed1b1849aad 100644 --- a/packages/app/e2e/browser/content-width.spec.ts +++ b/packages/app/e2e/browser/content-width.spec.ts @@ -1,20 +1,27 @@ -import { test } from "../support/fixtures"; +import { expect, test } from "../support/fixtures"; import { + chatOutlineRail, + disableChatOutline, + expectChatOutlinePrompts, + expectNoChatOutline, +} from "../support/helpers/chat-outline"; +import { + chooseContentWidth, + expectColumnAtLeftGutter, + expectColumnClearOfOutline, expectContentColumnWidth, - expectCustomContentWidthSetting, - expectDefaultContentWidthSetting, - openAppearanceSettings, - resetContentWidth, - setContentWidth, } from "../support/helpers/content-width"; import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 }; +const DEFAULT_COLUMN = { min: 800, max: 820 }; +const WIDE_COLUMN = { min: 1180, max: 1200 }; +const FULL_COLUMN = { min: 2000, max: ULTRAWIDE_VIEWPORT.width }; -test("widens chat and Markdown files to the chosen content width and resets to the default", async ({ +test("resizes mounted chat content and leaves room for the outline at full width", async ({ page, -}, testInfo) => { +}) => { test.setTimeout(120_000); const agent = await seedMockAgentWorkspace({ repoPrefix: "content-width-", @@ -23,47 +30,58 @@ test("widens chat and Markdown files to the chosen content width and resets to t }); try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await agent.client.sendAgentMessage(agent.agentId, "Write another paragraph."); await agent.client.waitForFinish(agent.agentId, 30_000); await page.setViewportSize(ULTRAWIDE_VIEWPORT); - const assistantMessage = page.getByTestId("assistant-message").first(); - const markdownPreview = page.getByTestId("markdown-preview-frame").first(); + await openAgentRoute(page, agent); + await expectChatOutlinePrompts(page, 2); + const reply = page.getByTestId("assistant-message").first(); + const composer = page.getByTestId("message-input-root"); + await expectContentColumnWidth(reply, DEFAULT_COLUMN); + const originalReply = await reply.elementHandle(); - await test.step("chat starts at the default width", async () => { - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { max: 820 }); - }); + await chooseContentWidth(page, "Wide"); + await expectContentColumnWidth(reply, WIDE_COLUMN); + await expectContentColumnWidth(composer, WIDE_COLUMN); - await test.step("settings show the default without a reset", async () => { - await openAppearanceSettings(page); - await expectDefaultContentWidthSetting(page, 820); - }); + await chooseContentWidth(page, "Full"); + await expectContentColumnWidth(reply, FULL_COLUMN); + await expectContentColumnWidth(composer, FULL_COLUMN); + await expectColumnClearOfOutline(reply, chatOutlineRail(page)); - await test.step("a custom width is saved and offers a reset", async () => { - await setContentWidth(page, 1600); - await expectCustomContentWidthSetting(page, 1600); - await page.screenshot({ path: testInfo.outputPath("settings-custom-width.png") }); - }); + await disableChatOutline(page); + await expectNoChatOutline(page); + await expectColumnAtLeftGutter(page, reply); - await test.step("chat and Markdown files use the custom width", async () => { - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { min: 1200, max: 1600 }); - await page.screenshot({ path: testInfo.outputPath("chat-custom-width.png") }); + await chooseContentWidth(page, "Default"); + await expectContentColumnWidth(reply, DEFAULT_COLUMN); + await expectContentColumnWidth(composer, DEFAULT_COLUMN); + expect(await originalReply?.evaluate((node) => node.isConnected)).toBe(true); + } finally { + await agent.cleanup(); + } +}); - await openFileExplorer(page); - await openFileFromExplorer(page, "README.md"); - await expectContentColumnWidth(markdownPreview, { min: 1200, max: 1600 }); - await page.screenshot({ path: testInfo.outputPath("markdown-custom-width.png") }); - }); +test("updates an open Markdown preview when the content width changes", async ({ page }) => { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "markdown-content-width-", + title: "Markdown content width", + }); + + try { + await page.setViewportSize(ULTRAWIDE_VIEWPORT); + await openAgentRoute(page, agent); + await openFileExplorer(page); + await openFileFromExplorer(page, "README.md"); + const preview = page.getByTestId("markdown-preview-frame").first(); + await expectContentColumnWidth(preview, DEFAULT_COLUMN); - await test.step("reset returns to the default without storing it", async () => { - await openAppearanceSettings(page); - await resetContentWidth(page); - await expectDefaultContentWidthSetting(page, 820); + await chooseContentWidth(page, "Wide"); + await expectContentColumnWidth(preview, WIDE_COLUMN); - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { max: 820 }); - await page.screenshot({ path: testInfo.outputPath("chat-default-width.png") }); - }); + await chooseContentWidth(page, "Full"); + await expectContentColumnWidth(preview, { min: 1500, max: ULTRAWIDE_VIEWPORT.width }); } finally { await agent.cleanup(); } diff --git a/packages/app/e2e/support/helpers/chat-outline.ts b/packages/app/e2e/support/helpers/chat-outline.ts index d219979fcf2b..e7411254642d 100644 --- a/packages/app/e2e/support/helpers/chat-outline.ts +++ b/packages/app/e2e/support/helpers/chat-outline.ts @@ -1,6 +1,6 @@ import { expect, type Locator, type Page } from "@playwright/test"; import { openSettings } from "./app"; -import { openSettingsSection } from "./settings"; +import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings"; import { runWorkspaceActionFromCommandCenter } from "./command-center-workspace-actions"; import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent"; import { loadSessionMessageReaders } from "./new-workspace"; @@ -81,12 +81,13 @@ export async function splitCurrentPanelRight(page: Page): Promise { await runWorkspaceActionFromCommandCenter(page, "Split pane right"); } -export async function disableChatOutlineFromAppearance(page: Page): Promise { - const timelineUrl = page.url(); +export async function disableChatOutline(page: Page): Promise { await openSettings(page); await openSettingsSection(page, "chat"); - await page.getByRole("switch", { name: "Chat outline" }).click(); - await page.goto(timelineUrl); + const outlineSwitch = page.getByRole("switch", { name: "Chat outline" }); + await outlineSwitch.click(); + await expect(outlineSwitch).not.toBeChecked(); + await clickSettingsBackToWorkspace(page); } /** Parks the pointer in the middle of the transcript, clear of the rail. */ diff --git a/packages/app/e2e/support/helpers/content-width.ts b/packages/app/e2e/support/helpers/content-width.ts index a99ee6a9560b..501a4f65cf45 100644 --- a/packages/app/e2e/support/helpers/content-width.ts +++ b/packages/app/e2e/support/helpers/content-width.ts @@ -1,63 +1,53 @@ import { expect, type Locator, type Page } from "@playwright/test"; import { openSettings } from "./app"; -import { openSettingsSection } from "./settings"; +import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings"; -const APP_SETTINGS_KEY = "@paseo:app-settings"; +type ContentWidthOption = "Default" | "Wide" | "Full"; -function contentWidthInput(page: Page): Locator { - return page.getByLabel("Content width in pixels", { exact: true }); +function contentWidthOption(page: Page, option: ContentWidthOption): Locator { + return page + .getByTestId("content-width-options") + .getByRole("button", { name: option, exact: true }); } -function resetContentWidthButton(page: Page): Locator { - return page.getByRole("button", { name: "Reset content width to default", exact: true }); -} - -export async function openAppearanceSettings(page: Page): Promise { +export async function chooseContentWidth(page: Page, option: ContentWidthOption): Promise { await openSettings(page); await openSettingsSection(page, "appearance"); + const button = contentWidthOption(page, option); + await button.click(); + await expect(button).toHaveAttribute("aria-selected", "true"); + await clickSettingsBackToWorkspace(page); } -export async function setContentWidth(page: Page, width: number): Promise { - const input = contentWidthInput(page); - await input.fill(String(width)); - await input.press("Tab"); -} - -export async function resetContentWidth(page: Page): Promise { - await resetContentWidthButton(page).click(); -} - -export async function expectDefaultContentWidthSetting(page: Page, width: number): Promise { - await expect(contentWidthInput(page)).toHaveValue(String(width)); - await expect(resetContentWidthButton(page)).toHaveCount(0); - await expect.poll(() => readStoredContentWidth(page)).toBeNull(); -} - -export async function expectCustomContentWidthSetting(page: Page, width: number): Promise { - await expect(contentWidthInput(page)).toHaveValue(String(width)); - await expect(resetContentWidthButton(page)).toBeVisible(); - await expect.poll(() => readStoredContentWidth(page)).toBe(width); -} - -/** Asserts the rendered width of a content-column element stays within `max` and above `min`. */ +/** Checks the rendered content width, allowing for padding inside the column. */ export async function expectContentColumnWidth( element: Locator, - bounds: { min?: number; max: number }, + bounds: { min: number; max: number }, ): Promise { await expect(element).toBeVisible({ timeout: 30_000 }); await expect .poll(async () => (await element.boundingBox())?.width ?? 0) + .toBeGreaterThanOrEqual(bounds.min); + await expect + .poll(async () => (await element.boundingBox())?.width ?? Infinity) .toBeLessThanOrEqual(bounds.max); +} + +export async function expectColumnClearOfOutline(column: Locator, outline: Locator): Promise { await expect - .poll(async () => (await element.boundingBox())?.width ?? 0) - .toBeGreaterThan(bounds.min ?? 0); + .poll(async () => { + const [content, rail] = await Promise.all([column.boundingBox(), outline.boundingBox()]); + return content && rail ? content.x - (rail.x + rail.width) : -1; + }) + .toBeGreaterThanOrEqual(8); } -async function readStoredContentWidth(page: Page): Promise { - return page.evaluate((key) => { - const raw = localStorage.getItem(key); - return raw === null - ? undefined - : (JSON.parse(raw) as { contentMaxWidth?: unknown }).contentMaxWidth; - }, APP_SETTINGS_KEY); +export async function expectColumnAtLeftGutter(page: Page, column: Locator): Promise { + const viewport = page.getByTestId("agent-chat-scroll"); + await expect + .poll(async () => { + const [content, scroll] = await Promise.all([column.boundingBox(), viewport.boundingBox()]); + return content && scroll ? content.x - scroll.x : Infinity; + }) + .toBeLessThanOrEqual(24); } diff --git a/packages/app/src/agent-stream/chat-outline/rail.tsx b/packages/app/src/agent-stream/chat-outline/rail.tsx index 0736ee21a252..d6db6c125139 100644 --- a/packages/app/src/agent-stream/chat-outline/rail.tsx +++ b/packages/app/src/agent-stream/chat-outline/rail.tsx @@ -11,3 +11,7 @@ export interface ChatOutlineRailProps { export function ChatOutlineRail(_props: ChatOutlineRailProps): null { return null; } + +export function useChatOutlineRailLayout(_enabled: boolean) { + return { onLayout: undefined, inset: 0 }; +} diff --git a/packages/app/src/agent-stream/chat-outline/rail.web.tsx b/packages/app/src/agent-stream/chat-outline/rail.web.tsx index 3cb79f108b26..875d8699cd5d 100644 --- a/packages/app/src/agent-stream/chat-outline/rail.web.tsx +++ b/packages/app/src/agent-stream/chat-outline/rail.web.tsx @@ -3,6 +3,7 @@ import { Pressable, Text, View, type PointerEvent as RNPointerEvent } from "reac import { StyleSheet } from "react-native-unistyles"; import { useReducedMotion } from "react-native-reanimated"; import { useContainerWidthBelow } from "@/hooks/use-container-width"; +import { SPACING } from "@/styles/theme"; import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style"; import { createChatOutlineHoverIntent } from "./hover-intent"; import { promptTickMagnification } from "./model"; @@ -11,6 +12,7 @@ import type { ChatOutlineRailProps } from "./rail"; // Hover tracking lives on the rail and the slots, never on the Pressable inside them: // magnifying a slot must not move the box the pointer is resting on. See docs/hover.md. const RAIL_WIDTH = 36; +const RAIL_LEFT = SPACING[2]; const SLOT_HEIGHT = 8; const MIN_PANEL_WIDTH = 918; const RESTING_PILL_HEIGHT = 2; @@ -22,6 +24,11 @@ const PREVIEW_WIDTH = 260; const PREVIEW_HEIGHT = 48; const PREVIEW_GAP = 4; +export function useChatOutlineRailLayout(enabled: boolean) { + const { onLayout, isBelow } = useContainerWidthBelow(MIN_PANEL_WIDTH); + return { onLayout, inset: enabled && !isBelow ? RAIL_LEFT + RAIL_WIDTH : 0 }; +} + export const ChatOutlineRail = memo(function ChatOutlineRail({ prompts, activePrompt, @@ -31,7 +38,6 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ const [focusedIndex, setFocusedIndex] = useState(null); const activeSeq = useSyncExternalStore(activePrompt.subscribe, activePrompt.getActiveSeq); const prefersReducedMotion = useReducedMotion(); - const { onLayout, isBelow: isPanelNarrow } = useContainerWidthBelow(MIN_PANEL_WIDTH); const hoverIntent = useMemo( () => @@ -60,9 +66,6 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ ); const handlePointerLeaveRail = useCallback(() => hoverIntent.leave(), [hoverIntent]); useEffect(() => () => hoverIntent.dispose(), [hoverIntent]); - useEffect(() => { - if (isPanelNarrow) hoverIntent.leave(); - }, [hoverIntent, isPanelNarrow]); const handleFocusChange = useCallback((index: number, focused: boolean) => { setFocusedIndex((current) => { if (focused) return index; @@ -74,40 +77,34 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ // same band and the same preview once the pointer leaves. const attentionIndex = hoveredIndex ?? focusedIndex; - if (prompts.length < 2) return null; - return ( - - {isPanelNarrow ? null : ( - - {prompts.map((prompt, index) => ( - - ))} - - )} + + {prompts.map((prompt, index) => ( + + ))} ); }); @@ -185,13 +182,9 @@ const ChatOutlineTick = memo(function ChatOutlineTick({ }); const styles = StyleSheet.create((theme) => ({ - panelMeasure: { - position: "absolute", - inset: 0, - }, rail: { position: "absolute", - left: theme.spacing[2], + left: RAIL_LEFT, top: "10%", bottom: "10%", width: RAIL_WIDTH, diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 465d98e8d886..ccc789f6b58d 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -314,6 +314,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool olderHistoryProgressKey, scrollEnabled, contentMaxWidth, + outlineInset = 0, isMobileBreakpoint, } = props; const historyVirtualized = useRevisedHistoryRows( @@ -453,7 +454,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool unsubscribe?.(); }; }, []); - const contentWidth = contentRef.current?.getBoundingClientRect().width; + // The scroll viewport keeps its width when the reading column changes. + // Track the effective column width for cached measurements and estimates. + const readContentWidth = () => { + const available = rowsHostRef.current?.getBoundingClientRect().width; + return available ? Math.min(available, contentMaxWidth ?? available) : contentMaxWidth; + }; + const contentWidth = readContentWidth(); const rowVirtualizer = useVirtualizer({ count: segments.historyVirtualized.length, enabled: shouldUseVirtualizer, @@ -469,7 +476,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const row = segments.historyVirtualized[index]; const measured = row && measuredRowHeights.current.get(row.id); if (measured && measured.width === contentWidth) return measured.height; - return row ? estimateStreamItemHeight({ item: row, contentMaxWidth }) : 120; + return row + ? estimateStreamItemHeight({ item: row, contentMaxWidth: contentWidth ?? 0 }) + : 120; }, observeElementOffset: observeVirtualOffset, rangeExtractor, @@ -477,6 +486,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool overscan: 8, }); rowVirtualizerRef.current = rowVirtualizer; + useLayoutEffect(() => { + // Discard offscreen sizes measured with the previous text wrapping. + rowVirtualizer.measure(); + }, [contentMaxWidth, outlineInset, rowVirtualizer]); // Scroll correction belongs to the viewport's committed layout. The virtualizer // otherwise writes scrollTop before React applies its new row positions. rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false; @@ -722,7 +735,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool if (!container || !content) return null; const viewportTop = container.getBoundingClientRect().top; const scrollTop = container.scrollTop; - const width = content.getBoundingClientRect().width; + const width = readContentWidth() ?? 0; return Array.from(content.querySelectorAll("[data-history-row-id]"), (element) => { const bounds = element.getBoundingClientRect(); const id = element.dataset.historyRowId!; @@ -1215,17 +1228,24 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool ]); const contentContainerStyle = useMemo((): CSSProperties => { + const gutter = isMobileBreakpoint ? 8 : 16; + const leftGutter = gutter + outlineInset; + // Balance the outline gutter using only the space the capped column has left over. + const rightGutter = + outlineInset > 0 && contentMaxWidth !== undefined + ? `clamp(${gutter}px, calc(100% - ${leftGutter + contentMaxWidth}px), ${leftGutter}px)` + : gutter; return { display: "flex", flexDirection: "column", minHeight: "100%", paddingTop: CONTENT_PADDING_TOP_PX, paddingBottom: 16, - paddingLeft: isMobileBreakpoint ? 8 : 16, - paddingRight: isMobileBreakpoint ? 8 : 16, + paddingLeft: leftGutter, + paddingRight: rightGutter, boxSizing: "border-box", }; - }, [isMobileBreakpoint]); + }, [contentMaxWidth, isMobileBreakpoint, outlineInset]); const scrollContainerStyle = useMemo((): CSSProperties => { const overlayScrollbarEnabled = scrollEnabled && !isMobileBreakpoint; return { diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index aab5b0413e60..7507f3442bee 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -107,7 +107,8 @@ export interface StreamRenderInput { baseListContentContainerStyle: StyleProp; forwardListContentContainerStyle: StyleProp; // The chat column's max width. The web viewport estimates unmeasured row heights with it. - contentMaxWidth: number; + contentMaxWidth: number | undefined; + outlineInset?: number; } export interface ResolveStreamRenderStrategyInput { diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 9f71998a4198..149e863400ce 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -80,7 +80,7 @@ import { resolveStreamRenderStrategy } from "./strategy-resolver"; import { type StreamSegmentRenderers, type StreamViewportHandle } from "./strategy"; import { renderStreamRow, type RenderStreamItem } from "./stream-row"; import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom"; -import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail"; +import { ChatOutlineRail, useChatOutlineRailLayout } from "@/agent-stream/chat-outline/rail"; import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; @@ -617,19 +617,22 @@ const AgentStreamViewComponent = forwardRef ({ @@ -1173,7 +1176,10 @@ const AgentStreamViewComponent = forwardRef - + @@ -1202,15 +1208,18 @@ const AgentStreamViewComponent = forwardRef - + {outlineLayout.inset > 0 && chatOutline.prompts.length >= 2 ? ( + + ) : null} }; } @@ -105,10 +105,13 @@ describe("applyAppearance", () => { ]); }); - it("patches the content max width into the theme", () => { - applyAppearance(makeInput({ contentMaxWidth: 1600 })); + it.each([ + [1600, "1600px"], + [undefined, "100%"], + ])("uses a CSS variable-compatible width on web for %s", (contentMaxWidth, cssWidth) => { + applyAppearance(makeInput({ contentMaxWidth })); - expect(runCapturedUpdater().contentMaxWidth).toBe(1600); + expect(runCapturedUpdater().contentMaxWidth).toBe(cssWidth); }); it("resolves an empty UI font family to the default stack", () => { diff --git a/packages/app/src/appearance/apply.ts b/packages/app/src/appearance/apply.ts index 04032a00b049..ea4486fe6323 100644 --- a/packages/app/src/appearance/apply.ts +++ b/packages/app/src/appearance/apply.ts @@ -5,6 +5,7 @@ import { DEFAULT_MONO_FONT_STACK, FONT_SIZE, REGISTERED_THEMES, + themeContentMaxWidth, type Theme, } from "@/styles/theme"; import { applyRootUiFont } from "./apply-root-font"; @@ -17,7 +18,7 @@ export interface AppearanceInput { uiBaseFontSize: number; // already clamped contentFontSize: number; // already clamped codeFontSize: number; // already clamped - contentMaxWidth: number; // already clamped, default resolved + contentMaxWidth: number | undefined; // undefined fills the available width syntaxTheme: SyntaxThemeId; } @@ -64,6 +65,7 @@ export function applyAppearance(input: AppearanceInput): void { const ui = input.uiFontFamily.trim() || DEFAULT_UI_FONT_STACK; const mono = input.monoFontFamily.trim() || DEFAULT_MONO_FONT_STACK; const diffLineHeight = Math.round(input.codeFontSize * 1.5); // couple to code size + const contentMaxWidth = themeContentMaxWidth(input.contentMaxWidth); const activeTheme = UnistylesRuntime.themeName; // Unistyles web emits after each registry patch. Updating the mounted theme // first ensures subscribers receive its new numeric tokens in this render; @@ -87,7 +89,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; } @@ -96,7 +98,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; }); diff --git a/packages/app/src/appearance/provider.tsx b/packages/app/src/appearance/provider.tsx index 77addad9a319..6466221197b7 100644 --- a/packages/app/src/appearance/provider.tsx +++ b/packages/app/src/appearance/provider.tsx @@ -65,6 +65,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { return options.find((option) => option.id === settings.pluginThemeId) ?? null; }, [options, settings.pluginThemeId, settings.theme]); + const contentMaxWidth = resolveContentMaxWidth(settings); useEffect(() => { if (isLoading) return; applyTheme({ preference: settings.theme, contributedTheme: selected }); @@ -74,7 +75,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { uiBaseFontSize: settings.uiBaseFontSize, contentFontSize: settings.contentFontSize, codeFontSize: settings.codeFontSize, - contentMaxWidth: resolveContentMaxWidth({ contentMaxWidth: settings.contentMaxWidth }), + contentMaxWidth, syntaxTheme: settings.syntaxTheme, }); setHasAppliedAppearance(true); @@ -87,7 +88,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { settings.uiBaseFontSize, settings.contentFontSize, settings.codeFontSize, - settings.contentMaxWidth, + contentMaxWidth, settings.syntaxTheme, ]); diff --git a/packages/app/src/assistant-selection-copy/surface.tsx b/packages/app/src/assistant-selection-copy/surface.tsx index 4f6464c190d1..691f7e3d6e5a 100644 --- a/packages/app/src/assistant-selection-copy/surface.tsx +++ b/packages/app/src/assistant-selection-copy/surface.tsx @@ -1,14 +1,20 @@ import type { ReactNode } from "react"; -import { View, type StyleProp, type ViewStyle } from "react-native"; +import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native"; interface AssistantSelectionCopySurfaceProps { children: ReactNode; style?: StyleProp; + onLayout?: (event: LayoutChangeEvent) => void; } export function AssistantSelectionCopySurface({ children, style, + onLayout, }: AssistantSelectionCopySurfaceProps) { - return {children}; + return ( + + {children} + + ); } diff --git a/packages/app/src/assistant-selection-copy/surface.web.tsx b/packages/app/src/assistant-selection-copy/surface.web.tsx index 280688b61e15..57ddd94e61a1 100644 --- a/packages/app/src/assistant-selection-copy/surface.web.tsx +++ b/packages/app/src/assistant-selection-copy/surface.web.tsx @@ -1,10 +1,11 @@ import { useCallback, type ClipboardEvent, type CSSProperties, type ReactNode } from "react"; -import { View, type StyleProp, type ViewStyle } from "react-native"; +import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native"; import { createAssistantSelectionClipboardContent } from "./content.web"; interface AssistantSelectionCopySurfaceProps { children: ReactNode; style?: StyleProp; + onLayout?: (event: LayoutChangeEvent) => void; } const DISPLAY_CONTENTS: CSSProperties = { display: "contents" }; @@ -12,6 +13,7 @@ const DISPLAY_CONTENTS: CSSProperties = { display: "contents" }; export function AssistantSelectionCopySurface({ children, style, + onLayout, }: AssistantSelectionCopySurfaceProps) { const handleCopy = useCallback((event: ClipboardEvent) => { const content = createAssistantSelectionClipboardContent(window.getSelection()); @@ -26,7 +28,9 @@ export function AssistantSelectionCopySurface({ return (
- {children} + + {children} +
); } diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index 5b18b7499dda..e0221d56d1a4 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -25,7 +25,7 @@ export interface SegmentedControlOption { interface SegmentedControlProps { options: SegmentedControlOption[]; - value: T; + value: T | null; onValueChange: (value: T) => void; size?: ControlSize; hideLabels?: boolean; @@ -112,7 +112,7 @@ function SegmentItem({ hideLabels: boolean; segmentSizeStyle: StyleProp; labelSizeStyle: StyleProp; - currentValue: T; + currentValue: T | null; onValueChange: (value: T) => void; }) { const labelStyle = useMemo( diff --git a/packages/app/src/hooks/use-settings/index.ts b/packages/app/src/hooks/use-settings/index.ts index 382ab350fc12..9113b2e6e40c 100644 --- a/packages/app/src/hooks/use-settings/index.ts +++ b/packages/app/src/hooks/use-settings/index.ts @@ -23,19 +23,16 @@ import { DEFAULT_UI_BASE_FONT_SIZE, MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, - MAX_CONTENT_MAX_WIDTH, MAX_TERMINAL_SCROLLBACK_LINES, MAX_UI_BASE_FONT_SIZE, MIN_CODE_FONT_SIZE, MIN_CONTENT_FONT_SIZE, - MIN_CONTENT_MAX_WIDTH, MIN_TERMINAL_SCROLLBACK_LINES, MIN_UI_BASE_FONT_SIZE, loadAppSettingsFromStorage as loadAppSettingsFromStoragePure, loadSettingsFromStorage as loadSettingsFromStoragePure, normalizeAppSettings, parseClampedFontSize, - parseContentMaxWidth, parseTerminalScrollbackLines, resolveContentMaxWidth, sanitizeFontFamily, @@ -43,6 +40,7 @@ import { type AppSettings, type AppSettingsUpdate, type ChatDisplay, + type ContentWidthPreset, type OpenInSidePanePreferences, type PullRequestOpenLocation, type DesktopSettingsBridge, @@ -69,16 +67,13 @@ export { DEFAULT_UI_BASE_FONT_SIZE, MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, - MAX_CONTENT_MAX_WIDTH, MAX_TERMINAL_SCROLLBACK_LINES, MAX_UI_BASE_FONT_SIZE, MIN_CODE_FONT_SIZE, MIN_CONTENT_FONT_SIZE, - MIN_CONTENT_MAX_WIDTH, MIN_TERMINAL_SCROLLBACK_LINES, MIN_UI_BASE_FONT_SIZE, parseClampedFontSize, - parseContentMaxWidth, parseTerminalScrollbackLines, resolveContentMaxWidth, sanitizeFontFamily, @@ -87,6 +82,7 @@ export type { AppSettings, AppSettingsUpdate, ChatDisplay, + ContentWidthPreset, AppLanguage, OpenInSidePanePreferences, PullRequestOpenLocation, diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index 8f426f9f2bea..55e2d2085b87 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -1121,49 +1121,64 @@ describe("parseClampedFontSize", () => { }); }); -describe("content max width", () => { - it("follows the current default until the user picks a width", async () => { +describe("content width", () => { + it("uses the default width when no preference is saved", async () => { const deps = makeDeps(); const queryClient = new QueryClient(); await saveAppSettings({ queryClient, updates: { codeFontSize: 14 }, deps }); - const stored = JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null"); - expect(stored.contentMaxWidth).toBeNull(); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe( - DEFAULT_CONTENT_MAX_WIDTH, - ); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe("default"); + expect(resolveContentMaxWidth(settings)).toBe(DEFAULT_CONTENT_MAX_WIDTH); }); - it("keeps a picked width and returns to the default when reset", async () => { + it.each([ + ["wide", 1200], + ["full", undefined], + ["default", DEFAULT_CONTENT_MAX_WIDTH], + ] as const)("persists the %s preset and resolves its width", async (contentWidth, expected) => { const deps = makeDeps(); const queryClient = new QueryClient(); + await saveAppSettings({ queryClient, updates: { contentWidth }, deps }); - await saveAppSettings({ queryClient, updates: { contentMaxWidth: 1600 }, deps }); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe(1600); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe(contentWidth); + expect(resolveContentMaxWidth(settings)).toBe(expected); + }); - await saveAppSettings({ queryClient, updates: { contentMaxWidth: null }, deps }); - expect(JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null").contentMaxWidth).toBe( - null, - ); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe( - DEFAULT_CONTENT_MAX_WIDTH, - ); + it("preserves a legacy custom width until a preset is picked", async () => { + const deps = makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth: 1600 }), + }), + }); + const queryClient = new QueryClient(); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe(1600); + expect(resolveContentMaxWidth(settings)).toBe(1600); + + await saveAppSettings({ queryClient, updates: { codeFontSize: 14 }, deps }); + expect((await loadAppSettingsFromStorage(deps)).contentWidth).toBe(1600); + + await saveAppSettings({ queryClient, updates: { contentWidth: "default" }, deps }); + expect((await loadAppSettingsFromStorage(deps)).contentWidth).toBe("default"); }); - it("clamps stored widths and drops malformed ones to the default", async () => { - const load = (contentMaxWidth: unknown) => - loadAppSettingsFromStorage( - makeDeps({ - storage: createInMemoryKeyValueStorage({ - [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth }), - }), + it.each([ + [100_000, 4000], + [10, 600], + [null, "default"], + ["wide", "default"], + ])("normalizes legacy width %s on load", async (contentMaxWidth, expected) => { + const settings = await loadAppSettingsFromStorage( + makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth }), }), - ); - - expect((await load(100_000)).contentMaxWidth).toBe(4000); - expect((await load(10)).contentMaxWidth).toBe(600); - expect((await load("wide")).contentMaxWidth).toBeNull(); + }), + ); + expect(settings.contentWidth).toBe(expected); }); }); diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index f04b7b6d94f3..11ba437dd4fd 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -73,8 +73,11 @@ export const MIN_CODE_FONT_SIZE = 9; export const MAX_CODE_FONT_SIZE = 22; // line-height 1.5×22=33 stays safe export const MAX_FONT_FAMILY_LENGTH = 200; export { DEFAULT_CONTENT_MAX_WIDTH }; -export const MIN_CONTENT_MAX_WIDTH = 600; -export const MAX_CONTENT_MAX_WIDTH = 4000; +const WIDE_CONTENT_MAX_WIDTH = 1200; +const legacyContentMaxWidthSchema = clampedNumber(600, 4000); +const contentWidthPresetSchema = z.enum(["default", "wide", "full"]); +export type ContentWidthPreset = z.infer; +type ContentWidth = ContentWidthPreset | number; export interface AppSettings { theme: ThemePreference; @@ -89,8 +92,8 @@ export interface AppSettings { uiBaseFontSize: number; // clamped px, platform default 14 or 15 contentFontSize: number; // clamped px, platform default 15 or 16 codeFontSize: number; // clamped px, default 12 - /** Max width of chat and markdown content in px; null follows the current default. */ - contentMaxWidth: number | null; + /** Numbers preserve widths saved before presets were introduced. */ + contentWidth: ContentWidth; syntaxTheme: SyntaxThemeId; // default "one" workspaceTitleSource: WorkspaceTitleSource; sidebarWorkspaceTrailing: SidebarWorkspaceTrailing; @@ -152,7 +155,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { uiBaseFontSize: DEFAULT_UI_BASE_FONT_SIZE, contentFontSize: DEFAULT_CONTENT_FONT_SIZE, codeFontSize: DEFAULT_CODE_FONT_SIZE, - contentMaxWidth: null, + contentWidth: "default", syntaxTheme: "one", workspaceTitleSource: "title", sidebarWorkspaceTrailing: "timestamp", @@ -244,10 +247,12 @@ const StoredAppSettingsSchema = z codeFontSize: clampedNumber(MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE).catch( DEFAULT_CODE_FONT_SIZE, ), - contentMaxWidth: z - .null() - .or(clampedNumber(MIN_CONTENT_MAX_WIDTH, MAX_CONTENT_MAX_WIDTH)) - .catch(null), + contentWidth: contentWidthPresetSchema + .or(legacyContentMaxWidthSchema) + .optional() + .catch(undefined), + // COMPAT(contentMaxWidth): preserve the previous numeric preference. + contentMaxWidth: legacyContentMaxWidthSchema.nullish().catch(undefined), syntaxTheme: z.string().refine(isSyntaxThemeId).catch("one"), workspaceTitleSource: z.enum(["title", "branch"]).catch("title"), sidebarWorkspaceTrailing: z.enum(["diff", "timestamp", "none"]).catch("timestamp"), @@ -303,9 +308,10 @@ const StoredAppSettingsSchema = z manageBuiltInDaemon: z.boolean().optional().catch(undefined), releaseChannel: z.enum(["stable", "beta"]).optional().catch(undefined), }) - .transform((stored) => { + .transform(({ contentMaxWidth, ...stored }) => { const { legacyPullRequestsInSidePane, ...openInSidePane } = stored.openInSidePane; const needsWrite = + contentMaxWidth !== undefined || (stored.uiBaseFontSize === undefined && stored.uiFontSize !== undefined) || stored.contentFontSize === undefined; const uiBaseFontSize = @@ -324,6 +330,7 @@ const StoredAppSettingsSchema = z const chatDisplay = stored.chatDisplay ?? (groupsToolCalls ? "collapseToolCalls" : "full"); return { ...stored, + contentWidth: stored.contentWidth ?? contentMaxWidth ?? "default", openInSidePane, pullRequestOpenLocation: stored.pullRequestOpenLocation ?? (legacyPullRequestsInSidePane ? "side" : "explorer"), @@ -497,12 +504,19 @@ export function parseTerminalScrollbackLines(value: unknown): number | null { ); } -export function parseContentMaxWidth(value: unknown): number | null { - return parseClampedFontSize(value, { min: MIN_CONTENT_MAX_WIDTH, max: MAX_CONTENT_MAX_WIDTH }); -} - -export function resolveContentMaxWidth(settings: Pick): number { - return settings.contentMaxWidth ?? DEFAULT_CONTENT_MAX_WIDTH; +export function resolveContentMaxWidth({ + contentWidth, +}: Pick): number | undefined { + switch (contentWidth) { + case "default": + return DEFAULT_CONTENT_MAX_WIDTH; + case "wide": + return WIDE_CONTENT_MAX_WIDTH; + case "full": + return undefined; + default: + return contentWidth; + } } export function parseClampedFontSize( diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 8050a802edd9..a2a16fc3e422 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2711,10 +2711,11 @@ export const ar: TranslationResources = { layout: { title: "التخطيط", contentWidth: "عرض المحتوى", - contentWidthHint: "أقصى عرض للمحادثة وملفات Markdown على الشاشات العريضة", - contentWidthAccessibility: "عرض المحتوى بالبكسل", - reset: "إعادة تعيين", - resetAccessibility: "إعادة عرض المحتوى إلى الافتراضي", + contentWidthHint: "عرض المحادثة ومحرر الرسائل ومعاينات Markdown", + contentWidthDefault: "افتراضي", + contentWidthWide: "عريض", + contentWidthFull: "كامل", + contentWidthCustom: "عرض مخصص · {{width}} بكسل", }, syntax: { title: "بناء الجملة", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 5f916373d49b..540e98479664 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2806,10 +2806,11 @@ export const en = { layout: { title: "Layout", contentWidth: "Content width", - contentWidthHint: "Max width of chat and Markdown files on wide screens", - contentWidthAccessibility: "Content width in pixels", - reset: "Reset", - resetAccessibility: "Reset content width to default", + contentWidthHint: "Width of chat, composer, and Markdown previews", + contentWidthDefault: "Default", + contentWidthWide: "Wide", + contentWidthFull: "Full", + contentWidthCustom: "Custom width · {{width}} px", }, syntax: { title: "Syntax", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 23fea2743a3f..cbd4b7ffd08e 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2734,10 +2734,11 @@ export const es: TranslationResources = { layout: { title: "Diseño", contentWidth: "Ancho del contenido", - contentWidthHint: "Ancho máximo del chat y de los archivos Markdown en pantallas anchas", - contentWidthAccessibility: "Ancho del contenido en píxeles", - reset: "Restablecer", - resetAccessibility: "Restablecer el ancho del contenido", + contentWidthHint: "Ancho del chat, el campo de mensaje y las vistas previas de Markdown", + contentWidthDefault: "Predeterminado", + contentWidthWide: "Ancho", + contentWidthFull: "Completo", + contentWidthCustom: "Ancho personalizado · {{width}} px", }, syntax: { title: "Sintaxis", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 2d451eed8824..d02d9688f5a4 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2735,11 +2735,11 @@ export const fr: TranslationResources = { layout: { title: "Mise en page", contentWidth: "Largeur du contenu", - contentWidthHint: - "Largeur maximale de la discussion et des fichiers Markdown sur les grands écrans", - contentWidthAccessibility: "Largeur du contenu en pixels", - reset: "Réinitialiser", - resetAccessibility: "Réinitialiser la largeur du contenu", + contentWidthHint: "Largeur du chat, de la zone de saisie et des aperçus Markdown", + contentWidthDefault: "Par défaut", + contentWidthWide: "Large", + contentWidthFull: "Pleine largeur", + contentWidthCustom: "Largeur personnalisée · {{width}} px", }, syntax: { title: "Syntaxe", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 2ba764a894fa..79630973c4f3 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2700,10 +2700,11 @@ export const ja: TranslationResources = { layout: { title: "レイアウト", contentWidth: "コンテンツ幅", - contentWidthHint: "ワイド画面でのチャットと Markdown ファイルの最大幅", - contentWidthAccessibility: "コンテンツ幅 (ピクセル)", - reset: "リセット", - resetAccessibility: "コンテンツ幅をデフォルトに戻す", + contentWidthHint: "チャット、入力欄、Markdown プレビューの幅", + contentWidthDefault: "標準", + contentWidthWide: "ワイド", + contentWidthFull: "全幅", + contentWidthCustom: "カスタム幅 · {{width}} px", }, syntax: { title: "構文ハイライト", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index e4988e9a19f8..eaa456998658 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2690,10 +2690,11 @@ export const ko: TranslationResources = { layout: { title: "레이아웃", contentWidth: "콘텐츠 너비", - contentWidthHint: "와이드 화면에서 채팅과 Markdown 파일의 최대 너비", - contentWidthAccessibility: "콘텐츠 너비(픽셀)", - reset: "재설정", - resetAccessibility: "콘텐츠 너비를 기본값으로 재설정", + contentWidthHint: "채팅, 메시지 입력란, Markdown 미리보기의 너비", + contentWidthDefault: "기본", + contentWidthWide: "넓게", + contentWidthFull: "전체", + contentWidthCustom: "사용자 지정 너비 · {{width}} px", }, syntax: { title: "구문", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index d92dffa1b67a..7f3ac5e25159 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2714,10 +2714,11 @@ export const ptBR: TranslationResources = { layout: { title: "Layout", contentWidth: "Largura do conteúdo", - contentWidthHint: "Largura máxima do chat e dos arquivos Markdown em telas largas", - contentWidthAccessibility: "Largura do conteúdo em pixels", - reset: "Redefinir", - resetAccessibility: "Redefinir a largura do conteúdo", + contentWidthHint: "Largura do chat, do campo de mensagem e das prévias de Markdown", + contentWidthDefault: "Padrão", + contentWidthWide: "Largo", + contentWidthFull: "Total", + contentWidthCustom: "Largura personalizada · {{width}} px", }, syntax: { title: "Sintaxe", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index cda5ba01215c..a200079654ae 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2722,10 +2722,11 @@ export const ru: TranslationResources = { layout: { title: "Макет", contentWidth: "Ширина содержимого", - contentWidthHint: "Максимальная ширина чата и файлов Markdown на широких экранах", - contentWidthAccessibility: "Ширина содержимого в пикселях", - reset: "Сбросить", - resetAccessibility: "Сбросить ширину содержимого", + contentWidthHint: "Ширина чата, поля ввода и предпросмотра Markdown", + contentWidthDefault: "По умолчанию", + contentWidthWide: "Широкий", + contentWidthFull: "На всю ширину", + contentWidthCustom: "Своя ширина · {{width}} пкс", }, syntax: { title: "Синтаксис", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index e8e59a127e64..fc253b1b6723 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2646,10 +2646,11 @@ export const zhCN: TranslationResources = { layout: { title: "布局", contentWidth: "内容宽度", - contentWidthHint: "宽屏上聊天和 Markdown 文件的最大宽度", - contentWidthAccessibility: "内容宽度(像素)", - reset: "重置", - resetAccessibility: "将内容宽度重置为默认值", + contentWidthHint: "聊天、消息输入框和 Markdown 预览的宽度", + contentWidthDefault: "默认", + contentWidthWide: "宽版", + contentWidthFull: "全宽", + contentWidthCustom: "自定义宽度 · {{width}} px", }, syntax: { title: "语法", diff --git a/packages/app/src/screens/settings/appearance/appearance-section.tsx b/packages/app/src/screens/settings/appearance/appearance-section.tsx index 9ff6adccade7..3600d97b6d4f 100644 --- a/packages/app/src/screens/settings/appearance/appearance-section.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-section.tsx @@ -13,7 +13,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/component import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; import { SettingsSection } from "@/components/settings/headings/settings-section"; import { ThemePicker } from "@/appearance/theme-picker"; -import { Button } from "@/components/ui/button"; +import { SegmentedControl } from "@/components/ui/segmented-control"; import { EditingTextInput, type EditingTextInputHandle } from "@/components/ui/text-input"; import { MAX_CODE_FONT_SIZE, @@ -23,11 +23,10 @@ import { MIN_CONTENT_FONT_SIZE, MIN_UI_BASE_FONT_SIZE, parseClampedFontSize, - parseContentMaxWidth, - resolveContentMaxWidth, sanitizeFontFamily, useAppSettings, type AppSettings, + type ContentWidthPreset, } from "@/hooks/use-settings"; import { DEFAULT_MONO_FONT_STACK, DEFAULT_UI_FONT_STACK } from "@/styles/theme"; import { isNative } from "@/constants/platform"; @@ -172,68 +171,35 @@ function FontSizeRow({ } // --------------------------------------------------------------------------- -// Content width: numeric field (commit on blur/submit) + reset to the default -// --------------------------------------------------------------------------- - -interface ContentWidthRowProps { - value: AppSettings["contentMaxWidth"]; - onChange: (value: AppSettings["contentMaxWidth"]) => void; -} - -function ContentWidthRow({ value, onChange }: ContentWidthRowProps) { +function ContentWidthRow({ + value, + onChange, +}: { + value: AppSettings["contentWidth"]; + onChange: (value: ContentWidthPreset) => void; +}) { const { t } = useTranslation(); - const width = resolveContentMaxWidth({ contentMaxWidth: value }); - // The field is uncontrolled, so a saved or reset width is written into it directly. - const input = useRef(null); - - useEffect(() => { - input.current?.replaceText(String(width)); - }, [width]); - - const commit = useCallback(() => { - const next = parseContentMaxWidth(input.current?.getText()) ?? width; - input.current?.replaceText(String(next)); - // Typing the width already in effect keeps following the default. - if (next !== width) { - onChange(next); - } - }, [onChange, width]); - - const reset = useCallback(() => { - onChange(null); - }, [onChange]); return ( - - + + {t("settings.appearance.layout.contentWidth")} - {t("settings.appearance.layout.contentWidthHint")} + {typeof value === "number" + ? t("settings.appearance.layout.contentWidthCustom", { width: value }) + : t("settings.appearance.layout.contentWidthHint")} - - {value === null ? null : ( - - )} - - px - + + testID="content-width-options" + value={typeof value === "number" ? null : value} + onValueChange={onChange} + options={[ + { value: "default", label: t("settings.appearance.layout.contentWidthDefault") }, + { value: "wide", label: t("settings.appearance.layout.contentWidthWide") }, + { value: "full", label: t("settings.appearance.layout.contentWidthFull") }, + ]} + /> ); } @@ -333,9 +299,9 @@ export function AppearanceSection() { setCodeSizeDraft(String(settings.codeFontSize)); }, [settings.codeFontSize]); - const handleContentMaxWidthChange = useCallback( - (contentMaxWidth: AppSettings["contentMaxWidth"]) => { - void updateSettings({ contentMaxWidth }); + const handleContentWidthChange = useCallback( + (contentWidth: ContentWidthPreset) => { + void updateSettings({ contentWidth }); }, [updateSettings], ); @@ -504,10 +470,7 @@ export function AppearanceSection() { - + @@ -571,18 +534,10 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, textAlign: "right", }, - widthInput: { - width: 80, - minHeight: 36, - paddingVertical: theme.spacing[2], - paddingHorizontal: theme.spacing[3], - borderRadius: theme.borderRadius.md, - borderWidth: theme.borderWidth[1], - borderColor: theme.colors.border, - backgroundColor: theme.colors.surface2, - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - textAlign: "right", + contentWidthRow: { + alignItems: "flex-start", + gap: theme.spacing[2], + padding: theme.spacing[4], }, unit: { color: theme.colors.foregroundMuted, diff --git a/packages/app/src/styles/theme.ts b/packages/app/src/styles/theme.ts index f90594fa5567..a1bff0292bd5 100644 --- a/packages/app/src/styles/theme.ts +++ b/packages/app/src/styles/theme.ts @@ -1,4 +1,5 @@ -import { Platform } from "react-native"; +import { Platform, type ViewStyle } from "react-native"; +import { isWeb } from "@/constants/platform"; import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight"; import { deriveSurfaceStates } from "./derive-colors"; @@ -641,6 +642,17 @@ export const DEFAULT_MONO_FONT_STACK: string = Platform.select({ // Chat and markdown content column; the appearance updater patches the user's width in. export const DEFAULT_CONTENT_MAX_WIDTH = 820; +// On web Unistyles puts string tokens in CSS variables, so mounted content +// receives width changes without regenerating its classes. The px string is +// emitted as CSS by Unistyles. Native always receives a number or percentage. +export function themeContentMaxWidth( + width: number | undefined, +): NonNullable { + return isWeb && width !== undefined + ? (`${width}px` as NonNullable) + : (width ?? "100%"); +} + // `fontSize`, `fontFamily`, `lineHeight`, and `contentMaxWidth` are deliberately widened to plain // `number`/`string` (not narrowed by `as const`) so the appearance updater can patch // them at runtime via `UnistylesRuntime.updateTheme`. The remaining tokens keep their @@ -650,7 +662,7 @@ interface CommonTheme { fontSize: Record; fontFamily: { ui: string; mono: string }; lineHeight: Record; - contentMaxWidth: number; + contentMaxWidth: ReturnType; iconSize: typeof ICON_SIZE; fontWeight: typeof FONT_WEIGHT; borderRadius: typeof BORDER_RADIUS; @@ -663,7 +675,7 @@ const commonTheme: CommonTheme = { fontSize: FONT_SIZE, fontFamily: { ui: DEFAULT_UI_FONT_STACK, mono: DEFAULT_MONO_FONT_STACK }, lineHeight: LINE_HEIGHT, - contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + contentMaxWidth: themeContentMaxWidth(DEFAULT_CONTENT_MAX_WIDTH), iconSize: ICON_SIZE, fontWeight: FONT_WEIGHT, borderRadius: BORDER_RADIUS, From d5d385afa7dcbf9f1c9afb9fddc412e3daa1537e Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 19 Nov 2026 21:30:31 +0700 Subject: [PATCH 005/109] Show each provider's state in the list and open one provider page everywhere (#9661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(app): leave providers that are not installed out of the model picker An agent's own provider stays in its selector, labelled Unavailable. * feat(app): open a provider's detail as a Settings page or a sheet Settings → Providers now pushes a provider page, like Projects and Plugins; the model picker gear and setup keep a sheet. Both frame one body, ordered error, Enabled, Installation, Models, Troubleshooting, Danger zone, so the old sheet's sticky footer and Retry button are gone. Refresh lives once, in the Troubleshooting status row. The page header (back link, icon, title) moves into the shared settings kit so projects, plugins and providers line up on the same rails. * feat(app): show each provider's version, updates and faults in the list Each row now says how its provider is: version and model count, Update available, a spinner while an update runs, a red dot with the error, or Not installed / Disabled. Only a broken provider gets a dot, and a provider that is not installed has no switch, since the model picker already leaves it out. The kebab is gone; Remove lives on the detail. Rows read the same installation and update queries as the detail, so opening a provider costs no new requests. Hosts without providerInstallation still get a correct list from the snapshot alone. Add provider is a "+ Provider" button in the header and a muted last row; both open one sheet with search and catalog rows, replacing the tile grid. After Add, the new provider's detail opens. The row is the settings kit's detail row, which gains a leading icon, a hint status (spinner, error dot, or a held line) and a control before the chevron. The Unistyles test stub now applies withUnistyles theme mappings, so browser tests render components that read colours through the theme. * feat(app): open setup's provider pages over the setup card The detail and Add provider sheets take the setup card's frame and a back arrow, so they read as pages of setup instead of a sheet over it. The step is renamed "Your providers" to match the list it shows. * docs: describe the provider list and pages as they are now * fix(app): keep settings rows one height and on one icon rail on phones On touch layouts a switch reserves a 44px control, so in the provider list rows with a switch stood 10px taller than "Not installed" rows without one. Card rows now reserve a default control's height, the rule nested rows already follow. A compact SettingsRow wrapped with a full `gap`, which added 12px on top of the leading slot's margin: catalog icons sat 24px from their labels instead of 12px. The wrap only needs space between lines, so it uses `rowGap`. * fix(app): keep a provider row's error to one line A long or multi-line error wrapped the hint to two lines with the dot centred between them. The row cuts it to one line; the provider's page shows it in full. * fix(app): title a provider's Settings page like a project's The page title and the detail header both named the provider. The screen now titles it "Providers" and the page names the provider once, the way a project's page does. * fix(app): keep a settings row's switch out of the row's button The provider row's switch rendered inside the row's - - ); -} - -export function ProviderCatalogList({ - serverId, - installingProviderId, - onInstall, -}: ProviderCatalogListProps) { - const { t } = useTranslation(); - const { entries: catalogEntries } = useAcpProviderCatalog(); - const { entries: providerEntries } = useProvidersSnapshot(serverId); - const [search, setSearch] = useState(""); - const [gridWidth, setGridWidth] = useState(null); - - const installedIds = useMemo( - () => new Set(providerEntries?.map((entry) => entry.provider) ?? []), - [providerEntries], - ); - - const availableEntries = useMemo( - () => - rankProviderCatalog( - catalogEntries.filter((entry) => !installedIds.has(entry.id)), - search, - ), - [catalogEntries, installedIds, search], - ); - - const handleGridLayout = useCallback((event: LayoutChangeEvent) => { - setGridWidth(event.nativeEvent.layout.width); - }, []); - - const tileWidth = useMemo(() => { - if (gridWidth === null) return undefined; - const columns = columnCountForWidth(gridWidth); - if (columns === 1) return undefined; - return Math.floor((gridWidth - TILE_GAP * (columns - 1)) / columns); - }, [gridWidth]); - - return ( - - - - - - {availableEntries.length === 0 ? ( - - {t("providerCatalog.noProviders")} - - ) : ( - - {availableEntries.map((entry) => ( - - ))} - - )} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - searchRail: { - flexDirection: "row", - marginBottom: theme.spacing[3], - }, - grid: { - flexDirection: "row", - flexWrap: "wrap", - gap: TILE_GAP, - }, - tile: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[3], - padding: theme.spacing[3], - }, - tileFull: { - width: "100%", - }, - details: { - flex: 1, - minWidth: 0, - gap: theme.spacing[1], - }, - iconFrame: { - flexShrink: 0, - width: 36, - height: 36, - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - alignItems: "center", - justifyContent: "center", - }, - addButton: { - flexShrink: 0, - }, - name: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.normal, - }, - metaRow: { - flexDirection: "row", - flexWrap: "wrap", - alignItems: "center", - gap: theme.spacing[2], - }, - stateBox: { - minHeight: 96, - alignItems: "center", - justifyContent: "center", - padding: theme.spacing[4], - }, - stateText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, -})); diff --git a/packages/app/src/components/provider-diagnostic-sheet.tsx b/packages/app/src/components/provider-diagnostic-sheet.tsx deleted file mode 100644 index 2426088e9dfa..000000000000 --- a/packages/app/src/components/provider-diagnostic-sheet.tsx +++ /dev/null @@ -1,836 +0,0 @@ -import * as Clipboard from "expo-clipboard"; -import { AlertTriangle, Copy, FileText, Plus, RotateCw, Trash2 } from "lucide-react-native"; -import type { TFunction } from "i18next"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Pressable, type PressableStateCallbackType, Text, View } from "react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { - AdaptiveModalSheet, - AdaptiveTextInput, - SheetHeaderIconButton, - type SheetHeader, -} from "@/components/adaptive-modal-sheet"; -import { Button } from "@/components/ui/button"; -import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface"; -import { useIsCompactFormFactor } from "@/constants/layout"; -import { isWeb } from "@/constants/platform"; -import { useToast } from "@/contexts/toast-context"; -import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; -import { useTimeAgo } from "@/hooks/use-time-ago"; -import { useHostRuntimeClient } from "@/runtime/host-runtime"; -import { settingsStyles } from "@/styles/settings"; -import { resolveProviderLabel } from "@/utils/provider-definitions"; -import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; -import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types"; -import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config"; -import { ProviderInstallationSection } from "./provider-installation-section"; -import { useProviderInstallation } from "./provider-installation"; -import { - resolveProviderDiscoveredModels, - type ProviderDiscoveredModelsCache, -} from "./provider-diagnostic-models"; - -interface ProviderDiagnosticSheetProps { - provider: string; - visible: boolean; - onClose: () => void; - serverId: string; -} - -function rankModels(items: T[], query: string, fields: (item: T) => string[]): T[] { - if (!query.trim()) return items; - const scored = items - .map((item) => ({ item, score: scoreTextFields(query, fields(item)) })) - .filter( - (entry): entry is { item: T; score: NonNullable } => entry.score !== null, - ); - scored.sort((a, b) => compareMatchScores(a.score, b.score)); - return scored.map((entry) => entry.item); -} - -function DiscoveredModelRow({ model }: { model: AgentModelDefinition }) { - return ( - - - {model.label} - - - {model.id} - - {model.description ? ( - - {model.description} - - ) : null} - - ); -} - -function CustomModelRow({ - model, - deleting, - onDelete, -}: { - model: ProviderProfileModel; - deleting: boolean; - onDelete: (modelId: string) => void; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const handleDelete = useCallback(() => onDelete(model.id), [model.id, onDelete]); - const deleteButtonStyle = useCallback( - ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ - sheetStyles.iconButton, - (Boolean(hovered) || pressed) && sheetStyles.iconButtonHovered, - deleting ? sheetStyles.disabled : null, - ], - [deleting], - ); - - return ( - - - {model.label} - - - {model.id} - - - - - - - ); -} - -function SectionHeader({ title, count, hint }: { title: string; count?: number; hint?: string }) { - return ( - - {title} - - {count !== undefined ? ( - {count} - ) : null} - {count !== undefined && hint ? ( - · - ) : null} - {hint ? {hint} : null} - - - ); -} - -function AddCustomModelSubSheet({ - provider, - serverId, - visible, - onClose, - refresh, -}: { - provider: string; - serverId: string; - visible: boolean; - onClose: () => void; - refresh: (providers?: AgentProvider[]) => Promise; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const { config, patchConfig } = useDaemonConfig(serverId); - const [input, setInput] = useState(""); - const [error, setError] = useState(null); - const [saving, setSaving] = useState(false); - - const additionalModels = useMemo( - () => config?.providers?.[provider]?.additionalModels ?? [], - [config?.providers, provider], - ); - const trimmed = input.trim(); - const canAdd = trimmed.length > 0 && !additionalModels.some((model) => model.id === trimmed); - - useEffect(() => { - if (!visible) { - setInput(""); - setError(null); - } - }, [visible]); - - const handleAdd = useCallback(() => { - if (!canAdd) return; - setError(null); - setSaving(true); - void patchConfig({ - providers: { - [provider]: { - additionalModels: [...additionalModels, { id: trimmed, label: trimmed }], - }, - }, - }) - .then(() => refresh([provider])) - .then(() => onClose()) - .catch((err) => { - setError(err instanceof Error ? err.message : t("settings.providers.models.failedToSave")); - }) - .finally(() => setSaving(false)); - }, [additionalModels, canAdd, onClose, patchConfig, provider, refresh, t, trimmed]); - - const header = useMemo( - () => ({ title: t("settings.providers.models.addCustomTitle") }), - [t], - ); - - return ( - - - {t("settings.providers.models.modelId")} - - {error ? {error} : null} - - - - - - - ); -} - -function DiagnosticSubSheet({ - provider, - serverId, - visible, - onClose, -}: { - provider: string; - serverId: string; - visible: boolean; - onClose: () => void; -}) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const toast = useToast(); - const client = useHostRuntimeClient(serverId); - const [diagnostic, setDiagnostic] = useState(null); - const [loading, setLoading] = useState(false); - - const fetchDiagnostic = useCallback(async () => { - if (!client) return; - setLoading(true); - try { - const result = await client.getProviderDiagnostic(provider); - setDiagnostic(result.diagnostic); - } catch (err) { - setDiagnostic( - err instanceof Error ? err.message : t("settings.providers.diagnostic.failedToFetch"), - ); - } finally { - setLoading(false); - } - }, [client, provider, t]); - - useEffect(() => { - if (visible) { - void fetchDiagnostic(); - } else { - setDiagnostic(null); - } - }, [visible, fetchDiagnostic]); - - const handleRefreshPress = useCallback(() => { - void fetchDiagnostic(); - }, [fetchDiagnostic]); - - const handleCopyPress = useCallback(() => { - if (!diagnostic) return; - void Clipboard.setStringAsync(diagnostic) - .then(() => toast.copied(t("settings.providers.diagnostic.copyLabel"))) - .catch(() => toast.error(t("settings.providers.diagnostic.copyFailed"))); - }, [diagnostic, t, toast]); - - const header = useMemo( - () => ({ - title: t("settings.providers.diagnostic.title"), - actions: ( - <> - - - - ), - }), - [diagnostic, handleCopyPress, handleRefreshPress, loading, t], - ); - - let body: React.ReactNode; - if (loading && !diagnostic) { - body = ( - - - - {t("settings.providers.diagnostic.running")} - - - ); - } else if (diagnostic) { - body = ( - - {diagnostic} - - ); - } else { - body = ( - - - {t("settings.providers.diagnostic.none")} - - - ); - } - - return ( - - {body} - - ); -} - -interface ProviderModalBodyProps { - discoveredCount: number; - additionalCount: number; - providerSnapshotRefreshing: boolean; - providerErrorMessage: string | null; - modelsRefreshing: boolean; - searchActive: boolean; - filteredDiscovered: AgentModelDefinition[]; - filteredCustom: ProviderProfileModel[]; - deletingModelId: string | null; - onRefresh: () => void; - onDeleteCustom: (modelId: string) => void; - theme: { iconSize: { md: number }; colors: { foregroundMuted: string } }; -} - -interface ProviderSheetFooterInput { - fetchedAt: string | null; - isCompact: boolean; - /** Models or the installation are being read again. */ - refreshing: boolean; - t: TFunction; - onOpenAddSheet: () => void; - onOpenDiagSheet: () => void; - onRefreshModels: () => void; -} - -function renderProviderSheetFooter({ - fetchedAt, - isCompact, - refreshing, - t, - onOpenAddSheet, - onOpenDiagSheet, - onRefreshModels, -}: ProviderSheetFooterInput) { - const contentStyle = isCompact ? sheetStyles.compactFooterContent : sheetStyles.footerContent; - const actionsStyle = isCompact ? sheetStyles.compactFooterActions : sheetStyles.footerActions; - const buttonStyle = isCompact ? sheetStyles.compactFooterButton : null; - return ( - - {fetchedAt || !isCompact ? ( - - ) : null} - - - - - - - ); -} - -function ProviderUpdatedLabel({ - fetchedAt, - isCompact, -}: { - fetchedAt: string | null; - isCompact: boolean; -}) { - const { t } = useTranslation(); - const label = useTimeAgo(fetchedAt ? new Date(fetchedAt) : null); - const style = isCompact - ? [sheetStyles.footerMeta, sheetStyles.compactFooterMeta] - : sheetStyles.footerMeta; - return ( - - {fetchedAt ? t("settings.providers.models.updated", { time: label }) : ""} - - ); -} - -function ProviderModalBody(props: ProviderModalBodyProps) { - const { t } = useTranslation(); - const { - discoveredCount, - additionalCount, - providerSnapshotRefreshing, - providerErrorMessage, - modelsRefreshing, - searchActive, - filteredDiscovered, - filteredCustom, - deletingModelId, - onRefresh, - onDeleteCustom, - theme, - } = props; - - if (discoveredCount === 0 && additionalCount === 0 && providerSnapshotRefreshing) { - return ( - - - {t("settings.providers.models.loading")} - - ); - } - if (discoveredCount === 0 && additionalCount === 0 && providerErrorMessage) { - return ( - - - {providerErrorMessage} - - - ); - } - if (filteredDiscovered.length === 0 && filteredCustom.length === 0 && searchActive) { - return ( - - {t("settings.providers.models.noSearchMatches")} - - ); - } - if (discoveredCount === 0 && additionalCount === 0) { - return ( - - {t("settings.providers.models.noneDetected")} - - ); - } - return ( - <> - {filteredDiscovered.length > 0 ? ( - - - - {filteredDiscovered.map((model) => ( - - ))} - - - ) : null} - {filteredCustom.length > 0 ? ( - - - - {filteredCustom.map((model) => ( - - ))} - - - ) : null} - - ); -} - -export function ProviderDiagnosticSheet({ - provider, - visible, - onClose, - serverId, -}: ProviderDiagnosticSheetProps) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const isCompact = useIsCompactFormFactor(); - const { entries: snapshotEntries, refresh, isRefreshing } = useProvidersSnapshot(serverId); - const { config, patchConfig } = useDaemonConfig(serverId); - const [query, setQuery] = useState(""); - const [addSheetOpen, setAddSheetOpen] = useState(false); - const [diagSheetOpen, setDiagSheetOpen] = useState(false); - const [deletingModelId, setDeletingModelId] = useState(null); - - const providerLabel = resolveProviderLabel(provider, snapshotEntries); - const providerEntry = useMemo( - () => snapshotEntries?.find((entry) => entry.provider === provider), - [snapshotEntries, provider], - ); - const additionalModels = useMemo( - () => config?.providers?.[provider]?.additionalModels ?? [], - [config?.providers, provider], - ); - const providerSnapshotRefreshing = providerEntry?.status === "loading"; - const providerErrorMessage = - providerEntry?.status === "error" - ? (providerEntry.error ?? t("settings.providers.diagnostic.unknownError")) - : null; - const modelsRefreshing = isRefreshing || providerSnapshotRefreshing; - - const stableDiscoveredRef = useRef(null); - const currentModels = providerEntry?.models; - const { models: discoveredModels, cache: nextDiscoveredCache } = resolveProviderDiscoveredModels({ - serverId, - provider, - currentModels, - providerSnapshotRefreshing, - previousCache: stableDiscoveredRef.current, - }); - stableDiscoveredRef.current = nextDiscoveredCache; - - useEffect(() => { - if (!visible) { - setQuery(""); - setAddSheetOpen(false); - setDiagSheetOpen(false); - } - }, [visible]); - - const q = query.trim(); - const filteredDiscovered = useMemo( - () => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]), - [discoveredModels, q], - ); - const filteredCustom = useMemo( - () => rankModels(additionalModels, q, (m) => [m.label, m.id]), - [additionalModels, q], - ); - - const installation = useProviderInstallation({ serverId, provider, visible }); - const refreshInstallation = installation.refresh; - const handleRefreshModels = useCallback(() => { - void refresh([provider]); - refreshInstallation(); - }, [provider, refresh, refreshInstallation]); - - const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []); - const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []); - const handleOpenDiagSheet = useCallback(() => setDiagSheetOpen(true), []); - const handleCloseDiagSheet = useCallback(() => setDiagSheetOpen(false), []); - - const handleDeleteCustom = useCallback( - (modelId: string) => { - setDeletingModelId(modelId); - void patchConfig({ - providers: { - [provider]: { - additionalModels: additionalModels.filter((model) => model.id !== modelId), - }, - }, - }) - .then(() => refresh([provider])) - .finally(() => { - setDeletingModelId((current) => (current === modelId ? null : current)); - }); - }, - [additionalModels, patchConfig, provider, refresh], - ); - - const sheetHeader = useMemo( - () => ({ - title: providerLabel, - search: { - onChange: setQuery, - placeholder: t("settings.providers.models.searchPlaceholder"), - testID: "provider-settings-search", - }, - }), - [providerLabel, t], - ); - - return ( - <> - - - - - - - - ); -} - -const sheetStyles = StyleSheet.create((theme) => ({ - mutedText: { - fontSize: theme.fontSize.base, - color: theme.colors.foregroundMuted, - }, - monoHint: { - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.code, - color: theme.colors.foregroundMuted, - flexShrink: 0, - }, - descriptionInline: { - flex: 1, - fontSize: theme.fontSize.sm, - color: theme.colors.foregroundMuted, - }, - errorText: { - fontSize: theme.fontSize.sm, - color: theme.colors.destructive, - }, - formInput: { - backgroundColor: theme.colors.surface2, - borderRadius: theme.borderRadius.lg, - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - color: theme.colors.foreground, - borderWidth: 1, - borderColor: theme.colors.border, - fontSize: theme.fontSize.base, - }, - iconButton: { - width: 28, - height: 28, - flexShrink: 0, - borderRadius: theme.borderRadius.full, - alignItems: "center", - justifyContent: "center", - }, - iconButtonHovered: { - backgroundColor: theme.colors.surface2, - }, - disabled: { - opacity: 0.5, - }, - section: { - marginBottom: theme.spacing[4], - }, - sectionHeader: { - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - gap: theme.spacing[2], - marginBottom: theme.spacing[2], - marginLeft: theme.spacing[1], - }, - sectionHeaderMeta: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1], - }, - modelRow: { - flexDirection: "row", - alignItems: "center", - paddingVertical: theme.spacing[2], - paddingHorizontal: theme.spacing[4], - gap: theme.spacing[3], - borderTopWidth: 1, - borderTopColor: theme.colors.border, - }, - modelTitle: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - flexShrink: 0, - }, - customModelText: { - flexShrink: 1, - minWidth: 0, - }, - modelRowFiller: { - flex: 1, - }, - emptyState: { - paddingVertical: theme.spacing[8], - alignItems: "center", - gap: theme.spacing[3], - }, - footerContent: { - flex: 1, - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - gap: theme.spacing[2], - }, - compactFooterContent: { - flex: 1, - gap: theme.spacing[2], - }, - footerMeta: { - flex: 1, - fontSize: theme.fontSize.sm, - color: theme.colors.foregroundMuted, - }, - compactFooterMeta: { - flex: 0, - }, - footerActions: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - compactFooterActions: { - gap: theme.spacing[2], - }, - compactFooterButton: { - alignSelf: "stretch", - }, - formGroup: { - gap: theme.spacing[3], - }, - formLabel: { - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - color: theme.colors.foreground, - }, - formActions: { - flexDirection: "row", - justifyContent: "flex-end", - gap: theme.spacing[2], - }, - codeBlockLoading: { - paddingVertical: theme.spacing[4], - paddingHorizontal: theme.spacing[4], - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, -})); - -const MAIN_SNAP_POINTS = ["65%", "92%"]; -const ADD_SNAP_POINTS = ["40%"]; -const DIAGNOSTIC_SNAP_POINTS = ["50%", "85%"]; diff --git a/packages/app/src/components/provider-settings-host.tsx b/packages/app/src/components/provider-settings-host.tsx index f6ff75c74e0a..c717a2705cd5 100644 --- a/packages/app/src/components/provider-settings-host.tsx +++ b/packages/app/src/components/provider-settings-host.tsx @@ -1,5 +1,5 @@ import { useCallback } from "react"; -import { ProviderDiagnosticSheet } from "@/components/provider-diagnostic-sheet"; +import { ProviderDetailSheet } from "@/provider-settings"; import { OverlayLayerProvider } from "@/lib/overlay-root"; import { useProviderSettingsStore } from "@/stores/provider-settings-store"; @@ -20,7 +20,7 @@ export function ProviderSettingsHost() { return ( - void; + testID?: string; +}) { + const layout = useSettingsRowLayout(); + const rowStyle = useCallback( + ({ hovered, pressed }: HoverState) => [ + layout.row, + styles.row, + hovered && styles.hovered, + pressed && styles.pressed, + ], + [layout], + ); + return ( + + + + + {label} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + row: { justifyContent: "flex-start" }, + leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" }, + label: { color: theme.colors.foregroundMuted }, + hovered: { backgroundColor: theme.colors.surface2 }, + pressed: { backgroundColor: theme.colors.surface3 }, +})); diff --git a/packages/app/src/components/settings/detail-header.tsx b/packages/app/src/components/settings/detail-header.tsx new file mode 100644 index 000000000000..d90d2c3e8489 --- /dev/null +++ b/packages/app/src/components/settings/detail-header.tsx @@ -0,0 +1,86 @@ +import { ArrowLeft } from "lucide-react-native"; +import type { ReactNode } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Button } from "@/components/ui/button"; + +/** + * "Back to …" above a settings detail page on wide layouts, where the page has no header of its + * own. The ghost button drops its padding so the arrow sits on the content's leading rail. + */ +export function SettingsBackLink({ + label, + onPress, + testID, +}: { + label: string; + onPress: () => void; + testID?: string; +}) { + return ( + + ); +} + +/** + * The top of a settings detail page: "Back to …" when the page has no header of its own, then the + * icon and name the page is about, with an optional action after the name. + */ +export function SettingsDetailHeader({ + back, + icon, + title, + trailing, + titleTestID, +}: { + back?: { label: string; onPress: () => void; testID?: string }; + icon: ReactNode; + title: string; + trailing?: ReactNode; + titleTestID?: string; +}) { + return ( + + {back ? : null} + + {icon} + + {title} + + {trailing} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + backLink: { + alignSelf: "flex-start", + paddingHorizontal: 0, + }, + header: { + gap: theme.spacing[2], + marginBottom: theme.spacing[4], + }, + titleRow: { + marginTop: theme.spacing[2], + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + }, + title: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.medium, + flexShrink: 1, + }, +})); diff --git a/packages/app/src/components/settings/detail-row.tsx b/packages/app/src/components/settings/detail-row.tsx index 0838d06ca4f5..a1d96c79b630 100644 --- a/packages/app/src/components/settings/detail-row.tsx +++ b/packages/app/src/components/settings/detail-row.tsx @@ -1,12 +1,16 @@ import type { ReactNode } from "react"; -import { SettingsRowHeader } from "./row-header"; +import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header"; interface SettingsDetailRowProps { label: string; + /** An icon before the label, such as the thing the row opens. */ + leading?: ReactNode; /** Shown beside the label, such as a badge. */ labelAccessory?: ReactNode; /** A line under the label saying what the row leads to. */ hint?: string; + /** Marks the hint as work under way, a fault, or a value still loading. */ + hintStatus?: SettingsRowHintStatus; /** What the detail is set to, so the row says it without being opened. */ summary?: string; onPress: () => void; @@ -14,6 +18,10 @@ interface SettingsDetailRowProps { disabled?: boolean; /** Opens a page outside the app; an outward arrow replaces the chevron. */ external?: boolean; + /** A control acting on the row's subject in place, such as a switch, before the chevron. */ + control?: ReactNode; + /** Names the row for assistive tech when the label alone does not say where it leads. */ + accessibilityLabel?: string; testID?: string; } diff --git a/packages/app/src/components/settings/index.tsx b/packages/app/src/components/settings/index.tsx index 567becfd01f5..f8153b0ff270 100644 --- a/packages/app/src/components/settings/index.tsx +++ b/packages/app/src/components/settings/index.tsx @@ -30,12 +30,17 @@ export { SettingsGroup } from "./headings/settings-group"; export { SettingsSection } from "./headings/settings-section"; export { SettingsCollapsibleRow } from "./collapsible-row"; export { SettingsDetailRow } from "./detail-row"; +export type { SettingsRowHintStatus } from "./row-header"; +export { SettingsAddRow } from "./add-row"; +export { SettingsBackLink, SettingsDetailHeader } from "./detail-header"; export { SettingsInfoTip } from "./headings/settings-info-tip"; export { MenuSettingsRows } from "./row-density"; /** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */ interface AppRowExtras { labelAccessory?: ReactNode; + /** An icon before the label, such as the thing the row is about. */ + leading?: ReactNode; } interface AppSettingsRowProps extends Omit, AppRowExtras { @@ -59,6 +64,7 @@ export function SettingsCard({ children, testID }: { children: ReactNode; testID export function SettingsRow({ label, + leading, labelAccessory, hint, error, @@ -71,6 +77,7 @@ export function SettingsRow({ const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]); return ( + {leading ? {leading} : null} {labelAccessory ? ( @@ -208,7 +215,11 @@ export function SettingsAction({ actionLabel, onPress, disabled, ...row }: Setti } const styles = StyleSheet.create((theme) => ({ - compactRow: { flexWrap: "wrap", gap: theme.spacing[3] }, + // A control that wraps under the label gets space above it. Across the row, the leading slot and + // the label already carry their own margins, so a column gap would double them. + compactRow: { flexWrap: "wrap", rowGap: theme.spacing[3] }, + // The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds. + leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" }, label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] }, labelRow: { flexDirection: "row", diff --git a/packages/app/src/components/settings/row-density.browser.test.tsx b/packages/app/src/components/settings/row-density.browser.test.tsx index d2742e31722b..8c94a0b4e061 100644 --- a/packages/app/src/components/settings/row-density.browser.test.tsx +++ b/packages/app/src/components/settings/row-density.browser.test.tsx @@ -2,7 +2,12 @@ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, describe, expect, it } from "vitest"; import { Button } from "@/components/ui/button"; -import { SettingsCard, SettingsCollapsibleRow, SettingsRow } from "@/components/settings"; +import { + SettingsCard, + SettingsCollapsibleRow, + SettingsDetailRow, + SettingsRow, +} from "@/components/settings"; let root: Root | null = null; let container: HTMLDivElement | null = null; @@ -14,6 +19,8 @@ afterEach(() => { container = null; }); +function openNothing() {} + function mountRows() { container = document.createElement("div"); document.body.appendChild(container); @@ -26,6 +33,7 @@ function mountRows() { Download + + + + ); if (loading) return ( @@ -542,7 +546,7 @@ function PluginPageBody({ } const styles = StyleSheet.create((theme) => ({ - back: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, + back: { marginBottom: theme.spacing[4] }, header: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/provider-selection/provider-selection.test.ts b/packages/app/src/provider-selection/provider-selection.test.ts index 1c04c0b154c0..dd0fae3ef4ad 100644 --- a/packages/app/src/provider-selection/provider-selection.test.ts +++ b/packages/app/src/provider-selection/provider-selection.test.ts @@ -7,6 +7,7 @@ import { buildProviderSelectorProviders, buildSelectableProviderSelectorProviders, buildSelectedTriggerLabel, + buildSelectorProvider, filterAndRankModelRows, matchesModelSearch, resolveEffectiveComposerModeId, @@ -21,7 +22,7 @@ describe("combined model selector data", () => { snapshotEntry({ provider: "waiting", status: "loading", models: [] }), snapshotEntry({ provider: "codex", status: "ready", models: [codexModel] }), ], - false, + { isConnected: false, selectedProvider: null }, ); expect(providers[0].modelSelection).toEqual({ kind: "error", @@ -54,13 +55,16 @@ describe("combined model selector data", () => { it("builds selector providers from ready enabled snapshot entries", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [codexModel], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [codexModel], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "codex", @@ -91,9 +95,10 @@ describe("combined model selector data", () => { isSelectable: false, }; - const [provider] = buildSelectableProviderSelectorProviders([ - snapshotEntry({ provider: "codex", models: [codexModel, compatibilityModel] }), - ]); + const [provider] = buildSelectableProviderSelectorProviders( + [snapshotEntry({ provider: "codex", models: [codexModel, compatibilityModel] })], + { selectedProvider: null }, + ); expect(provider?.modelSelection).toMatchObject({ kind: "models", @@ -103,13 +108,16 @@ describe("combined model selector data", () => { it("synthesizes a default model row for ready enabled providers without explicit models", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "codewhale", @@ -134,33 +142,34 @@ describe("combined model selector data", () => { it("excludes disabled providers from selector data", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - enabled: false, - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + enabled: false, + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([]); }); it("surfaces non-ready providers with their state-specific selection", () => { expect( - buildSelectableProviderSelectorProviders([ - snapshotEntry({ provider: "loading-provider", status: "loading", models: [] }), - snapshotEntry({ - provider: "error-provider", - status: "error", - error: "boom", - models: [], - }), - snapshotEntry({ - provider: "unavailable-provider", - status: "unavailable", - models: [], - }), - ]), + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "loading-provider", status: "loading", models: [] }), + snapshotEntry({ + provider: "error-provider", + status: "error", + error: "boom", + models: [], + }), + ], + { selectedProvider: null }, + ), ).toEqual([ { id: "loading-provider", @@ -172,14 +181,45 @@ describe("combined model selector data", () => { label: "error-provider", modelSelection: { kind: "error", message: "boom" }, }, - { - id: "unavailable-provider", - label: "unavailable-provider", - modelSelection: { kind: "error", message: "Unavailable" }, - }, ]); }); + it("leaves out enabled providers that are not installed", () => { + expect( + buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ], + { selectedProvider: null }, + ).map((provider) => provider.id), + ).toEqual(["codex"]); + }); + + it("keeps a saved choice whose provider is not installed, labelled Unavailable", () => { + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ], + { selectedProvider: "gemini" }, + ); + expect(providers.map((provider) => provider.id)).toEqual(["codex", "gemini"]); + expect(providers[1].modelSelection).toEqual({ kind: "error", message: "Unavailable" }); + }); + + it("keeps an agent's own provider in its selector when that provider is not installed", () => { + expect( + buildSelectorProvider( + snapshotEntry({ provider: "gemini", status: "unavailable", models: [] }), + ), + ).toEqual({ + id: "gemini", + label: "gemini", + modelSelection: { kind: "error", message: "Unavailable" }, + }); + }); + it("builds selector providers from an already-curated provider list", () => { const providerDefinitions: AgentProviderDefinition[] = [ { @@ -278,18 +318,21 @@ describe("combined model selector data", () => { }); it("resolves selected labels from explicit provider model-selection state", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [codexModel], - }), - snapshotEntry({ - provider: "codewhale", - label: "CodeWhale", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [codexModel], + }), + snapshotEntry({ + provider: "codewhale", + label: "CodeWhale", + models: [], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -329,13 +372,16 @@ describe("combined model selector data", () => { }); it("keeps a stored selected model visible when current snapshot rows no longer offer it", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "codex", - label: "Codex", - models: [{ provider: "codex", id: "gpt-5.4", label: "GPT-5.4", isDefault: true }], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "codex", + label: "Codex", + models: [{ provider: "codex", id: "gpt-5.4", label: "GPT-5.4", isDefault: true }], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -348,15 +394,18 @@ describe("combined model selector data", () => { }); it("keeps provider snapshot errors visible in the selected trigger label", () => { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "opencode", - label: "OpenCode", - status: "error", - error: "OpenCode app.agents timed out after 10s", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "opencode", + label: "OpenCode", + status: "error", + error: "OpenCode app.agents timed out after 10s", + models: [], + }), + ], + { selectedProvider: null }, + ); expect( resolveSelectedModelLabel({ @@ -410,21 +459,27 @@ describe("combined model selector data", () => { it("uses the active app language for utility labels", async () => { await i18n.changeLanguage("zh-CN"); try { - const providers = buildSelectableProviderSelectorProviders([ - snapshotEntry({ - provider: "deepseek-tui", - label: "DeepSeek TUI", - models: [], - }), - snapshotEntry({ - provider: "unavailable-provider", - status: "unavailable", - models: [], - }), - ]); + const providers = buildSelectableProviderSelectorProviders( + [ + snapshotEntry({ + provider: "deepseek-tui", + label: "DeepSeek TUI", + models: [], + }), + ], + { selectedProvider: null }, + ); expect(getAllModelLabels(providers)).toContain("默认"); - expect(providers[1]?.modelSelection).toEqual({ + expect( + buildSelectorProvider( + snapshotEntry({ + provider: "unavailable-provider", + status: "unavailable", + models: [], + }), + ).modelSelection, + ).toEqual({ kind: "error", message: "不可用", }); diff --git a/packages/app/src/provider-selection/provider-selection.ts b/packages/app/src/provider-selection/provider-selection.ts index 592824341a7b..dbcc0010ea62 100644 --- a/packages/app/src/provider-selection/provider-selection.ts +++ b/packages/app/src/provider-selection/provider-selection.ts @@ -143,20 +143,35 @@ export function buildProviderSelectorProviders(input: { })); } +/** One provider in a selector, whatever its state. */ +export function buildSelectorProvider( + entry: ProviderSnapshotEntry, + isConnected = true, +): ProviderSelectorProvider { + const label = entry.label ?? entry.provider; + return { + id: entry.provider, + label, + modelSelection: buildEntryModelSelection(entry, label, isConnected), + }; +} + +/** + * The providers a user can pick a model from: enabled, and installed or still being probed. The + * provider of the picker's current choice stays whatever its state, so the selector still names + * it. Every picker says what that choice is, or `null` for none, so none can forget it. + */ export function buildSelectableProviderSelectorProviders( entries: ProviderSnapshotEntry[] | undefined, - isConnected = true, + options: { isConnected?: boolean; selectedProvider: string | null }, ): ProviderSelectorProvider[] { + const { isConnected = true, selectedProvider } = options; return (entries ?? []) - .filter((entry) => entry.enabled) - .map((entry) => { - const label = entry.label ?? entry.provider; - return { - id: entry.provider, - label, - modelSelection: buildEntryModelSelection(entry, label, isConnected), - }; - }); + .filter( + (entry) => + entry.provider === selectedProvider || (entry.enabled && entry.status !== "unavailable"), + ) + .map((entry) => buildSelectorProvider(entry, isConnected)); } export function getProviderModelRows( diff --git a/packages/app/src/provider-settings/index.ts b/packages/app/src/provider-settings/index.ts new file mode 100644 index 000000000000..44a7fb50c23d --- /dev/null +++ b/packages/app/src/provider-settings/index.ts @@ -0,0 +1,4 @@ +export { ProviderList } from "./internal/provider-list"; +export { ProviderDetailPage } from "./internal/provider-detail-page"; +export { ProviderDetailSheet } from "./internal/provider-detail-sheet"; +export type { ProviderSheetFrame } from "./internal/sheet-frame"; diff --git a/packages/app/src/provider-settings/internal/add-provider-sheet.tsx b/packages/app/src/provider-settings/internal/add-provider-sheet.tsx new file mode 100644 index 000000000000..b0f7848b364d --- /dev/null +++ b/packages/app/src/provider-settings/internal/add-provider-sheet.tsx @@ -0,0 +1,187 @@ +import { PackagePlus } from "lucide-react-native"; +import { useCallback, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { SvgXml } from "react-native-svg"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { rankProviderCatalog } from "@/components/provider-catalog-search"; +import { SettingsCard, SettingsRow } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { + useAcpProviderCatalog, + type AcpProviderCatalogItem, +} from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { settingsStyles } from "@/styles/settings"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { useProviderConfigActions } from "./provider-config"; +import { OVERLAY_SHEET_FRAME, type ProviderSheetFrame } from "./sheet-frame"; + +const ThemedPackagePlus = withUnistyles(PackagePlus); +const ThemedSvgXml = withUnistyles(SvgXml); +const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); + +export interface AddProviderSheetProps { + serverId: string; + visible: boolean; + onClose: () => void; + /** The provider is in config and listed; open its detail. */ + onAdded: (providerId: string) => void; + frame?: ProviderSheetFrame; +} + +/** The catalog of providers not added yet, searchable, each with Add. */ +export function AddProviderSheet({ + serverId, + visible, + onClose, + onAdded, + frame = OVERLAY_SHEET_FRAME, +}: AddProviderSheetProps) { + const { t } = useTranslation(); + const { entries: catalog } = useAcpProviderCatalog(); + const { entries: providers } = useProvidersSnapshot(serverId); + const { add, addingProviderId } = useProviderConfigActions(serverId); + const [search, setSearch] = useState(""); + // Each opening starts from an empty search; the field clears when this changes. + const [session, setSession] = useState(0); + // Read when an add finishes, to tell whether the sheet it started in is still open. + const sessionRef = useRef(0); + const endSession = useCallback(() => { + setSearch(""); + sessionRef.current += 1; + setSession(sessionRef.current); + }, []); + const handleClose = useCallback(() => { + endSession(); + onClose(); + }, [endSession, onClose]); + + const available = useMemo(() => { + const added = new Set(providers?.map((entry) => entry.provider) ?? []); + return rankProviderCatalog( + catalog.filter((entry) => !added.has(entry.id)), + search, + ); + }, [catalog, providers, search]); + + const handleAdd = useCallback( + (entry: AcpProviderCatalogItem) => { + const startedIn = sessionRef.current; + void add(entry).then((added) => { + // Closed before the add finished: the provider is added, but the user has moved on. + if (!added || sessionRef.current !== startedIn) return added; + endSession(); + onAdded(entry.id); + return added; + }); + }, + [add, endSession, onAdded], + ); + + const header = useMemo( + () => ({ + title: t("settings.providers.addProvider"), + back: frame.returns + ? { + onPress: handleClose, + accessibilityLabel: t("settings.providers.detail.backToProviders"), + } + : undefined, + search: { + onChange: setSearch, + placeholder: t("providerCatalog.search"), + resetKey: session, + testID: "provider-catalog-search", + }, + }), + [frame.returns, handleClose, session, t], + ); + + return ( + + + {available.length === 0 ? ( + + {t("providerCatalog.noProviders")} + + ) : ( + available.map((entry) => ( + + )) + )} + + + ); +} + +function CatalogRow({ + entry, + adding, + disabled, + onAdd, +}: { + entry: AcpProviderCatalogItem; + adding: boolean; + disabled: boolean; + onAdd: (entry: AcpProviderCatalogItem) => void; +}) { + const { t } = useTranslation(); + const handleAdd = useCallback(() => onAdd(entry), [entry, onAdd]); + const icon = useMemo( + () => + entry.iconSvg ? ( + + ) : ( + + ), + [entry.iconSvg], + ); + return ( + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + empty: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/provider-settings/internal/detail-sections.test.ts b/packages/app/src/provider-settings/internal/detail-sections.test.ts new file mode 100644 index 000000000000..790f900f1581 --- /dev/null +++ b/packages/app/src/provider-settings/internal/detail-sections.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationState } from "@/components/provider-installation-section"; +import { readDetailPresence, readDetailSections, readShownInstallation } from "./detail-sections"; + +function entry(overrides: Partial = {}): ProviderSnapshotEntry { + return { + provider: "opencode", + label: "OpenCode", + status: "ready", + enabled: true, + modes: [], + models: [], + ...overrides, + }; +} + +const unsupported: ProviderInstallationState = { status: "unsupported" }; +const notInstalled: ProviderInstallationState = { + status: "ready", + installation: { inspection: { status: "not_installed" }, canUpdate: false }, +}; + +describe("provider detail sections", () => { + it("shows every model for a provider that runs", () => { + expect(readDetailSections(entry(), unsupported)).toEqual({ error: null, models: "all" }); + }); + + it("keeps every model while the provider is probed again", () => { + expect(readDetailSections(entry({ status: "loading" }), unsupported).models).toBe("all"); + }); + + it("leads with the error and keeps custom models when the provider fails", () => { + expect( + readDetailSections( + entry({ status: "error", error: "opencode exited with code 1" }), + unsupported, + ), + ).toEqual({ error: "opencode exited with code 1", models: "custom" }); + }); + + it("says nothing extra and lists no models when Installation already says Not installed", () => { + expect(readDetailSections(entry({ status: "unavailable" }), unsupported)).toEqual({ + error: null, + models: null, + }); + expect( + readDetailSections(entry({ status: "error", error: "spawn ENOENT" }), notInstalled), + ).toEqual({ error: null, models: null }); + }); + + it("hides models and the error for a disabled provider", () => { + expect( + readDetailSections(entry({ enabled: false, status: "error", error: "boom" }), unsupported), + ).toEqual({ error: null, models: null }); + }); + + it("gives an error with no message an empty one, so the alert still shows", () => { + expect(readDetailSections(entry({ status: "error" }), unsupported).error).toBe(""); + }); +}); + +describe("provider detail installation", () => { + const guide = "https://example.com/install"; + const noContract: ProviderInstallationState = { status: "ready", installation: null }; + + it("says Not installed with the install guide when the host reports nothing about it", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: noContract, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { inspection: { status: "not_installed" }, installUrl: guide }, + }); + }); + + it("keeps the host's install link over the guide", () => { + const hosted: ProviderInstallationState = { + status: "ready", + installation: { + inspection: { status: "not_installed" }, + installUrl: "https://host.example/install", + canUpdate: false, + }, + }; + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: hosted, + installGuide: guide, + }), + ).toEqual(hosted); + }); + + it("gives the host's Not installed the guide when the host has no link", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: notInstalled, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { + inspection: { status: "not_installed" }, + canUpdate: false, + installUrl: guide, + }, + }); + }); + + it("adds nothing for an installed or disabled provider", () => { + expect( + readShownInstallation({ entry: entry(), installation: noContract, installGuide: guide }), + ).toEqual(noContract); + expect( + readShownInstallation({ + entry: entry({ enabled: false, status: "unavailable" }), + installation: noContract, + installGuide: guide, + }), + ).toEqual(noContract); + }); + + it("says nothing it cannot back with a guide", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: noContract, + installGuide: null, + }), + ).toEqual(noContract); + }); + + it("says Not installed with the guide on a host that cannot report installations", () => { + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: unsupported, + installGuide: guide, + }), + ).toEqual({ + status: "ready", + installation: { inspection: { status: "not_installed" }, installUrl: guide }, + }); + // Without a guide, or for a provider the host runs, there is nothing to show. + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: unsupported, + installGuide: null, + }), + ).toEqual(unsupported); + expect( + readShownInstallation({ entry: entry(), installation: unsupported, installGuide: guide }), + ).toEqual(unsupported); + }); + + it("waits while the host is still checking", () => { + const checking: ProviderInstallationState = { status: "loading" }; + expect( + readShownInstallation({ + entry: entry({ status: "unavailable" }), + installation: checking, + installGuide: guide, + }), + ).toEqual(checking); + }); +}); + +describe("provider detail presence", () => { + const loaded = [entry(), entry({ provider: "codex", label: "Codex" })]; + + it("finds the provider among the host's providers", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: loaded, + error: null, + removing: null, + }), + ).toEqual({ kind: "found", entry: loaded[1] }); + }); + + it("is loading until the host's providers arrive", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: undefined, + error: null, + removing: null, + }), + ).toEqual({ kind: "loading" }); + }); + + it("says the provider is missing once the host's providers have arrived without it", () => { + expect( + readDetailPresence({ + provider: "gone", + connected: true, + entries: loaded, + error: null, + removing: null, + }), + ).toEqual({ kind: "missing" }); + }); + + it("keeps showing a provider this page is removing once it leaves the list", () => { + const gone = entry({ provider: "gone", label: "Gone" }); + expect( + readDetailPresence({ + provider: "gone", + connected: true, + entries: loaded, + error: null, + removing: gone, + }), + ).toEqual({ kind: "found", entry: gone }); + }); + + it("says the host is offline rather than loading forever", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: false, + entries: undefined, + error: null, + removing: null, + }), + ).toEqual({ kind: "offline" }); + }); + + it("shows why the host's providers could not be read", () => { + expect( + readDetailPresence({ + provider: "codex", + connected: true, + entries: undefined, + error: "Request timed out", + removing: null, + }), + ).toEqual({ kind: "failed", message: "Request timed out" }); + }); +}); diff --git a/packages/app/src/provider-settings/internal/detail-sections.ts b/packages/app/src/provider-settings/internal/detail-sections.ts new file mode 100644 index 000000000000..c582544d5f27 --- /dev/null +++ b/packages/app/src/provider-settings/internal/detail-sections.ts @@ -0,0 +1,97 @@ +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationState } from "@/components/provider-installation-section"; + +export interface DetailSections { + /** The failure the page leads with, or null. Empty when the provider gave no message. */ + error: string | null; + /** + * Which models the page lists. The provider reports its own only while it runs; custom models + * live in config, so they stay manageable while it fails. + */ + models: "all" | "custom" | null; +} + +/** Which of the detail's state-dependent parts show, so each fact is said once. */ +export function readDetailSections( + entry: ProviderSnapshotEntry, + installation: ProviderInstallationState, +): DetailSections { + const notInstalled = + entry.status === "unavailable" || + (installation.status === "ready" && + installation.installation?.inspection?.status === "not_installed"); + const failing = entry.enabled && entry.status === "error" && !notInstalled; + return { + error: failing ? (entry.error?.trim() ?? "") : null, + models: readShownModels(entry, notInstalled), + }; +} + +function readShownModels( + entry: ProviderSnapshotEntry, + notInstalled: boolean, +): DetailSections["models"] { + if (!entry.enabled || notInstalled) return null; + return entry.status === "error" ? "custom" : "all"; +} + +/** + * The installation the page shows. A provider added from the catalog has no installation the + * host can report, so when its CLI is missing the page says so with the catalog's install guide. + * The host's own install link wins over the guide. A host that cannot report installations gets + * the same row, because the guide is the app's own catalog data. + */ +export function readShownInstallation(input: { + entry: ProviderSnapshotEntry; + installation: ProviderInstallationState; + /** The catalog's install guide for this provider, or null. */ + installGuide: string | null; +}): ProviderInstallationState { + const { entry, installation, installGuide } = input; + if (!installGuide) return installation; + if (installation.status !== "ready" && installation.status !== "unsupported") return installation; + const reported = installation.status === "ready" ? installation.installation : null; + if (reported?.installUrl) return installation; + const notInstalled = + reported?.inspection?.status === "not_installed" || + (!reported?.inspection && entry.enabled && entry.status === "unavailable"); + if (!notInstalled) return installation; + return { + status: "ready", + installation: { + ...reported, + inspection: { status: "not_installed" }, + installUrl: installGuide, + }, + }; +} + +export type DetailPresence = + | { kind: "found"; entry: ProviderSnapshotEntry } + | { kind: "loading" } + | { kind: "missing" } + | { kind: "offline" } + | { kind: "failed"; message: string }; + +/** + * Whether the page has a provider to show. A page opened from its URL renders before the host's + * providers arrive, and its id may name a provider the host no longer has. A provider this page is + * removing leaves the list before the removal answers; the page keeps showing it until it closes. + */ +export function readDetailPresence(input: { + provider: string; + connected: boolean; + entries: ProviderSnapshotEntry[] | undefined; + error: string | null; + /** The provider this page's own Remove is deleting, as it was when the user confirmed. */ + removing: ProviderSnapshotEntry | null; +}): DetailPresence { + const entry = + input.entries?.find((candidate) => candidate.provider === input.provider) ?? + (input.removing?.provider === input.provider ? input.removing : undefined); + if (entry) return { kind: "found", entry }; + if (!input.connected) return { kind: "offline" }; + if (input.entries) return { kind: "missing" }; + if (input.error) return { kind: "failed", message: input.error }; + return { kind: "loading" }; +} diff --git a/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx b/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx new file mode 100644 index 000000000000..9f8c07d5d83b --- /dev/null +++ b/packages/app/src/provider-settings/internal/diagnostic-sheet.tsx @@ -0,0 +1,149 @@ +import * as Clipboard from "expo-clipboard"; +import { Copy, RotateCw } from "lucide-react-native"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface"; +import { useToast } from "@/contexts/toast-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import type { Theme } from "@/styles/theme"; + +const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); +const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const DIAGNOSTIC_SNAP_POINTS = ["50%", "85%"]; + +/** The provider's diagnostic report, run on open, with copy and run again. */ +export function DiagnosticSheet({ + serverId, + provider, + visible, + onClose, +}: { + serverId: string; + provider: string; + visible: boolean; + onClose: () => void; +}) { + const { t } = useTranslation(); + const toast = useToast(); + const client = useHostRuntimeClient(serverId); + const [diagnostic, setDiagnostic] = useState(null); + const [loading, setLoading] = useState(false); + + const fetchDiagnostic = useCallback(async () => { + if (!client) return; + setLoading(true); + try { + const result = await client.getProviderDiagnostic(provider); + setDiagnostic(result.diagnostic); + } catch (err) { + setDiagnostic( + err instanceof Error ? err.message : t("settings.providers.diagnostic.failedToFetch"), + ); + } finally { + setLoading(false); + } + }, [client, provider, t]); + + useEffect(() => { + if (visible) { + void fetchDiagnostic(); + } else { + setDiagnostic(null); + } + }, [visible, fetchDiagnostic]); + + const handleRefresh = useCallback(() => { + if (loading) return; + void fetchDiagnostic(); + }, [fetchDiagnostic, loading]); + const handleCopy = useCallback(() => { + if (!diagnostic) return; + void Clipboard.setStringAsync(diagnostic) + .then(() => toast.copied(t("settings.providers.diagnostic.copyLabel"))) + .catch(() => toast.error(t("settings.providers.diagnostic.copyFailed"))); + }, [diagnostic, t, toast]); + + const header = useMemo( + () => ({ + title: t("settings.providers.diagnostic.title"), + actions: ( + <> + + + + ), + }), + [diagnostic, handleCopy, handleRefresh, loading, t], + ); + + let body: React.ReactNode; + if (loading && !diagnostic) { + body = ( + + + + {t("settings.providers.diagnostic.running")} + + + ); + } else if (diagnostic) { + body = {diagnostic}; + } else { + body = ( + + + {t("settings.providers.diagnostic.none")} + + + ); + } + + return ( + + {body} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + placeholder: { + paddingVertical: theme.spacing[4], + paddingHorizontal: theme.spacing[4], + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + mutedText: { + fontSize: theme.fontSize.base, + color: theme.colors.foregroundMuted, + }, +})); diff --git a/packages/app/src/components/provider-diagnostic-models.test.ts b/packages/app/src/provider-settings/internal/discovered-models.test.ts similarity index 98% rename from packages/app/src/components/provider-diagnostic-models.test.ts rename to packages/app/src/provider-settings/internal/discovered-models.test.ts index 4ad536945f8c..0d139deb33de 100644 --- a/packages/app/src/components/provider-diagnostic-models.test.ts +++ b/packages/app/src/provider-settings/internal/discovered-models.test.ts @@ -3,7 +3,7 @@ import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types"; import { resolveProviderDiscoveredModels, type ProviderDiscoveredModelsCache, -} from "./provider-diagnostic-models"; +} from "./discovered-models"; const piModel: AgentModelDefinition = { provider: "pi", diff --git a/packages/app/src/components/provider-diagnostic-models.ts b/packages/app/src/provider-settings/internal/discovered-models.ts similarity index 100% rename from packages/app/src/components/provider-diagnostic-models.ts rename to packages/app/src/provider-settings/internal/discovered-models.ts diff --git a/packages/app/src/provider-settings/internal/provider-config.ts b/packages/app/src/provider-settings/internal/provider-config.ts new file mode 100644 index 000000000000..bbef1c0f231b --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-config.ts @@ -0,0 +1,151 @@ +import { useCallback, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Alert } from "react-native"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { + buildAcpProviderConfigPatch, + getAcpProviderCatalog, + type AcpProviderCatalogItem, +} from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { selectHostFeature, useHostFeature } from "@/runtime/host-features"; +import { useSessionStore } from "@/stores/session-store"; +import { confirmDialog } from "@/utils/confirm-dialog"; + +export type ProviderEntry = NonNullable["entries"]>[number]; + +export interface ProviderConfigActions { + /** The provider whose Enabled switch is being saved. */ + togglingProviderId: string | null; + setEnabled: (providerId: string, enabled: boolean) => void; + /** Config owns the provider, so Remove can delete it. */ + canRemove: (entry: ProviderEntry) => boolean; + /** + * The provider being removed, as it was when the user confirmed. It stays set once the removal + * succeeds, because whatever shows the provider closes next and keeps showing it until then, and + * ends when the host lists the provider again, as when the user adds it back. + */ + removing: ProviderEntry | null; + /** Asks first; resolves true once the provider is gone from config. */ + remove: (entry: ProviderEntry, providerLabel: string) => Promise; + /** The catalog provider being written to config. */ + addingProviderId: string | null; + /** Writes a catalog provider to config and probes it; resolves true once it is listed. */ + add: (entry: AcpProviderCatalogItem) => Promise; +} + +/** Writes a provider's Enabled flag, adds catalog providers and removes config-owned ones. */ +export function useProviderConfigActions(serverId: string): ProviderConfigActions { + const { t } = useTranslation(); + const toast = useToast(); + const { config, patchConfig } = useDaemonConfig(serverId); + const { entries, refresh } = useProvidersSnapshot(serverId); + const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval"); + const [togglingProviderId, setTogglingProviderId] = useState(null); + const [removal, setRemoval] = useState<{ entry: ProviderEntry; done: boolean } | null>(null); + const removingRef = useRef(null); + const [addingProviderId, setAddingProviderId] = useState(null); + const addingRef = useRef(null); + + const setEnabled = useCallback( + (providerId: string, enabled: boolean) => { + setTogglingProviderId(providerId); + void patchConfig({ providers: { [providerId]: { enabled } } }) + .catch((error: unknown) => { + Alert.alert( + t("settings.providers.updateErrorTitle"), + error instanceof Error ? error.message : String(error), + ); + }) + .finally(() => { + setTogglingProviderId((current) => (current === providerId ? null : current)); + }); + }, + [patchConfig, t], + ); + + // Config owns derived providers and the opt-in bundled catalog providers. + const canRemove = useCallback( + (entry: ProviderEntry) => { + const providerConfig = config?.providers?.[entry.provider]; + if (!supportsProviderRemoval || entry.source !== "custom" || !providerConfig) return false; + return Boolean( + providerConfig.extends || + getAcpProviderCatalog().some( + (catalogEntry) => catalogEntry.id === entry.provider && catalogEntry.bundledProvider, + ), + ); + }, + [config, supportsProviderRemoval], + ); + + const remove = useCallback( + async (entry: ProviderEntry, providerLabel: string) => { + if (removingRef.current) return false; + removingRef.current = entry.provider; + try { + const confirmed = await confirmDialog({ + title: t("settings.providers.remove.confirmTitle", { name: providerLabel }), + message: t("settings.providers.remove.confirmMessage"), + confirmLabel: t("settings.providers.remove.confirm"), + destructive: true, + }); + if (!confirmed) return false; + setRemoval({ entry, done: false }); + await patchConfig({ removeProviders: [entry.provider] }); + setRemoval({ entry, done: true }); + return true; + } catch (error) { + setRemoval(null); + Alert.alert( + t("settings.providers.remove.errorTitle"), + error instanceof Error ? error.message : String(error), + ); + return false; + } finally { + removingRef.current = null; + } + }, + [patchConfig, t], + ); + + // A sheet outlives each opening, so a finished removal ends here rather than with the sheet. + if (removal?.done && entries?.some((entry) => entry.provider === removal.entry.provider)) { + setRemoval(null); + } + + const add = useCallback( + async (entry: AcpProviderCatalogItem) => { + if (addingRef.current) return false; + addingRef.current = entry.id; + setAddingProviderId(entry.id); + try { + await patchConfig( + buildAcpProviderConfigPatch(entry, (feature) => + selectHostFeature(useSessionStore.getState(), serverId, feature), + ), + ); + await refresh([entry.id]); + return true; + } catch (error) { + toast.error(error instanceof Error ? error.message : String(error)); + return false; + } finally { + if (addingRef.current === entry.id) addingRef.current = null; + setAddingProviderId((current) => (current === entry.id ? null : current)); + } + }, + [patchConfig, refresh, serverId, toast], + ); + + return { + togglingProviderId, + setEnabled, + canRemove, + removing: removal?.entry ?? null, + remove, + addingProviderId, + add, + }; +} diff --git a/packages/app/src/provider-settings/internal/provider-detail-page.tsx b/packages/app/src/provider-settings/internal/provider-detail-page.tsx new file mode 100644 index 000000000000..f5ae12f28481 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail-page.tsx @@ -0,0 +1,49 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { SettingsDetailHeader } from "@/components/settings"; +import { ProviderDetail, useProviderDetail } from "./provider-detail"; +import { ProviderGlyph } from "./provider-glyph"; + +/** + * A provider's detail as a Settings page, shaped like a project's: the screen titles it + * "Providers", the page names the provider. On wide layouts the page has no back button of its + * own, so it draws "Back to providers". + */ +export function ProviderDetailPage({ + serverId, + provider, + onBack, + showBack, +}: { + serverId: string; + provider: string; + onBack: () => void; + showBack: boolean; +}) { + const { t } = useTranslation(); + const detail = useProviderDetail({ serverId, provider, onRemoved: onBack }); + const back = useMemo( + () => ({ + label: t("settings.providers.detail.backToProviders"), + onPress: onBack, + testID: "provider-detail-back", + }), + [onBack, t], + ); + const icon = useMemo( + () => , + [provider, serverId], + ); + return ( + + + + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx b/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx new file mode 100644 index 000000000000..c2b8f07db626 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail-sheet.tsx @@ -0,0 +1,52 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { ProviderDetail, useProviderDetail } from "./provider-detail"; +import { ProviderGlyph } from "./provider-glyph"; +import { OVERLAY_SHEET_FRAME, type ProviderSheetFrame } from "./sheet-frame"; + +/** A provider's detail as a sheet, for surfaces with no Settings route to push. */ +export function ProviderDetailSheet({ + serverId, + provider, + visible, + onClose, + frame = OVERLAY_SHEET_FRAME, +}: { + serverId: string; + provider: string; + visible: boolean; + onClose: () => void; + frame?: ProviderSheetFrame; +}) { + const { t } = useTranslation(); + const detail = useProviderDetail({ serverId, provider, onRemoved: onClose }); + const label = detail.label; + const header = useMemo( + () => ({ + title: label, + leading: , + back: frame.returns + ? { + onPress: onClose, + accessibilityLabel: t("settings.providers.detail.backToProviders"), + } + : undefined, + }), + [frame.returns, label, onClose, provider, serverId, t], + ); + return ( + + + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-detail.tsx b/packages/app/src/provider-settings/internal/provider-detail.tsx new file mode 100644 index 000000000000..6e4b89451e96 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-detail.tsx @@ -0,0 +1,255 @@ +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { ProviderInstallationSection } from "@/components/provider-installation-section"; +import { useProviderInstallation } from "@/components/provider-installation"; +import { + SettingsCard, + SettingsDetailRow, + SettingsRow, + SettingsSection, + SettingsSwitch, +} from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { readAcpProviderInstallGuide } from "@/hooks/use-acp-provider-catalog"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { useTimeAgo } from "@/hooks/use-time-ago"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { settingsStyles } from "@/styles/settings"; +import { + readDetailPresence, + readDetailSections, + readShownInstallation, + type DetailPresence, +} from "./detail-sections"; +import { DiagnosticSheet } from "./diagnostic-sheet"; +import { useProviderConfigActions, type ProviderEntry } from "./provider-config"; +import { ProviderModels } from "./provider-models"; +import { ProviderNotice } from "./provider-notice"; + +export interface ProviderDetailState { + provider: string; + /** The provider's name, kept while this page removes it. */ + label: string; + presence: DetailPresence; + /** Config owns the provider, so Remove can delete it. */ + canRemove: (entry: ProviderEntry) => boolean; + /** This page's Remove is running, or has succeeded and the page is closing. */ + removing: boolean; + remove: () => void; +} + +/** + * What a provider's detail shows and its Remove, shared by the frame's title and the body. A + * provider this page removes leaves the host's list before the removal answers; both keep showing + * it until the frame closes. + */ +export function useProviderDetail({ + serverId, + provider, + onRemoved, +}: { + serverId: string; + provider: string; + /** The provider was removed; leave its detail. */ + onRemoved: () => void; +}): ProviderDetailState { + const { entries, error } = useProvidersSnapshot(serverId); + const connected = useHostRuntimeIsConnected(serverId); + const { canRemove, remove, removing } = useProviderConfigActions(serverId); + const presence = readDetailPresence({ provider, connected, entries, error, removing }); + const shown = presence.kind === "found" ? presence.entry : null; + const label = shown?.label ?? provider; + const handleRemove = useCallback(() => { + if (!shown) return; + void remove(shown, label).then((removed) => { + if (removed) onRemoved(); + return removed; + }); + }, [label, onRemoved, remove, shown]); + return { + provider, + label, + presence, + canRemove, + removing: removing?.provider === provider, + remove: handleRemove, + }; +} + +/** + * Everything about one provider, top to bottom: what is wrong, whether it runs, its installation, + * its models, then the rare actions. The page and the sheet frame the same body. + */ +export function ProviderDetail({ + serverId, + detail, +}: { + serverId: string; + detail: ProviderDetailState; +}) { + const { provider, presence, label } = detail; + const { refresh, isRefreshing } = useProvidersSnapshot(serverId); + const installation = useProviderInstallation({ serverId, provider, visible: true }); + const refreshInstallation = installation.refresh; + const handleRefresh = useCallback(() => { + void refresh([provider]); + refreshInstallation(); + }, [provider, refresh, refreshInstallation]); + if (presence.kind !== "found") return ; + + const entry = presence.entry; + const shownInstallation = readShownInstallation({ + entry, + installation: installation.state, + installGuide: readAcpProviderInstallGuide(provider), + }); + const sections = readDetailSections(entry, shownInstallation); + + return ( + + {sections.error !== null ? : null} + + + {sections.models ? ( + + ) : null} + + {/* Config no longer owns a provider whose removal has succeeded. */} + {detail.removing || detail.canRemove(entry) ? ( + + ) : null} + + ); +} + +function AbsentProvider({ presence }: { presence: Exclude }) { + const { t } = useTranslation(); + const messages = { + loading: t("settings.providers.loading"), + missing: t("settings.providers.detail.notOnHost"), + offline: t("settings.providers.unavailable"), + }; + const message = presence.kind === "failed" ? presence.message : messages[presence.kind]; + return ; +} + +function ProviderErrorAlert({ label, error }: { label: string; error: string }) { + const { t } = useTranslation(); + return ( + + + + ); +} + +function EnabledCard({ serverId, entry }: { serverId: string; entry: ProviderEntry }) { + const { t } = useTranslation(); + const { setEnabled, togglingProviderId } = useProviderConfigActions(serverId); + const handleChange = useCallback( + (enabled: boolean) => setEnabled(entry.provider, enabled), + [entry.provider, setEnabled], + ); + return ( + + + + + + ); +} + +function Troubleshooting({ + serverId, + entry, + refreshing, + onRefresh, +}: { + serverId: string; + entry: ProviderEntry; + refreshing: boolean; + onRefresh: () => void; +}) { + const { t } = useTranslation(); + const [diagnosticOpen, setDiagnosticOpen] = useState(false); + const openDiagnostic = useCallback(() => setDiagnosticOpen(true), []); + const closeDiagnostic = useCallback(() => setDiagnosticOpen(false), []); + const checked = useTimeAgo(entry.fetchedAt ? new Date(entry.fetchedAt) : null); + // The probe running again is a refresh too, whoever asked for it. + const busy = refreshing || entry.status === "loading"; + + return ( + + + + + + + + + + ); +} + +function DangerZone({ removing, onRemove }: { removing: boolean; onRemove: () => void }) { + const { t } = useTranslation(); + return ( + + + + + + + + ); +} diff --git a/packages/app/src/provider-settings/internal/provider-glyph.tsx b/packages/app/src/provider-settings/internal/provider-glyph.tsx new file mode 100644 index 000000000000..af298e29aa54 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-glyph.tsx @@ -0,0 +1,13 @@ +import { StyleSheet } from "react-native-unistyles"; +import { useProviderIcon } from "@/components/provider-icons"; +import { ICON_SIZE } from "@/styles/theme"; + +/** A provider's icon at row size, drawn in the foreground colour. */ +export function ProviderGlyph({ serverId, provider }: { serverId: string; provider: string }) { + const Icon = useProviderIcon(provider, serverId); + return ; +} + +const styles = StyleSheet.create((theme) => ({ + glyph: { color: theme.colors.foreground }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-list.tsx b/packages/app/src/provider-settings/internal/provider-list.tsx new file mode 100644 index 000000000000..dc3b9b1dfdf7 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-list.tsx @@ -0,0 +1,206 @@ +import { Plus } from "lucide-react-native"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useProviderInstallation } from "@/components/provider-installation"; +import { SettingsAddRow, SettingsCard, SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; +import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { settingsStyles } from "@/styles/settings"; +import { buildProviderDefinitions } from "@/utils/provider-definitions"; +import { AddProviderSheet } from "./add-provider-sheet"; +import { useProviderConfigActions, type ProviderEntry } from "./provider-config"; +import { ProviderGlyph } from "./provider-glyph"; +import { ProviderNotice } from "./provider-notice"; +import { ProviderRow } from "./provider-row"; +import { readRowSummary } from "./row-summary"; +import type { ProviderSheetFrame } from "./sheet-frame"; + +export interface ProviderListProps { + serverId: string; + /** Opens a provider's detail wherever the host shows it: a Settings page or a sheet. */ + onOpenProvider: (providerId: string) => void; + /** Where the sheets the list opens sit. Defaults to a sheet over the current screen. */ + sheetFrame?: ProviderSheetFrame; +} + +/** The host's providers, each saying how it is, and the way to add one. */ +export function ProviderList({ serverId, onOpenProvider, sheetFrame }: ProviderListProps) { + const { t } = useTranslation(); + const isConnected = useHostRuntimeIsConnected(serverId) && serverId.length > 0; + const { entries, isLoading } = useProvidersSnapshot(serverId); + const { setEnabled, togglingProviderId } = useProviderConfigActions(serverId); + const definitions = useMemo(() => buildProviderDefinitions(entries), [entries]); + const [adding, setAdding] = useState(false); + const openAdd = useCallback(() => setAdding(true), []); + const closeAdd = useCallback(() => setAdding(false), []); + const handleAdded = useCallback( + (providerId: string) => { + setAdding(false); + onOpenProvider(providerId); + }, + [onOpenProvider], + ); + + const addButton = useMemo( + () => + isConnected ? ( + + ) : null, + [isConnected, openAdd, t], + ); + + let body: React.ReactNode; + if (!isConnected) { + body = ; + } else if (isLoading) { + body = ; + } else { + body = ( + + {definitions.map((definition) => { + const entry = entries?.find((candidate) => candidate.provider === definition.id); + if (!entry) return null; + return ( + + ); + })} + + + ); + } + + return ( + <> + + {body} + + {isConnected ? ( + + ) : null} + + ); +} + +/** A row reads its provider's installation itself; the detail shares the same requests. */ +function ListedProvider({ + serverId, + entry, + label, + toggling, + onOpen, + onToggle, +}: { + serverId: string; + entry: ProviderEntry; + label: string; + toggling: boolean; + onOpen: (provider: string) => void; + onToggle: (provider: string, enabled: boolean) => void; +}) { + const installation = useProviderInstallation({ + serverId, + provider: entry.provider, + visible: true, + }); + const icon = useMemo( + () => , + [entry.provider, serverId], + ); + return ( + + ); +} + +const SKELETON_ROW_KEYS = [0, 1, 2, 3].map((index) => `provider-skeleton-row-${index}`); + +function ProviderRowsSkeleton() { + const { t } = useTranslation(); + const pulse = useSkeletonPulse(); + return ( + + {SKELETON_ROW_KEYS.map((key, index) => ( + 0 && settingsStyles.rowBorder]}> + + + + + + + ))} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + skeletonContent: { + flex: 1, + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + }, + skeletonIcon: { + width: 16, + height: 16, + borderRadius: theme.borderRadius.md, + backgroundColor: theme.colors.surface2, + }, + skeletonTitle: { + width: 160, + height: 12, + borderRadius: theme.borderRadius.sm, + backgroundColor: theme.colors.surface2, + }, + skeletonSwitch: { + width: 36, + height: 20, + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.surface2, + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-models.tsx b/packages/app/src/provider-settings/internal/provider-models.tsx new file mode 100644 index 000000000000..df141d93ff3c --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-models.tsx @@ -0,0 +1,444 @@ +import { Plus, Trash2 } from "lucide-react-native"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types"; +import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config"; +import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; +import { + AdaptiveModalSheet, + AdaptiveTextInput, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { SearchField } from "@/components/ui/search-field"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { isWeb } from "@/constants/platform"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { CODE_SURFACE_DATASET } from "@/styles/code-surface"; +import { settingsStyles } from "@/styles/settings"; +import type { Theme } from "@/styles/theme"; +import { + resolveProviderDiscoveredModels, + type ProviderDiscoveredModelsCache, +} from "./discovered-models"; +import type { ProviderEntry } from "./provider-config"; + +const ThemedTrash = withUnistyles(Trash2); +const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive }); +const ThemedTextInput = withUnistyles(AdaptiveTextInput, (theme: Theme) => ({ + placeholderTextColor: theme.colors.foregroundMuted, +})); + +function rankModels(items: T[], query: string, fields: (item: T) => string[]): T[] { + if (!query) return items; + const scored = items + .map((item) => ({ item, score: scoreTextFields(query, fields(item)) })) + .filter( + (entry): entry is { item: T; score: NonNullable } => entry.score !== null, + ); + scored.sort((a, b) => compareMatchScores(a.score, b.score)); + return scored.map((entry) => entry.item); +} + +/** + * A provider's models: search, the ones it reports, and the ones added by hand. The caller decides + * whether it appears and whether the provider's own models are listed. + */ +export function ProviderModels({ + serverId, + entry, + discovered, + refresh, +}: { + serverId: string; + entry: ProviderEntry; + /** List the models the provider reports, with search. Only a running provider reports them. */ + discovered: boolean; + refresh: (providers?: AgentProvider[]) => Promise; +}) { + const { t } = useTranslation(); + const provider = entry.provider; + const { config, patchConfig } = useDaemonConfig(serverId); + const [query, setQuery] = useState(""); + const [addSheetOpen, setAddSheetOpen] = useState(false); + const [deletingModelId, setDeletingModelId] = useState(null); + + const additionalModels = useMemo( + () => config?.providers?.[provider]?.additionalModels ?? [], + [config?.providers, provider], + ); + const loading = entry.status === "loading"; + // A refresh briefly empties the snapshot's models; keep the last list on screen meanwhile. + const discoveredCacheRef = useRef(null); + const { models: discoveredModels, cache } = resolveProviderDiscoveredModels({ + serverId, + provider, + currentModels: entry.models, + providerSnapshotRefreshing: loading, + previousCache: discoveredCacheRef.current, + }); + discoveredCacheRef.current = cache; + + // Search shows only beside the provider's own models; a query typed then must not hide custom ones. + const q = discovered ? query.trim() : ""; + const filteredDiscovered = useMemo( + () => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]), + [discoveredModels, q], + ); + const filteredCustom = useMemo( + () => rankModels(additionalModels, q, (m) => [m.label, m.id]), + [additionalModels, q], + ); + + const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []); + const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []); + const handleDeleteCustom = useCallback( + (modelId: string) => { + setDeletingModelId(modelId); + void patchConfig({ + providers: { + [provider]: { + additionalModels: additionalModels.filter((model) => model.id !== modelId), + }, + }, + }) + .then(() => refresh([provider])) + .finally(() => { + setDeletingModelId((current) => (current === modelId ? null : current)); + }); + }, + [additionalModels, patchConfig, provider, refresh], + ); + + const customTrailing = useMemo( + () => ( + + {additionalModels.length > 0 ? ( + {additionalModels.length} + ) : null} + + + + + + ); +} + +const ADD_SNAP_POINTS = ["40%"]; + +const styles = StyleSheet.create((theme) => ({ + searchRail: { + flexDirection: "row", + marginBottom: theme.spacing[3], + }, + headerTrailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1], + }, + modelRow: { + flexDirection: "row", + alignItems: "center", + paddingVertical: theme.spacing[2], + paddingHorizontal: theme.spacing[4], + gap: theme.spacing[3], + }, + modelTitle: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + flexShrink: 0, + }, + monoHint: { + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.code, + color: theme.colors.foregroundMuted, + flexShrink: 0, + }, + descriptionInline: { + flex: 1, + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + customModelText: { + flexShrink: 1, + minWidth: 0, + }, + modelRowFiller: { + flex: 1, + }, + formGroup: { + gap: theme.spacing[3], + }, + formLabel: { + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.medium, + color: theme.colors.foreground, + }, + formInput: { + backgroundColor: theme.colors.surface2, + borderRadius: theme.borderRadius.lg, + paddingHorizontal: theme.spacing[4], + paddingVertical: theme.spacing[3], + color: theme.colors.foreground, + borderWidth: 1, + borderColor: theme.colors.border, + fontSize: theme.fontSize.base, + }, + errorText: { + fontSize: theme.fontSize.sm, + color: theme.colors.destructive, + }, + formActions: { + flexDirection: "row", + justifyContent: "flex-end", + gap: theme.spacing[2], + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-notice.tsx b/packages/app/src/provider-settings/internal/provider-notice.tsx new file mode 100644 index 000000000000..62482bdd9075 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-notice.tsx @@ -0,0 +1,23 @@ +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { settingsStyles } from "@/styles/settings"; + +/** A card holding one muted line, where a provider list or page has nothing to show yet. */ +export function ProviderNotice({ message, testID }: { message: string; testID?: string }) { + return ( + + {message} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + card: { + padding: theme.spacing[4], + alignItems: "center", + }, + text: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx b/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx new file mode 100644 index 000000000000..e8e9177410a5 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-row.browser.test.tsx @@ -0,0 +1,178 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Text } from "react-native"; +import { i18n as testI18n } from "@/i18n/i18next"; +import { ProviderRow } from "./provider-row"; +import type { RowSummary } from "./row-summary"; + +// Load translations so rows expose their real accessible names and copy. +void testI18n; + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const mounted: { root: Root; container: HTMLDivElement }[] = []; +afterEach(() => { + for (const entry of mounted.splice(0)) { + act(() => entry.root.unmount()); + entry.container.remove(); + } +}); + +const ICON = *; + +function mount(summary: RowSummary, options: { enabled?: boolean; label?: string } = {}) { + const onOpen = vi.fn(); + const onToggle = vi.fn(); + const label = options.label ?? "Claude"; + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => + root.render( + , + ), + ); + mounted.push({ root, container }); + const view = within(container); + return { + view, + onOpen, + onToggle, + row: () => view.getByTestId("provider-row-claude"), + opener: () => view.getByRole("button", { name: `${label} provider details` }), + toggle: () => view.queryByRole("switch", { name: `Enable ${label}` }), + }; +} + +function pressEnter(target: HTMLElement) { + target.focus(); + for (const type of ["keydown", "keyup"]) { + target.dispatchEvent( + new KeyboardEvent(type, { key: "Enter", bubbles: true, cancelable: true }), + ); + } +} + +function textOrder(row: HTMLElement, texts: string[]): number[] { + const content = row.textContent ?? ""; + return texts.map((text) => content.indexOf(text)); +} + +describe("provider row", () => { + it("names the provider with its label and says Disabled when it is off", () => { + const row = mount({ kind: "disabled" }, { enabled: false, label: "Codex" }); + expect(row.row().textContent).toContain("Codex"); + expect(row.view.getByText("Disabled")).toBeTruthy(); + expect(row.toggle()?.getAttribute("aria-checked")).toBe("false"); + }); + + it("composes the row as icon, label, version and models, then switch", () => { + const row = mount({ kind: "ready", version: "2.1.321", models: 3 }); + const element = row.row(); + expect(row.view.getByText("2.1.321 · 3 models")).toBeTruthy(); + const [icon, label, summary] = textOrder(element, ["*", "Claude", "2.1.321 · 3 models"]); + expect(icon).toBeLessThan(label); + expect(label).toBeLessThan(summary); + const toggle = row.toggle(); + expect(toggle).not.toBeNull(); + expect( + row.view.getByText("2.1.321 · 3 models").compareDocumentPosition(toggle as Node) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + }); + + it("asks its host to open the provider when the row is pressed", () => { + const row = mount({ kind: "disabled" }, { enabled: false }); + act(() => row.opener().click()); + expect(row.onOpen).toHaveBeenCalledWith("claude"); + }); + + it("keeps the switch out of the row's button, so Enter on the switch only toggles", () => { + const row = mount({ kind: "ready", version: null, models: 3 }); + const toggle = row.toggle() as HTMLElement; + expect(row.opener().contains(toggle)).toBe(false); + // Dispatched in one act, so the test ends before the Switch's animation runs a frame. + act(() => pressEnter(toggle)); + expect(row.onToggle).toHaveBeenCalledWith("claude", false); + expect(row.onOpen).not.toHaveBeenCalled(); + }); + + it("toggles the provider from the switch without opening it", () => { + const row = mount({ kind: "ready", version: null, models: 3 }); + act(() => row.toggle()?.click()); + expect(row.onToggle).toHaveBeenCalledWith("claude", false); + expect(row.onOpen).not.toHaveBeenCalled(); + }); + + it("leaves the state line readable to screen readers, and the name to the row's button", () => { + const row = mount({ kind: "failing", message: "opencode exited with code 1" }); + expect(row.view.getByText("opencode exited with code 1").closest("[aria-hidden]")).toBeNull(); + expect(row.view.getByText("Claude").closest("[aria-hidden]")).not.toBeNull(); + }); + + it("says an update is available after the version", () => { + const row = mount({ kind: "updateAvailable", version: "2.1.321" }); + expect(row.view.getByText("2.1.321 · Update available")).toBeTruthy(); + }); + + it("names the target while an update runs, or says Updating... without one", () => { + expect( + mount({ kind: "updating", target: "1.0.31" }).view.getByText("Updating to 1.0.31..."), + ).toBeTruthy(); + expect(mount({ kind: "updating", target: null }).view.getByText("Updating...")).toBeTruthy(); + }); + + it("shows the error in the hint", () => { + const row = mount({ kind: "failing", message: "opencode exited with code 1" }); + expect(row.view.getByText("opencode exited with code 1")).toBeTruthy(); + expect(row.toggle()).not.toBeNull(); + }); + + it("offers no switch on a provider that is not installed", () => { + const row = mount({ kind: "notInstalled" }); + expect(row.view.getByText("Not installed")).toBeTruthy(); + expect(row.toggle()).toBeNull(); + act(() => row.opener().click()); + expect(row.onOpen).toHaveBeenCalledWith("claude"); + }); + + it("keeps the row as tall while its line loads as once it has arrived", () => { + const pending = mount({ kind: "pending" }).row().getBoundingClientRect().height; + const ready = mount({ kind: "ready", version: "2.1.321", models: 3 }) + .row() + .getBoundingClientRect().height; + const updating = mount({ kind: "updating", target: "1.0.31" }) + .row() + .getBoundingClientRect().height; + const failing = mount({ kind: "failing", message: "boom" }) + .row() + .getBoundingClientRect().height; + expect(pending).toBe(ready); + expect(updating).toBe(ready); + expect(failing).toBe(ready); + }); + + it("keeps a long, multi-line error to the row's one line", () => { + const ready = mount({ kind: "ready", version: "2.1.321", models: 3 }) + .row() + .getBoundingClientRect().height; + const message = [ + "ACP agent process exited before initialization completed (exit code 1)", + "broken-acp: exited with code 1", + ].join("\n"); + const failing = mount({ kind: "failing", message }).row().getBoundingClientRect().height; + expect(failing).toBe(ready); + }); +}); diff --git a/packages/app/src/provider-settings/internal/provider-row.tsx b/packages/app/src/provider-settings/internal/provider-row.tsx new file mode 100644 index 000000000000..d69a22200d36 --- /dev/null +++ b/packages/app/src/provider-settings/internal/provider-row.tsx @@ -0,0 +1,110 @@ +import type { TFunction } from "i18next"; +import { useCallback, useMemo, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { SettingsDetailRow, type SettingsRowHintStatus } from "@/components/settings"; +import { Switch } from "@/components/ui/switch"; +import { rowHasSwitch, type RowSummary } from "./row-summary"; + +export interface ProviderRowProps { + provider: string; + label: string; + icon: ReactNode; + summary: RowSummary; + enabled: boolean; + /** The Enabled switch is being saved. */ + toggling: boolean; + onOpen: (provider: string) => void; + onToggle: (provider: string, enabled: boolean) => void; +} + +/** + * One provider in the list: its icon and name, a line saying how it is, the Enabled switch when + * there is something to switch, and the chevron to its detail. + */ +export function ProviderRow({ + provider, + label, + icon, + summary, + enabled, + toggling, + onOpen, + onToggle, +}: ProviderRowProps) { + const { t } = useTranslation(); + const handleOpen = useCallback(() => onOpen(provider), [onOpen, provider]); + const handleToggle = useCallback( + (value: boolean) => onToggle(provider, value), + [onToggle, provider], + ); + const hint = describeRowSummary(summary, t); + const hasSwitch = rowHasSwitch(summary); + const toggle = useMemo( + () => + hasSwitch ? ( + + ) : null, + [enabled, handleToggle, hasSwitch, label, t, toggling], + ); + return ( + + ); +} + +function describeRowSummary( + summary: RowSummary, + t: TFunction, +): { text: string | undefined; status: SettingsRowHintStatus | undefined } { + switch (summary.kind) { + case "pending": + return { text: undefined, status: "pending" }; + case "ready": { + const models = + summary.models === 1 + ? t("settings.providers.models.one") + : t("settings.providers.models.many", { count: summary.models }); + const parts = [summary.version, summary.models > 0 ? models : null].filter(Boolean); + return { + text: parts.length ? parts.join(" · ") : t("settings.providers.statuses.available"), + status: undefined, + }; + } + case "updateAvailable": + return { + text: [summary.version, t("settings.providers.installation.updateAvailable")] + .filter(Boolean) + .join(" · "), + status: undefined, + }; + case "updating": + return { + text: summary.target + ? t("settings.providers.list.updatingTo", { version: summary.target }) + : t("settings.providers.installation.updating"), + status: "busy", + }; + case "failing": + return { + text: summary.message ?? t("settings.providers.diagnostic.unknownError"), + status: "error", + }; + case "notInstalled": + return { text: t("settings.providers.statuses.notInstalled"), status: undefined }; + case "disabled": + return { text: t("settings.providers.statuses.disabled"), status: undefined }; + } +} diff --git a/packages/app/src/provider-settings/internal/row-summary.test.ts b/packages/app/src/provider-settings/internal/row-summary.test.ts new file mode 100644 index 000000000000..ad46913f0aae --- /dev/null +++ b/packages/app/src/provider-settings/internal/row-summary.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderInstallationUpdate } from "@getpaseo/protocol/messages"; +import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; +import type { ProviderInstallationRead } from "@/components/provider-installation"; +import { readRowSummary } from "./row-summary"; + +type Read = Pick; + +function entry(overrides: Partial = {}): ProviderSnapshotEntry { + return { + provider: "claude", + label: "Claude", + status: "ready", + enabled: true, + modes: [], + models: [ + { provider: "claude", id: "opus", label: "Opus" }, + { provider: "claude", id: "sonnet", label: "Sonnet" }, + ], + ...overrides, + }; +} + +function installed(version: string | undefined, overrides: Partial = {}): Read { + return { + state: { + status: "ready", + installation: { inspection: { status: "installed", version }, canUpdate: true }, + }, + updates: { status: "ready", updateCheck: { status: "current" } }, + action: { current: null, starting: false, startError: null, start: () => undefined }, + ...overrides, + }; +} + +function update(operation: ProviderInstallationUpdate["operation"]): ProviderInstallationUpdate { + return { operation, output: [] }; +} + +const oldHost: Read = { + state: { status: "unsupported" }, + updates: { status: "hidden" }, + action: undefined, +}; + +describe("provider row summary", () => { + it("reads version and model count for a provider that runs", () => { + expect(readRowSummary(entry(), installed("2.1.321"))).toEqual({ + kind: "ready", + version: "2.1.321", + models: 2, + }); + }); + + it("says an update is available after the version", () => { + const read = installed("2.1.321", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["2.1.400"] } }, + }); + expect(readRowSummary(entry(), read)).toEqual({ kind: "updateAvailable", version: "2.1.321" }); + }); + + it("names the target version while an update runs, when the check reported one", () => { + const running = update({ status: "running", id: "u1", startedAt: "2026-11-14T10:00:00Z" }); + const one = installed("1.0.30", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["1.0.31"] } }, + action: { current: running, starting: false, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), one)).toEqual({ kind: "updating", target: "1.0.31" }); + + const unknown = installed("1.0.30", { + updates: { status: "ready", updateCheck: { status: "available" } }, + action: { current: null, starting: true, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), unknown)).toEqual({ kind: "updating", target: null }); + }); + + it("reports a failed update as the fault", () => { + const failed = update({ + status: "failed", + id: "u1", + startedAt: "2026-11-14T10:00:00Z", + finishedAt: "2026-11-14T10:01:00Z", + message: "npm exited with code 1", + }); + const read = installed("1.0.30", { + action: { current: failed, starting: false, startError: null, start: () => undefined }, + }); + expect(readRowSummary(entry(), read)).toEqual({ + kind: "failing", + message: "npm exited with code 1", + }); + }); + + it("reads the provider's own state once Refresh drops a failed update", () => { + const failed = update({ + status: "failed", + id: "u1", + startedAt: "2026-11-14T10:00:00Z", + finishedAt: "2026-11-14T10:01:00Z", + message: "npm exited with code 1", + }); + const stillFailed = { current: failed, starting: false, startError: null, start: () => {} }; + // A fresh inspection alone leaves the failure: reopening without Refresh still shows it. + expect(readRowSummary(entry(), installed("2.1.400", { action: stillFailed }))).toEqual({ + kind: "failing", + message: "npm exited with code 1", + }); + + // Refresh drops the failed update, so the row has no current update to report. + const cleared = { current: null, starting: false, startError: null, start: () => {} }; + expect(readRowSummary(entry(), installed("2.1.400", { action: cleared }))).toEqual({ + kind: "ready", + version: "2.1.400", + models: 2, + }); + const pending = installed("2.1.321", { + updates: { status: "ready", updateCheck: { status: "available", versions: ["2.1.400"] } }, + action: cleared, + }); + expect(readRowSummary(entry(), pending)).toEqual({ + kind: "updateAvailable", + version: "2.1.321", + }); + }); + + it("reports the provider's error", () => { + expect( + readRowSummary(entry({ status: "error", error: " opencode exited with code 1 " }), oldHost), + ).toEqual({ kind: "failing", message: "opencode exited with code 1" }); + expect(readRowSummary(entry({ status: "error" }), oldHost)).toEqual({ + kind: "failing", + message: null, + }); + }); + + it("calls a missing CLI Not installed, not a fault", () => { + expect(readRowSummary(entry({ status: "unavailable" }), oldHost)).toEqual({ + kind: "notInstalled", + }); + const missing: Read = { + ...oldHost, + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }; + expect(readRowSummary(entry({ status: "error", error: "spawn ENOENT" }), missing)).toEqual({ + kind: "notInstalled", + }); + }); + + it("says Disabled for a provider that is off", () => { + expect(readRowSummary(entry({ enabled: false }), installed("2.1.321"))).toEqual({ + kind: "disabled", + }); + }); + + it("calls a disabled provider whose CLI is missing Not installed, so turning it on changes nothing", () => { + const missing: Read = { + ...oldHost, + state: { status: "ready", installation: { inspection: { status: "not_installed" } } }, + }; + expect(readRowSummary(entry({ enabled: false, status: "unavailable" }), missing)).toEqual({ + kind: "notInstalled", + }); + // A disabled provider is never probed, so without an inspection it is only Disabled. + expect(readRowSummary(entry({ enabled: false, status: "unavailable" }), oldHost)).toEqual({ + kind: "disabled", + }); + }); + + it("holds the line until the installation is read", () => { + const reading: Read = { ...oldHost, state: { status: "loading" } }; + expect(readRowSummary(entry(), reading)).toEqual({ kind: "pending" }); + }); + + it("holds the line while the provider's first probe runs", () => { + expect(readRowSummary(entry({ status: "loading", models: [] }), oldHost)).toEqual({ + kind: "pending", + }); + }); + + it("keeps the last count while the provider is probed again", () => { + expect(readRowSummary(entry({ status: "loading" }), installed("2.1.321"))).toEqual({ + kind: "ready", + version: "2.1.321", + models: 2, + }); + }); + + it("reads a count alone on hosts that cannot report installations", () => { + expect(readRowSummary(entry(), oldHost)).toEqual({ kind: "ready", version: null, models: 2 }); + }); +}); diff --git a/packages/app/src/provider-settings/internal/row-summary.ts b/packages/app/src/provider-settings/internal/row-summary.ts new file mode 100644 index 000000000000..4198eb4232f7 --- /dev/null +++ b/packages/app/src/provider-settings/internal/row-summary.ts @@ -0,0 +1,69 @@ +import type { ProviderInstallationRead } from "@/components/provider-installation"; +import { filterSelectableModels } from "@/provider-selection/model-catalog"; +import type { ProviderEntry } from "./provider-config"; + +/** What a provider's list row says under its name. */ +export type RowSummary = + /** Not known yet; the row holds the line's space. */ + | { kind: "pending" } + | { kind: "ready"; version: string | null; models: number } + | { kind: "updateAvailable"; version: string | null } + | { kind: "updating"; target: string | null } + /** The provider or its last update failed. A null message has no detail to show. */ + | { kind: "failing"; message: string | null } + | { kind: "notInstalled" } + | { kind: "disabled" }; + +type InstallationFacts = Pick; + +/** + * One line per provider, from the snapshot and the installation read. A running update leads + * because the user just started it; then whatever keeps the provider from running, where a missing + * CLI is not a fault; then the version and update state once the host has answered. + */ +export function readRowSummary(entry: ProviderEntry, facts: InstallationFacts): RowSummary { + return readRunningUpdate(facts) ?? readBlocker(entry, facts) ?? readSettled(entry, facts); +} + +function readRunningUpdate({ updates, action }: InstallationFacts): RowSummary | null { + if (!action || !(action.starting || action.current?.operation.status === "running")) return null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + const versions = updateCheck?.status === "available" ? updateCheck.versions : undefined; + return { kind: "updating", target: versions?.length === 1 ? versions[0] : null }; +} + +function readBlocker( + entry: ProviderEntry, + { state, action }: InstallationFacts, +): RowSummary | null { + // A missing CLI wins over Disabled, so the row offers no switch that turning on would take away. + // Without an inspection a disabled provider is only Disabled: the host never probes it. + const inspection = state.status === "ready" ? state.installation?.inspection : undefined; + if (inspection?.status === "not_installed") return { kind: "notInstalled" }; + if (!entry.enabled) return { kind: "disabled" }; + if (entry.status === "unavailable") return { kind: "notInstalled" }; + if (entry.status === "error") return { kind: "failing", message: entry.error?.trim() || null }; + const operation = action?.current?.operation; + if (operation?.status === "failed") { + return { kind: "failing", message: operation.message.trim() || null }; + } + return null; +} + +function readSettled(entry: ProviderEntry, { state, updates }: InstallationFacts): RowSummary { + const models = filterSelectableModels(entry.models ?? null)?.length ?? 0; + // The last count stays while the provider is probed again; only a first probe holds the line. + if (state.status === "loading" || (entry.status === "loading" && models === 0)) { + return { kind: "pending" }; + } + const inspection = state.status === "ready" ? state.installation?.inspection : undefined; + const version = inspection?.status === "installed" ? (inspection.version ?? null) : null; + const updateCheck = updates.status === "ready" ? updates.updateCheck : null; + if (updateCheck?.status === "available") return { kind: "updateAvailable", version }; + return { kind: "ready", version, models }; +} + +/** A provider that is not installed has nothing to switch: the picker leaves it out already. */ +export function rowHasSwitch(summary: RowSummary): boolean { + return summary.kind !== "notInstalled"; +} diff --git a/packages/app/src/provider-settings/internal/sheet-frame.ts b/packages/app/src/provider-settings/internal/sheet-frame.ts new file mode 100644 index 000000000000..c41cb5261cb6 --- /dev/null +++ b/packages/app/src/provider-settings/internal/sheet-frame.ts @@ -0,0 +1,15 @@ +import type { DimensionValue } from "react-native"; + +/** + * Where a provider sheet sits, decided by the surface that opens it. Setup passes its own card's + * size so the sheet covers the card exactly and reads as a page of setup. + */ +export interface ProviderSheetFrame { + desktopMaxWidth?: number; + desktopHeight?: DimensionValue; + snapPoints?: string[]; + /** A back arrow replaces the close button: the sheet stands in for a page of the surface below. */ + returns?: boolean; +} + +export const OVERLAY_SHEET_FRAME: ProviderSheetFrame = { snapPoints: ["65%", "92%"] }; diff --git a/packages/app/src/schedules/schedule-form-model.ts b/packages/app/src/schedules/schedule-form-model.ts index 5c5be3a6413a..52cc3e5b72cc 100644 --- a/packages/app/src/schedules/schedule-form-model.ts +++ b/packages/app/src/schedules/schedule-form-model.ts @@ -1008,7 +1008,9 @@ export function openScheduleForm(snapshot: ScheduleFormSnapshot): ScheduleFormMo } publish({ ...resolved, - modelSelectorProviders: buildSelectableProviderSelectorProviders(providerEntries), + modelSelectorProviders: buildSelectableProviderSelectorProviders(providerEntries, { + selectedProvider: resolved.selectedProvider, + }), providerResolutionByServerId, providerSnapshotRequest: isPendingResolution ? null : state.providerSnapshotRequest, }); diff --git a/packages/app/src/screens/project-settings-screen.tsx b/packages/app/src/screens/project-settings-screen.tsx index ae6f31fef117..d278a21bc5ca 100644 --- a/packages/app/src/screens/project-settings-screen.tsx +++ b/packages/app/src/screens/project-settings-screen.tsx @@ -5,7 +5,7 @@ import { Pressable, Text, View } from "react-native"; import { useFocusEffect } from "expo-router/react-navigation"; import { StyleSheet } from "react-native-unistyles"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, MoreVertical, Pencil, Plus } from "lucide-react-native"; +import { MoreVertical, Pencil, Plus } from "lucide-react-native"; import { ProjectIconView } from "@/components/project-icon-view"; import type { PaseoConfigRaw, @@ -29,6 +29,7 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input"; import { SettingsTextAreaCard } from "@/components/settings-textarea"; import { SettingsGroup } from "@/components/settings/headings/settings-group"; import { SettingsSection } from "@/components/settings/headings/settings-section"; +import { SettingsBackLink, SettingsDetailHeader } from "@/components/settings"; import { settingsStyles } from "@/styles/settings"; import { useProjects } from "@/hooks/use-projects"; import type { ProjectEditFormSnapshot } from "@/projects/edit-form"; @@ -170,16 +171,11 @@ function NoEditableTarget({ function BackToProjectsButton({ onPress }: { onPress: () => void }) { const { t } = useTranslation(); return ( - + testID="project-settings-back-link" + /> ); } @@ -260,33 +256,51 @@ function ProjectSettingsBody({ const handleReload = useCallback(() => { void readQuery.refetch(); }, [readQuery]); + const backLink = useMemo( + () => + showBackToProjects + ? { + label: t("settings.project.backToProjects"), + onPress: onBackToProjects, + testID: "project-settings-back-link", + } + : undefined, + [onBackToProjects, showBackToProjects, t], + ); + const titleIcon = useMemo( + () => ( + + ), + [project.viewKey, projectIconDataUri, selectedHost.projectName], + ); + const editButton = useMemo( + () => ( + + + + ), + [openEditSheet, t], + ); return ( - {showBackToProjects ? : null} - - - - - - {selectedHost.projectName} - - - - - - + ({ padding: theme.spacing[4], gap: theme.spacing[2], }, - backButton: { - alignSelf: "flex-start", - paddingHorizontal: 0, - }, - headerBlock: { - marginTop: theme.spacing[2], - marginBottom: theme.spacing[4], - gap: theme.spacing[2], - }, - titleRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[3], - }, - projectTitle: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - flexShrink: 1, - }, editButton: { padding: theme.spacing[1], }, diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 7fc6dbe2487e..b1966dc04ad3 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -118,6 +118,7 @@ import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-p import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; import ProjectSettingsScreen from "@/screens/project-settings-screen"; +import { ProviderDetailPage } from "@/provider-settings"; import { SETTINGS_DESKTOP_DETAIL_MIN_WIDTH, SETTINGS_DESKTOP_SIDEBAR_WIDTH, @@ -990,6 +991,7 @@ function SettingsSidebar({ let selectedHostSection: HostSectionSlug | null = null; if (view.kind === "host") selectedHostSection = view.section; if (view.kind === "project") selectedHostSection = "projects"; + if (view.kind === "provider") selectedHostSection = "providers"; if (view.kind === "plugin" || view.kind === "pluginListing") selectedHostSection = "plugins"; const sidebarBody = ( @@ -1137,7 +1139,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { view.kind === "host" || view.kind === "project" || view.kind === "plugin" || - view.kind === "pluginListing" + view.kind === "pluginListing" || + view.kind === "provider" ) return view.serverId; return resolveActiveHostServerId({ @@ -1216,8 +1219,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const handleSelectHost = useCallback( (serverId: string) => { selectSettingsHost(serverId); - if (view.kind === "project") { - const target = buildSettingsHostSectionRoute(serverId, "projects"); + if (view.kind === "project" || view.kind === "provider") { + // The detail belongs to the old host; open the same list on the new one. + const target = buildSettingsHostSectionRoute( + serverId, + view.kind === "project" ? "projects" : "providers", + ); if (isCompactLayout) { router.push(target); } else { @@ -1296,6 +1303,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (view.kind === "project") { return t("settings.projects"); } + if (view.kind === "provider") return t("settings.hostSections.providers"); return undefined; })(); @@ -1331,6 +1339,16 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { /> ); } + if (view.kind === "provider") { + return ( + + ); + } if (view.kind === "section") { const item = SIDEBAR_SECTION_ITEMS.find((candidate) => candidate.id === view.section); if (!item || !isSectionAvailable(item, isDesktopApp, hardwareKeyboardPresent)) return null; diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 9c0c95248840..6e27f7065010 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -49,7 +49,8 @@ import { useHostRuntimeSnapshot, useHosts, } from "@/runtime/host-runtime"; -import { ProvidersSection } from "@/screens/settings/providers-section"; +import { ProviderList } from "@/provider-settings"; +import { openProviderSettings } from "@/navigation/settings-navigation"; import { HostUsageSection } from "@/usage"; import { HostAppearanceSection } from "@/screens/settings/host-appearance-section"; import { SettingsSection } from "@/components/settings/headings/settings-section"; @@ -334,6 +335,10 @@ export function HostWorkspacesPage({ serverId }: { serverId: string }) { export function HostProvidersPage({ serverId }: { serverId: string }) { const host = useHostProfile(serverId); + const openProvider = useCallback( + (providerId: string) => openProviderSettings(serverId, providerId), + [serverId], + ); if (!host) { return ; @@ -341,7 +346,7 @@ export function HostProvidersPage({ serverId }: { serverId: string }) { return ( - + ); } diff --git a/packages/app/src/screens/settings/metadata-generation-page.tsx b/packages/app/src/screens/settings/metadata-generation-page.tsx index 0e8d895228ab..e88c379df63f 100644 --- a/packages/app/src/screens/settings/metadata-generation-page.tsx +++ b/packages/app/src/screens/settings/metadata-generation-page.tsx @@ -19,12 +19,15 @@ export function MetadataGenerationPage({ serverId }: { serverId: string }) { const { t } = useTranslation(); const { config, isLoading: isConfigLoading, patchConfig } = useDaemonConfig(serverId); const snapshot = useProvidersSnapshot(serverId); - const providers = useMemo( - () => buildSelectableProviderSelectorProviders(snapshot.entries), - [snapshot.entries], - ); const configuredProviders = config?.metadataGeneration.providers; const configuredProvider = configuredProviders?.[0] ?? null; + const providers = useMemo( + () => + buildSelectableProviderSelectorProviders(snapshot.entries, { + selectedProvider: configuredProvider?.provider ?? null, + }), + [configuredProvider?.provider, snapshot.entries], + ); const savedMode: SelectionMode = configuredProvider ? "preferred" : "automatic"; const [draftMode, setDraftMode] = useState(null); const [isSaving, setIsSaving] = useState(false); diff --git a/packages/app/src/screens/settings/providers-section.test.tsx b/packages/app/src/screens/settings/providers-section.test.tsx deleted file mode 100644 index 3e551345202a..000000000000 --- a/packages/app/src/screens/settings/providers-section.test.tsx +++ /dev/null @@ -1,453 +0,0 @@ -/** - * @vitest-environment jsdom - */ -import React, { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; -import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; -import { ToastApiProvider } from "@/contexts/toast-api-context"; - -const { snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted( - () => ({ - snapshotState: { - entries: undefined as ProviderSnapshotEntry[] | undefined, - isLoading: false, - isRefreshing: false, - }, - configState: { - config: null as MutableDaemonConfig | null, - }, - patchConfigMock: vi.fn(async () => undefined), - openProviderSettingsMock: vi.fn(), - }), -); - -vi.mock("react-native", async (importOriginal) => ({ - ...(await importOriginal()), - View: ({ children, testID }: { children?: React.ReactNode; testID?: string }) => - React.createElement("div", { "data-testid": testID }, children), - Text: ({ children }: { children?: React.ReactNode }) => - React.createElement("span", null, children), - Pressable: ({ - children, - onPress, - onHoverIn, - onHoverOut, - accessibilityRole, - accessibilityLabel, - disabled, - testID, - }: { - children?: - | React.ReactNode - | ((state: { pressed: boolean; hovered: boolean }) => React.ReactNode); - onPress?: (event: React.MouseEvent) => void; - onHoverIn?: () => void; - onHoverOut?: () => void; - accessibilityRole?: string; - accessibilityLabel?: string; - disabled?: boolean; - testID?: string; - }) => - React.createElement( - "div", - { - role: accessibilityRole, - "aria-label": accessibilityLabel, - "aria-disabled": disabled ? "true" : undefined, - "data-testid": testID, - onClick: disabled ? undefined : onPress, - onMouseEnter: onHoverIn, - onMouseLeave: onHoverOut, - }, - typeof children === "function" ? children({ pressed: false, hovered: false }) : children, - ), - ActivityIndicator: () => React.createElement("span", { "data-testid": "activity-indicator" }), -})); - -vi.mock("lucide-react-native", () => { - const icon = (name: string) => () => React.createElement("span", { "data-icon": name }); - return { - ChevronRight: icon("ChevronRight"), - MoreHorizontal: icon("MoreHorizontal"), - Trash2: icon("Trash2"), - }; -}); - -vi.mock("react-i18next", () => ({ - useTranslation: () => ({ - t: (key: string, values?: Record) => - ( - ({ - "settings.providers.providerDetails": "{{name}} provider details", - "settings.providers.enableProvider": "Enable {{name}}", - "settings.providers.statuses.disabled": "Disabled", - "settings.providers.statuses.available": "Available", - "settings.providers.statuses.loading": "Loading", - "settings.providers.statuses.error": "Error", - "settings.providers.statuses.notInstalled": "Not installed", - "settings.providers.models.one": "1 model", - "settings.providers.models.many": "{{count}} models", - "settings.providers.addErrorTitle": "Unable to add provider", - "settings.providers.updateErrorTitle": "Unable to update provider", - "settings.providers.actions.menu": "{{name}} actions", - "settings.providers.actions.remove": "Remove provider", - "settings.providers.actions.removing": "Removing...", - "settings.providers.remove.confirmTitle": "Remove {{name}}?", - "settings.providers.remove.confirmMessage": - "This deletes the provider entry from config.json. It cannot be undone.", - "settings.providers.remove.confirm": "Remove", - "settings.providers.remove.errorTitle": "Unable to remove provider", - })[key] ?? key - ) - .replaceAll("{{name}}", String(values?.name ?? "")) - .replaceAll("{{count}}", String(values?.count ?? "")), - }), -})); - -vi.mock("@/components/ui/switch", () => ({ - Switch: ({ - value, - onValueChange, - disabled, - accessibilityLabel, - testID, - }: { - value: boolean; - onValueChange?: (next: boolean) => void; - disabled?: boolean; - accessibilityLabel?: string; - testID?: string; - }) => - React.createElement("div", { - role: "switch", - "aria-checked": value ? "true" : "false", - "aria-disabled": disabled ? "true" : undefined, - "aria-label": accessibilityLabel, - "data-testid": testID ?? "provider-switch", - onClick: (event: React.MouseEvent) => { - event.stopPropagation(); - if (disabled) return; - onValueChange?.(!value); - }, - }), -})); - -vi.mock("@/components/ui/loading-spinner", () => ({ - LoadingSpinner: () => React.createElement("span", { "data-testid": "loading-spinner" }), -})); - -vi.mock("@/components/settings/headings/settings-info-tip", () => ({ - SettingsInfoTip: () => null, -})); - -vi.mock("@/components/ui/external-link", () => ({ - ExternalLink: () => null, - ExternalLinkLabel: () => null, -})); - -vi.mock("@/components/ui/dropdown-menu", () => ({ - DropdownMenu: ({ children }: { children?: React.ReactNode }) => - React.createElement("div", null, children), - DropdownMenuTrigger: ({ - children, - onPressIn, - accessibilityRole, - accessibilityLabel, - testID, - }: { - children?: - | React.ReactNode - | ((state: { pressed: boolean; hovered: boolean; open: boolean }) => React.ReactNode); - onPressIn?: (event: { stopPropagation: () => void }) => void; - accessibilityRole?: string; - accessibilityLabel?: string; - testID?: string; - }) => - React.createElement( - "button", - { - type: "button", - role: accessibilityRole, - "aria-label": accessibilityLabel, - "data-testid": testID, - onMouseDown: (event: React.MouseEvent) => onPressIn?.(event), - onClick: (event: React.MouseEvent) => event.stopPropagation(), - }, - typeof children === "function" - ? children({ pressed: false, hovered: false, open: false }) - : children, - ), - DropdownMenuContent: ({ children }: { children?: React.ReactNode }) => - React.createElement("div", null, children), - DropdownMenuItem: ({ - children, - onSelect, - status, - pendingLabel, - testID, - }: { - children?: React.ReactNode; - onSelect?: () => void; - status?: "idle" | "pending" | "success"; - pendingLabel?: string; - testID?: string; - }) => - React.createElement( - "button", - { - type: "button", - "data-testid": testID, - disabled: status === "pending" || status === "success", - onClick: (event: React.MouseEvent) => { - event.stopPropagation(); - onSelect?.(); - }, - }, - status === "pending" ? pendingLabel : children, - ), -})); - -vi.mock("@/components/provider-icons", () => ({ - useProviderIcon: (provider: string) => () => - React.createElement("span", { "data-icon": `provider-${provider}` }), -})); - -vi.mock("@/stores/provider-settings-store", () => ({ - useProviderSettingsStore: (selector: (state: unknown) => unknown) => - selector({ open: openProviderSettingsMock }), -})); - -vi.mock("@/components/provider-catalog-list", () => ({ - ProviderCatalogList: () => null, -})); - -vi.mock("@/hooks/use-providers-snapshot", () => ({ - useProvidersSnapshot: () => ({ - entries: snapshotState.entries, - isLoading: snapshotState.isLoading, - isFetching: false, - isRefreshing: snapshotState.isRefreshing, - error: null, - supportsSnapshot: true, - refresh: vi.fn(async () => {}), - refetchIfStale: vi.fn(), - }), -})); - -vi.mock("@/hooks/use-daemon-config", () => ({ - useDaemonConfig: () => ({ - config: configState.config, - isLoading: false, - patchConfig: patchConfigMock, - }), -})); - -vi.mock("@/runtime/host-runtime", () => ({ - useHostRuntimeIsConnected: () => true, -})); - -vi.mock("@/runtime/host-features", () => ({ - useHostFeature: () => false, -})); - -vi.mock("@/utils/confirm-dialog", () => ({ - confirmDialog: vi.fn(async () => true), -})); - -import { ProvidersSection } from "./providers-section"; - -function unexpectedToast(): never { - throw new Error("Provider row interactions should not display a toast"); -} - -const toastApi = { show: unexpectedToast, copied: unexpectedToast, error: unexpectedToast }; - -const claudeEntry: ProviderSnapshotEntry = { - provider: "claude", - status: "ready", - enabled: true, - label: "Claude", - description: "Claude Code", - defaultModeId: null, - modes: [], - models: [ - { provider: "claude", id: "claude-opus-4-7", label: "Claude Opus 4.7" }, - { provider: "claude", id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" }, - { provider: "claude", id: "claude-haiku-4-5", label: "Claude Haiku 4.5" }, - ], -}; - -const disabledCodexEntry: ProviderSnapshotEntry = { - provider: "codex", - status: "unavailable", - enabled: false, - label: "Codex", - description: "OpenAI Codex", - defaultModeId: null, - modes: [], -}; - -function makeConfig(providers: MutableDaemonConfig["providers"] = {}): MutableDaemonConfig { - return { - relay: { enabled: false }, - mcp: { injectIntoAgents: false }, - browserTools: { enabled: false }, - providers, - metadataGeneration: { providers: [] }, - autoArchiveAfterMerge: false, - enableTerminalAgentHooks: false, - appendSystemPrompt: "", - }; -} - -function descendants(el: HTMLElement): HTMLElement[] { - return Array.from(el.querySelectorAll("*")); -} - -function indexOfMatches(nodes: HTMLElement[], selector: string): number { - return nodes.findIndex((node) => node.matches(selector)); -} - -function indexOfText(nodes: HTMLElement[], text: string): number { - return nodes.findIndex((node) => node.textContent?.trim() === text); -} - -describe("ProvidersSection", () => { - let root: Root | null = null; - let container: HTMLElement | null = null; - - beforeEach(() => { - vi.stubGlobal("React", React); - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - - snapshotState.entries = undefined; - snapshotState.isLoading = false; - snapshotState.isRefreshing = false; - configState.config = null; - patchConfigMock.mockReset(); - patchConfigMock.mockResolvedValue(undefined); - openProviderSettingsMock.mockReset(); - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - root = null; - container?.remove(); - container = null; - vi.unstubAllGlobals(); - }); - - function render(): void { - act(() => { - root?.render( - - - , - ); - }); - } - - function findRow(accessibilityLabel: string): HTMLElement { - const row = container?.querySelector( - `[role="button"][aria-label="${accessibilityLabel}"]`, - ); - if (!row) throw new Error(`Expected row with aria-label "${accessibilityLabel}"`); - return row; - } - - it("renders the disabled provider with its server-provided label in snapshot order", () => { - snapshotState.entries = [claudeEntry, disabledCodexEntry]; - configState.config = makeConfig({ codex: { enabled: false } }); - - render(); - - const rows = Array.from( - container?.querySelectorAll('[role="button"][aria-label$="provider details"]') ?? - [], - ); - expect(rows.map((row) => row.getAttribute("aria-label"))).toEqual([ - "Claude provider details", - "Codex provider details", - ]); - - const codexRow = findRow("Codex provider details"); - const codexNodes = descendants(codexRow); - expect(indexOfText(codexNodes, "Codex")).toBeGreaterThanOrEqual(0); - expect(indexOfText(codexNodes, "codex")).toBe(-1); - expect(indexOfText(codexNodes, "Disabled")).toBeGreaterThanOrEqual(0); - }); - - it("composes the row as chevron, icon, label, status, model count, then switch", () => { - snapshotState.entries = [claudeEntry]; - configState.config = makeConfig(); - - render(); - - const row = findRow("Claude provider details"); - const nodes = descendants(row); - const chevron = indexOfMatches(nodes, '[data-icon="ChevronRight"]'); - const icon = indexOfMatches(nodes, '[data-icon="provider-claude"]'); - const label = indexOfText(nodes, "Claude"); - const status = indexOfText(nodes, "Available"); - const modelCount = indexOfText(nodes, "3 models"); - const switchEl = indexOfMatches(nodes, '[role="switch"]'); - - expect(chevron).toBeGreaterThanOrEqual(0); - expect(icon).toBeGreaterThan(chevron); - expect(label).toBeGreaterThan(icon); - expect(status).toBeGreaterThan(label); - expect(modelCount).toBeGreaterThan(status); - expect(switchEl).toBeGreaterThan(modelCount); - }); - - it("opens the diagnostic sheet when the outer row is pressed for a disabled provider", () => { - snapshotState.entries = [disabledCodexEntry]; - configState.config = makeConfig({ codex: { enabled: false } }); - - render(); - - expect(openProviderSettingsMock).not.toHaveBeenCalled(); - - const row = findRow("Codex provider details"); - act(() => { - row.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect(openProviderSettingsMock).toHaveBeenCalledTimes(1); - expect(openProviderSettingsMock).toHaveBeenCalledWith({ - serverId: "server-1", - provider: "codex", - }); - }); - - it("toggles the provider enabled flag through patchConfig when the switch is pressed", async () => { - snapshotState.entries = [claudeEntry]; - configState.config = makeConfig(); - - render(); - - const row = findRow("Claude provider details"); - const switchEl = row.querySelector('[role="switch"]'); - expect(switchEl).not.toBeNull(); - expect(switchEl?.getAttribute("aria-checked")).toBe("true"); - - await act(async () => { - switchEl?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); - }); - - expect(patchConfigMock).toHaveBeenCalledTimes(1); - expect(patchConfigMock).toHaveBeenCalledWith({ - providers: { claude: { enabled: false } }, - }); - }); -}); diff --git a/packages/app/src/screens/settings/providers-section.tsx b/packages/app/src/screens/settings/providers-section.tsx deleted file mode 100644 index 078cf086f5a5..000000000000 --- a/packages/app/src/screens/settings/providers-section.tsx +++ /dev/null @@ -1,622 +0,0 @@ -import { useCallback, useMemo, useRef, useState } from "react"; -import type { TFunction } from "i18next"; -import { useTranslation } from "react-i18next"; -import { - Alert, - Pressable, - Text, - View, - type GestureResponderEvent, - type PressableStateCallbackType, -} from "react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { useIsCompactFormFactor } from "@/constants/layout"; -import { useToast } from "@/contexts/toast-api-context"; -import { settingsStyles } from "@/styles/settings"; -import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; -import { selectHostFeature, useHostFeature } from "@/runtime/host-features"; -import { useSessionStore } from "@/stores/session-store"; -import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { buildProviderDefinitions } from "@/utils/provider-definitions"; -import { - buildAcpProviderConfigPatch, - getAcpProviderCatalog, - type AcpProviderCatalogItem, -} from "@/hooks/use-acp-provider-catalog"; -import { ProviderCatalogList } from "@/components/provider-catalog-list"; -import { useProviderIcon } from "@/components/provider-icons"; -import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; -import { Switch } from "@/components/ui/switch"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { SettingsSection } from "@/components/settings/headings/settings-section"; -import { useProviderSettingsStore } from "@/stores/provider-settings-store"; -import { confirmDialog } from "@/utils/confirm-dialog"; -import { filterSelectableModels } from "@/provider-selection/model-catalog"; -import { ChevronRight, MoreHorizontal, Trash2 } from "lucide-react-native"; - -type ProviderDefinition = ReturnType[number]; -type ProviderEntry = NonNullable["entries"]>[number]; - -type StatusTone = "success" | "warning" | "danger" | "muted" | "loading"; - -interface ProviderStatus { - tone: StatusTone; - label: string; - modelCount: number | null; -} - -function getProviderStatus( - status: string, - enabled: boolean, - modelCount: number, - t: TFunction, -): ProviderStatus { - if (!enabled) - return { tone: "muted", label: t("settings.providers.statuses.disabled"), modelCount: null }; - if (status === "loading") { - return { tone: "loading", label: t("settings.providers.statuses.loading"), modelCount: null }; - } - if (status === "error") { - return { tone: "danger", label: t("settings.providers.statuses.error"), modelCount: null }; - } - if (status === "ready") { - return { - tone: "success", - label: t("settings.providers.statuses.available"), - modelCount: modelCount > 0 ? modelCount : null, - }; - } - return { - tone: "warning", - label: t("settings.providers.statuses.notInstalled"), - modelCount: null, - }; -} - -interface ProviderRowProps { - serverId: string; - def: ProviderDefinition; - entry: ProviderEntry; - enabled: boolean; - isToggling: boolean; - isRemoving: boolean; - canRemove: boolean; - isFirst: boolean; - onPress: (providerId: string) => void; - onToggleEnabled: (providerId: string, enabled: boolean) => void; - onRemove: (providerId: string, providerLabel: string) => void; -} - -function stopPressInPropagation(event: GestureResponderEvent) { - event.stopPropagation(); -} - -interface ProviderActionsMenuProps { - providerId: string; - providerLabel: string; - isRemoving: boolean; - iconSize: number; - foregroundColor: string; - foregroundMutedColor: string; - dangerColor: string; - onRemove: (providerId: string, providerLabel: string) => void; -} - -function ProviderActionsMenu({ - providerId, - providerLabel, - isRemoving, - iconSize, - foregroundColor, - foregroundMutedColor, - dangerColor, - onRemove, -}: ProviderActionsMenuProps) { - const { t } = useTranslation(); - const handleRemove = useCallback(() => { - onRemove(providerId, providerLabel); - }, [onRemove, providerId, providerLabel]); - const triggerStyle = useCallback( - ({ - pressed, - hovered, - open, - }: PressableStateCallbackType & { hovered?: boolean; open?: boolean }) => [ - styles.menuButton, - (hovered || open) && styles.menuButtonHovered, - pressed && styles.menuButtonPressed, - ], - [], - ); - const trashLeading = useMemo(() => , [dangerColor]); - - return ( - - - {({ hovered, open }) => ( - - )} - - - - {t("settings.providers.actions.remove")} - - - - ); -} - -const SKELETON_ROW_KEYS = [0, 1, 2, 3].map((index) => `provider-skeleton-row-${index}`); - -function ProviderRowsSkeleton() { - const { t } = useTranslation(); - const pulse = useSkeletonPulse(); - return ( - - {SKELETON_ROW_KEYS.map((key, index) => ( - 0 && settingsStyles.rowBorder, styles.row]} - > - - - - - - - ))} - - ); -} - -function ProviderRow({ - serverId, - def, - entry, - enabled, - isToggling, - isRemoving, - canRemove, - isFirst, - onPress, - onToggleEnabled, - onRemove, -}: ProviderRowProps) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const isCompact = useIsCompactFormFactor(); - const ProviderIcon = useProviderIcon(def.id, serverId); - const providerError = - enabled && - entry.status === "error" && - typeof entry.error === "string" && - entry.error.trim().length > 0 - ? entry.error.trim() - : null; - const modelCount = filterSelectableModels(entry.models ?? null)?.length ?? 0; - const providerStatus = getProviderStatus(entry.status, enabled, modelCount, t); - - const handlePress = useCallback(() => { - onPress(def.id); - }, [def.id, onPress]); - const handleToggleValueChange = useCallback( - (value: boolean) => { - onToggleEnabled(def.id, value); - }, - [def.id, onToggleEnabled], - ); - const rowStyle = useCallback( - ({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => [ - settingsStyles.row, - !isFirst && settingsStyles.rowBorder, - styles.row, - hovered && styles.rowHovered, - pressed && styles.rowPressed, - ], - [isFirst], - ); - - return ( - - {({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => ( - <> - - - - - - - {def.label} - - {!isCompact ? · : null} - - - {providerError && !isCompact ? ( - - {providerError} - - ) : null} - - - {/* The menu leads the switch, so every switch sits on the row's right edge without - rows that have no menu reserving room for one. */} - - {canRemove ? ( - - ) : null} - - - - )} - - ); -} - -function getDotColor(tone: StatusTone, theme: ReturnType["theme"]): string { - switch (tone) { - case "success": - return theme.colors.statusSuccess; - case "warning": - return theme.colors.statusWarning; - case "danger": - return theme.colors.statusDanger; - default: - return theme.colors.foregroundMuted; - } -} - -function StatusIndicator({ status, compact }: { status: ProviderStatus; compact: boolean }) { - const { t } = useTranslation(); - const { theme } = useUnistyles(); - const dotStyle = useMemo( - () => [styles.statusDot, { backgroundColor: getDotColor(status.tone, theme) }], - [status.tone, theme], - ); - - return ( - - {status.tone === "loading" ? ( - - ) : ( - - )} - {!compact ? ( - <> - {status.label} - {status.modelCount !== null ? ( - <> - · - - {status.modelCount === 1 - ? t("settings.providers.models.one") - : t("settings.providers.models.many", { count: status.modelCount })} - - - ) : null} - - ) : null} - - ); -} - -export interface ProvidersSectionProps { - serverId: string; -} - -export function ProvidersSection({ serverId }: ProvidersSectionProps) { - const { t } = useTranslation(); - const toast = useToast(); - const isConnected = useHostRuntimeIsConnected(serverId); - const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval"); - const { entries, isLoading, refresh } = useProvidersSnapshot(serverId); - const { config, patchConfig } = useDaemonConfig(serverId); - const openProviderSettings = useProviderSettingsStore((state) => state.open); - const [pendingProviderId, setPendingProviderId] = useState(null); - const [removingProviderId, setRemovingProviderId] = useState(null); - const removingProviderIdRef = useRef(null); - const [installingProviderId, setInstallingProviderId] = useState(null); - - const providerDefinitions = useMemo(() => buildProviderDefinitions(entries), [entries]); - const hasServer = serverId.length > 0; - - /** Config owns derived providers and opt-in bundled catalog providers. */ - const isConfigOwnedProvider = useCallback( - (providerId: string) => - Boolean( - config?.providers?.[providerId] && - (config.providers[providerId].extends || - getAcpProviderCatalog().some( - (entry) => entry.id === providerId && entry.bundledProvider, - )), - ), - [config], - ); - - const handleOpenProviderSettings = useCallback( - (providerId: string) => { - openProviderSettings({ serverId, provider: providerId }); - }, - [openProviderSettings, serverId], - ); - - const handleToggleEnabled = useCallback( - async (providerId: string, enabled: boolean) => { - setPendingProviderId(providerId); - try { - await patchConfig({ providers: { [providerId]: { enabled } } }); - } catch (error) { - Alert.alert( - t("settings.providers.updateErrorTitle"), - error instanceof Error ? error.message : String(error), - ); - } finally { - setPendingProviderId((current) => (current === providerId ? null : current)); - } - }, - [patchConfig, t], - ); - - const handleRemoveProvider = useCallback( - async (providerId: string, providerLabel: string) => { - if (removingProviderIdRef.current) return; - removingProviderIdRef.current = providerId; - setRemovingProviderId(providerId); - try { - const confirmed = await confirmDialog({ - title: t("settings.providers.remove.confirmTitle", { name: providerLabel }), - message: t("settings.providers.remove.confirmMessage"), - confirmLabel: t("settings.providers.remove.confirm"), - destructive: true, - }); - if (!confirmed) { - return; - } - - await patchConfig({ removeProviders: [providerId] }); - } catch (error) { - Alert.alert( - t("settings.providers.remove.errorTitle"), - error instanceof Error ? error.message : String(error), - ); - } finally { - if (removingProviderIdRef.current === providerId) { - removingProviderIdRef.current = null; - } - setRemovingProviderId((current) => (current === providerId ? null : current)); - } - }, - [patchConfig, t], - ); - - const handleInstall = useCallback( - async (entry: AcpProviderCatalogItem) => { - if (installingProviderId) return; - setInstallingProviderId(entry.id); - try { - await patchConfig( - buildAcpProviderConfigPatch(entry, (feature) => - selectHostFeature(useSessionStore.getState(), serverId, feature), - ), - ); - await refresh([entry.id]); - } catch (error) { - toast.error(error instanceof Error ? error.message : String(error)); - } finally { - setInstallingProviderId((current) => (current === entry.id ? null : current)); - } - }, - [installingProviderId, patchConfig, refresh, serverId, toast], - ); - - return ( - <> - - {!hasServer || !isConnected ? ( - - {t("settings.providers.unavailable")} - - ) : null} - {hasServer && isConnected && isLoading ? : null} - {hasServer && isConnected && !isLoading && providerDefinitions.length > 0 ? ( - - {providerDefinitions.map((def, index) => { - const entry = entries?.find((candidate) => candidate.provider === def.id); - if (!entry) return null; - return ( - - ); - })} - - ) : null} - - - {hasServer && isConnected ? ( - - - - ) : null} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - sectionSpacing: { - marginBottom: theme.spacing[4], - }, - addProviderSection: { - marginTop: theme.spacing[4], - }, - emptyCard: { - padding: theme.spacing[4], - alignItems: "center", - }, - emptyText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - row: { - gap: theme.spacing[3], - minHeight: 56, - }, - rowHovered: { - backgroundColor: theme.colors.surface2, - }, - skeletonIcon: { - width: 20, - height: 20, - marginLeft: theme.spacing[6], - borderRadius: theme.borderRadius.md, - backgroundColor: theme.colors.surface2, - }, - skeletonTitle: { - width: 160, - height: 12, - borderRadius: theme.borderRadius.sm, - backgroundColor: theme.colors.surface2, - }, - skeletonSwitch: { - width: 36, - height: 20, - borderRadius: theme.borderRadius.full, - backgroundColor: theme.colors.surface2, - }, - rowPressed: { - backgroundColor: theme.colors.surface3, - }, - rowContent: { - flex: 1, - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - textColumn: { - flex: 1, - minWidth: 0, - }, - titleRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - statusRow: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1.5], - }, - statusDot: { - width: 8, - height: 8, - borderRadius: 4, - }, - statusLabel: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - separator: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - }, - errorText: { - color: theme.colors.palette.red[300], - fontSize: theme.fontSize.sm, - marginTop: theme.spacing[1], - }, - trailingControls: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1], - }, - menuButton: { - width: 32, - height: 32, - borderRadius: theme.borderRadius.lg, - alignItems: "center", - justifyContent: "center", - }, - menuButtonHovered: { - backgroundColor: theme.colors.surface2, - }, - menuButtonPressed: { - backgroundColor: theme.colors.surface3, - }, -})); diff --git a/packages/app/src/utils/host-routes.test.ts b/packages/app/src/utils/host-routes.test.ts index 1687563603cd..2defc505f62b 100644 --- a/packages/app/src/utils/host-routes.test.ts +++ b/packages/app/src/utils/host-routes.test.ts @@ -17,6 +17,7 @@ import { isSettingsSectionSlug, normalizeHostSectionSlug, normalizeProjectSettingsRouteId, + buildProviderSettingsRoute, parseHostAgentRouteFromPathname, parseHostWorkspaceOpenIntentFromPathname, parseHostWorkspaceRouteFromPathname, @@ -199,6 +200,14 @@ describe("projects settings routes", () => { }); }); +describe("provider settings routes", () => { + it("buildProviderSettingsRoute addresses one provider on a host", () => { + expect(buildProviderSettingsRoute("host a", "acp/gemini")).toBe( + "/settings/hosts/host%20a/providers/acp%2Fgemini", + ); + }); +}); + describe("global routes", () => { it("buildSessionsRoute returns the all-host Sessions route", () => { expect(buildSessionsRoute()).toBe("/sessions"); diff --git a/packages/app/src/utils/host-routes.ts b/packages/app/src/utils/host-routes.ts index f258c6ba5b19..14db64125d09 100644 --- a/packages/app/src/utils/host-routes.ts +++ b/packages/app/src/utils/host-routes.ts @@ -584,6 +584,13 @@ export function buildProjectSettingsRoute(serverId: string, projectId: string) { return `/settings/hosts/${encodeSegment(serverId)}/projects/${encodeSegment(projectId)}` as const; } +export function buildProviderSettingsRoute(serverId: string, providerId: string) { + if (!serverId.trim() || !providerId.trim()) { + throw new Error("buildProviderSettingsRoute requires a serverId and providerId"); + } + return `/settings/hosts/${encodeSegment(serverId)}/providers/${encodeSegment(providerId)}` as const; +} + export function normalizeProjectSettingsRouteId(value: string | string[] | undefined): string { const id = Array.isArray(value) ? value[0] : value; return typeof id === "string" ? id : ""; diff --git a/packages/app/test-stubs/react-native-unistyles.ts b/packages/app/test-stubs/react-native-unistyles.ts index dfd3b58d932b..0b28532b823d 100644 --- a/packages/app/test-stubs/react-native-unistyles.ts +++ b/packages/app/test-stubs/react-native-unistyles.ts @@ -4,7 +4,10 @@ import { lightTheme } from "../src/styles/theme"; const pinnedTheme = { colorScheme: "light", + // The light theme's colours, so a `withUnistyles` mapping finds every key it reads, with the + // values below pinned so a test can name the colour it expects. colors: { + ...lightTheme.colors, syntax: lightHighlightColors, foreground: "#111111", foregroundMuted: "#666666", @@ -157,12 +160,16 @@ export const StyleSheet = { type UniPropsMapping = (theme: typeof testTheme, runtime: object) => Record; -/** Applies `uniProps` with the test theme, the way Unistyles maps theme values onto props. */ -export const withUnistyles = (Component: T): T => { +/** + * Applies the theme mapping and `uniProps` with the test theme, the way Unistyles maps theme values + * onto props: mapped props first, then `uniProps`, then the props the caller passed. + */ +export const withUnistyles = (Component: T, mapping?: UniPropsMapping): T => { function ThemedComponent({ uniProps, ...props }: { uniProps?: UniPropsMapping }) { // Explicit props win over mapped ones, as in Unistyles' `deepMergeObjects(mappings, uniProps, props)`. return createElement(Component as ElementType, { - ...(uniProps ? uniProps(testTheme, {}) : {}), + ...mapping?.(testTheme, {}), + ...uniProps?.(testTheme, {}), ...props, }); } diff --git a/public-docs/cli.md b/public-docs/cli.md index 700206e5a58d..99e4d4c32ac2 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -99,7 +99,7 @@ paseo provider diagnostic codex --json paseo --host devbox:6767 provider diagnostic opencode ``` -The diagnostic includes the configured command, daemon `PATH` and shell, matching binaries, resolved path, version, model count, and provider status. Use the global `--host` option for a remote daemon. This is the same diagnostic shown under **Settings → your host → Providers → provider → Diagnostic**. +The diagnostic includes the configured command, daemon `PATH` and shell, matching binaries, resolved path, version, model count, and provider status. Use the global `--host` option for a remote daemon. This is the same diagnostic shown under **Settings → your host → Providers → provider → Diagnostic report**. ## Running agents diff --git a/public-docs/cli.zh-CN.md b/public-docs/cli.zh-CN.md index 29b8aec65f6b..a60c13ed8874 100644 --- a/public-docs/cli.zh-CN.md +++ b/public-docs/cli.zh-CN.md @@ -96,7 +96,7 @@ paseo provider diagnostic codex --json paseo --host devbox:6767 provider diagnostic opencode ``` -诊断信息包括配置的命令、daemon 的 `PATH` 和 shell、匹配到的二进制文件、解析出的路径、版本、模型数量和 Provider 状态。对于远程 daemon,请使用全局的 `--host` 选项。这与 **设置 → 你的主机 → Providers → 对应 Provider → 诊断** 下显示的诊断相同。 +诊断信息包括配置的命令、daemon 的 `PATH` 和 shell、匹配到的二进制文件、解析出的路径、版本、模型数量和 Provider 状态。对于远程 daemon,请使用全局的 `--host` 选项。这与 **设置 → 你的主机 → Providers → 对应 Provider → 诊断报告** 下显示的诊断相同。 ## 运行 Agent {#running-agents} diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 265b80b4bb1a..0a6d56b56326 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -460,7 +460,7 @@ interface ProviderInstallation { | Member | Called | Deadline | Answer kept | | ----------------- | ------------------------------------------------------------ | -------- | ------------------------------------------------ | -| `inspect` | When provider settings open | 20 s | 30 s | +| `inspect` | When the provider list or a provider's page shows | 20 s | 30 s | | `checkForUpdates` | After `inspect` answers `installed`, or without `inspect` | 25 s | 1 hour for `current` or `available`, else 30 s | | `update` | When the user selects **Update**, one at a time per provider | None | Paseo reads both answers again after `succeeded` | diff --git a/public-docs/supported-providers/fx.md b/public-docs/supported-providers/fx.md index e86372a4cc8d..0b9cd24b6f63 100644 --- a/public-docs/supported-providers/fx.md +++ b/public-docs/supported-providers/fx.md @@ -14,7 +14,7 @@ Run fx, the coding agent from Vercel Labs, in Paseo with your existing fx instal 1. [Install fx](https://fx.sh/docs/getting-started/installation) on your daemon host. 2. [Connect fx to a model provider](https://fx.sh/docs/getting-started/authentication), for example with `fx login`. -3. In Paseo, open **Settings → Hosts → your host → Providers**, find **fx** in the catalog, and choose **Add**. +3. In Paseo, open **Settings → Hosts → your host → Providers**, select **+ Provider**, find **fx**, and choose **Add**. Paseo launches `fx acp` and uses your fx credentials and settings. Until fx has credentials, the provider reports the sign-in message from fx. diff --git a/public-docs/supported-providers/fx.zh-CN.md b/public-docs/supported-providers/fx.zh-CN.md index d0fcc799c62e..e01edd6f2267 100644 --- a/public-docs/supported-providers/fx.zh-CN.md +++ b/public-docs/supported-providers/fx.zh-CN.md @@ -12,7 +12,7 @@ nav: fx 1. 在 daemon 主机上[安装 fx](https://fx.sh/docs/getting-started/installation)。 2. [为 fx 连接一个模型提供方](https://fx.sh/docs/getting-started/authentication),例如运行 `fx login`。 -3. 在 Paseo 中打开 **设置 → Hosts → 你的主机 → Providers**,在目录里找到 **fx** 并选择 **添加**。 +3. 在 Paseo 中打开 **设置 → Hosts → 你的主机 → Providers**,选择 **+ Provider**,找到 **fx** 并选择 **添加**。 Paseo 会启动 `fx acp`,并使用你的 fx 凭据和设置。在 fx 拿到凭据之前,该 Provider 会显示 fx 给出的登录提示。 diff --git a/public-docs/supported-providers/hoplite.md b/public-docs/supported-providers/hoplite.md index 87dd98302a79..130d591a9a0c 100644 --- a/public-docs/supported-providers/hoplite.md +++ b/public-docs/supported-providers/hoplite.md @@ -14,7 +14,7 @@ Run Hoplite's cloud coding agent in Paseo through the Hoplite CLI on your daemon 1. Install the [Hoplite CLI](https://hoplite.sh/docs/cli) on your daemon host. 2. Run `hoplite login`. -3. In Paseo, open **Settings → Hosts → your host → Providers**, find **Hoplite** in the catalog, and choose **Add**. +3. In Paseo, open **Settings → Hosts → your host → Providers**, select **+ Provider**, find **Hoplite**, and choose **Add**. Paseo launches `hoplite acp`. See [Hoplite's ACP guide](https://hoplite.sh/docs/cli/acp) for authentication and project setup. diff --git a/public-docs/supported-providers/hoplite.zh-CN.md b/public-docs/supported-providers/hoplite.zh-CN.md index 8a4627816a05..9449a1343f13 100644 --- a/public-docs/supported-providers/hoplite.zh-CN.md +++ b/public-docs/supported-providers/hoplite.zh-CN.md @@ -12,7 +12,7 @@ nav: Hoplite 1. 在 daemon 主机上安装 [Hoplite CLI](https://hoplite.sh/docs/cli)。 2. 运行 `hoplite login`。 -3. 在 Paseo 中打开 **设置 → Hosts → 你的主机 → Providers**,在目录里找到 **Hoplite** 并选择 **添加**。 +3. 在 Paseo 中打开 **设置 → Hosts → 你的主机 → Providers**,选择 **+ Provider**,找到 **Hoplite** 并选择 **添加**。 Paseo 会启动 `hoplite acp`。认证和项目设置见 [Hoplite 的 ACP 指南](https://hoplite.sh/docs/cli/acp)。 diff --git a/public-docs/supported-providers/index.md b/public-docs/supported-providers/index.md index 120836ebc389..2c52cc35ac57 100644 --- a/public-docs/supported-providers/index.md +++ b/public-docs/supported-providers/index.md @@ -29,7 +29,7 @@ Paseo ships an integration for each of these agents. Paseo runs any agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com) (ACP). The in-app catalog lists the agents below. -To add one, open **Settings → Hosts → your host → Providers**, find the agent in the catalog, and choose **Add**. Entries that launch through `npx` or `uvx` need only that tool on your daemon host. For the other entries, install the CLI of the agent first. Each entry links to its install instructions. +To add one, open **Settings → Hosts → your host → Providers**, select **+ Provider**, find the agent, and choose **Add**. Entries that launch through `npx` or `uvx` need only that tool on your daemon host. For the other entries, install the CLI of the agent first. If the CLI is missing, the page of the provider says **Not installed**, and **Install** opens its install instructions. - [Agoragentic](https://agoragentic.com), agent marketplace with 174+ AI capabilities. - [Amp](https://github.com/tao12345666333/amp-acp), frontier coding agent. diff --git a/public-docs/supported-providers/index.zh-CN.md b/public-docs/supported-providers/index.zh-CN.md index 9fecf4f30c7c..b81b815a2bcc 100644 --- a/public-docs/supported-providers/index.zh-CN.md +++ b/public-docs/supported-providers/index.zh-CN.md @@ -27,7 +27,7 @@ Paseo 为以下每个 Agent 都提供了集成。 Paseo 可以运行任何使用 [Agent Client Protocol](https://agentclientprotocol.com)(ACP)的 Agent。应用内目录列出了以下 Agent。 -要添加其中一个,请打开 **设置 → Hosts → 你的主机 → Providers**,在目录里找到该 Agent 并选择 **添加**。通过 `npx` 或 `uvx` 启动的条目只需要 daemon 主机上有该工具。其他条目请先安装该 Agent 的 CLI。每个条目都附有安装说明的链接。 +要添加其中一个,请打开 **设置 → Hosts → 你的主机 → Providers**,选择 **+ Provider**,找到该 Agent 并选择 **添加**。通过 `npx` 或 `uvx` 启动的条目只需要 daemon 主机上有该工具。其他条目请先安装该 Agent 的 CLI。如果缺少 CLI,该 provider 的页面会显示 **未安装**,**安装** 会打开它的安装说明。 - [Agoragentic](https://agoragentic.com):拥有 174 种以上 AI 能力的 Agent 市场。 - [Amp](https://github.com/tao12345666333/amp-acp):前沿的编程 Agent。 diff --git a/public-docs/troubleshooting.md b/public-docs/troubleshooting.md index 420c3363aa6e..9b4e23464cc3 100644 --- a/public-docs/troubleshooting.md +++ b/public-docs/troubleshooting.md @@ -33,7 +33,7 @@ Paseo launches the agent CLIs you've already installed, it doesn't bundle them ( ### See what Paseo sees -Open **Settings → your host → Providers**, tap the provider, then tap **Diagnostic**. The rows that matter: +Open **Settings → your host → Providers**, tap the provider, then tap **Diagnostic report**. The rows that matter: - **Resolved path** — where Paseo found the binary, or `not found`. - **Daemon PATH** — the `PATH` Paseo is searching. Compare it to `echo $PATH` in a fresh terminal. diff --git a/public-docs/troubleshooting.zh-CN.md b/public-docs/troubleshooting.zh-CN.md index 739ce464796a..0055b5369666 100644 --- a/public-docs/troubleshooting.zh-CN.md +++ b/public-docs/troubleshooting.zh-CN.md @@ -31,7 +31,7 @@ Paseo 启动的是你已经安装的 Agent CLI,它并不自带这些 CLI(参 ### 查看 Paseo 看到的内容 {#see-what-paseo-sees} -打开 **设置 → 你的主机 → Providers**,点击该 Provider,然后点击 **诊断**。重要的几行: +打开 **设置 → 你的主机 → Providers**,点击该 Provider,然后点击 **诊断报告**。重要的几行: - **Resolved path**:Paseo 找到二进制文件的位置,或 `not found`。 - **Daemon PATH**:Paseo 正在搜索的 `PATH`。把它和新终端中 `echo $PATH` 的结果进行比较。 From 93ff95b20fa17e280cda4c78c4078a176bf98072 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 19 Nov 2026 21:31:18 +0700 Subject: [PATCH 006/109] Reconcile 0.17.0 beta metadata (#10233) * docs(changelog): prepare 0.17.0 beta (cherry picked from commit fbbfcf42bcbefa2d0594e78a3373d1b3c723ac89) * chore(release): cut 0.17.0-beta.1 (cherry picked from commit 6c89950b2ef77efee47b127d09d05eb347d25f33) --- CHANGELOG.md | 52 ++++++++++++++++++++++ CHANGELOG.zh-CN.md | 52 ++++++++++++++++++++++ package-lock.json | 56 ++++++++++++------------ package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 ++-- packages/client/package.json | 6 +-- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++--- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++--- packages/website/package.json | 2 +- plugins/package.json | 2 +- 16 files changed, 159 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96e886c275bf..8b4b3dce520d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,57 @@ # Changelog +## 0.17.0-beta.1 - 2026-11-19 + +- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from any branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190)) +- **Antigravity approvals and history:** Pick a permission mode, answer tool approvals, import CLI sessions and see your history when you reopen a chat. ([#10193](https://github.com/getpaseo/paseo/pull/10193)) +- **Watch pull requests:** Agents can watch a GitHub PR and get notified when checks, reviews or comments change. ([#10148](https://github.com/getpaseo/paseo/pull/10148)) +- **Heartbeats in Background work:** See and stop an agent's heartbeats next to its background tasks. ([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216)) +- **Agent messages wait their turn:** Reports and notifications from other agents arrive when the current turn ends instead of interrupting it. ([#9757](https://github.com/getpaseo/paseo/pull/9757)) +- **Plugin agent instructions:** Plugins can add their own instructions to agents. ([#9781](https://github.com/getpaseo/paseo/pull/9781)) + +### Added + +- Added shortcuts to open the model picker and cycle thinking levels with Cmd/Ctrl+/ and Cmd/Ctrl+Shift+/ ([#10147](https://github.com/getpaseo/paseo/pull/10147)) +- Added agent settings to Command Center search before the first message ([#10182](https://github.com/getpaseo/paseo/pull/10182) by [@cleiter](https://github.com/cleiter)) +- Added Rewind to Command Center for the latest turn ([#10144](https://github.com/getpaseo/paseo/pull/10144)) +- Added a separate Ultracode toggle for eligible Claude models ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku)) +- Added Flex speed for Codex ([#9809](https://github.com/getpaseo/paseo/pull/9809) by [@qjqqyy](https://github.com/qjqqyy)) +- Added syntax highlighting for shell scripts and Dockerfiles ([#10178](https://github.com/getpaseo/paseo/pull/10178)) +- Added labels and workspace IDs to `paseo ls --json` ([#10076](https://github.com/getpaseo/paseo/pull/10076)) + +### Changed + +- Changed `browser_new_tab` to ask agents to choose a Desktop when several are connected ([#10189](https://github.com/getpaseo/paseo/pull/10189)) +- Changed workspace Git status to reuse its snapshot after a short reconnect when the checkout has not changed ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP)) +- Changed workspace navigation to acknowledge taps promptly and initially load fewer offscreen chat rows on mobile ([#9887](https://github.com/getpaseo/paseo/pull/9887)) +- Changed worktree teardown to stop after one minute by default and keep the worktree; set `worktree.teardownTimeoutMs` in `paseo.json` for longer commands ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan)) + +### Fixed + +- Fixed Collapse turns hiding a finished OMP or Pi reply when an idle provider notice appears ([#10135](https://github.com/getpaseo/paseo/pull/10135)) +- Fixed repeated finish notifications while an agent responds to background tasks and its earlier finish is unread ([#10200](https://github.com/getpaseo/paseo/pull/10200)) +- Fixed an empty chat losing the prompt and start of a reply after reconnecting mid-reply ([#9723](https://github.com/getpaseo/paseo/pull/9723) by [@ragokan](https://github.com/ragokan)) +- Fixed changes between Claude thinking levels stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin)) +- Fixed OpenCode turns staying running after a shared OpenCode service stops ([#10187](https://github.com/getpaseo/paseo/pull/10187)) +- Fixed OMP denying an approved tool call when session or grant choices were offered ([#10126](https://github.com/getpaseo/paseo/pull/10126) by [@dsingal0](https://github.com/dsingal0)) +- Fixed Changes failing to open when Git metadata watching reaches its limit ([#10188](https://github.com/getpaseo/paseo/pull/10188)) +- Fixed copying selected reply text into plain-text targets with unwanted Markdown syntax ([#10079](https://github.com/getpaseo/paseo/pull/10079) by [@danberindei](https://github.com/danberindei)) +- Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang)) +- Fixed file tabs in split panes showing or focusing the wrong file ([#9888](https://github.com/getpaseo/paseo/pull/9888) by [@KosmoCHE](https://github.com/KosmoCHE)) +- Fixed touch-screen submenus closing as soon as they open ([#10175](https://github.com/getpaseo/paseo/pull/10175) by [@christiantwu](https://github.com/christiantwu)) +- Fixed dictation failing after another chat that used the microphone closes ([#10185](https://github.com/getpaseo/paseo/pull/10185) by [@Brandon168](https://github.com/Brandon168)) +- Fixed composer taps being lost on Android after zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057)) +- Fixed clipped text on Samsung DeX ([#9995](https://github.com/getpaseo/paseo/pull/9995) by [@easyhunjune](https://github.com/easyhunjune)) +- Fixed workspace images in chat failing to load after a slow host connection ([#10111](https://github.com/getpaseo/paseo/pull/10111) by [@ragokan](https://github.com/ragokan)) +- Fixed desktop browser screenshots returning fully transparent images ([#9807](https://github.com/getpaseo/paseo/pull/9807) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) +- Fixed Mermaid flowcharts with `@` in labels showing source instead of the diagram ([#10165](https://github.com/getpaseo/paseo/pull/10165) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) +- Fixed hidden background workspaces triggering the dock badge and favicon ([#9983](https://github.com/getpaseo/paseo/pull/9983)) +- Fixed desktop sidebar navigation crowding out workspaces ([#9903](https://github.com/getpaseo/paseo/pull/9903) by [@pentatonic-alex](https://github.com/pentatonic-alex)) +- Fixed plugin agents failing to reopen after their provider closes the session ([#10153](https://github.com/getpaseo/paseo/pull/10153)) +- Fixed plugin screens and settings failing to use plugin state hooks ([#10049](https://github.com/getpaseo/paseo/pull/10049)) +- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae)) +- Fixed historical closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053)) + ## 0.16.2 - 2026-11-18 ### Fixed diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 3f3d5ff52864..4639ea80e5e5 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,5 +1,57 @@ # Changelog +## 0.17.0-beta.1 - 2026-11-19 + +- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从任意分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190)) +- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批、导入 CLI 会话,并在重新打开对话时查看历史记录。([#10193](https://github.com/getpaseo/paseo/pull/10193)) +- **监视 PR**:Agent 可以监视 GitHub PR,在检查、审查或评论有变化时收到通知。([#10148](https://github.com/getpaseo/paseo/pull/10148)) +- **在后台任务中查看 heartbeat**:在 Agent 的后台任务旁查看和停止 heartbeat。([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216)) +- **Agent 消息排队等待**:其他 Agent 的报告和通知会在当前轮次结束后到达,不会打断当前轮次。([#9757](https://github.com/getpaseo/paseo/pull/9757)) +- **插件 Agent 指令**:插件可以向 Agent 添加自己的指令。([#9781](https://github.com/getpaseo/paseo/pull/9781)) + +### 新增 + +- 新增 Cmd/Ctrl+/ 和 Cmd/Ctrl+Shift+/ 快捷键,用于打开模型选择器和切换思考级别 ([#10147](https://github.com/getpaseo/paseo/pull/10147)) +- 新增在发送第一条消息前通过命令中心搜索 Agent 设置 ([#10182](https://github.com/getpaseo/paseo/pull/10182),贡献者:[@cleiter](https://github.com/cleiter)) +- 新增在命令中心回退最近轮次的操作 ([#10144](https://github.com/getpaseo/paseo/pull/10144)) +- 新增符合条件的 Claude 模型的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku)) +- 新增 Codex Flex 速度选项 ([#9809](https://github.com/getpaseo/paseo/pull/9809),贡献者:[@qjqqyy](https://github.com/qjqqyy)) +- 新增 shell 脚本和 Dockerfile 的语法高亮 ([#10178](https://github.com/getpaseo/paseo/pull/10178)) +- 新增 `paseo ls --json` 输出的标签和工作区 ID ([#10076](https://github.com/getpaseo/paseo/pull/10076)) + +### 变更 + +- 连接多个 Desktop 时,`browser_new_tab` 会让 Agent 选择打开标签页的 Desktop ([#10189](https://github.com/getpaseo/paseo/pull/10189)) +- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP)) +- 工作区导航会立即响应点击,并在手机端初始加载时减少屏幕外的对话行数 ([#9887](https://github.com/getpaseo/paseo/pull/9887)) +- worktree 清理命令默认在一分钟后停止并保留 worktree;如需更长时间,可在 `paseo.json` 中设置 `worktree.teardownTimeoutMs` ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan)) + +### 修复 + +- 修复启用“折叠轮次”时,空闲的 Provider 通知导致已完成的 OMP 或 Pi 回复被隐藏的问题 ([#10135](https://github.com/getpaseo/paseo/pull/10135)) +- 修复 Agent 响应后台任务时,在之前的完成状态未读的情况下重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200)) +- 修复空对话在回复中途重连后丢失提示词和回复开头的问题 ([#9723](https://github.com/getpaseo/paseo/pull/9723),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复切换 Claude 思考级别时停止后台任务的问题 ([#10008](https://github.com/getpaseo/paseo/pull/10008),贡献者:[@gilad-rubin](https://github.com/gilad-rubin)) +- 修复共享 OpenCode 服务停止后轮次一直显示为运行中的问题 ([#10187](https://github.com/getpaseo/paseo/pull/10187)) +- 修复 OMP 提供会话或授权选项时拒绝已批准工具调用的问题 ([#10126](https://github.com/getpaseo/paseo/pull/10126),贡献者:[@dsingal0](https://github.com/dsingal0)) +- 修复 Git 元数据监听达到上限时无法打开“更改”的问题 ([#10188](https://github.com/getpaseo/paseo/pull/10188)) +- 修复将选中的回复复制到纯文本目标时出现多余 Markdown 语法的问题 ([#10079](https://github.com/getpaseo/paseo/pull/10079),贡献者:[@danberindei](https://github.com/danberindei)) +- 修复在预览和源码之间切换时文件视图丢失滚动位置的问题,iOS 的 HTML 预览除外 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang)) +- 修复拆分窗格中的文件标签页显示或聚焦错误文件的问题 ([#9888](https://github.com/getpaseo/paseo/pull/9888),贡献者:[@KosmoCHE](https://github.com/KosmoCHE)) +- 修复触摸屏上的子菜单打开后立即关闭的问题 ([#10175](https://github.com/getpaseo/paseo/pull/10175),贡献者:[@christiantwu](https://github.com/christiantwu)) +- 修复关闭另一个使用过麦克风的对话后无法听写的问题 ([#10185](https://github.com/getpaseo/paseo/pull/10185),贡献者:[@Brandon168](https://github.com/Brandon168)) +- 修复 Android 缩放对话图片后 Composer 点击失效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057)) +- 修复 Samsung DeX 上的文字被裁剪的问题 ([#9995](https://github.com/getpaseo/paseo/pull/9995),贡献者:[@easyhunjune](https://github.com/easyhunjune)) +- 修复主机连接缓慢后对话中的工作区图片无法加载的问题 ([#10111](https://github.com/getpaseo/paseo/pull/10111),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复桌面浏览器截图返回全透明图片的问题 ([#9807](https://github.com/getpaseo/paseo/pull/9807),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) +- 修复 Mermaid 流程图标签含有 `@` 时显示源码而非图表的问题 ([#10165](https://github.com/getpaseo/paseo/pull/10165),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) +- 修复隐藏的后台工作区触发程序坞徽标和网站图标状态的问题 ([#9983](https://github.com/getpaseo/paseo/pull/9983)) +- 修复桌面侧边栏导航占满工作区列表空间的问题 ([#9903](https://github.com/getpaseo/paseo/pull/9903),贡献者:[@pentatonic-alex](https://github.com/pentatonic-alex)) +- 修复 Provider 关闭会话后插件 Agent 无法重新打开的问题 ([#10153](https://github.com/getpaseo/paseo/pull/10153)) +- 修复插件页面和设置无法使用插件状态钩子的问题 ([#10049](https://github.com/getpaseo/paseo/pull/10049)) +- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae)) +- 修复仓库默认分支显示历史已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053)) + ## 0.16.2 - 2026-11-18 ### 修复 diff --git a/package-lock.json b/package-lock.json index 5c2949dd59ff..6429b4be0d28 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.16.2", + "version": "0.17.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.16.2", + "version": "0.17.0-beta.1", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37468,7 +37468,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.16.2", + "version": "0.17.0-beta.1", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39637,13 +39637,13 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", - "@getpaseo/server": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/server": "0.17.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -39890,11 +39890,11 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { - "@getpaseo/protocol": "0.16.2", - "@getpaseo/relay": "0.16.2", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/relay": "0.17.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -39906,7 +39906,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40149,7 +40149,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40195,7 +40195,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@codemirror/language": "6.12.4", @@ -40225,7 +40225,7 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -40233,8 +40233,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40244,8 +40244,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40267,7 +40267,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "semver": "^7.8.5", @@ -40295,7 +40295,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@noble/ciphers": "^2.4.0", @@ -40517,17 +40517,17 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.2", - "@getpaseo/highlight": "0.16.2", - "@getpaseo/plugin": "0.16.2", - "@getpaseo/protocol": "0.16.2", - "@getpaseo/relay": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/highlight": "0.17.0-beta.1", + "@getpaseo/plugin": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/relay": "0.17.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41474,7 +41474,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.16.2", + "version": "0.17.0-beta.1", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43084,7 +43084,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.16.2", + "version": "0.17.0-beta.1", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 6b50d21dc93a..c6faaeafaa7a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.16.2", + "version": "0.17.0-beta.1", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index 8729f5dbed7d..aa851fa0d0fd 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.16.2", + "version": "0.17.0-beta.1", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index bb0fd7f17738..85c32956ba72 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", - "@getpaseo/server": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/server": "0.17.0-beta.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 44489dfb4ac0..8320c37cd950 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.16.2", - "@getpaseo/relay": "0.16.2", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/relay": "0.17.0-beta.1", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 2d9e9525c042..06b1b6aac3b5 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.16.2", + "version": "0.17.0-beta.1", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 222517145a30..6c99857c2fa4 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index fbeed2b4ccf5..21be0606fcea 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.16.2", + "version": "0.17.0-beta.1", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 75585b6ec5af..d984ff933cb7 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.2", - "@getpaseo/protocol": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index ae4b866e3329..2a44a96e725f 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/relay/package.json b/packages/relay/package.json index 8aa405b669a4..7656c38b0193 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo relay for bridging daemon and client connections", "license": "Apache-2.0", "files": [ diff --git a/packages/server/package.json b/packages/server/package.json index c04e5e6902f9..15da911f626f 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.16.2", + "version": "0.17.0-beta.1", "description": "Paseo backend server", "license": "Apache-2.0", "files": [ @@ -109,11 +109,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.2", - "@getpaseo/highlight": "0.16.2", - "@getpaseo/plugin": "0.16.2", - "@getpaseo/protocol": "0.16.2", - "@getpaseo/relay": "0.16.2", + "@getpaseo/client": "0.17.0-beta.1", + "@getpaseo/highlight": "0.17.0-beta.1", + "@getpaseo/plugin": "0.17.0-beta.1", + "@getpaseo/protocol": "0.17.0-beta.1", + "@getpaseo/relay": "0.17.0-beta.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 12f032f4e86e..0f04e6b9d826 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.16.2", + "version": "0.17.0-beta.1", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index 3f7e3b59992b..da04b99d2d97 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.16.2", + "version": "0.17.0-beta.1", "private": true, "type": "module", "scripts": { From 1a45b4684074f5128721753ec73e94347ece9501 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:40:12 +0000 Subject: [PATCH 007/109] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 05a357293c92..7bb9e37d1294 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-yLTaVMgu3tc/dgngJ7RP0htJcWE0ZtQ4mouypevyv0s= +sha256-T3mbzIj0+IZBS4XA+4Ab6e6LtIi8PX4Rzs4wFEWeClk= From 95542dbfe6047ad45f9b5a10df5619278e53ac17 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 19 Nov 2026 22:10:26 +0700 Subject: [PATCH 008/109] Show the current Claude usage after switching accounts (#10236) * fix(usage): show the current Claude account after a login switch Agent usage discovery kept the old account bound to a credential store after an account switch. Refresh those discoveries and have the usage source verify account ownership when it rereads the store. * test(server): synchronize the provider update check fixture The Windows runner can finish reading the installed version before the update callback starts. Wait for the callback to start and keep it pending while verifying the independent reads. --- .../provider-installations.test.ts | 16 ++- .../plugins/usage-sources/index.test.ts | 113 +++++++++++++++++- .../src/server/plugins/usage-sources/index.ts | 76 +++++------- .../server/keychain.test.ts | 5 +- .../claude-usage-source/server/stores.test.ts | 36 ++++-- .../claude-usage-source/server/usage.test.ts | 6 +- plugins/claude-usage-source/server/usage.ts | 38 ++++-- plugins/claude-usage-source/shared/input.ts | 4 +- public-docs/plugins/reference.md | 17 +-- 9 files changed, 225 insertions(+), 86 deletions(-) diff --git a/packages/server/src/server/agent/provider-installation/provider-installations.test.ts b/packages/server/src/server/agent/provider-installation/provider-installations.test.ts index 9bf04add83c1..c1a2ad96bf84 100644 --- a/packages/server/src/server/agent/provider-installation/provider-installations.test.ts +++ b/packages/server/src/server/agent/provider-installation/provider-installations.test.ts @@ -302,27 +302,31 @@ describe("provider installation", () => { }); test("availability, discovery and the installed version never wait on an update check", async () => { - let checks = 0; + const started = Promise.withResolvers(); + const finish = Promise.withResolvers(); const manager = managerWith({ plugin: pluginProvider({ async inspect() { return { status: "installed", version: "1.0.0" }; }, - checkForUpdates() { - checks += 1; - return new Promise(() => {}); + async checkForUpdates() { + started.resolve(); + await finish.promise; + return { status: "current" }; }, }), }); + const updateCheck = manager.installations.checkForUpdates("installation-plugin"); try { - void manager.installations.checkForUpdates("installation-plugin"); + await started.promise; const entry = await manager.getProvider({ provider: "installation-plugin", wait: true }); expect(entry.status).toBe("ready"); await expect(manager.installations.inspect("installation-plugin")).resolves.toEqual({ inspection: { status: "installed", version: "1.0.0" }, }); - expect(checks).toBe(1); } finally { + finish.resolve(); + await updateCheck; manager.destroy(); } }); diff --git a/packages/server/src/server/plugins/usage-sources/index.test.ts b/packages/server/src/server/plugins/usage-sources/index.test.ts index da9d52eaeb14..7851e20184d3 100644 --- a/packages/server/src/server/plugins/usage-sources/index.test.ts +++ b/packages/server/src/server/plugins/usage-sources/index.test.ts @@ -3,12 +3,121 @@ import { UsageSourceRegistry } from "./index.js"; import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { + discover as discoverClaude, + fetchUsage as fetchClaudeUsage, +} from "../../../../../../plugins/claude-usage-source/server/usage.js"; +import { inputSchema as claudeInputSchema } from "../../../../../../plugins/claude-usage-source/shared/input.js"; import { discoverSession as discoverCursorSession, fetchUsage as fetchCursorUsage, } from "../../../../../../plugins/cursor-usage-source/server/usage.js"; import { inputSchema as cursorInputSchema } from "../../../../../../plugins/cursor-usage-source/shared/input.js"; +test("switching a shared Claude home replaces the account without borrowing its usage", async () => { + const root = await mkdtemp(join(tmpdir(), "claude-accounts-")); + try { + const defaultHome = join(root, "default"); + const otherHome = join(root, "other"); + await Promise.all([mkdir(defaultHome), mkdir(otherHome)]); + const login = (home: string, token: string) => + writeFile( + join(home, ".credentials.json"), + JSON.stringify({ claudeAiOauth: { accessToken: token } }), + ); + await login(defaultHome, "old"); + + const sessions = new Map([ + [ + "default", + { + sessionKey: "first", + provider: "claude", + env: { HOME: root, CLAUDE_CONFIG_DIR: defaultHome }, + }, + ], + ]); + const registry = new UsageSourceRegistry(Date.now, 300_000, undefined, { + hasAgent: (id) => sessions.has(id), + usageSession: (id) => sessions.get(id) ?? null, + }); + const usageTokens: string[] = []; + const fetchApi: typeof fetch = async (url, init) => { + const token = new Headers(init?.headers).get("Authorization")?.split(" ")[1]; + if (!token) throw new Error("Missing fixture token"); + const account = token === "rotated" ? "old" : token; + if (String(url).endsWith("/profile")) { + return Response.json({ + account: { uuid: account, email: account + "@example.com" }, + organization: { uuid: "org" }, + }); + } + usageTokens.push(token); + return Response.json({ five_hour: { utilization: account === "old" ? 100 : 17 } }); + }; + registry.register({ + id: "claude", + label: "Claude", + discover: (scope) => + discoverClaude( + scope, + { + home: root, + env: { CLAUDE_CONFIG_DIR: defaultHome }, + platform: "linux", + }, + fetchApi, + ), + fetch: (input) => fetchClaudeUsage(claudeInputSchema.parse(input), fetchApi), + }); + const usage = (reports: Awaited>) => + Object.fromEntries( + reports.map((entry) => [entry.account.label, entry.report.windows?.[0]?.usedPct]), + ); + + expect(usage(await registry.listReports({ agentId: "default" }))).toEqual({ + "old@example.com": 100, + }); + await login(defaultHome, "rotated"); + expect( + usage(await registry.listReports({ reportIds: ["claude:old.org"], forceRefresh: true })), + ).toEqual({ "old@example.com": 100 }); + expect(usageTokens).toContain("rotated"); + await login(defaultHome, "new"); + usageTokens.length = 0; + const [stale] = await registry.listReports({ + reportIds: ["claude:old.org"], + forceRefresh: true, + }); + expect.soft(stale?.report).toEqual({ + status: "error", + error: "This Claude login now belongs to a different account. Refresh the usage list.", + }); + expect.soft(stale?.lastSuccessful?.report.windows[0]?.usedPct).toBe(100); + expect.soft(usageTokens).toEqual([]); + + const host = await registry.listReports({ forceRefresh: true }); + expect.soft(usage(host)).toEqual({ "new@example.com": 17 }); + expect + .soft(usage(await registry.listReports({ agentId: "default" }))) + .toEqual({ "new@example.com": 17 }); + + await login(otherHome, "old"); + sessions.set("other", { + sessionKey: "second", + provider: "claude", + env: { HOME: root, CLAUDE_CONFIG_DIR: otherHome }, + }); + await registry.listReports({ agentId: "other" }); + expect(usage(await registry.listReports({ forceRefresh: true }))).toEqual({ + "new@example.com": 17, + "old@example.com": 100, + }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("#7142: host usage retains distinct Cursor accounts after their individual details are read", async () => { const root = await mkdtemp(join(tmpdir(), "cursor-accounts-")); try { @@ -373,7 +482,7 @@ test("failed fallbacks preserve the final problem", async () => { }); }); -test("session discovery reuses accounts, separates launches, and retains live agent reports globally", async () => { +test("session discovery rechecks logins, reuses cached usage, and includes live agent reports globally", async () => { const sessions = new Map([ ["one", { provider: "claude", env: { HOME: "/one" }, sessionKey: "launch-1" }], ["two", { provider: "claude", env: { HOME: "/two" }, sessionKey: "launch-2" }], @@ -404,7 +513,7 @@ test("session discovery reuses accounts, separates launches, and retains live ag ]); await registry.listReports({ agentId: "one" }); await registry.listReports({ agentId: "two" }); - expect(discoveries).toEqual(["/one", "/two"]); + expect(discoveries).toEqual(["/one", "/one", "/two"]); expect(fetches).toBe(2); expect((await registry.listReports()).map((r) => r.id)).toEqual([ "claude:default", diff --git a/packages/server/src/server/plugins/usage-sources/index.ts b/packages/server/src/server/plugins/usage-sources/index.ts index e9e2e9c8afd3..3a6837271766 100644 --- a/packages/server/src/server/plugins/usage-sources/index.ts +++ b/packages/server/src/server/plugins/usage-sources/index.ts @@ -42,19 +42,12 @@ export interface ListUsageReportsOptions { onReport?: (report: UsageReportEntry) => void; } -interface AgentReports { - provider: string; - model?: string; - sessionKey: string; - reports: Map; -} - -/** Owns account identity, ordered logins for each account, and the five-minute fetch cache. */ +/** Groups discovered logins by account and caches their usage for five minutes. */ export class UsageSourceRegistry { private readonly sources = new Map(); private readonly known = new Map(); private defaults = new Map(); - private readonly byAgent = new Map(); + private readonly byAgent = new Map>(); private readonly cache = new Map(); private readonly successful = new Map>(); private readonly pending = new Map>(); @@ -75,10 +68,8 @@ export class UsageSourceRegistry { unregister(id: string): void { this.sources.delete(id); for (const key of this.defaults.keys()) if (key.startsWith(`${id}:`)) this.defaults.delete(key); - // Re-discover on the next session query when a source is replaced. - for (const [agentId, mapping] of this.byAgent) { - if ([...mapping.reports.values()].some((report) => report.source.id === id)) - this.byAgent.delete(agentId); + for (const reports of this.byAgent.values()) { + for (const key of reports.keys()) if (key.startsWith(`${id}:`)) reports.delete(key); } for (const key of this.known.keys()) if (key.startsWith(`${id}:`)) this.known.delete(key); for (const key of this.cache.keys()) if (key.startsWith(`${id}:`)) this.cache.delete(key); @@ -94,12 +85,19 @@ export class UsageSourceRegistry { let ids: string[]; let reports = this.known; if (options.agentId !== undefined) { - ids = await this.discoverAgent(options.agentId); - reports = this.byAgent.get(options.agentId)?.reports ?? new Map(); + if (!this.agents.hasAgent(options.agentId)) + throw new Error(`Unknown agent: ${options.agentId}`); + reports = await this.discoverAgent(options.agentId); + this.mergeKnown(); + ids = [...reports.keys()]; } else if (options.reportIds !== undefined) { ids = options.reportIds; } else { - this.defaults = await this.discover({ kind: "global" }, this.defaults); + const [defaults] = await Promise.all([ + this.discover({ kind: "global" }, this.defaults), + ...[...this.byAgent.keys()].map((agentId) => this.discoverAgent(agentId)), + ]); + this.defaults = defaults; this.mergeKnown(); ids = [...this.known.keys()]; } @@ -124,44 +122,36 @@ export class UsageSourceRegistry { this.mergeKnown(); } - private async discoverAgent(agentId: string): Promise { - if (!this.agents.hasAgent(agentId)) throw new Error(`Unknown agent: ${agentId}`); + private async discoverAgent(agentId: string): Promise> { const session = this.agents.usageSession(agentId); if (!session) { this.byAgent.delete(agentId); - this.mergeKnown(); - return []; + return new Map(); } const previous = this.byAgent.get(agentId); - const sameScope = - previous?.sessionKey === session.sessionKey && - previous.provider === session.provider && - previous.model === session.model; - if (sameScope) return [...previous.reports.keys()]; const reports = await this.discover({ kind: "session", provider: session.provider, model: session.model, env: session.env, }); - // A query that finishes after a resume must not publish the previous launch's mapping. - if (this.agents.usageSession(agentId)?.sessionKey !== session.sessionKey) return []; - this.byAgent.set(agentId, { - sessionKey: session.sessionKey, - provider: session.provider, - model: session.model, - reports, - }); - this.mergeKnown(); - return [...reports.keys()]; + const current = this.agents.usageSession(agentId); + if ( + current?.sessionKey !== session.sessionKey || + current.provider !== session.provider || + current.model !== session.model + ) { + if (this.byAgent.get(agentId) === previous) this.byAgent.delete(agentId); + return new Map(); + } + + this.byAgent.set(agentId, reports); + return reports; } private mergeKnown(): void { this.known.clear(); - for (const reports of [ - this.defaults, - ...[...this.byAgent.values()].map((agent) => agent.reports), - ]) { + for (const reports of [this.defaults, ...this.byAgent.values()]) { for (const [id, report] of reports) { if (this.sources.get(report.source.id) !== report.source) continue; const known = this.known.get(id); @@ -183,11 +173,9 @@ export class UsageSourceRegistry { private activeCacheKeys(): Set { return new Set( - [ - this.known, - this.defaults, - ...[...this.byAgent.values()].map((agent) => agent.reports), - ].flatMap((reports) => [...reports].map(([id, report]) => cacheIdentity(id, report))), + [this.known, this.defaults, ...this.byAgent.values()].flatMap((reports) => + [...reports].map(([id, report]) => cacheIdentity(id, report)), + ), ); } diff --git a/plugins/claude-usage-source/server/keychain.test.ts b/plugins/claude-usage-source/server/keychain.test.ts index dd6c58f77a5f..10ba07a67c2d 100644 --- a/plugins/claude-usage-source/server/keychain.test.ts +++ b/plugins/claude-usage-source/server/keychain.test.ts @@ -142,7 +142,10 @@ describe("Claude credential routes", () => { { key: "fixture-account.fixture-org", harness: "Claude", - input: { route: { store: "claude", path: join(dir, ".credentials.json") } }, + input: { + route: { store: "claude", path: join(dir, ".credentials.json") }, + accountKey: "fixture-account.fixture-org", + }, }, ]); expect( diff --git a/plugins/claude-usage-source/server/stores.test.ts b/plugins/claude-usage-source/server/stores.test.ts index 093fbf114f80..4462889f4a12 100644 --- a/plugins/claude-usage-source/server/stores.test.ts +++ b/plugins/claude-usage-source/server/stores.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { afterEach, beforeEach, expect, test } from "vitest"; +import { inputSchema } from "../shared/input.js"; import { discover, fetchUsage } from "./usage.js"; let home: string; @@ -32,14 +33,15 @@ async function accountIdentity( ) { const accounts = await discover({ kind: "global" }, lookup(env), profile); const account = accounts.find( - (candidate) => JSON.stringify(candidate.input) === JSON.stringify(input), + (candidate) => + JSON.stringify(inputSchema.parse(candidate.input).route) === JSON.stringify(input.route), ); if (!account) throw new Error("Expected discovered login"); return { key: account.key, ...(account.label ? { label: account.label } : {}) }; } async function logins(options: Parameters[1]) { - return (await discover({ kind: "global" }, options, profile)).map( - (account) => account.input as Parameters[0], + return (await discover({ kind: "global" }, options, profile)).map((account) => + inputSchema.parse(account.input), ); } async function database(path: string) { @@ -103,8 +105,9 @@ test("Pi uses its own OAuth identity and re-reads rotated tokens without writing ( await fetchUsage( inputs[0]!, - async (_url, init) => { + async (url, init) => { expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer fixture-rotated"); + if (String(url).endsWith("/profile")) return profile(url, init); return new Response("{}", { status: 401 }); }, lookup(), @@ -119,7 +122,9 @@ test("Pi honors directory override and ignores API keys and malformed files", as const env = { PI_CODING_AGENT_DIR: directory }; const path = join(directory, "auth.json"); await json(path, { anthropic: { type: "oauth", access: "fixture-pi", accountId: "pi-account" } }); - expect(await logins(lookup(env))).toEqual([{ route: { store: "pi", path } }]); + expect(await logins(lookup(env))).toEqual([ + { route: { store: "pi", path }, accountKey: "pi-account.pi-org" }, + ]); await json(path, { anthropic: { type: "api_key", key: "fixture-key" } }); expect(await logins(lookup(env))).toEqual([]); await writeFile(path, "broken"); @@ -169,7 +174,7 @@ for (const location of ["default", "profile", "xdg", "override", "config"]) { const before = await readFile(path); const inputs = await logins(lookup(env)); expect(inputs).toEqual([ - { route: { store: "omp", path, credentialId: 1 } }, + { route: { store: "omp", path, credentialId: 1 }, accountKey: "pi-account.pi-org" }, { route: { store: "omp", path, credentialId: 2 } }, ]); expect(await accountIdentity(inputs[0]!, env)).toEqual({ key: "pi-account.pi-org" }); @@ -196,7 +201,10 @@ test("missing SQLite skips only OMP", async () => { }); const inputs = await logins({ ...lookup(), sqlite: () => undefined }); expect(inputs).toEqual([ - { route: { store: "pi", path: join(home, ".pi", "agent", "auth.json") } }, + { + route: { store: "pi", path: join(home, ".pi", "agent", "auth.json") }, + accountKey: "pi-account.pi-org", + }, ]); }); @@ -211,7 +219,10 @@ test("Claude Keychain login replaces the fallback file", async () => { readKeychainCredentials: async () => ({ claudeAiOauth: { accessToken: "fixture-keychain" } }), }); expect(inputs).toEqual([ - { route: { store: "keychain", service: "Claude Code-credentials", account: "fixture-user" } }, + { + route: { store: "keychain", service: "Claude Code-credentials", account: "fixture-user" }, + accountKey: "pi-account.pi-org", + }, ]); }); @@ -243,6 +254,7 @@ test("keychain identity belongs to its token even when Claude Code metadata name harness: "Claude", input: { route: { store: "keychain", service: "Claude Code-credentials", account: "fixture-user" }, + accountKey: "pi-account.pi-org", }, }); }); @@ -259,10 +271,11 @@ test("OMP fetch re-reads its row after rotation and skips a newly disabled login ( await fetchUsage( input!, - async (_url, init) => { + async (url, init) => { expect(new Headers(init?.headers).get("Authorization")).toBe( "Bearer fixture-rotated-omp", ); + if (String(url).endsWith("/profile")) return profile(url, init); return new Response("{}", { status: 401 }); }, lookup(), @@ -295,6 +308,9 @@ test("Claude discovery honors CLAUDE_CONFIG_DIR", async () => { lookup({ CLAUDE_CONFIG_DIR: directory, CLAUDE_HOME: ignoredDirectory }), ); expect(inputs).toEqual([ - { route: { store: "claude", path: join(directory, ".credentials.json") } }, + { + route: { store: "claude", path: join(directory, ".credentials.json") }, + accountKey: "pi-account.pi-org", + }, ]); }); diff --git a/plugins/claude-usage-source/server/usage.test.ts b/plugins/claude-usage-source/server/usage.test.ts index 29e78a54e993..d38266c42cfb 100644 --- a/plugins/claude-usage-source/server/usage.test.ts +++ b/plugins/claude-usage-source/server/usage.test.ts @@ -938,7 +938,9 @@ async function accountFor( lookup: Parameters[0] = {}, ) { const accounts = await discover({ kind: "global" }, { ...lookup, now }, fetchApi); - const account = accounts.find((candidate) => isDeepStrictEqual(candidate.input, input)); + const account = accounts.find((candidate) => + isDeepStrictEqual(inputSchema.parse(candidate.input).route, input.route), + ); if (!account) throw new Error("Expected discovered login"); return { key: account.key, ...(account.label ? { label: account.label } : {}) }; } @@ -1082,7 +1084,7 @@ it("session discovery reads only its Claude home and excludes foreign sessions", key: "session-account.org", label: "session@example.test", harness: "Claude", - input: credentialInput(home), + input: { ...credentialInput(home), accountKey: "session-account.org" }, }, ]); await discover(scope, lookup, api); diff --git a/plugins/claude-usage-source/server/usage.ts b/plugins/claude-usage-source/server/usage.ts index 9efade206260..e1a91ec41102 100644 --- a/plugins/claude-usage-source/server/usage.ts +++ b/plugins/claude-usage-source/server/usage.ts @@ -394,7 +394,11 @@ export async function discover( fetchApi, lookup.now ?? Date.now, ); - accounts.push("status" in profile ? fallback : { ...profile, harness, input }); + accounts.push( + "status" in profile + ? fallback + : { ...profile, harness, input: { ...input, accountKey: profile.key } }, + ); } catch { // Keep the login visible; fetching usage reports the vendor failure. accounts.push(fallback); @@ -567,16 +571,14 @@ export async function fetchUsage( expiresAt: new Date(credentials.expires).toISOString(), refreshedBy, }); - const profile = await cachedProfile( - credentials.oauth.accessToken, - (credentialLookup.now ?? Date.now)(), - ); - if (profile && "status" in profile) - return unavailable({ kind: "rejected", status: profile.status, refreshedBy }); - const { oauth } = credentials; + const now = credentialLookup.now ?? Date.now; + const rejected = await verifyLoginAccount(oauth.accessToken, input.accountKey, fetchApi, now); + if (rejected !== undefined) + return unavailable({ kind: "rejected", status: rejected, refreshedBy }); + const plan = buildClaudePlan(oauth.subscriptionType, oauth.rateLimitTier); - const resp = await callClaudeApi(oauth.accessToken, (credentialLookup.now ?? Date.now)()); + const resp = await callClaudeApi(oauth.accessToken, now()); if (typeof resp === "number") return unavailable({ kind: "rejected", status: resp, refreshedBy }); @@ -640,9 +642,21 @@ const PROFILE_TTL_MS = 300_000; const PROFILE_CACHE_LIMIT = 128; const profileCache = new Map }>(); -function cachedProfile(token: string, now: number): Promise | undefined { - pruneProfileCache(now); - return profileCache.get(hashAccountKey(token))?.result; +async function verifyLoginAccount( + token: string, + accountKey: string | undefined, + fetchApi: typeof fetch, + now: () => number, +): Promise { + pruneProfileCache(now()); + const profile = accountKey + ? await readProfile(token, fetchApi, now) + : await profileCache.get(hashAccountKey(token))?.result; + if (profile && "status" in profile) return profile.status; + if (accountKey && profile?.key !== accountKey) + throw new Error( + "This Claude login now belongs to a different account. Refresh the usage list.", + ); } function pruneProfileCache(now: number): void { diff --git a/plugins/claude-usage-source/shared/input.ts b/plugins/claude-usage-source/shared/input.ts index b82c69cfde6a..207b164828e6 100644 --- a/plugins/claude-usage-source/shared/input.ts +++ b/plugins/claude-usage-source/shared/input.ts @@ -17,5 +17,7 @@ export const routeSchema = z.discriminatedUnion("store", [ }) .strict(), ]); -export const inputSchema = z.object({ route: routeSchema }).strict(); +export const inputSchema = z + .object({ route: routeSchema, accountKey: z.string().min(1).optional() }) + .strict(); export type UsageInput = z.infer; diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 0a6d56b56326..ef50640c3e2e 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -609,10 +609,10 @@ window IDs across all accounts, so users must select the corrected window again. effective selection for cards, the sidebar, and toggles. The first edit snapshots those defaults; an explicit empty selection stays empty. -Re-read the selected store in `fetch()` so the CLI's token rotations take effect. Never redeem -refresh tokens or write credential stores: refreshing elsewhere can invalidate the CLI's copy, -and rewriting parsed files can discard fields you do not model. If the store disappeared after -discovery, throw; the card shows the error until the next discovery removes it. +Re-read the selected store in `fetch()` so the CLI's token rotations take effect. If you discover +a specific account, pass its identity in the input and verify it before returning usage. +Throw if the store disappears or the login changes accounts. The next discovery updates the card. +Only the CLI should redeem its refresh tokens or write its credential stores. Use `unavailable(problem)` to explain why an existing login cannot supply quota. It requires a problem; there is no zero-argument form. `expiresAt` is an ISO timestamp. A rejected login carries @@ -662,10 +662,11 @@ hash. Codex prefers Codex CLI, OpenCode, Pi, then OMP and groups by the ChatGPT metadata or JWT claims. Pi and OMP logins remain discoverable when expired. OMP requires `node:sqlite`. -`usage.list_reports` discovers accounts when called without IDs. With IDs, it refreshes known -accounts without rediscovering identity. If a store switches accounts, the existing card shows the -new login's quota until the next discovery. Reports are cached for five minutes; `forceRefresh` -bypasses that cache. Entries carry `id`, `account.label`, and `fetchedAt`. Failed accounts also carry optional +`usage.list_reports` discovers accounts for the requested agent. A host-wide request discovers +the defaults and revisits the agents whose usage Paseo has already queried. A request with report +IDs fetches known reports using their existing discovery inputs. Reports are cached for five minutes. +Set `forceRefresh` to bypass that cache. Entries carry `id`, `account.label`, and `fetchedAt`. +Failed accounts also carry optional `loginErrors` entries with `harness` and each login's failed `report`. Clients gate the feature on `server_info.features.usageSources`. The older `provider.usage.list` RPC maps the same reports for 0.10 clients and renders problems into its `error` string. From a0ed629b7d2f21ca4e26908e4696b50f1f28bef8 Mon Sep 17 00:00:00 2001 From: Pedro Vieira Date: Fri, 20 Nov 2026 02:46:13 +0000 Subject: [PATCH 009/109] fix(app): word and line selection in diff views (#10252) Use the native mouse click count to select words and source lines in canvas diffs. Extend the selection by whole words or lines while dragging. Closes #10116. --- packages/app/e2e/browser/changes-pane.spec.ts | 259 +++++++++++++++++- .../src/git/diff-document/hit-testing.test.ts | 44 +++ .../app/src/git/diff-document/hit-testing.ts | 49 +++- .../git/diff-document/pointer-gesture.test.ts | 131 ++++++++- .../src/git/diff-document/pointer-gesture.ts | 41 +++ .../app/src/git/diff-document/surface.web.tsx | 148 ++++++++-- packages/app/src/git/diff-document/types.ts | 2 + .../git/diff-document/word-boundaries.test.ts | 70 +++++ .../src/git/diff-document/word-boundaries.ts | 88 ++++++ 9 files changed, 789 insertions(+), 43 deletions(-) create mode 100644 packages/app/src/git/diff-document/word-boundaries.test.ts create mode 100644 packages/app/src/git/diff-document/word-boundaries.ts diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index 3ce36b15e4c8..79ae55092ad5 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -1598,6 +1598,237 @@ test("canvas diff replaces a selection with forward and backward drags", async ( } }); +test("canvas diff double-click selects the grapheme under the pointer, not the nearest caret", async ({ + context, + page, +}) => { + const content = "call(foo bar)"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + fraction: 0.75, + start: { line: 0, offset: 3 }, + end: { line: 0, offset: 3 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "call"); + + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + fraction: 0.1, + start: { line: 0, offset: 4 }, + end: { line: 0, offset: 4 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "("); +}); + +test("canvas diff double-click selects the clicked word and replaces an existing selection", async ({ + context, + page, +}) => { + const content = "alpha bravo charlie delta"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 4 }, + }); + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + start: { line: 0, offset: 8 }, + end: { line: 0, offset: 8 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "bravo"); +}); + +test("canvas diff double-click drag extends the selection word by word in both directions", async ({ + context, + page, +}) => { + const content = "alpha bravo charlie delta"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end, expectedText] of [ + [{ line: 0, offset: 8 }, { line: 0, offset: 14 }, "bravo charlie"], + [{ line: 0, offset: 14 }, { line: 0, offset: 2 }, "alpha bravo charlie"], + ] as const) { + await dragAddedTextRange(page, { lines: [content], clickCount: 2, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, expectedText); + } +}); + +test("canvas diff double-click drag extends word by word across lines and wrapped lines", async ({ + context, + page, +}) => { + const lines = ["alpha bravo", "charlie delta"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end, expectedText] of [ + [{ line: 0, offset: 8 }, { line: 1, offset: 10 }, "bravo\ncharlie delta"], + [{ line: 1, offset: 10 }, { line: 0, offset: 2 }, "alpha bravo\ncharlie delta"], + ] as const) { + await dragAddedTextRange(page, { lines, clickCount: 2, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, expectedText); + } + + const wrapped = `${"alpha ".repeat(40)}bravo charlie`; + const wrappedWorkspace = await createWorkspaceWithExactSelectionDiff(wrapped); + await configureDiffPresentation(page, { layout: "unified", wrapLines: true }); + await openSelectionWorkspaceChanges(page, wrappedWorkspace); + await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true }); + const bravoStart = 40 * "alpha ".length; + await dragAddedTextRange(page, { + lines: [wrapped], + wrapped: true, + clickCount: 2, + start: { line: 0, offset: bravoStart + 2 }, + end: { line: 0, offset: bravoStart + 9 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "bravo charlie"); +}); + +test("canvas diff double-click drag keeps word selection on the split side", async ({ + context, + page, +}) => { + const lines = ["RIGHT-ONE", "RIGHT-TWO"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "split", wrapLines: false }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "split", wrapLines: false }); + + await dragAddedTextRange(page, { + lines, + side: "right", + clickCount: 2, + start: { line: 0, offset: 7 }, + end: { line: 1, offset: 3 }, + }); + await page.keyboard.press("ControlOrMeta+C"); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ONE\nRIGHT"); +}); + +test("canvas diff triple-click selects the whole source line and replaces an existing selection", async ({ + context, + page, +}) => { + const content = "alpha bravo"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 3 }, + }); + await dragAddedTextRange(page, { + lines: [content], + clickCount: 3, + start: { line: 0, offset: 8 }, + end: { line: 0, offset: 8 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, content); +}); + +test("canvas diff triple-click drag extends whole source lines in both directions", async ({ + context, + page, +}) => { + const lines = ["alpha", "bravo", "charlie"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end] of [ + [ + { line: 0, offset: 2 }, + { line: 2, offset: 3 }, + ], + [ + { line: 2, offset: 3 }, + { line: 0, offset: 1 }, + ], + ] as const) { + await dragAddedTextRange(page, { lines, clickCount: 3, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "alpha\nbravo\ncharlie"); + } +}); + +test("canvas diff triple-click selects every wrapped fragment of a source line", async ({ + context, + page, +}) => { + const content = `${"alpha ".repeat(80)}omega`; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "unified", wrapLines: true }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true }); + + await dragAddedTextRange(page, { + lines: [content], + wrapped: true, + clickCount: 3, + start: { line: 0, offset: 20 }, + end: { line: 0, offset: 20 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, content); +}); + +test("canvas diff triple-click drag keeps whole source lines on the split side", async ({ + context, + page, +}) => { + const lines = ["RIGHT-ONE", "RIGHT-TWO"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "split", wrapLines: false }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "split", wrapLines: false }); + + await dragAddedTextRange(page, { + lines, + side: "right", + clickCount: 3, + start: { line: 1, offset: 3 }, + end: { line: 0, offset: 4 }, + }); + await page.keyboard.press("ControlOrMeta+C"); + await expect + .poll(() => page.evaluate(() => navigator.clipboard.readText())) + .toBe("RIGHT-ONE\nRIGHT-TWO"); +}); + test("canvas diff copies only the selected split side", async ({ context, page }) => { const lines = ["RIGHT-ONE", "RIGHT-TWO"]; const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); @@ -2482,6 +2713,8 @@ async function dragAddedTextRange( side?: "left" | "right"; wrapped?: boolean; horizontalOffset?: number; + clickCount?: 1 | 2 | 3; + fraction?: number; }, ): Promise { const body = page.getByTestId("diff-file-0-body"); @@ -2520,14 +2753,38 @@ async function dragAddedTextRange( columnLeft + gutterWidth + 8 + - localOffset * metrics.characterWidth - + (localOffset + (input.fraction ?? 0)) * metrics.characterWidth - (input.horizontalOffset ?? 0), y: bounds.y + (1 + fragmentsBefore(line) + fragment + 0.5) * lineHeight, }; }; const start = point(input.start); const end = point(input.end); + const clickCount = input.clickCount ?? 1; await page.mouse.move(start.x, start.y); + if (clickCount > 1) { + const isSinglePoint = + input.start.line === input.end.line && input.start.offset === input.end.offset; + if (isSinglePoint && clickCount === 2) { + await page.mouse.dblclick(start.x, start.y); + return; + } + if (isSinglePoint) { + for (let count = 1; count <= clickCount; count += 1) { + await page.mouse.down({ clickCount: count }); + await page.mouse.up({ clickCount: count }); + } + return; + } + for (let count = 1; count < clickCount; count += 1) { + await page.mouse.down({ clickCount: count }); + await page.mouse.up({ clickCount: count }); + } + await page.mouse.down({ clickCount }); + await page.mouse.move(end.x, end.y, { steps: 12 }); + await page.mouse.up({ clickCount }); + return; + } await page.mouse.down(); await page.mouse.move(end.x, end.y, { steps: 12 }); await page.mouse.up(); diff --git a/packages/app/src/git/diff-document/hit-testing.test.ts b/packages/app/src/git/diff-document/hit-testing.test.ts index d728c2f2d71d..a1a59ad3f81c 100644 --- a/packages/app/src/git/diff-document/hit-testing.test.ts +++ b/packages/app/src/git/diff-document/hit-testing.test.ts @@ -2,6 +2,7 @@ import type { ParsedDiffFile } from "@getpaseo/protocol/messages"; import { describe, expect, it } from "vitest"; import { characterOffsetAtPoint, + graphemeOffsetAtPoint, hitTestDiffDocument, orderedSelection, selectAllSource, @@ -43,6 +44,49 @@ describe("diff hit testing", () => { ).toBe(combining?.end); }); + it("keeps the nearest caret for character drags but hits the grapheme under word gestures", () => { + const cell = changedCell(buildModel("call(foo)", { wrapLines: false, viewportWidth: 300 })); + const graphemes = cell.fragments[0]!.graphemes; + const lastOfWord = graphemes[3]!; + const punctuation = graphemes[4]!; + const beforeLastOfWord = graphemes + .slice(0, 3) + .reduce((width, grapheme) => width + grapheme.width, 0); + const rightHalfOfWord = beforeLastOfWord + lastOfWord.width * 0.75; + const leftHalfOfPunctuation = beforeLastOfWord + lastOfWord.width + punctuation.width * 0.1; + + expect(characterOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe( + lastOfWord.start, + ); + expect(characterOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + expect(graphemeOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + }); + + it("keeps wrapped fragment boundaries from stealing the grapheme under the pointer", () => { + const cell = changedCell(buildModel("abcdef", { viewportWidth: 90 })); + const firstFragment = cell.fragments[0]!; + expect(cell.fragments.length).toBeGreaterThan(1); + const lastGrapheme = firstFragment.graphemes.at(-1)!; + const beforeLastGrapheme = firstFragment.graphemes + .slice(0, -1) + .reduce((width, grapheme) => width + grapheme.width, 0); + const rightHalfOfLastGrapheme = beforeLastGrapheme + lastGrapheme.width * 0.75; + + expect(characterOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe( + firstFragment.end, + ); + expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe( + lastGrapheme.start, + ); + }); + it("normalizes backwards selection and copies exact source including empty lines", () => { const model = buildModel("", { wrapLines: false }); const cell = changedCell(model); diff --git a/packages/app/src/git/diff-document/hit-testing.ts b/packages/app/src/git/diff-document/hit-testing.ts index ed0519e281cc..1dba723f656d 100644 --- a/packages/app/src/git/diff-document/hit-testing.ts +++ b/packages/app/src/git/diff-document/hit-testing.ts @@ -3,6 +3,7 @@ import type { DiffCell, DiffCharacterPosition, DiffDocumentModel, + DiffFragment, DiffHit, DiffSelection, } from "./types"; @@ -33,12 +34,7 @@ export function hitTestDiffDocument(input: { localX - file.gutterWidth - CODE_LEFT_PADDING + input.horizontalOffset, ); const textY = input.documentY - row.top; - const sourceOffset = characterOffsetAtPoint({ - cell, - x: contentX, - y: textY, - lineHeight: input.model.lineHeight, - }); + const point = { cell, x: contentX, y: textY, lineHeight: input.model.lineHeight }; return { kind: "cell", target: cell.reviewTarget, @@ -47,8 +43,9 @@ export function hitTestDiffDocument(input: { rowIndex: row.index, cellIndex, side: cell.reviewTarget?.side ?? (cellIndex === 0 ? "old" : "new"), - sourceOffset, + sourceOffset: characterOffsetAtPoint(point), }, + graphemeOffset: graphemeOffsetAtPoint(point), }; } @@ -58,11 +55,7 @@ export function characterOffsetAtPoint(input: { y: number; lineHeight: number; }): number { - const fragmentIndex = Math.min( - input.cell.fragments.length - 1, - Math.max(0, Math.floor(input.y / input.lineHeight)), - ); - const fragment = input.cell.fragments[fragmentIndex]; + const fragment = fragmentAtPoint(input); if (!fragment) return 0; let width = 0; for (const grapheme of fragment.graphemes) { @@ -72,6 +65,36 @@ export function characterOffsetAtPoint(input: { return fragment.end; } +/** The grapheme under the pointer, unlike `characterOffsetAtPoint`, which snaps to the nearest caret. */ +export function graphemeOffsetAtPoint(input: { + cell: DiffCell; + x: number; + y: number; + lineHeight: number; +}): number { + const fragment = fragmentAtPoint(input); + if (!fragment) return 0; + let width = 0; + for (const grapheme of fragment.graphemes) { + if (input.x < width + grapheme.width) return grapheme.start; + width += grapheme.width; + } + const lastGrapheme = fragment.graphemes.at(-1); + return lastGrapheme ? lastGrapheme.start : fragment.start; +} + +function fragmentAtPoint(input: { + cell: DiffCell; + y: number; + lineHeight: number; +}): DiffFragment | null { + const fragmentIndex = Math.min( + input.cell.fragments.length - 1, + Math.max(0, Math.floor(input.y / input.lineHeight)), + ); + return input.cell.fragments[fragmentIndex] ?? null; +} + function rowAtOffset( rows: readonly DiffDocumentModel["rows"][number][], start: number, @@ -163,7 +186,7 @@ export function selectAllSource( return first && last ? { anchor: first, focus: last } : null; } -function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number { +export function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number { return ( left.rowIndex - right.rowIndex || left.cellIndex - right.cellIndex || diff --git a/packages/app/src/git/diff-document/pointer-gesture.test.ts b/packages/app/src/git/diff-document/pointer-gesture.test.ts index 498712939d95..4577dd8dd02a 100644 --- a/packages/app/src/git/diff-document/pointer-gesture.test.ts +++ b/packages/app/src/git/diff-document/pointer-gesture.test.ts @@ -1,5 +1,38 @@ import { describe, expect, it } from "vitest"; -import { hasPointerDragStarted } from "./pointer-gesture"; +import { + hasPointerDragStarted, + lineSelectionForDrag, + wordSelectionForDrag, + type LineAtPosition, + type WordAtPosition, +} from "./pointer-gesture"; +import type { DiffCharacterPosition } from "./types"; + +function positionAt(offset: number, rowIndex = 1, cellIndex = 0): DiffCharacterPosition { + return { fileIndex: 0, rowIndex, cellIndex, side: "new", sourceOffset: offset }; +} + +function wordAt( + input: { offset: number; start: number; end: number }, + rowIndex = 1, + cellIndex = 0, +): WordAtPosition { + return { + position: positionAt(input.offset, rowIndex, cellIndex), + word: { start: input.start, end: input.end }, + }; +} + +function lineAt( + input: { offset: number; end: number }, + rowIndex = 1, + cellIndex = 0, +): LineAtPosition { + return { + position: positionAt(input.offset, rowIndex, cellIndex), + end: input.end, + }; +} describe("diff pointer gesture", () => { it("classifies pointer movement as a drag without requiring a character change", () => { @@ -26,3 +59,99 @@ describe("diff pointer gesture", () => { ).toBe(true); }); }); + +describe("diff word drag selection", () => { + it("extends forward from the start of the anchor word to the end of the focus word", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 8, start: 6, end: 11 }), + focus: wordAt({ offset: 14, start: 12, end: 19 }), + }), + ).toEqual({ + anchor: positionAt(6), + focus: positionAt(19), + }); + }); + + it("extends backward from the end of the anchor word to the start of the focus word", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 15, start: 13, end: 20 }), + focus: wordAt({ offset: 7, start: 6, end: 11 }), + }), + ).toEqual({ + anchor: positionAt(6), + focus: positionAt(20), + }); + }); + + it("keeps the anchor word whole while the pointer stays inside it", () => { + const anchor = wordAt({ offset: 10, start: 6, end: 11 }); + const expected = { anchor: positionAt(6), focus: positionAt(11) }; + expect( + wordSelectionForDrag({ anchor, focus: wordAt({ offset: 7, start: 6, end: 11 }) }), + ).toEqual(expected); + expect( + wordSelectionForDrag({ anchor, focus: wordAt({ offset: 9, start: 6, end: 11 }) }), + ).toEqual(expected); + }); + + it("snaps both ends to word boundaries across rows", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 3, start: 2, end: 5 }, 1), + focus: wordAt({ offset: 2, start: 0, end: 4 }, 3), + }), + ).toEqual({ + anchor: positionAt(2, 1), + focus: positionAt(4, 3), + }); + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 2, start: 0, end: 4 }, 3), + focus: wordAt({ offset: 3, start: 2, end: 5 }, 1), + }), + ).toEqual({ + anchor: positionAt(2, 1), + focus: positionAt(4, 3), + }); + }); +}); + +describe("diff line drag selection", () => { + it("selects the whole clicked source line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 3, end: 12 }), + focus: lineAt({ offset: 3, end: 12 }), + }), + ).toEqual({ + anchor: positionAt(0), + focus: positionAt(12), + }); + }); + + it("extends forward to the end of the focus line while keeping the anchor line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 3, end: 12 }), + focus: lineAt({ offset: 1, end: 7 }, 3), + }), + ).toEqual({ + anchor: positionAt(0), + focus: positionAt(7, 3), + }); + }); + + it("extends backward from the start of the focus line to the end of the anchor line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 5, end: 9 }, 3), + focus: lineAt({ offset: 2, end: 12 }, 1), + }), + ).toEqual({ + anchor: positionAt(0, 1), + focus: positionAt(9, 3), + }); + }); +}); diff --git a/packages/app/src/git/diff-document/pointer-gesture.ts b/packages/app/src/git/diff-document/pointer-gesture.ts index e5da48aa0998..e0928398b482 100644 --- a/packages/app/src/git/diff-document/pointer-gesture.ts +++ b/packages/app/src/git/diff-document/pointer-gesture.ts @@ -1,5 +1,46 @@ +import { comparePosition } from "./hit-testing"; +import type { DiffCharacterPosition, DiffSelection } from "./types"; +import type { SourceWordRange } from "./word-boundaries"; + const DRAG_THRESHOLD = 4; +export interface WordAtPosition { + position: DiffCharacterPosition; + word: SourceWordRange; +} + +export interface LineAtPosition { + position: DiffCharacterPosition; + /** UTF-16 length of the canonical source line. */ + end: number; +} + +export function wordSelectionForDrag(input: { + anchor: WordAtPosition; + focus: WordAtPosition; +}): DiffSelection { + const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0; + const start = isBackward ? input.focus : input.anchor; + const end = isBackward ? input.anchor : input.focus; + return { + anchor: { ...start.position, sourceOffset: start.word.start }, + focus: { ...end.position, sourceOffset: end.word.end }, + }; +} + +export function lineSelectionForDrag(input: { + anchor: LineAtPosition; + focus: LineAtPosition; +}): DiffSelection { + const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0; + const start = isBackward ? input.focus : input.anchor; + const end = isBackward ? input.anchor : input.focus; + return { + anchor: { ...start.position, sourceOffset: 0 }, + focus: { ...end.position, sourceOffset: end.end }, + }; +} + export function hasPointerDragStarted(input: { startX: number; startY: number; diff --git a/packages/app/src/git/diff-document/surface.web.tsx b/packages/app/src/git/diff-document/surface.web.tsx index 393f6dfcd732..e4247636b7d5 100644 --- a/packages/app/src/git/diff-document/surface.web.tsx +++ b/packages/app/src/git/diff-document/surface.web.tsx @@ -35,7 +35,13 @@ import { resolveRelayoutScrollTop, } from "./model"; import { paintWebFileHeader, paintWebViewport } from "./paint.web"; -import { hasPointerDragStarted } from "./pointer-gesture"; +import { + hasPointerDragStarted, + lineSelectionForDrag, + wordSelectionForDrag, + type LineAtPosition, + type WordAtPosition, +} from "./pointer-gesture"; import { createMeasuredAdvances, createAdditiveAdvances, @@ -44,6 +50,8 @@ import { } from "./text-measurement"; import { retainDiffViewport } from "./viewport"; import type { + DiffCell, + DiffCharacterPosition, DiffHit, DiffFileSection, DiffSelection, @@ -51,6 +59,7 @@ import type { DiffTypography, TextMeasurer, } from "./types"; +import { wordRangeAtOffset } from "./word-boundaries"; import { useDiffDocumentWorkspaceCache } from "./workspace-cache"; const DEFAULT_MONO_STACK = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"; @@ -104,6 +113,11 @@ export function DiffSurface(props: DiffSurfaceProps) { startY: number; moved: boolean; dismissSelectionOnClick: boolean; + granularity: + | { kind: "character" } + | { kind: "word"; anchor: WordAtPosition } + | { kind: "line"; anchor: LineAtPosition }; + pointerType: string; } | null>(null); const frameRef = useRef(null); const activeHeaderPathRef = useRef(null); @@ -591,6 +605,31 @@ export function DiffSurface(props: DiffSurfaceProps) { desiredTypography, setSelection, ]); + const cellAt = useCallback((position: DiffCharacterPosition): DiffCell | null => { + const currentModel = modelRef.current; + if (!currentModel) return null; + const row = currentModel.rows[position.rowIndex]; + return row?.kind === "line" ? row.cells[position.cellIndex] : null; + }, []); + const wordAt = useCallback( + (hit: Extract): WordAtPosition | null => { + const cell = cellAt(hit.position); + if (!cell) return null; + return { + position: { ...hit.position, sourceOffset: hit.graphemeOffset }, + word: wordRangeAtOffset(cell.content, hit.graphemeOffset), + }; + }, + [cellAt], + ); + const lineAt = useCallback( + (hit: Extract): LineAtPosition | null => { + const cell = cellAt(hit.position); + if (!cell) return null; + return { position: hit.position, end: cell.content.length }; + }, + [cellAt], + ); const pointerDown = useCallback( (event: React.PointerEvent) => { if (event.button !== 0) return; @@ -602,18 +641,18 @@ export function DiffSurface(props: DiffSurfaceProps) { ) ) return; - const dismissSelectionOnClick = selectionRef.current !== null; - if (dismissSelectionOnClick) { - setSelection(null); - } const hit = pointHit(event); + const hadSelection = selectionRef.current !== null; + if (hadSelection) setSelection(null); if (hit?.kind !== "cell") return; dragRef.current = { anchor: hit.position, startX: event.clientX, startY: event.clientY, moved: false, - dismissSelectionOnClick, + dismissSelectionOnClick: hadSelection, + granularity: { kind: "character" }, + pointerType: event.pointerType, }; setSelection({ anchor: hit.position, focus: hit.position }); event.currentTarget.focus(); @@ -621,6 +660,38 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [pointHit, setSelection], ); + // The native click count honors the OS double-click setting and arrives on the + // second mousedown, after pointerdown has opened the character drag. + const mouseDown = useCallback( + (event: React.MouseEvent) => { + const drag = dragRef.current; + if (!drag || event.button !== 0 || event.detail < 2 || drag.pointerType === "touch") return; + const target = event.target; + if ( + target instanceof Element && + target.closest( + '[data-diff-header="true"], [data-diff-review="true"], [role="menuitem"], button, input, textarea', + ) + ) + return; + const hit = pointHitAt(event.clientX, event.clientY); + if (hit?.kind !== "cell") return; + if (event.detail >= 3) { + const lineAnchor = lineAt(hit); + if (!lineAnchor) return; + drag.granularity = { kind: "line", anchor: lineAnchor }; + drag.dismissSelectionOnClick = false; + setSelection(lineSelectionForDrag({ anchor: lineAnchor, focus: lineAnchor })); + return; + } + const wordAnchor = wordAt(hit); + if (!wordAnchor) return; + drag.granularity = { kind: "word", anchor: wordAnchor }; + drag.dismissSelectionOnClick = false; + setSelection(wordSelectionForDrag({ anchor: wordAnchor, focus: wordAnchor })); + }, + [lineAt, pointHitAt, setSelection, wordAt], + ); const updateActiveHeader = useCallback( (target: EventTarget | null) => { const header = @@ -634,6 +705,32 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [paintStickyHeaderPool, schedulePaint], ); + const updateHoveredAffordance = useCallback( + (hit: Extract, clientX: number) => { + const row = modelRef.current?.rows[hit.position.rowIndex]; + const file = modelRef.current?.files[hit.position.fileIndex]; + const sideIndex = + row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0; + if (row && file) { + const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1); + const gutterBorder = sideIndex * columnWidth + file.gutterWidth; + const rootBounds = rootRef.current?.getBoundingClientRect(); + const pointerX = rootBounds ? clientX - rootBounds.left : Number.NaN; + if (hit.target && Number.isFinite(pointerX)) { + hasHoveredAffordanceRef.current = true; + setHoveredAffordance({ + hit, + left: gutterBorder - 12, + top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2, + }); + return; + } + } + hasHoveredAffordanceRef.current = false; + setHoveredAffordance(null); + }, + [viewport.width], + ); const pointerMove = useCallback( (event: React.PointerEvent) => { updateActiveHeader(event.target); @@ -649,35 +746,29 @@ export function DiffSurface(props: DiffSurfaceProps) { } const hit = pointHit(event); if (hit?.kind === "cell") { - const row = modelRef.current?.rows[hit.position.rowIndex]; - const file = modelRef.current?.files[hit.position.fileIndex]; - const sideIndex = - row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0; - if (row && file) { - const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1); - const gutterBorder = sideIndex * columnWidth + file.gutterWidth; - const rootBounds = rootRef.current?.getBoundingClientRect(); - const pointerX = rootBounds ? event.clientX - rootBounds.left : Number.NaN; - if (hit.target && Number.isFinite(pointerX)) { - hasHoveredAffordanceRef.current = true; - setHoveredAffordance({ - hit, - left: gutterBorder - 12, - top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2, - }); - } else { - hasHoveredAffordanceRef.current = false; - setHoveredAffordance(null); - } - } + updateHoveredAffordance(hit, event.clientX); } else { hasHoveredAffordanceRef.current = false; setHoveredAffordance(null); } if (!drag || hit?.kind !== "cell") return; + if (drag.granularity.kind === "word") { + const focusWord = wordAt(hit); + if (focusWord) { + setSelection(wordSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusWord })); + } + return; + } + if (drag.granularity.kind === "line") { + const focusLine = lineAt(hit); + if (focusLine) { + setSelection(lineSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusLine })); + } + return; + } setSelection({ anchor: drag.anchor, focus: hit.position }); }, - [pointHit, setSelection, updateActiveHeader, viewport.width], + [lineAt, pointHit, setSelection, updateActiveHeader, updateHoveredAffordance, wordAt], ); const pointerUp = useCallback( (event: React.PointerEvent) => { @@ -822,6 +913,7 @@ export function DiffSurface(props: DiffSurfaceProps) { data-overlay-scrollbar="true" tabIndex={0} onPointerDown={pointerDown} + onMouseDown={mouseDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={cancelPointer} diff --git a/packages/app/src/git/diff-document/types.ts b/packages/app/src/git/diff-document/types.ts index d98880eb8ce6..3024fda838ec 100644 --- a/packages/app/src/git/diff-document/types.ts +++ b/packages/app/src/git/diff-document/types.ts @@ -208,6 +208,8 @@ export type DiffHit = kind: "cell"; target: ReviewableDiffTarget | null; position: DiffCharacterPosition; + /** The grapheme under the pointer, which word gestures select from. */ + graphemeOffset: number; }; export interface DiffSelection { diff --git a/packages/app/src/git/diff-document/word-boundaries.test.ts b/packages/app/src/git/diff-document/word-boundaries.test.ts new file mode 100644 index 000000000000..47b9052410c7 --- /dev/null +++ b/packages/app/src/git/diff-document/word-boundaries.test.ts @@ -0,0 +1,70 @@ +import { CharCategory, EditorState } from "@codemirror/state"; +import { describe, expect, it } from "vitest"; +import { wordRangeAtOffset } from "./word-boundaries"; + +describe("diff word boundaries", () => { + it("selects the identifier under the offset", () => { + expect(wordRangeAtOffset("alpha bravo charlie", 8)).toEqual({ start: 6, end: 11 }); + }); + + it("selects the surrounding whitespace when the offset is inside a run of spaces", () => { + expect(wordRangeAtOffset("alpha bravo", 6)).toEqual({ start: 5, end: 8 }); + }); + + it("selects a run of punctuation without merging it into neighboring words", () => { + expect(wordRangeAtOffset("call(foo, bar)", 4)).toEqual({ start: 4, end: 5 }); + expect(wordRangeAtOffset("call(foo, bar)", 6)).toEqual({ start: 5, end: 8 }); + expect(wordRangeAtOffset("fn()", 3)).toEqual({ start: 2, end: 4 }); + expect(wordRangeAtOffset("foo.bar", 3)).toEqual({ start: 3, end: 4 }); + expect(wordRangeAtOffset("foo.bar", 5)).toEqual({ start: 4, end: 7 }); + }); + + it("selects the final word when the offset reaches the end of the line", () => { + expect(wordRangeAtOffset("alpha bravo", 11)).toEqual({ start: 6, end: 11 }); + expect(wordRangeAtOffset("alpha bravo", 99)).toEqual({ start: 6, end: 11 }); + }); + + it("selects the leading word when the offset is clamped at the start", () => { + expect(wordRangeAtOffset("alpha bravo", 0)).toEqual({ start: 0, end: 5 }); + }); + + it("keeps combining sequences and emoji clusters whole", () => { + const combining = "ai\u0301b"; + expect(wordRangeAtOffset(combining, 1)).toEqual({ start: 0, end: 4 }); + expect(wordRangeAtOffset(combining, 2)).toEqual({ start: 0, end: 4 }); + + const emoji = "hi 👨‍👩‍👧‍👦 there"; + const emojiStart = emoji.indexOf("👨"); + expect(wordRangeAtOffset(emoji, emojiStart)).toEqual({ + start: emojiStart, + end: emojiStart + "👨‍👩‍👧‍👦".length, + }); + }); + + it("treats tabs as whitespace and returns an empty range for empty content", () => { + expect(wordRangeAtOffset("\tfoo", 0)).toEqual({ start: 0, end: 1 }); + expect(wordRangeAtOffset("", 0)).toEqual({ start: 0, end: 0 }); + }); + + it("matches CodeMirror word runs for offsets inside a word", () => { + const content = "alpha bravo charlie"; + const state = EditorState.create({ doc: content }); + for (const offset of [0, 2, 8, 14, 18]) { + const word = state.wordAt(offset); + expect(word).not.toBeNull(); + expect(wordRangeAtOffset(content, offset)).toEqual({ start: word!.from, end: word!.to }); + } + }); + + it("classifies leading graphemes with CodeMirror character categories", () => { + const categorize = EditorState.create({ doc: "" }).charCategorizer(0); + const clusters = ["a", "1", "_", "中", "👨‍👩‍👧‍👦", "\u0301", "\ufe0f", "\u00a0"]; + for (const cluster of clusters) { + const isWord = categorize(cluster) === CharCategory.Word; + expect(wordRangeAtOffset(`${cluster}x`, 0)).toEqual({ + start: 0, + end: isWord ? cluster.length + 1 : cluster.length, + }); + } + }); +}); diff --git a/packages/app/src/git/diff-document/word-boundaries.ts b/packages/app/src/git/diff-document/word-boundaries.ts new file mode 100644 index 000000000000..705722cc38ef --- /dev/null +++ b/packages/app/src/git/diff-document/word-boundaries.ts @@ -0,0 +1,88 @@ +import { CharCategory, EditorState } from "@codemirror/state"; +import { graphemeBoundaries } from "./model"; + +export interface SourceWordRange { + start: number; + end: number; +} + +interface SourceText { + state: EditorState; + boundaries: number[]; + categorize: (cluster: string) => CharCategory; +} + +// Word gestures query the same line repeatedly while dragging. Keep a bounded +// set of parsed sources instead of rebuilding an EditorState on every move. +const SOURCE_CACHE_LIMIT = 8; +const sources = new Map(); + +/** + * The run around `offset` that a double click selects: a word, a run of + * whitespace, or a run of punctuation. Runs never cross grapheme boundaries. + */ +export function wordRangeAtOffset(content: string, offset: number): SourceWordRange { + if (content.length === 0) return { start: 0, end: 0 }; + const source = sourceText(content); + const { boundaries } = source; + const clusterIndex = clusterIndexAt(boundaries, offset); + const category = source.categorize(clusterText(content, boundaries, clusterIndex)); + if (category === CharCategory.Word) { + const word = source.state.wordAt(boundaries[clusterIndex]); + if (word) return { start: word.from, end: word.to }; + } + let first = clusterIndex; + while (first > 0 && categoryAt(source, content, boundaries, first - 1) === category) first -= 1; + let last = clusterIndex; + while ( + last < boundaries.length - 2 && + categoryAt(source, content, boundaries, last + 1) === category + ) + last += 1; + return { start: boundaries[first], end: boundaries[last + 1] }; +} + +function sourceText(content: string): SourceText { + const cached = sources.get(content); + if (cached) { + sources.delete(content); + sources.set(content, cached); + return cached; + } + const state = EditorState.create({ doc: content }); + const source: SourceText = { + state, + boundaries: graphemeBoundaries(content), + categorize: state.charCategorizer(0), + }; + sources.set(content, source); + if (sources.size > SOURCE_CACHE_LIMIT) { + const oldest = sources.keys().next(); + if (!oldest.done) sources.delete(oldest.value); + } + return source; +} + +function clusterIndexAt(boundaries: readonly number[], offset: number): number { + let low = 0; + let high = boundaries.length - 2; + while (low < high) { + const middle = (low + high + 1) >>> 1; + if (boundaries[middle] <= offset) low = middle; + else high = middle - 1; + } + return low; +} + +function categoryAt( + source: SourceText, + content: string, + boundaries: readonly number[], + index: number, +): CharCategory { + return source.categorize(clusterText(content, boundaries, index)); +} + +function clusterText(content: string, boundaries: readonly number[], index: number): string { + return content.slice(boundaries[index], boundaries[index + 1]); +} From cba515ef7300bc00cc7c73cf69ee4d8c00907578 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 11:15:58 +0700 Subject: [PATCH 010/109] fix(github): prioritize private repositories in clone search (#10264) The general GitHub search can fill its result limit with public repositories before returning a private match. Fetch private matches separately so users can find them by name. --- .../services/github-repository-search.test.ts | 45 ++++++++++++++++--- .../server/src/services/github-service.ts | 44 ++++++++++-------- 2 files changed, 66 insertions(+), 23 deletions(-) diff --git a/packages/server/src/services/github-repository-search.test.ts b/packages/server/src/services/github-repository-search.test.ts index d324aab16c20..88837d1205e9 100644 --- a/packages/server/src/services/github-repository-search.test.ts +++ b/packages/server/src/services/github-repository-search.test.ts @@ -75,7 +75,7 @@ describe("GitHub repository search", () => { ]); }); - it("searches accessible repositories for a typed query", async () => { + it("respects an explicit visibility qualifier and normalizes the search result", async () => { const runner = createRunner([ JSON.stringify([ { @@ -96,7 +96,7 @@ describe("GitHub repository search", () => { }); await expect( - service.searchRepositories({ cwd: "/tmp", query: " private project ", limit: 5 }), + service.searchRepositories({ cwd: "/tmp", query: " is:private private project ", limit: 5 }), ).resolves.toEqual([ { id: "42", @@ -113,15 +113,15 @@ describe("GitHub repository search", () => { args: [ "search", "repos", - "private project", + "is:private private project", "--json", "id,name,fullName,description,isPrivate,updatedAt,url", + "--limit", + "5", "--sort", "updated", "--order", "desc", - "--limit", - "5", ], options: { cwd: "/tmp" }, }, @@ -131,4 +131,39 @@ describe("GitHub repository search", () => { }, ]); }); + + it("puts private matches first even when the general search omits some of them", async () => { + const repository = (id: number, fullName: string, isPrivate: boolean) => ({ + id, + name: fullName.split("/")[1], + fullName, + description: "An editor", + isPrivate, + updatedAt: "2026-07-14T08:00:00Z", + url: `https://github.com/${fullName}`, + }); + const privateEditor = repository(1, "example/editor", true); + const publicEditor = repository(2, "public/recent-editor", false); + const anotherPublicEditor = repository(3, "public/another-editor", false); + const recentPrivateEditor = repository(4, "example/recent-editor", true); + const service = createGitHubService({ + runner: async (args) => { + if (args[0] === "config") { + return { stdout: "https", stderr: "" }; + } + const results = args.includes("--visibility=private") + ? [privateEditor, recentPrivateEditor] + : [publicEditor, recentPrivateEditor, anotherPublicEditor]; + return { stdout: JSON.stringify(results), stderr: "" }; + }, + resolveGhPath: async () => "/usr/bin/gh", + }); + + const results = await service.searchRepositories({ cwd: "/tmp", query: "editor", limit: 3 }); + expect(results.map((result) => result.nameWithOwner)).toEqual([ + "example/editor", + "example/recent-editor", + "public/recent-editor", + ]); + }); }); diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 36e6a39c8f2f..556b307de116 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -2639,26 +2639,34 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return parseRepositoryList(stdout, cloneProtocol); } - const [stdout, cloneProtocol] = await Promise.all([ - run( - [ - "search", - "repos", - query, - "--json", - "id,name,fullName,description,isPrivate,updatedAt,url", - "--sort", - "updated", - "--order", - "desc", - "--limit", - String(limit), - ], - { cwd: input.cwd }, - ), + const searchArgs = [ + "search", + "repos", + query, + "--json", + "id,name,fullName,description,isPrivate,updatedAt,url", + "--limit", + String(limit), + ]; + const hasVisibilityFilter = /(?:^|\s)-?is:(?:public|private|internal)(?=\s|$)/i.test(query); + // The general search can hit its limit before returning a single private match. + const [stdout, privateStdout, cloneProtocol] = await Promise.all([ + run([...searchArgs, "--sort", "updated", "--order", "desc"], { cwd: input.cwd }), + hasVisibilityFilter + ? "[]" + : run([...searchArgs, "--visibility=private"], { cwd: input.cwd }), resolveConfiguredCloneProtocol(input.cwd, run), ]); - return parseRepositorySearch(stdout, cloneProtocol); + const repositories = parseRepositorySearch(stdout, cloneProtocol); + const privateMatches = parseRepositorySearch(privateStdout, cloneProtocol); + const ranked = new Map( + [ + ...privateMatches, + ...repositories.filter((repository) => repository.visibility === "private"), + ...repositories, + ].map((repository) => [repository.id, repository]), + ); + return [...ranked.values()].slice(0, limit); }, async searchIssuesAndPrs(input) { From 1972864b1923a563aa78eab3a03bec92f8908d5f Mon Sep 17 00:00:00 2001 From: luke Date: Fri, 20 Nov 2026 12:57:43 +0800 Subject: [PATCH 011/109] feat(antigravity): show account usage (#10232) * feat(antigravity): show account usage Resolve the provider launch for usage discovery and report quota windows from agy. Co-authored-by: RoundRedDot * fix(usage): clear reports when a provider executable is missing Usage discovery treated a missing executable as a transient error and kept the previous account report. Treat the unresolved launch as absent so the next refresh removes that report. --------- Co-authored-by: RoundRedDot Co-authored-by: Mohamed Boudra --- packages/plugin/src/server/usage.ts | 6 +- .../src/server/agent/agent-sdk-types.ts | 4 + .../src/server/agent/plugin-provider.test.ts | 24 ++++ .../src/server/agent/plugin-provider.ts | 33 ++++- .../src/server/agent/provider-registry.ts | 1 + .../server/agent/provider-snapshot-manager.ts | 6 + packages/server/src/server/bootstrap.ts | 1 + packages/server/src/server/plugins/index.ts | 29 ++++- .../server/plugins/plugin-process-protocol.ts | 2 + .../src/server/plugins/plugin-process.ts | 1 + .../server/plugins/usage-sources.e2e.test.ts | 54 ++++++++ .../src/server/plugins/usage-sources/index.ts | 4 + plugins/antigravity-provider/index.server.ts | 3 + .../antigravity-provider/server/usage.test.ts | 101 +++++++++++++++ plugins/antigravity-provider/server/usage.ts | 120 ++++++++++++++++++ public-docs/plugins/reference.md | 16 ++- 16 files changed, 400 insertions(+), 5 deletions(-) create mode 100644 plugins/antigravity-provider/server/usage.test.ts create mode 100644 plugins/antigravity-provider/server/usage.ts diff --git a/packages/plugin/src/server/usage.ts b/packages/plugin/src/server/usage.ts index fa23ca9c915c..425e2e5545e5 100644 --- a/packages/plugin/src/server/usage.ts +++ b/packages/plugin/src/server/usage.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import { z, type ZodType } from "zod"; +import { ProviderLaunchSchema } from "./provider.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; export interface UsageWindow { @@ -65,12 +66,13 @@ export interface UsageAccount { } export const UsageScopeSchema = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("global") }), + z.object({ kind: z.literal("global"), launch: ProviderLaunchSchema.optional() }), z.object({ kind: z.literal("session"), provider: z.string(), model: z.string().optional(), env: z.record(z.string(), z.string()), + launch: ProviderLaunchSchema.optional(), }), ]); export type UsageScope = z.infer; @@ -79,6 +81,8 @@ export interface UsageSourceRegistration { id: string; label: string; icon?: string; + /** Provider whose resolved launch is needed for discovery. */ + provider?: string; input: ZodType; /** Accounts for this scope only. The same key in any scope identifies the same account. */ discover(scope: UsageScope): Promise; diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index aa2a21dda556..5116f74f2f5c 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -699,6 +699,7 @@ export interface AgentPermissionResult { } export interface AgentUsageSession { + launch?: import("@getpaseo/plugin/server/provider").ProviderLaunch; provider: string; model?: string; env: Record; @@ -849,6 +850,9 @@ export interface AgentClientUpdateContext extends AgentClientInstallationContext } export interface AgentClient { + resolveUsageLaunch?(): Promise< + import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined + >; readonly provider: AgentProvider; readonly capabilities: AgentCapabilityFlags; /** diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index e3633ee58b1c..b95935a515ac 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -2512,6 +2512,30 @@ describe("plugin provider launch and status", () => { } }); + test("exposes the session launch for usage discovery", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([{ ...harness.registration, command: [process.execPath, "acp"] }]); + try { + const client = registry.clients()[harness.registration.id]!; + const session = await client.createSession( + { provider: harness.registration.id, cwd: "/workspace" }, + { env: { HOME: "/session-home" } }, + ); + expect(session.usageSession?.()).toMatchObject({ + provider: harness.registration.id, + model: "plugin-model", + env: { HOME: "/session-home" }, + launch: { command: process.execPath, args: ["acp"], env: { HOME: "/session-home" } }, + sessionKey: expect.any(String), + }); + await session.close(); + expect(session.usageSession?.()).toBeNull(); + } finally { + await registry.shutdown(); + } + }); + test("resolves relative executable paths before sending launch data", async () => { const harness = createProviderHarness(); const launches: Array = []; diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 4090467f61d5..6a756553648c 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -137,6 +137,7 @@ function isProviderRequestReply( class ProviderRuntime { private connection: ProviderConnection | null = null; + connectedLaunch: ProviderLaunch | undefined; private connecting: Promise | null = null; private closed = false; private generation = 0; @@ -192,6 +193,12 @@ class ProviderRuntime { return { command: launch.command, args: launch.args, env: launch.env }; } + async resolveUsageLaunch(): Promise { + const launch = await this.resolveEffectiveLaunch(); + if (!launch?.resolved) return undefined; + return { command: launch.command, args: launch.args, env: launch.env }; + } + async inspectInstallation(signal: AbortSignal): Promise { const inspect = this.registration.installation?.inspect; if (!inspect) throw new Error("Provider does not report its installation"); @@ -425,8 +432,9 @@ class ProviderRuntime { } private async establishConnection(generation: number): Promise { + const launch = await this.resolveLaunch(); const rawConnection = await this.registration.connect({ - launch: await this.resolveLaunch(), + launch, versions: [PROVIDER_PROTOCOL_VERSION], capabilities: PROVIDER_CAPABILITIES, }); @@ -440,6 +448,7 @@ class ProviderRuntime { await rawConnection.close().catch(() => undefined); throw error; } + this.connectedLaunch = launch; const connection = normalizeConnection(rawConnection); const unsubscribe = connection.onEvent((event) => this.accept(event)); if (this.closed || generation !== this.generation) { @@ -1032,6 +1041,10 @@ class PluginAgentClient implements AgentClient { this.runtime.onSessionOpened((session, opened) => this.acceptChild(session, opened)); } + resolveUsageLaunch() { + return this.runtime.resolveUsageLaunch(); + } + get capabilities(): AgentCapabilityFlags { return agentCapabilities(this.runtime.negotiatedCapabilities); } @@ -1197,6 +1210,12 @@ class PluginAgentClient implements AgentClient { }, bind, config.settings, + this.runtime.connectedLaunch + ? { + ...this.runtime.connectedLaunch, + env: { ...this.runtime.connectedLaunch.env, ...config.env }, + } + : undefined, ); bind(bridge); return session; @@ -1297,6 +1316,7 @@ class PluginAgentSession implements AgentSession { ) => Promise, private readonly onBind: (bridge: ProviderRuntimeSession) => void, givenOptions: Readonly>, + private readonly usageLaunch: ProviderLaunch | undefined, ) { this.subagentIdsBySession.set(bridge.id, null); // Every setting the session opened with that was not given, including ones nobody set. @@ -1312,6 +1332,17 @@ class PluginAgentSession implements AgentSession { this.unsubscribe = bridge.onEvent((event) => this.accept(event, true)); } + usageSession() { + if (this.closed || !this.usageLaunch) return null; + return { + provider: this.provider, + model: this.bridge.config.model, + env: this.usageLaunch.env, + launch: this.usageLaunch, + sessionKey: this.bridge.id, + }; + } + get id(): string { return this.describePersistence()?.sessionId ?? this.bridge.id; } diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index bba0b3d5e7bf..a80dc2695a65 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -623,6 +623,7 @@ function wrapClientProvider( unarchiveNativeSession: unarchiveNativeSession ? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider }) : undefined, + resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner), getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner), isAvailable: (signal, options) => inner.isAvailable(signal, options), getDiagnostic: inner.getDiagnostic?.bind(inner), diff --git a/packages/server/src/server/agent/provider-snapshot-manager.ts b/packages/server/src/server/agent/provider-snapshot-manager.ts index f20844aff52e..0de61db82a1a 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.ts @@ -473,6 +473,12 @@ export class ProviderSnapshotManager { return client; } + async resolveUsageLaunch(provider: string) { + const definition = this.generation.definitions[provider]; + if (!definition?.enabled) return undefined; + return this.ensureClient(provider, definition).resolveUsageLaunch?.(); + } + async listProviders(input: ProviderSnapshotReadOptions = {}): Promise { const target = resolveProviderSnapshotTarget(input.cwd); if (input.wait) { diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 52b25283542c..3a12d6dfa6fc 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -677,6 +677,7 @@ export async function createPaseoDaemon( usageAgents: { hasAgent: (id) => agentManager.getAgent(id) !== null, usageSession: (id) => agentManager.usageSession(id), + resolveLaunch: (provider) => providerSnapshotManager.resolveUsageLaunch(provider), }, managedSources: new ManagedPluginSources(config.paseoHome, { registries: config.pluginRegistries, diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index b848b6130f32..89f09275bfae 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -669,12 +669,39 @@ export class PluginService { const registered: string[] = []; try { for (const source of metadata) { + if ( + source.provider && + !this.runtime + .getProviderRegistrations?.(pluginId) + .some((provider) => provider.id === source.provider) + ) { + throw new Error( + `Usage source ${source.id} references a provider outside plugin ${pluginId}`, + ); + } this.usageSources.register({ id: source.id, label: source.label, icon: source.icon, discover: async (scope) => { - const result = await this.runtime.discoverUsage(pluginId, source.id, scope); + const launch = + scope.kind === "global" && source.provider + ? await this.dependencies.usageAgents?.resolveLaunch?.(source.provider) + : undefined; + const scoped = + scope.kind === "session" && source.provider !== scope.provider + ? { + kind: "session" as const, + provider: scope.provider, + model: scope.model, + env: scope.env, + } + : scope; + const result = await this.runtime.discoverUsage( + pluginId, + source.id, + scoped.kind === "global" && launch ? { ...scoped, launch } : scoped, + ); if (!Array.isArray(result)) throw new Error(`Invalid usage discovery from ${source.id}`); return result; diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index b867d21e20af..8608be8e1165 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -41,6 +41,7 @@ export interface PluginProviderInstallationMetadata { export interface PluginUsageSourceMetadata { id: string; label: string; + provider?: string; icon?: string; } @@ -175,6 +176,7 @@ const usageSourceMetadataSchema = z .object({ id: z.string().min(1), label: z.string().min(1), + provider: z.string().min(1).optional(), icon: z.string().optional(), }) .strict(); diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index 5af2bab78579..d95078d23b32 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -448,6 +448,7 @@ export function createPluginWorker(options: { .map(async (source) => ({ id: source.id, label: source.label, + provider: source.provider, icon: source.icon ? await readPluginProviderIcon(message.pluginDirectory, source.icon) : undefined, diff --git a/packages/server/src/server/plugins/usage-sources.e2e.test.ts b/packages/server/src/server/plugins/usage-sources.e2e.test.ts index 46dc134ff6eb..7c680bda06af 100644 --- a/packages/server/src/server/plugins/usage-sources.e2e.test.ts +++ b/packages/server/src/server/plugins/usage-sources.e2e.test.ts @@ -410,3 +410,57 @@ dns.lookup = function(host, ...args) { }, 60_000, ); + +test("resolves a plugin provider launch for cold usage discovery", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paseo-usage-launch-")); + const directory = path.join(root, "launch-source"); + await mkdir(directory, { recursive: true }); + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "launch-source", requirements: { paseo: ">=0.9.2" } }), + ); + await writeFile( + path.join(directory, "index.server.ts"), + ` +import { z } from 'zod'; +export default function contribute(server) { + server.registerProvider({ id: 'usage-launch-fixture', label: 'Launch fixture', command: [${JSON.stringify(process.execPath)}, 'fixture-arg'], connect: async () => { throw new Error('Must not connect'); } }); + server.registerUsageSource({ id: 'launch-fixture', label: 'Launch fixture', provider: 'usage-launch-fixture', input: z.object({}), + discover: async scope => scope.kind === 'global' && scope.launch?.args[0] === 'fixture-arg' ? [{ key: 'default', input: {} }] : [], + fetch: async () => ({ status: 'available', windows: [{ id: 'weekly', label: 'Weekly', usedPct: 12 }] }) }); + return () => {}; +}`, + ); + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.16.2", + pluginsEnabled: false, + builtinPlugins: new BuiltinPluginLoader(root, ["launch-source"]), + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.16.2", + }); + try { + await client.connect(); + const result = await client.listUsageReports(); + expect(result.reports).toContainEqual( + expect.objectContaining({ + id: "launch-fixture:default", + report: expect.objectContaining({ + status: "available", + windows: [{ id: "weekly", label: "Weekly", usedPct: 12 }], + }), + }), + ); + await client.patchDaemonConfig({ + providers: { + "usage-launch-fixture": { command: [path.join(root, "missing-cli")] }, + }, + }); + expect((await client.listUsageReports()).reports).toEqual([]); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true }); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/usage-sources/index.ts b/packages/server/src/server/plugins/usage-sources/index.ts index 3a6837271766..55b865416ffc 100644 --- a/packages/server/src/server/plugins/usage-sources/index.ts +++ b/packages/server/src/server/plugins/usage-sources/index.ts @@ -33,6 +33,9 @@ interface KnownReport { export interface AgentUsageLookup { hasAgent(id: string): boolean; usageSession(id: string): AgentUsageSession | null; + resolveLaunch?( + provider: string, + ): Promise; } export interface ListUsageReportsOptions { @@ -134,6 +137,7 @@ export class UsageSourceRegistry { provider: session.provider, model: session.model, env: session.env, + launch: session.launch, }); const current = this.agents.usageSession(agentId); if ( diff --git a/plugins/antigravity-provider/index.server.ts b/plugins/antigravity-provider/index.server.ts index 661fa8445d71..4485bea2c921 100644 --- a/plugins/antigravity-provider/index.server.ts +++ b/plugins/antigravity-provider/index.server.ts @@ -1,7 +1,10 @@ import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { Usage } from "./server/usage.js"; import { createAntigravityProvider } from "./server/provider.js"; export default function contribute(server: PluginServerContext) { + const usage = new Usage(); + server.registerUsageSource(usage.registration()); server.registerProvider(createAntigravityProvider()); return () => {}; } diff --git a/plugins/antigravity-provider/server/usage.test.ts b/plugins/antigravity-provider/server/usage.test.ts new file mode 100644 index 000000000000..f3d76d64e360 --- /dev/null +++ b/plugins/antigravity-provider/server/usage.test.ts @@ -0,0 +1,101 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, expect, it } from "vitest"; +import { Usage } from "./usage.js"; + +const directories: string[] = []; +afterEach(async () => { + await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true }))); +}); + +it("discovers the resolved account and maps the CLI's quota buckets", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-")); + directories.push(directory); + const cli = path.join(directory, "cli.cjs"); + await writeFile( + cli, + ` + if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(['-p', '/usage', '--output-format', 'json'])) process.exit(2); + console.log(JSON.stringify({ status: 'SUCCESS', command: { name: 'usage', data: { groups: [ + { name: 'Gemini Models', buckets: [ + { id: 'gemini-5h', name: 'Five Hour Limit Remaining', window: '5h', remaining_fraction: 0.25, reset_time: '2026-11-19T14:25:08Z' }, + { id: 'gemini-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 0.7 }, + { id: 'disabled', name: 'Weekly', window: 'weekly', disabled: true, remaining_fraction: 1 } + ] } + ] } } })); + `, + ); + const usage = new Usage(); + const launch = { + command: process.execPath, + args: [cli, "acp", "--disable-telemetry"], + env: { HOME: directory }, + }; + const source = usage.registration(); + const accounts = await source.discover({ kind: "global", launch }); + expect(accounts).toHaveLength(1); + expect( + await source.discover({ + kind: "session", + provider: "antigravity", + env: { HOME: directory }, + launch, + }), + ).toEqual(accounts); + expect( + await source.discover({ + kind: "session", + provider: "antigravity", + env: { HOME: `${directory}-other` }, + }), + ).toEqual([]); + expect( + await source.discover({ kind: "session", provider: "codex", env: { HOME: directory } }), + ).toEqual([]); + const otherLaunch = { ...launch, env: { HOME: `${directory}-other` } }; + const other = await source.discover({ + kind: "session", + provider: "antigravity", + env: otherLaunch.env, + launch: otherLaunch, + }); + expect(other[0]?.key).not.toBe(accounts[0]?.key); + expect(other[0]?.input).not.toEqual(accounts[0]?.input); + expect(await source.fetch(accounts[0]!.input)).toMatchObject({ + status: "available", + windows: [ + { id: "gemini-5h", usedPct: 75, remainingPct: 25, resetsAt: "2026-11-19T14:25:08Z" }, + { id: "gemini-weekly", usedPct: expect.closeTo(30), summary: true }, + { id: "disabled", usedPct: null, remainingPct: null }, + ], + }); +}); + +it("surfaces CLI errors instead of reporting a successful quota", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-")); + directories.push(directory); + const cli = path.join(directory, "cli.cjs"); + await writeFile( + cli, + `console.log(JSON.stringify({ status: 'ERROR', error: 'Authentication required' }));`, + ); + const usage = new Usage(); + const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } }; + const source = usage.registration(); + const [account] = await source.discover({ kind: "global", launch }); + await expect(source.fetch(account!.input)).rejects.toThrow("Authentication required"); +}); + +it("reports a failed CLI without exposing its stderr", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-")); + directories.push(directory); + const cli = path.join(directory, "cli.cjs"); + await writeFile(cli, `process.stderr.write('authentication token=private'); process.exit(1);`); + const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } }; + const source = new Usage().registration(); + const [account] = await source.discover({ kind: "global", launch }); + await expect(source.fetch(account!.input)).rejects.toThrow( + "Antigravity usage command failed or timed out. Check that agy is signed in.", + ); +}); diff --git a/plugins/antigravity-provider/server/usage.ts b/plugins/antigravity-provider/server/usage.ts new file mode 100644 index 000000000000..d0bfc5d005ad --- /dev/null +++ b/plugins/antigravity-provider/server/usage.ts @@ -0,0 +1,120 @@ +import { homedir } from "node:os"; +import path from "node:path"; +import { z } from "zod"; +import { execCommand } from "@getpaseo/plugin/server"; +import type { ProviderLaunch } from "@getpaseo/plugin/server/provider"; +import { + hashAccountKey, + toneFromUsedPct, + unavailable, + windowFromUsedPct, + type UsageSourceRegistration, +} from "@getpaseo/plugin/server/usage"; + +const input = z.object({ launch: z.string() }).strict(); +const response = z.object({ + status: z.string(), + error: z.string().optional(), + response: z.string().optional(), + command: z + .object({ + name: z.literal("usage"), + data: z.object({ + groups: z.array( + z.object({ + name: z.string(), + buckets: z.array( + z.object({ + id: z.string().min(1), + name: z.string(), + window: z.string(), + remaining_fraction: z.number().min(0).max(1).nullish(), + reset_time: z.string().nullish(), + disabled: z.boolean().optional(), + }), + ), + }), + ), + }), + }) + .optional(), +}); + +function accountKey(env: ProviderLaunch["env"]): string { + return hashAccountKey( + path.resolve( + env.ANTIGRAVITY_HOME ?? path.join(env.HOME ?? homedir(), ".gemini", "antigravity-cli"), + ), + ); +} + +export class Usage { + private readonly launches = new Map(); + + registration(): UsageSourceRegistration { + return { + id: "antigravity", + label: "Antigravity", + icon: "icon.svg", + input, + provider: "antigravity", + discover: async (scope) => { + if (scope.kind === "session" && scope.provider !== "antigravity") return []; + if (!scope.launch) return []; + const launch = scope.launch; + const key = accountKey(launch.env); + const locator = hashAccountKey(JSON.stringify(launch)); + this.launches.set(locator, launch); + return [{ key, input: { launch: locator } }]; + }, + fetch: async (value) => { + const { launch: locator } = input.parse(value); + const launch = this.launches.get(locator); + if (!launch) throw new Error("Antigravity launch no longer exists"); + const acpIndex = launch.args.indexOf("acp"); + if (acpIndex < 0) throw new Error("Antigravity launch does not contain the acp subcommand"); + let result; + try { + result = await execCommand( + launch.command, + [...launch.args.slice(0, acpIndex), "-p", "/usage", "--output-format", "json"], + { + env: launch.env, + timeout: 18_000, + maxBuffer: 1024 * 1024, + }, + ); + } catch { + throw new Error( + "Antigravity usage command failed or timed out. Check that agy is signed in.", + ); + } + const data = response.parse(JSON.parse(result.stdout)); + if (data.status !== "SUCCESS") { + throw new Error(data.error || data.response || `agy usage returned ${data.status}`); + } + if (!data.command) throw new Error("agy did not return usage data"); + const windows = data.command.data.groups.flatMap((group) => + group.buckets.flatMap((bucket) => { + if (!bucket.disabled && bucket.remaining_fraction == null) return []; + const used = bucket.disabled ? null : (1 - bucket.remaining_fraction!) * 100; + return [ + windowFromUsedPct({ + id: bucket.id, + label: `${group.name} · ${bucket.name}${bucket.disabled ? " · Disabled" : ""}`, + shortLabel: `${group.name} ${bucket.window}`, + summary: !bucket.disabled && bucket.window === "weekly", + utilizationPct: used, + resetsAt: bucket.disabled ? null : bucket.reset_time, + tone: used === null ? "default" : toneFromUsedPct(used), + }), + ]; + }), + ); + if (windows.length === 0) + return unavailable({ kind: "no_quota", detail: "No usage quota reported by agy" }); + return { status: "available", windows }; + }, + }; + } +} diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index ef50640c3e2e..7494b3b03228 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -504,6 +504,11 @@ offers `updateUrl` on the same terms. `server.registerUsageSource()`. Import its contract and helpers from `@getpaseo/plugin/server/usage`. +A source that needs its plugin's provider command may set `provider` to that provider's ID. +The daemon supplies the resolved launch in `scope.launch` for global discovery and for that +provider's sessions. The launch includes the trusted process environment; keep it daemon-side and +use an opaque store locator as the input. It is absent when the provider is unavailable. + A source implements two calls: ```ts @@ -515,13 +520,20 @@ interface UsageAccount { } type UsageScope = - | { kind: "global" } - | { kind: "session"; provider: string; model?: string; env: Record }; + | { kind: "global"; launch?: ProviderLaunch } + | { + kind: "session"; + provider: string; + model?: string; + env: Record; + launch?: ProviderLaunch; + }; interface UsageSourceRegistration { id: string; label: string; icon?: string; + provider?: string; input: ZodType; discover(scope: UsageScope): Promise; fetch(input: unknown): Promise; From 05fc260b962614f3952755458c6ab84943724441 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 12:13:01 +0700 Subject: [PATCH 012/109] Show OpenRouter credits and spend in Usage (#10269) Show remaining account credits and API-key spend for today, this week, and this month in the host Usage panel and CLI. --- .../src/server/plugins/builtin/index.ts | 1 + .../test-fixtures/usage-proxy-daemon.ts | 10 +- .../server/plugins/usage-sources.e2e.test.ts | 3 + plugins/openrouter-host-usage-source/LICENSE | 21 ++++ plugins/openrouter-host-usage-source/icon.svg | 3 + .../index.server.ts | 15 +++ .../paseo-plugin.json | 1 + .../server/usage.test.ts | 73 ++++++++++++ .../server/usage.ts | 104 ++++++++++++++++++ public-docs/cli.md | 2 + 10 files changed, 231 insertions(+), 2 deletions(-) create mode 100644 plugins/openrouter-host-usage-source/LICENSE create mode 100644 plugins/openrouter-host-usage-source/icon.svg create mode 100644 plugins/openrouter-host-usage-source/index.server.ts create mode 100644 plugins/openrouter-host-usage-source/paseo-plugin.json create mode 100644 plugins/openrouter-host-usage-source/server/usage.test.ts create mode 100644 plugins/openrouter-host-usage-source/server/usage.ts diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index d51f6ee4d803..c49eab905ddd 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -15,6 +15,7 @@ export const builtinPlugins = [ "minimax-usage-source", "muse-provider", "opencode-go-usage-source", + "openrouter-host-usage-source", "worktree-include", "zai-usage-source", ] as const; diff --git a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts index 23364d3fda81..d58c8950aaa2 100644 --- a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts +++ b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts @@ -2,11 +2,17 @@ import path from "node:path"; import { initializeEnvironmentProxy } from "../../network/index.js"; import { DaemonClient } from "../../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js"; -import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js"; +import { + builtinPlugins, + BuiltinPluginLoader, + resolveBuiltinPluginsRoot, +} from "../builtin/index.js"; const mode = process.argv[2]; if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory"); -const sources = ["claude-usage-source", "codex-usage-source"]; +const sources = builtinPlugins.filter((id) => + ["claude-usage-source", "codex-usage-source", "openrouter-host-usage-source"].includes(id), +); // Built-ins run inside the daemon; directory plugins initialize their own subprocess network. if (mode === "builtin") initializeEnvironmentProxy(); const daemon = await createTestPaseoDaemon({ diff --git a/packages/server/src/server/plugins/usage-sources.e2e.test.ts b/packages/server/src/server/plugins/usage-sources.e2e.test.ts index 7c680bda06af..645eee625842 100644 --- a/packages/server/src/server/plugins/usage-sources.e2e.test.ts +++ b/packages/server/src/server/plugins/usage-sources.e2e.test.ts @@ -392,6 +392,8 @@ dns.lookup = function(host, ...args) { HOME: root, USERPROFILE: root, CODEX_HOME: path.join(root, ".codex"), + OPENROUTER_API_KEY: "fixture-openrouter", + OPENROUTER_MANAGEMENT_KEY: "fixture-openrouter-management", CLAUDE_CONFIG_DIR: path.join(root, ".claude"), NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`, https_proxy: `http://127.0.0.1:${address.port}`, @@ -402,6 +404,7 @@ dns.lookup = function(host, ...args) { ); expect(tunnels).toContain("api.anthropic.com:443"); expect(tunnels).toContain("chatgpt.com:443"); + expect(tunnels.filter((target) => target === "openrouter.ai:443")).toHaveLength(2); } finally { proxy.closeAllConnections(); await new Promise((resolve) => proxy.close(() => resolve())); diff --git a/plugins/openrouter-host-usage-source/LICENSE b/plugins/openrouter-host-usage-source/LICENSE new file mode 100644 index 000000000000..3b93b1ab1749 --- /dev/null +++ b/plugins/openrouter-host-usage-source/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Sian Lerk Lau + +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. diff --git a/plugins/openrouter-host-usage-source/icon.svg b/plugins/openrouter-host-usage-source/icon.svg new file mode 100644 index 000000000000..16793e7b0e09 --- /dev/null +++ b/plugins/openrouter-host-usage-source/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/plugins/openrouter-host-usage-source/index.server.ts b/plugins/openrouter-host-usage-source/index.server.ts new file mode 100644 index 000000000000..fa68bc0c61ee --- /dev/null +++ b/plugins/openrouter-host-usage-source/index.server.ts @@ -0,0 +1,15 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { discover, fetchUsage, inputSchema } from "./server/usage.js"; + +export default function contribute(server: PluginServerContext) { + server.registerUsageSource({ + // The marketplace plugin already registers "openrouter". + id: "openrouter-host", + label: "OpenRouter", + icon: "icon.svg", + input: inputSchema, + discover, + fetch: fetchUsage, + }); + return () => {}; +} diff --git a/plugins/openrouter-host-usage-source/paseo-plugin.json b/plugins/openrouter-host-usage-source/paseo-plugin.json new file mode 100644 index 000000000000..da34ffbf59cc --- /dev/null +++ b/plugins/openrouter-host-usage-source/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "openrouter-host-usage-source", "requirements": { "paseo": ">=0.11.0" } } diff --git a/plugins/openrouter-host-usage-source/server/usage.test.ts b/plugins/openrouter-host-usage-source/server/usage.test.ts new file mode 100644 index 000000000000..1db1a45aa92b --- /dev/null +++ b/plugins/openrouter-host-usage-source/server/usage.test.ts @@ -0,0 +1,73 @@ +import { expect, test } from "vitest"; +import { discover, fetchUsage, inputSchema } from "./usage.js"; + +const scope = { kind: "global" } as const; +const env = { + OPENROUTER_API_KEY: " api-key ", + OPENROUTER_MANAGEMENT_KEY: " management-key ", +}; + +const spend = { + usage: 32, + usage_daily: 0.0123, + usage_weekly: 1, + usage_monthly: 8, +}; + +test("discovers only host credentials and returns credential-free inputs", async () => { + expect(await discover(scope, env)).toEqual([ + { key: "key", label: "API key spend", input: { meter: "key" } }, + { key: "credits", label: "Account credits", input: { meter: "credits" } }, + ]); + expect(await discover(scope, { OPENROUTER_API_KEY: " " })).toEqual([]); + expect(await discover({ kind: "session", provider: "pi", env }, env)).toEqual([]); + expect(inputSchema.safeParse({ meter: "key", token: "secret" }).success).toBe(false); +}); + +test("reports spend for the three UTC periods", async () => { + const report = await fetchUsage( + { meter: "key" }, + async (url, init) => { + expect(url).toBe("https://openrouter.ai/api/v1/key"); + expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer api-key"); + expect(init?.redirect).toBe("error"); + return Response.json({ data: spend }); + }, + env, + ); + expect(report).toEqual({ + status: "available", + windows: [], + details: [ + { id: "spend_daily", label: "Spent today (UTC)", value: "$0.0123" }, + { id: "spend_weekly", label: "Spent this week (UTC)", value: "$1.00" }, + { id: "spend_monthly", label: "Spent this month (UTC)", value: "$8.00" }, + ], + }); +}); + +test("uses the management key exclusively for account credits", async () => { + const report = await fetchUsage( + { meter: "credits" }, + async (url, init) => { + expect(url).toBe("https://openrouter.ai/api/v1/credits"); + expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer management-key"); + return Response.json({ data: { total_credits: 15, total_usage: 4 } }); + }, + env, + ); + expect(report).toEqual({ + status: "available", + windows: [], + balances: [{ id: "credits", label: "Credits", remaining: 11, unit: "usd", tone: "ok" }], + }); +}); + +test("reports rejected credentials without including the upstream body", async () => { + const report = await fetchUsage( + { meter: "credits" }, + async () => new Response("sensitive upstream error", { status: 403 }), + env, + ); + expect(report).toEqual({ status: "unavailable", problem: { kind: "rejected", status: 403 } }); +}); diff --git a/plugins/openrouter-host-usage-source/server/usage.ts b/plugins/openrouter-host-usage-source/server/usage.ts new file mode 100644 index 000000000000..78053e7e7f15 --- /dev/null +++ b/plugins/openrouter-host-usage-source/server/usage.ts @@ -0,0 +1,104 @@ +// Adapted from kiawin/paseo-openrouter-usage. See LICENSE. +import { + balanceToneFromRemaining, + unavailable, + type UsageAccount, + type UsageReport, + type UsageScope, +} from "@getpaseo/plugin/server/usage"; +import { z } from "zod"; + +const meters = { + key: { env: "OPENROUTER_API_KEY", label: "API key spend" }, + credits: { env: "OPENROUTER_MANAGEMENT_KEY", label: "Account credits" }, +} as const; + +export const inputSchema = z.strictObject({ meter: z.enum(["key", "credits"]) }); + +const keyResponse = z.object({ + data: z.object({ + usage_daily: z.number(), + usage_weekly: z.number(), + usage_monthly: z.number(), + }), +}); + +const creditsResponse = z.object({ + data: z.object({ total_credits: z.number(), total_usage: z.number() }), +}); + +export async function discover( + scope: UsageScope, + env: NodeJS.ProcessEnv = process.env, +): Promise { + if (scope.kind !== "global") return []; + return inputSchema.shape.meter.options.flatMap((meter) => { + const { env: variable, label } = meters[meter]; + return env[variable]?.trim() ? [{ key: meter, label, input: { meter } }] : []; + }); +} + +export async function fetchUsage( + value: unknown, + fetchApi: typeof fetch = fetch, + env: NodeJS.ProcessEnv = process.env, +): Promise { + const { meter } = inputSchema.parse(value); + const variable = meters[meter].env; + const token = env[variable]?.trim(); + if (!token) throw new Error(`OpenRouter usage requires ${variable}`); + + const response = await fetchApi(`https://openrouter.ai/api/v1/${meter}`, { + headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }, + redirect: "error", + signal: AbortSignal.timeout(15_000), + }); + if (response.status === 401 || response.status === 403) { + return unavailable({ kind: "rejected", status: response.status }); + } + if (!response.ok) throw new Error(`OpenRouter usage API returned ${response.status}`); + + const body: unknown = await response.json(); + return meter === "key" + ? keyReport(keyResponse.parse(body).data) + : creditsReport(creditsResponse.parse(body).data); +} + +const usd = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + maximumFractionDigits: 4, +}); + +function keyReport(key: z.infer["data"]): UsageReport { + return { + status: "available", + windows: [], + details: [ + { id: "spend_daily", label: "Spent today (UTC)", value: usd.format(key.usage_daily) }, + { id: "spend_weekly", label: "Spent this week (UTC)", value: usd.format(key.usage_weekly) }, + { + id: "spend_monthly", + label: "Spent this month (UTC)", + value: usd.format(key.usage_monthly), + }, + ], + }; +} + +function creditsReport(credits: z.infer["data"]): UsageReport { + const remaining = credits.total_credits - credits.total_usage; + return { + status: "available", + windows: [], + balances: [ + { + id: "credits", + label: "Credits", + remaining, + unit: "usd", + tone: balanceToneFromRemaining(remaining), + }, + ], + }; +} diff --git a/public-docs/cli.md b/public-docs/cli.md index 99e4d4c32ac2..9ec7b659ed40 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -44,6 +44,8 @@ Copy the full report ID from the list into `inspect` to see reset times, balance Queries use the host's five-minute cache when available. Add `--refresh` to bypass it. Use `--host` or `--home` to [select a daemon](#select-one-daemon). Hosts without usage-source support return an update message. +For OpenRouter, set `OPENROUTER_API_KEY` in the daemon’s environment to show what the key spent today, this week, and this month in UTC. Set `OPENROUTER_MANAGEMENT_KEY` to show the remaining account credits. Each variable adds its own report to the host’s Usage panel and `paseo usage`. + ### Usage in scripts ```bash From 66f764eefddd4403d08702624f47a97b0a879bf7 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 12:19:58 +0700 Subject: [PATCH 013/109] chore(brand): add Paseo and Paseo Hub marks, lockups, and font (#10270) --- assets/brand/README.md | 63 ++++++++ assets/brand/build.mjs | 146 ++++++++++++++++++ assets/brand/fonts/OFL.txt | 93 +++++++++++ .../brand/fonts/PlusJakartaSans-SemiBold.ttf | Bin 0 -> 129288 bytes assets/brand/lockups/hub-black.svg | 4 + assets/brand/lockups/hub-white.svg | 4 + assets/brand/lockups/paseo-black.svg | 4 + assets/brand/lockups/paseo-hub-black.svg | 4 + assets/brand/lockups/paseo-hub-white.svg | 4 + assets/brand/lockups/paseo-white.svg | 4 + assets/brand/marks/paseo-black.svg | 3 + assets/brand/marks/paseo-green.svg | 3 + assets/brand/marks/paseo-hub-black.svg | 3 + assets/brand/marks/paseo-hub-green.svg | 3 + assets/brand/marks/paseo-hub-white.svg | 3 + assets/brand/marks/paseo-white.svg | 3 + 16 files changed, 344 insertions(+) create mode 100644 assets/brand/README.md create mode 100644 assets/brand/build.mjs create mode 100644 assets/brand/fonts/OFL.txt create mode 100644 assets/brand/fonts/PlusJakartaSans-SemiBold.ttf create mode 100644 assets/brand/lockups/hub-black.svg create mode 100644 assets/brand/lockups/hub-white.svg create mode 100644 assets/brand/lockups/paseo-black.svg create mode 100644 assets/brand/lockups/paseo-hub-black.svg create mode 100644 assets/brand/lockups/paseo-hub-white.svg create mode 100644 assets/brand/lockups/paseo-white.svg create mode 100644 assets/brand/marks/paseo-black.svg create mode 100644 assets/brand/marks/paseo-green.svg create mode 100644 assets/brand/marks/paseo-hub-black.svg create mode 100644 assets/brand/marks/paseo-hub-green.svg create mode 100644 assets/brand/marks/paseo-hub-white.svg create mode 100644 assets/brand/marks/paseo-white.svg diff --git a/assets/brand/README.md b/assets/brand/README.md new file mode 100644 index 000000000000..805b84a0544a --- /dev/null +++ b/assets/brand/README.md @@ -0,0 +1,63 @@ +# Brand assets + +Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work. + +## Brand architecture + +- **Paseo** (butterfly mark): the local client, daemon, CLI, SDK, and small account features (sign-in, share links, tunnels). +- **Paseo Hub** (flower mark): the software factory, team features, hosted service, and paid plans (`Hub Free`, `Hub Solo`, `Hub Team`). +- **Hub** (flower mark + `Hub`): used only where Paseo is already on screen, such as inside the Hub dashboard header. + +## Specifications + +### Marks + +Both marks are single-line stroked paths on a `700 × 700` viewBox with `stroke-width="50"`, `stroke-linecap="round"`, and `stroke-linejoin="round"`. Both are optically centered to a `527`-unit ink footprint: + +- **Paseo (`marks/paseo-*.svg`)**: refit of the hand-drawn butterfly (redraw B) with smooth curvature on the large wing and lower loop and a uniform `50` stroke width. +- **Paseo Hub (`marks/paseo-hub-*.svg`)**: five-petal looped flower (variant A) with a `12°` clockwise petal lean, sized up to match the butterfly's `527` footprint with the same `50` stroke. + +Colors: + +- `white` (`#FFFFFF`) for dark surfaces (`#101615`, `#101010`, `#000000`) +- `black` (`#000000`) for light surfaces +- `green` (`#20744A`) brand accent + +### Lockups + +All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink height with a `2`-unit margin on all sides) so stacked lockups align cleanly: + +- **Font**: Plus Jakarta Sans SemiBold (`600`), bundled in `fonts/PlusJakartaSans-SemiBold.ttf` under the SIL Open Font License 1.1 (`fonts/OFL.txt`). +- **Outlined text**: lockup SVGs outline the wordmark to `` elements so they render identically everywhere without the font installed. +- **Proportions**: marks are `15%` larger against text and `20%` closer than the original website header baseline (`24 px` box, `12 px` gap, `18 px` text). +- **Optical balance**: in the `paseo` lockup, the butterfly is scaled to `94%` (`stroke-width` proportional) so `Paseo`, `Paseo Hub`, and `Hub` sit at equal visual weight when shown together. + +## Files + +```text +assets/brand/ + build.mjs Regenerates all marks and lockups + fonts/ + PlusJakartaSans-SemiBold.ttf + OFL.txt + marks/ + paseo-white.svg + paseo-black.svg + paseo-green.svg + paseo-hub-white.svg + paseo-hub-black.svg + paseo-hub-green.svg + lockups/ + paseo-white.svg + paseo-black.svg + paseo-hub-white.svg + paseo-hub-black.svg + hub-white.svg + hub-black.svg +``` + +## Regenerate + +```sh +node assets/brand/build.mjs +``` diff --git a/assets/brand/build.mjs b/assets/brand/build.mjs new file mode 100644 index 000000000000..4bc84ca54090 --- /dev/null +++ b/assets/brand/build.mjs @@ -0,0 +1,146 @@ +// Generates the canonical Paseo and Paseo Hub brand marks and lockup SVGs. +// +// node assets/brand/build.mjs +// +// Marks are single-line stroked paths on a 700x700 viewBox (stroke-width 50, +// round caps and joins, centered to a 527-unit ink footprint). Lockups outline +// Plus Jakarta Sans SemiBold to SVG paths so every file is self-contained. + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { loadSync } from "opentype.js"; + +const root = path.dirname(fileURLToPath(import.meta.url)); +const marksDir = path.join(root, "marks"); +const lockupsDir = path.join(root, "lockups"); +const fontPath = path.join(root, "fonts", "PlusJakartaSans-SemiBold.ttf"); + +const VIEWBOX = 700; +const STROKE = 50; +const FOOTPRINT = 527; + +// Lockup proportions relative to the original website header (24px box, 12px gap, 18px text): +// - marks are 15% larger against text +// - ink-to-text gap is 20% tighter +// - butterfly is undersized by 6% in lockups so Paseo, Paseo Hub, and Hub read as one family +const MARK_SCALE = 1.15; +const GAP_SCALE = 0.8; +const BUTTERFLY_LOCKUP_SCALE = 0.94; + +// Lockup coordinate system: flower ink spans 140 units with a 2-unit margin on all sides (height 144). +const LOCKUP_INK = 140; +const LOCKUP_PAD = 2; +const LOCKUP_HEIGHT = LOCKUP_INK + LOCKUP_PAD * 2; + +const MARK_COLORS = [ + { name: "white", hex: "#FFFFFF" }, + { name: "black", hex: "#000000" }, + { name: "green", hex: "#20744A" }, +]; + +const LOCKUP_COLORS = [ + { name: "white", hex: "#FFFFFF" }, + { name: "black", hex: "#000000" }, +]; + +// Paseo butterfly mark (redraw B): smoothed centreline of the original mark, centered in 700x700. +const PASEO_MARK_PATH = + "M456.84 526.11C462.73 521.72 467.57 517.89 471.79 514.38C476.02 510.88 479.65 507.69 483.14 504.58C486.63 501.46 489.94 498.44 493.24 495.35C496.54 492.27 499.85 489.11 503.26 485.77C506.67 482.44 510.16 478.96 513.7 475.36C517.23 471.76 520.81 468.03 524.4 464.2C527.99 460.37 531.59 456.44 535.18 452.41C538.77 448.39 542.36 444.27 545.89 440.08C549.42 435.9 552.88 431.65 556.23 427.37C559.58 423.08 562.81 418.77 565.83 414.39C568.86 410.01 571.68 405.57 574.2 401.02C576.72 396.48 578.95 391.82 580.73 387C582.5 382.18 583.83 377.16 584.55 371.94C585.27 366.73 585.37 361.37 584.63 356.15C583.9 350.93 582.28 345.83 579.74 341.22C577.21 336.62 573.83 332.53 569.82 329.45C565.81 326.37 561.14 324.38 556.21 323.54C551.28 322.69 546.1 322.94 541.16 324.13C536.22 325.32 531.58 327.49 527.2 330.24C522.82 332.99 518.68 336.32 514.69 339.8C510.7 343.27 506.85 346.9 503.11 350.61C499.36 354.32 495.71 358.12 492.11 361.94C488.51 365.76 484.97 369.62 481.47 373.49C477.98 377.37 474.53 381.27 471.12 385.19C467.71 389.11 464.33 393.05 460.99 397C457.65 400.94 454.33 404.9 451.04 408.87C447.74 412.83 444.47 416.8 441.21 420.78C437.95 424.75 434.7 428.73 431.46 432.71C428.22 436.69 424.98 440.68 421.74 444.67C418.5 448.66 415.27 452.66 412.02 456.67C408.78 460.68 405.52 464.69 402.26 468.72C398.99 472.75 395.71 476.78 392.41 480.83C389.11 484.88 385.78 488.95 382.42 493.02C379.06 497.09 375.66 501.16 372.22 505.23C368.78 509.3 365.28 513.37 361.73 517.41C358.17 521.45 354.55 525.46 350.85 529.41C347.14 533.36 343.36 537.24 339.47 541.02C335.59 544.8 331.62 548.47 327.54 551.97C323.45 555.47 319.27 558.81 314.98 561.93C310.68 565.05 306.29 567.97 301.8 570.62C297.31 573.28 292.72 575.68 288.04 577.8C283.37 579.92 278.61 581.75 273.79 583.28C268.96 584.81 264.07 586.03 259.14 586.93C254.2 587.83 249.23 588.4 244.24 588.64C239.25 588.88 234.24 588.79 229.26 588.36C224.28 587.93 219.32 587.16 214.42 586.06C209.51 584.95 204.67 583.52 199.91 581.77C195.16 580.01 190.5 577.94 185.97 575.56C181.45 573.19 177.05 570.51 172.82 567.55C168.58 564.59 164.52 561.36 160.64 557.87C156.77 554.39 153.09 550.65 149.64 546.7C146.19 542.75 142.95 538.58 139.97 534.23C136.98 529.88 134.23 525.34 131.75 520.67C129.27 515.99 127.04 511.16 125.09 506.23C123.15 501.3 121.47 496.26 120.08 491.16C118.69 486.05 117.57 480.88 116.75 475.67C115.93 470.47 115.39 465.24 115.14 460.02C114.89 454.79 114.93 449.58 115.26 444.41C115.58 439.24 116.2 434.12 117.1 429.08C117.99 424.04 119.18 419.08 120.64 414.24C122.11 409.4 123.86 404.67 125.88 400.08C127.91 395.49 130.21 391.05 132.78 386.77C135.36 382.5 138.21 378.39 141.32 374.47C144.44 370.55 147.83 366.82 151.47 363.3C155.12 359.77 159.03 356.47 163.19 353.41C167.35 350.36 171.76 347.55 176.39 345.05C181.03 342.55 185.88 340.35 190.91 338.52C195.94 336.7 201.17 335.24 206.49 334.19C211.82 333.15 217.24 332.51 222.68 332.31C228.11 332.12 233.55 332.37 238.92 333.01C244.29 333.66 249.59 334.71 254.75 336.09C259.91 337.48 264.92 339.21 269.75 341.29C274.58 343.36 279.23 345.78 283.63 348.53C288.04 351.29 292.18 354.4 295.95 357.9C299.71 361.39 303.1 365.29 305.97 369.58C308.84 373.86 311.2 378.51 312.91 383.42C314.62 388.32 315.66 393.52 315.96 398.78C316.25 404.03 315.8 409.35 314.55 414.46C313.3 419.57 311.22 424.48 308.43 428.88C305.64 433.29 302.15 437.19 298.08 440.28C294.02 443.37 289.39 445.66 284.5 447.04C279.61 448.43 274.47 448.92 269.39 448.45C264.3 447.98 259.26 446.59 254.46 444.51C249.67 442.43 245.14 439.66 241.03 436.43C236.91 433.2 233.16 429.52 229.72 425.64C226.28 421.76 223.16 417.73 220.26 413.65C217.37 409.57 214.68 405.42 212.07 401.22C209.46 397.01 206.9 392.76 204.38 388.43C201.85 384.1 199.36 379.71 196.91 375.21C194.46 370.72 192.05 366.13 189.7 361.45C187.35 356.76 185.06 351.99 182.86 347.13C180.67 342.28 178.57 337.34 176.57 332.32C174.57 327.31 172.68 322.22 170.91 317.07C169.13 311.91 167.48 306.69 165.96 301.42C164.44 296.14 163.05 290.8 161.8 285.42C160.55 280.03 159.45 274.6 158.51 269.13C157.57 263.67 156.78 258.17 156.18 252.66C155.58 247.15 155.16 241.62 154.94 236.11C154.72 230.6 154.7 225.1 154.91 219.65C155.11 214.2 155.54 208.8 156.21 203.47C156.89 198.15 157.8 192.91 158.98 187.8C160.16 182.69 161.59 177.71 163.3 172.9C165.01 168.09 166.99 163.45 169.24 159.04C171.49 154.63 174.02 150.44 176.81 146.52C179.61 142.61 182.67 138.96 185.98 135.62C189.29 132.28 192.85 129.25 196.64 126.57C200.42 123.89 204.43 121.55 208.62 119.57C212.82 117.59 217.2 115.98 221.73 114.74C226.26 113.5 230.93 112.62 235.71 112.12C240.49 111.61 245.36 111.47 250.3 111.67C255.24 111.87 260.23 112.42 265.24 113.28C270.25 114.15 275.28 115.34 280.29 116.8C285.31 118.27 290.3 120.03 295.25 122.03C300.2 124.03 305.1 126.28 309.94 128.74C314.77 131.2 319.54 133.87 324.23 136.72C328.91 139.56 333.51 142.59 338.01 145.76C342.52 148.93 346.93 152.24 351.24 155.68C355.54 159.11 359.75 162.67 363.85 166.33C367.95 169.99 371.94 173.74 375.82 177.59C379.7 181.43 383.47 185.36 387.13 189.37C390.78 193.37 394.32 197.46 397.74 201.61C401.16 205.76 404.46 209.99 407.63 214.28C410.8 218.57 413.84 222.93 416.75 227.36C419.66 231.79 422.42 236.28 425.04 240.84C427.66 245.4 430.14 250.03 432.45 254.72C434.76 259.41 436.91 264.16 438.88 268.98C440.86 273.79 442.66 278.66 444.27 283.59C445.89 288.51 447.31 293.49 448.54 298.51C449.77 303.53 450.8 308.59 451.62 313.68C452.45 318.77 453.06 323.89 453.46 329.02C453.86 334.15 454.05 339.29 454.02 344.42C454 349.55 453.75 354.67 453.29 359.76C452.83 364.85 452.16 369.91 451.27 374.92C450.39 379.92 449.29 384.88 447.98 389.76C446.68 394.64 445.17 399.44 443.46 404.15C441.75 408.87 439.85 413.49 437.75 418C435.65 422.51 433.38 426.88 430.83 431.24C428.27 435.6 425.41 439.96 422.06 444.51C418.7 449.06 414.7 453.93 410.99 458.32C407.29 462.71 403.92 466.59 401.91 469.1"; + +// Paseo Hub flower mark (5-petal A, 12 deg clockwise lean): scaled to the butterfly's 527 footprint. +const PASEO_HUB_MARK_PATH = + "M389.47 112.65C383.85 111.46 377.9 111.12 371.85 111.7C365.8 112.28 359.66 113.78 353.67 116.15C347.7 118.52 341.89 121.77 336.47 125.79C331.07 129.81 326.07 134.6 321.7 139.98C317.32 145.37 313.55 151.35 310.53 157.69C307.52 164.02 305.25 170.72 303.79 177.54C302.32 184.35 301.67 191.27 301.77 198.07C301.87 204.87 302.75 211.54 304.28 217.89C305.8 224.25 307.98 230.28 310.66 235.86C313.33 241.46 316.5 246.6 319.96 251.26C323.43 255.92 327.19 260.09 331.07 263.82C334.95 267.53 338.95 270.81 342.89 273.74C346.84 276.67 350.75 279.26 354.51 281.62C358.27 283.98 361.88 286.13 365.3 288.2C368.7 290.29 371.92 292.29 374.95 294.34C377.98 296.38 380.81 298.49 383.54 300.73C386.26 302.97 388.87 305.36 391.48 307.96C394.08 310.55 396.69 313.35 399.42 316.37C402.14 319.4 404.99 322.65 408.09 326.09C411.18 329.51 414.51 333.14 418.18 336.89C421.83 340.63 425.82 344.49 430.16 348.36C434.5 352.22 439.2 356.09 444.25 359.82C449.31 363.56 454.71 367.15 460.41 370.46C466.11 373.77 472.11 376.79 478.3 379.39C484.49 381.98 490.9 384.15 497.37 385.76C503.83 387.38 510.38 388.43 516.83 388.85C523.28 389.26 529.64 389.03 535.73 388.12C541.83 387.2 547.65 385.6 553.03 383.33C558.4 381.05 563.31 378.09 567.59 374.55C571.88 370.99 575.53 366.83 578.41 362.22C581.28 357.6 583.38 352.5 584.59 347.13C585.79 341.76 586.13 336.1 585.52 330.39C584.92 324.69 583.4 318.92 580.98 313.34C578.55 307.78 575.24 302.4 571.14 297.43C567.03 292.48 562.15 287.96 556.66 284.06C551.16 280.16 545.05 276.89 538.59 274.39C532.11 271.89 525.27 270.15 518.3 269.24C511.34 268.33 504.27 268.24 497.34 268.96C490.4 269.67 483.61 271.19 477.18 273.38C470.75 275.58 464.67 278.47 459.11 281.9C453.53 285.31 448.47 289.25 443.98 293.52C439.49 297.79 435.58 302.39 432.22 307.12C428.86 311.86 426.05 316.73 423.71 321.56C421.37 326.41 419.49 331.22 417.92 335.88C416.36 340.55 415.11 345.06 414.03 349.37C412.93 353.67 412.01 357.78 411.09 361.66C410.16 365.55 409.26 369.22 408.24 372.73C407.23 376.24 406.11 379.59 404.82 382.87C403.52 386.16 402.06 389.38 400.4 392.66C398.73 395.94 396.87 399.28 394.84 402.81C392.81 406.34 390.6 410.05 388.29 414.05C385.98 418.06 383.56 422.36 381.13 426.99C378.7 431.63 376.26 436.6 373.93 441.93C371.59 447.26 369.37 452.92 367.38 458.88C365.4 464.83 363.64 471.09 362.26 477.53C360.86 483.98 359.84 490.61 359.29 497.31C358.73 504 358.66 510.76 359.12 517.41C359.58 524.06 360.6 530.6 362.2 536.87C363.81 543.13 365.99 549.12 368.74 554.63C371.49 560.14 374.82 565.19 378.64 569.59C382.47 574 386.78 577.76 391.49 580.73C396.2 583.71 401.28 585.9 406.55 587.21C411.84 588.51 417.33 588.93 422.82 588.42C428.3 587.91 433.78 586.48 439.02 584.14C444.26 581.81 449.28 578.57 453.82 574.54C458.38 570.53 462.47 565.7 465.92 560.28C469.36 554.84 472.16 548.79 474.17 542.37C476.18 535.93 477.4 529.12 477.78 522.19C478.16 515.26 477.69 508.22 476.41 501.32C475.13 494.41 473.02 487.66 470.2 481.29C467.38 474.91 463.85 468.93 459.76 463.49C455.68 458.04 451.05 453.17 446.08 448.92C441.11 444.68 435.8 441.08 430.35 438.14C424.9 435.18 419.32 432.88 413.78 431.15C408.24 429.41 402.74 428.25 397.41 427.52C392.08 426.79 386.92 426.48 382.01 426.44C377.09 426.4 372.41 426.6 367.98 426.9C363.55 427.2 359.36 427.58 355.38 427.9C351.41 428.23 347.63 428.5 343.97 428.62C340.32 428.74 336.8 428.72 333.27 428.5C329.75 428.29 326.23 427.89 322.59 427.32C318.96 426.75 315.2 426.01 311.23 425.17C307.24 424.32 303.03 423.38 298.51 422.42C293.98 421.45 289.15 420.48 283.99 419.61C278.84 418.72 273.35 417.94 267.56 417.37C261.78 416.79 255.7 416.43 249.41 416.38C243.14 416.33 236.65 416.6 230.09 417.26C223.53 417.94 216.9 419.01 210.37 420.56C203.83 422.1 197.38 424.11 191.19 426.61C185.02 429.11 179.11 432.1 173.64 435.56C168.18 439.01 163.16 442.94 158.77 447.26C154.38 451.58 150.61 456.29 147.61 461.3C144.6 466.3 142.35 471.57 140.98 476.96C139.59 482.36 139.08 487.87 139.48 493.29C139.86 498.73 141.16 504.07 143.34 509.13C145.52 514.19 148.57 518.96 152.42 523.22C156.27 527.49 160.89 531.25 166.12 534.34C171.35 537.43 177.19 539.83 183.43 541.42C189.66 543.02 196.27 543.81 203.01 543.73C209.75 543.66 216.6 542.72 223.32 540.94C230.02 539.16 236.58 536.53 242.75 533.18C248.92 529.83 254.69 525.74 259.87 521.09C265.06 516.43 269.67 511.22 273.58 505.66C277.49 500.1 280.71 494.19 283.2 488.15C285.7 482.11 287.49 475.95 288.6 469.85C289.72 463.76 290.19 457.74 290.13 451.93C290.06 446.13 289.47 440.54 288.52 435.25C287.57 429.96 286.26 424.96 284.79 420.27C283.32 415.58 281.66 411.19 280.02 407.07C278.36 402.94 276.71 399.09 275.16 395.4C273.63 391.72 272.21 388.2 270.96 384.77C269.72 381.34 268.65 377.96 267.77 374.55C266.88 371.13 266.17 367.66 265.59 364.03C265.01 360.4 264.55 356.61 264.12 352.56C263.69 348.51 263.29 344.21 262.81 339.61C262.32 335.01 261.77 330.11 261 324.94C260.24 319.76 259.28 314.29 258.05 308.62C256.8 302.93 255.28 297.05 253.38 291.05C251.48 285.07 249.23 278.98 246.56 272.95C243.9 266.92 240.83 260.95 237.34 255.21C233.85 249.46 229.94 243.95 225.66 238.85C221.37 233.74 216.7 229.04 211.72 224.92C206.75 220.79 201.47 217.23 196.01 214.39C190.54 211.55 184.89 209.42 179.2 208.1C173.52 206.79 167.81 206.29 162.25 206.64C156.7 207 151.3 208.21 146.25 210.26C141.22 212.31 136.52 215.19 132.38 218.84C128.25 222.47 124.66 226.85 121.79 231.82C118.92 236.8 116.77 242.35 115.45 248.28C114.13 254.22 113.66 260.52 114.07 266.94C114.47 273.36 115.77 279.9 117.91 286.28C120.07 292.66 123.08 298.89 126.85 304.73C130.61 310.55 135.14 315.98 140.23 320.81C145.33 325.63 151 329.86 157.03 333.36C163.06 336.86 169.44 339.62 175.94 341.63C182.44 343.63 189.04 344.85 195.57 345.37C202.08 345.87 208.49 345.67 214.62 344.85C220.77 344.04 226.65 342.61 232.15 340.76C237.65 338.9 242.77 336.61 247.52 334.08C252.26 331.53 256.61 328.75 260.62 325.9C264.61 323.05 268.28 320.12 271.69 317.28C275.11 314.43 278.27 311.67 281.3 309.06C284.33 306.46 287.22 304.02 290.1 301.77C292.99 299.53 295.85 297.48 298.83 295.59C301.81 293.68 304.89 291.94 308.17 290.27C311.44 288.59 314.91 286.98 318.63 285.31C322.35 283.66 326.31 281.95 330.53 280.07C334.76 278.19 339.24 276.14 343.93 273.82C348.62 271.49 353.52 268.9 358.54 265.97C363.56 263.02 368.68 259.75 373.8 256.09C378.91 252.44 384 248.42 388.91 244.02C393.82 239.62 398.55 234.85 402.93 229.76C407.32 224.67 411.35 219.25 414.88 213.6C418.41 207.94 421.44 202.05 423.83 196.05C426.21 190.03 427.96 183.92 428.97 177.84C429.99 171.76 430.26 165.73 429.76 159.92C429.25 154.11 427.97 148.52 425.91 143.34C423.86 138.18 421.05 133.42 417.53 129.25C414.03 125.09 409.83 121.52 405.09 118.71C400.35 115.9 395.08 113.84 389.47 112.65Z"; + +const round = (value) => Number(value.toFixed(2)); + +function transformPath(d, scale, offsetX, offsetY) { + let index = 0; + return d.replace(/-?\d+(?:\.\d+)?/g, (token) => { + const value = Number.parseFloat(token); + const out = index % 2 === 0 ? offsetX + value * scale : offsetY + value * scale; + index += 1; + return String(round(out)); + }); +} + +function renderMarkSvg(d, color) { + return [ + ``, + ` `, + "", + "", + ].join("\n"); +} + +function renderLockupSvg({ font, markPath, markFactor, label, color }) { + const emptyShare = (VIEWBOX - FOOTPRINT) / 2 / VIEWBOX; + const headerBoxEm = (24 / 18) * MARK_SCALE; + const flowerInkEm = headerBoxEm * (FOOTPRINT / VIEWBOX); + const visibleGapEm = GAP_SCALE * (12 / 18 + (24 / 18) * emptyShare); + + const fontSize = LOCKUP_INK / flowerInkEm; + const markCenter = LOCKUP_PAD + LOCKUP_INK / 2; + const unitScale = (LOCKUP_INK / FOOTPRINT) * markFactor; + const markOffset = markCenter - (VIEWBOX / 2) * unitScale; + const bakedMark = transformPath(markPath, unitScale, markOffset, markOffset); + const strokeWidth = round(STROKE * unitScale); + + // Baseline matches CSS display:flex; align-items:center; line-height:1 for Plus Jakarta Sans. + const ascender = (font.ascender / font.unitsPerEm) * fontSize; + const descender = (font.descender / font.unitsPerEm) * fontSize; + const halfLeading = (fontSize - (ascender - descender)) / 2; + const baselineY = markCenter - fontSize / 2 + halfLeading + ascender; + + const textOriginX = LOCKUP_PAD + LOCKUP_INK + visibleGapEm * fontSize; + const textPath = font.getPath(label, textOriginX, baselineY, fontSize); + const bounds = textPath.getBoundingBox(); + const width = Math.ceil(bounds.x2 + LOCKUP_PAD); + + return [ + ``, + ` `, + ` `, + "", + "", + ].join("\n"); +} + +function build() { + mkdirSync(marksDir, { recursive: true }); + mkdirSync(lockupsDir, { recursive: true }); + + const font = loadSync(fontPath); + + const marks = [ + { slug: "paseo", d: PASEO_MARK_PATH }, + { slug: "paseo-hub", d: PASEO_HUB_MARK_PATH }, + ]; + + for (const mark of marks) { + for (const color of MARK_COLORS) { + const file = path.join(marksDir, `${mark.slug}-${color.name}.svg`); + writeFileSync(file, renderMarkSvg(mark.d, color.hex)); + } + } + + const lockups = [ + { + slug: "paseo", + markPath: PASEO_MARK_PATH, + markFactor: BUTTERFLY_LOCKUP_SCALE, + label: "Paseo", + }, + { slug: "paseo-hub", markPath: PASEO_HUB_MARK_PATH, markFactor: 1, label: "Paseo Hub" }, + { slug: "hub", markPath: PASEO_HUB_MARK_PATH, markFactor: 1, label: "Hub" }, + ]; + + for (const lockup of lockups) { + for (const color of LOCKUP_COLORS) { + const file = path.join(lockupsDir, `${lockup.slug}-${color.name}.svg`); + writeFileSync(file, renderLockupSvg({ font, ...lockup, color: color.hex })); + } + } +} + +build(); diff --git a/assets/brand/fonts/OFL.txt b/assets/brand/fonts/OFL.txt new file mode 100644 index 000000000000..ea69b0ca12a0 --- /dev/null +++ b/assets/brand/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/brand/fonts/PlusJakartaSans-SemiBold.ttf b/assets/brand/fonts/PlusJakartaSans-SemiBold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c12d4b0e72bde4d78af22aa73184024d2495bef3 GIT binary patch literal 129288 zcmdqK34B%6wLiZ1Ip^M+iOe^1Ztl&^JOP(OZ1R*2{$UF&%2skiE z)lwX4mHO-jhf+%|RUft1N3FHiQtP8=ty*iX)3a7`|KGLux%Zx%LEGQI|NrOx|Ix!a zXYF;?UVH7e*Is+=;WEw`i@-k`3vZZOS6>!8;TFd4Sr6z-4Q(@KN3`|KW&E3sjMaxW z%)Yv&CAH~U#@}pb%=+kz*<%aO{b9i%WBeHKI~T3&>i_Y;!yhviy_d0oJ&V?@v73LE zI*+m3caXkyN&nK7-DCMy#*)Js3k_M?b$vhJ;mD8f0ZUhGSn^12NHAk1k25~LbJ^mq zp47&e`$0bm>7~m62zcG1;r%MSr!8B#X8q>SKNjQtbH*YMu2{9GD?H=Jpq00bvB2h) zUF-Wz{}UFCbSjU%uWRMv@BHxD|6zP7V5ax_S6#nm)7Gr38DELyv8(!5FYe!Y-;xUO zOZokrk!+O6eCtiYA1@56`jmyKR1Wt0Q+aW8zx16$_qeZdn@s)MMZB7sLQwpXI78j3 z$m6v8nk)NF{eqHA6aQ-W3!Dd7JF~Dk%!Ds<*j#o1iTguCn2J@RXRJlu z`2v>3>kOpWy^Oi5S?4AX?5Y_pGuSyc<{ygALpblTGk%EDm1N~z-0VzMwzDebaTfgl z^rilu1=EFmTGc>SHrl29k+quASS#IeMeFxg?T7k%2k!s;RrN36wyMRfOlbsv`QR^> z6{v~0|C^qbH^BEB?l0w?o>?mo$MqB|QI7bYdAR!mU{2g$!aW`L9sDWxtGK^OxVZm8 z-dVH%-TjvS96%2T)-pA%WDwiYnlhh8f9 z7qD)YsV;}ya4ByBzgOPr*?6h14SDZ_eE%0*+RLc-J>YFOtM~Au9K`$WxJJKELVCrh z={G^X|Kw#F1Ken|jnS^>S%dNlc=>nS|4XOy&))y<mpc|L@(7@+F{r3F7|0ynO15ERQbbIIB?>;6B=Q9C(cak8s5W+mfdoz_s}Q zyBEKMCDNtbiZcAWuV%>9d%53Jnmv~v{8_;D%LiwlvKpSrQrYj&Z$yE|WcV2RGy9$U zF&^dqGwx5|{sHbwaQ_zW&jXj^eje|Gz#mKBf>xEd|IYn0J$+Dr_t5z@-pAm(%eW`t zPIUjm-(@xIQ};Rcw)-5nx-WU3Q;@fWKhE*2l!5Odm*77cWx!>8=HCKLzW|R!y1ecN zT)zar$>5nT$-`xy4BqHk$Q+(ay_409bP1VX?USYQfB39U27S~Y-AAR_&L(*4nA*bs zyH`B&qsuQ}EgSFDp3k#Xai{irp5^i7knt*9_rQ1Xe~tq@4sZwHk$8@jIPMqtDqQ!t ze+76I;8ps!F?f!_a|&OMI$4G59%h5+dD7@UM!$@( z1jxPYU%XO)@45c9Z?__^f5-K&^Zc*znSnlg?(j>AWg$uh`fbnEf%15s>Hfdqo&N@- z*ddo1&l1)5SfUmR8{Lg-4{YI2pv&(=r>{df;e$fQ6O0slP9OhJRVC8roi*c9(S1zt1T$#91a24Px)vsdQi}{@_jmM%LT*Kn|5*Eu3Fgw~n z3h!jed0NwYHZyEAE zfqef1`TiF9x{&V!$ae?QpJkci`JcpN-@{lD7ypDY8u_AZ3}s^Mzi{Q?qCZN%hOOa^ zY@xWXVr!H?T>=OA>|@BR7r1lgPujBgLJLY1x)7~jxkX7&6En*#sdq22@k`)-VtaMv`z zOl$$4$2Kd0Y%{-3UKm$YDz`w_PO%oXjpb>-z&CP?F2>H}U(xtkL7Et2ti!v;k|2*v z8m}t%1O9V7&&BiY(9ff|XzcJM?(gfDi)Cswws{2C9k>XO#vfL+hZDMQ9>NwVMbP7a zuui%Z1$FyAYY@*N>{>p^u2tyn#s#=?h1F;U=o>uvI{}kdC+>7D)UTm%Px`e;r|UZX z@;rO+8v&n#i{9zpt=`Y(tNkb^WG~t=wdW@2*iqJ?J_*=`?sF{)yLr zvMkC;;NB13KgHPie)NYYSs(8Gc(>p_ODkcMl^?M-^(9t?%c8EweLZvP_p8(aybrKN z>RqUFx|Xscy3h|)sefRb#dS3+R=MM{~{q5M?&y{f4pYM2_SCaP&_mRg{W zR}ZTXtLH)|+X8K2wpd%T&0$No<=V#D%50UkCfjV=HMU;cD%&R8ZriQ4L$*6@$8CSN ztM*`fxZP?`u-ojZ_6++tdy##DeX70RzQMlLezX0c{a*V6_DAhc*q^fh*b(K3ailsj z90iW6919%ZaGZ2Jma3$hQ^QgtQ?029skYSI)W+1#)WzxdrazYc{q!HD|0MmV=|4~Z zMTR*yG&lSoirbB{jzMg09Gk#Sut#~bDB}tKJ^mbjo4?1uP;!)UqKxO2*HosOQN{?A z(Wz$ml`+5;VvDvV+3dD7TaK;3R%)AItFcY9&9g1At+1`PZMPk?-66_&!mijYC}X5O z&Yonqi!v74D?}OB*f-j@+xMZ2_uC(|pR%8^pEZE|k%PGDe_`@!m4_ zq@PGXo&IF{+4OVi=hI(68BL;$-0fC(qmrXgQt>zVxH84_?76%D=)Qr!D&P28zJ{;h zi+K-U$gg!j;y&iy`RNf4=2zd}a$c@w?9H3s-18l5@D&uYN=YTHmc3)H1(i*m|%b&R*$O>%IBf~ zs`nu60rjN%i2A7NQctUot52$D)br{q>Z|Je>PPD5nu1;ge;TzKx<9HtuAR}&>Tgf! z_a~78nD&hJoc43DAeN56E)8-To_UD7W5!zoq0Sv{uy68wFrO;CTU zzN|i>eqX&`ixsWxkos-)hrl^0_%<5a}@3cGB z*VRet&$N8?_u9ScB`sUsq3+b~(#q9~>T&Hpb-OxQ{kghIU7_})r;db83S{w^p@_xE z*3K$fJ{!-<*=ks$C2Tp%W#44~fwp=d`w@FsOJqM}|HJ;w{>nav^?O$N9v|T2c`HA_ zd--mDJHL~k;}7sh_)|&<|59O!#_v@YD65sl%2H*g(x)XW+m&A{&niDtexZgdH>+{X z3QtkxB^WL3U^adP-pn@;A-)Tq%~5!e_rRO`CYywjPXT`rp4C}4g};bV`$KFxMna8f zLs#+3Y$pG2^wNK0*YH2X+lXQ7l}OeD>$?%Xejook>r&#_b|r=FR??IVwh#X9eq|iH zMagFe-~-&QOk_uuCU#7j!R}P1vExb?`@XW7-K#8NPbeGNPv9#*kJ!hHh#|iKf8saF zx7q9HD}Sdv%zmqUhy77`lD!2V=1t`^k5b$`SoxU!MLEwSlrOnO`3nzI{>~HB0B%>K zxr1k`B|KLx<2h<6`<}9f{X_X3OJ_O!1iP8tiV?>Vb~k*`7WlPKDcdmSyjjFw&cX)_ z+yXzm@-BuPG0*i^@anlJY3~lX8~5qdd*6s=~)8 zpYbF$h{vlIo~Q=$R5gj`spS~=tYlGqEeql^F%Is)c=uWs%Ddo8U(GaL!OR$QSTJW4 zz?+zfPh=DL(-@0C1E1&uE98&D&pVAc(c`R?Kgo(PURa}q!p{j}k0=A|QRRAezp{*d zTUpK?#F*(j$_n-Xe0CT7;?o!xJ*KQ@k1HG4DPKE#u z`akNQwdq=;)~rp_+O(P446R9P(OR|fTCrBD#cLL=Ov}%VKUYj`t&Wgr@3FhiwYjv6d8f1ZnA*BUbuM#VyThfXcg(t` z9mt9M+U>5kHh`)-678;XdMfYeu%D9H;3x|q{mt$gN9p4T^ITiI9n#p>Wp@R&wRZwy zr?en?Dy65=&cx1+j*dh~%N0_)$i-&0yI2b$JMf;^;S%X%I6CaE>e=l` zOC-7ItmL~ad9J|P+|%e3gwzA@>a1}>U7R&tE~R^ki!TBrE=x|nD=^Pa+=il98tVoM z_^s~jAe7Fjg4>|H(}AI^wyq|};Z>aAJby(BkyLmtSOD+oo%XtY&MvA{A#9dN72>id zf=LgTs9I;&RGGz?Q9gI2;VXRXEt>J8P||;A&0}LQ4PA#SN_09pa-hUvd8ZVm&ehX3 zHQyDUha%YRuCUr>Dj6P7L#}Xon}xS|CGkipp!5+1@f+0uvp8M+taz-YFJYdv*J%$jDk3@2YV{hfzs&{v}8){KuH?Fe*>WY zl{HEgo?!5WKpS{#_~B(K0EkIMfvFNMEU5RhVs!p9p$5Y2FgeGOq7rA zStuXfvr#^}=b(IaFUYf3iH0;b&)(^Z>$Jn@@lMi-F5F!Oq_gAlTw`-xW6>VRqbW2% zV@GU|&aQGN8TPNlfI8;83O!YPD%4y@8s{3HbIQc6b?q>UREtFh@r;I3oM$f)oR@%_ zq*FKCOu+h#$SuKH%;Rvw8JjxES$?XRTdAz2kOvAd;y0aWEM4XKuCly>*s6S2`PZRB zu@?co0#(Ff((MKI1~Lf{ZPUJe4bBFbpmub8u)64x$~m`2L&6hayJB3iK+|AO(*@e8 z5LV*~uFYM%ufS=ySM3AMN`Ewafu!d$J8L}Hc2_6al(p4ffwz-&LOI zL=N>RCvGAa&>JBWFhVBT3?qWdFhSwagACyW6uYRmA|_P)t6NfEUQm`Qk1R0sc9}AC zSvad8ritDpR}hSe-Cpl(piHS2CwbCDVWgy8?5g$xdlfo#;$D$J5cO7t%bbq4CM0=% z7g>qJHLugD*A^^)zH724Hz9q!x;n|h8Cqmd6<5Q46p$3_U9q+8ZHeep?NuEGr^fMU zwA(3usk0K>{8DTDQa#@q=?(p&HqSL7*NEWx$dlpJJXdAzKByn**gmxM(Rf3J7P!WN z#X3=BQsWFM`7StUHL~cW&Q7$n0<=6?p!&R1LFj8p`-SHJYbxC^l7ju8Xfer~>{ykv zJkep$7e|NAX9EoIgj|nQ8u3<{>!3O#x#*?wil7N1u*zl+?*uJ8s=!r>R^B`cyanWV zbd;+MIMec66}YvM6zd>vdp$Z~kF=)ekwUv#A?6u*r?ILK4{dnh^e{8;G#8Lrco2}; zgwuees|bf4t|lCMm_s=9FgNcp*uq*owc`nWJDxi79z!68p6206!mc4aPO$leC!Ve) zJn^)E@Wj(X%Cin=os=g%bWxu4&`o*L!y>|I#6u6^(8FTFp@$`eLk~*@UsLh4Oz=fd zy@D@#S}ypar|Se?^t3|oMNcaQU-Z-`_@bv(ka3l_0{g|As~QOd@^K0tSCh~Q%~gZ9 z>(STZk#N??N5WYva43Or*5TucUaB{UH}S=K`AA=EkdK7E5p*U>lAGisA#9e9gs=s; zlf3k{iZ?-Tn|vhn?edY(ci_uOlHN}FNC-E|M?%;I+{s>gyTzNJw?{q_`c3kY(D&lY z$&%j9@{ths$wxxCCGT{w@N8Y?#M6ij)nU+tzO17r*A=kXrKYv5_jKs_3C$mP60gK@}KTIs&X_El3AUR7#X=bD|~y!8Jb$-5#<%V7qBM z*4PFEC9LL0tXlt%AU|M;dQUx-#`n&|AYpGiz4uH#l|}Do0+b;Au5|~J!zv`e$1i+o^X_-{K!)5FD*!D9e@2$_r`?qWBZk zdUd|qhX~yn^@4gyeMkL7V_LY@uI)k0=A?F3dkL}1PfS6kBvXN@+BD15V_Ik0X*z6r z&~(Q1g6VbB2c|E~A?79K+syA+mRO#)ykxm-`6R#`5EqaWP!%vepfg}a!1{n)0Y?KK z3V15u#eg>gJ`79>ToAZCaC6|^!21GU416u{y}&PnLWArc( zIVNCC#+bq}Q^&N8nLp<6m=j|j8FOaLJD~}o8KKid=Y_5a-5R);{ZY>mAnP)|1w=)(h5) z*0-&n#{|X1#H7Y-jyV`}BIb0=b1^T)T#or5mc@p|rp6Y;w#9Cby(9K`?8(?CW1orr zJT4(FFK$v?TU>YCnz%i2$Kp=LosGK?cQNkmxX( zq7yO_$`hIs<|p(eY)`l&;emuF6P{1FnDBnW=ZRWkOk!5zgv4oy3ljSi4<|mC_-f)i ziC-jzBuz-_PFj<+C+S$y$)qQfo=>`%^nTJ{a$fSJdgUyeDAefGQTCoyC5g8icXZTm;|K}V37 zxhZf=aMU|yVeV$RW4&XKYmg)Qje#eOnox-nbZrZ7gOI({U~+N8RU#{roxY!;H-DfaxQQ#cdm2pbRKlx z<$Tb2+WEBe1?Q{I%gzs+U!$7KNFUao8-kQBH`)Kxk z*^g#Fm3=<@0iN687zNyy2_Da@Ia)0{IWr#q)FXJgKuoI7%k=bX%WGUu6` z3pp2a-p;Mc-JE+eZ&`kL{?qvv^54k+ApeU3b3tT*tstkMw4kwIUcrij^#!{MZY#K_ z;Gu%Y3*H|aJ+@}-zOm=V4vq^N7c(w(T=BU2aqZ)J#`TZeJnq49ua5h0eCYU$@rC0j zjc*&@J-%=J#_@Z`-!cC9_><$G9RJMt3*#@2e|!8#;|B|a3S$aW3kwP-6xJ8cD(o)o zFWg+XxA1V`+eKMLJB!X0yU~66~9>gMM-o?Vac45WhEO+_Lm$h zd7#8qa<=68l2=O2rB$WtOLvvtR(enAL#2f>mR%|jFHb7ZDlabI zTzgZ4LQ_UlVbi3h=B7DK-A#Q>8=Lkt-O+Ts>15NB zP0uu4Xu8<+cGE{qgUvzBG0myX1zijaFKAxgysmj?^TFo3njdU_q4|pzb4z54 zttF>rPRogw*QNzc+dggov}4mAnC6;xcG~mPUYT}j+WXT!Z`E4ETa#L|T8mq&TW7WQ zw61I2+j_Y5MC&81XIh_YeW~^J)^}Pzna-w%OplwMHhtXms_Bi>*G=C!{owSwraw5t zJY&U-SK8v*I@>PH44*k|<~=i?n-wrCW7hInXJ>sfyK(l>*-u@SbJhB*9>411)wZkq zuYTz2FXv2~(?93Z+=99Na}Umau|2N6x&2uCTOH<(6&FT`L72TEEwXW+@*9YA}-ErNM zx|esa?|z{Bvqj;HY>Or=YFyN_X!W9li|$!;X3_aY7Z$y`=#52#J*hp7J4BJmB?F(Wp1=D1^$V_lVU4n8$(q;JMy_4A_N8?R>*lO`;D*o}w%%~z zhKuW)*B@U0`iAfg(>Ay^e6%rXW9i23jR!ZL+<1A@giX^o^=!Ir)6<(i+x+yFr?*_( z^4V6~*1WBaTjy+Dy>0v1?O*P& z?a13PYsdMWH9Pn1ykqBGJJ0X@^2UN2H{W<^*WTSdyASR@v-{OOse3l=Ik@M6JumGU zys7-AOMB1medFe!o6B!ra`V2MpS=0Q5A*A5IGj5}C!aLvI74_>}C`qtuG=ij>d)_ZO} zf9prLh1^znTl;MXZ+q@`^X=1b-+%ijcg(uOb;nDGltVd(W*yph=*dIx9S%A?{czvm zV~5Wi{_IHck>yAB9l3P0^ymY3+V5dfIy;DKj86lv3fC}$#F(?ygjp<}#=&Y}0MINE z5fSEq_}n61#GRQAOH`2>%*}Uj^VW*NUrw0+?i%IYE3x1C4iD#Z7*ONpT! zw`iE1VlT3QQwn#z=qkyDPwK(>s~2ZIW}SZ_aem>4qdnxs!OCrkqquxH?rh~@Ri}d$ zQ+wG%B2N!Jl^bxW+y;8LjYLo2T=eF7`=~gNdvWeyvt{{|q2+tui?fy$j4T7q>BTwZ z!7r@Sk1m_^o~S3i6@)Q=VBBkGVA>7{=oyJ2J;)mIO@QJ*8yQGe{EvyDw3j^nl} zXAFGqhpKz^*ucXE)+fI;)}fGjpO^l|(Qwp1cyTs)>cvyPvfZj@(Qd;qJu$hu3J^7b ztVaMdYXRn^fe4FW%?7n!rfH^yK^DbiN;9DmM@2@2y*MtB}t`GnpLj@06Un{W8fpN^X_VcbtIOlWABa6x%@<+V9Y zi7E3-mfyh7mF4FZU3t5@th5F;sSM-c-($q=VB@O`Y{_Av8q6J7Q+OAmP1&u)T$cvh zm4gKuEHOSRA~=vaxWg0>lWR&XP)dp?DMf`bF|n463}>p@Y>keI0Xt=}p$dO!#!WqC zWs7cVo4#dk)bhCA=H}ItC$Da9?u}a>HFrx$#j^cZ&ECJPqO`rRu&Skg%dFX3>YA$x zi{_R>u7WQiSB%?*-TYF>m3wr+i$nS>an`ZTBj8x6d=dw3>K67(QEz3?;op1c!yk);mzUH`+_Vo3IVQC7co3eYE6XF=Gu8>3%Eh70QD$ z6MeE*&+G7s2Dn)}*yrU(`>tyD@S_$JKlpB)@&N7%)=oMNLyt)0Guqc**L~5yCi_*&f?6D)d{SdN4S<8j~ z<>~r;r@y|Cd<72m=MrZrzOrV_w&PWq&%q|OPpR9J|P1GouN2= zDBmzSkqkuJ03FdbAOo+AsV|rG`#tmxc1_S1{iwvbk#!EIFUsPptKHCzVLS*N>dPga zZMyF=v_8wVZ+mfevci$eYrxsz;n^q?(lJAM_p@_`@={+edDt{mKhdtpzFt8el!SG2 z)zuTj&~;EB#L+!+bdQRncEMI=w^}&d|1PuajBLrAr8<(+ZRydGAwd>1OX5iZqEpJq zC@C&;6e#G9ESc0h*%WJZsFDfmS>~`Q{LtcW&a)_u=BfP+4Slvnao28Yn7MCpS#js? zX%l;<1PvDP2|Xe6Pb^Kf*RPm7xoliXTV7@Ffmv<)dMj5Hb=6MpD${L4A#6h+%dXBC zZW~NsHBEzw0zx2}1#>`x&niT;@;?sV&Km}Q0E=*`ckpMx15L<5RUn5X68yqjNBu`Mqs7 zEiNnVA-`l!)Uvqc%`F4fQ&zW3S~BS^-qxGDe#EjDUOP$a8N6=p_(D%zDW9Y49*s3A zsmTgDh-oA6PcD?V!W{M#PlcuP^slL~GErZsuJ6sbd1*yi&z>1Gw$6z{bxms;sIFhv zP`@_iGH>UEs{VK~%QKNmO+I?fFv;i!tR|1z(2Sam$qHp#rme#yMnVSVyY9GMs4$h_8J zSIG!CetE5B*A2rNn%7!({V<%Nd9B5~&+xoV)IPxv$_1Ogk730+WLw}iQ9F=j5pb;5 z7cw`Ij!6Cm980jgbwPcMlusXfYgk^AXTp*4>0|E?!;w4_j+9Ry_NNW!88$_X=VV^n z*uG&nGB4^UWM13Y9m8;BUW6m_+Qz=&kE7ef+l9YG-Yr}=m1|2Cv{`4X*`(+`+Ymnq zo>BySHvHSVj(4nGJNO;t-N7@w@k%T&AA~!JE{ygRDQ|*q6#9KwMpOb1HY-><49_r# z1z3UtmTH{5!;nD5Vo9^W?8d@n27Z+A$mpLj0V&cqEGe=&aKRZAxkflj9IZ2FQr@#> zA$Q&Z4(v<2@wfEKCE|hKyA5^L>NYDV8_GWqJejovJ|A1TUFbUC@T%4_IsWtOW8n+< zz9m2TN1!46ORTu3cvyTj_H95+h&0KupNMFw(*K8KD5eAid{csd_6QlH-%)|CJH|9b zGhysFqBjbUnCw0Viq?|8K0dRrZ>f^BWXYAcmI{3&f1?>RGsG~|!nWe97t&L}dA{&b zF_K2v2Hdav*Ew(mKLV#y;$W}A5FK=1KuWE!8IsO=_q<^?!wH;Y0!PwW@BZFU9QRAW znIdE@>8y3nADS2JG2=%Cj-<2JeQGF~fEhI6i;I{VH(w2pmagm%Doy z&YQr=SE>C;I=${yLveKZ5RRnN>wa!1j{6UwlPmlyN#{EEN{OTT;#oq@0!Pxh&i%|V zoMy(@PYwL^p%g>vVi-St7|RXCX?AC`p9);kL4O4f5Q76ACKi zY4wxmer#VNc}hJepIPR+X;eKY9GUN?p?VHmK_2%6wCfO-Qk{fo4u;QY>0K&pWtu|1 zX$T9Ba%cf@xkV)uLV_WtI741;Vb$95C3St3g-Ym^&!+Z}znhAFKNPgWSypvA#fW5- z2qZBc21z|Y6cQX@X5lfnhtMBBw_Yh+8^uMCx?;NyV6*(Pxi(hBTOP_P!xf1K6k1XE4rb=LxZ35=vywXKv#4R?-~60;52^q*55#2Sm*@_ z-YR68U!8*i2^RyEk$buj7J{`65fL&XfT#rK3Xq30qJG`g|F!?GJo>f|XCsSe_@u!D zgZud8!Ji-t;@|y+@;&5XWmi=PhJ{$nng(gNxH92lM^WvGI0)oF<{4R69^6rPHUMCT5C=5c&yL9aJ?n=n1#?3LZYuvhi&O_T+&k z+lI5fhzIJ+Ou`lcK1!b@aD-nbzSY(+v~;~(;0JsX9Oa_+g0Y>%Cq5(CxaxeSnK?Wg zwHJvx%O=^RFbZX3g3S?@2;hQs3pFjlx|)hXX(>W^h~!Z*P9$e$CMRZPiQ@3_;yE!n z6BGp>*%dkRp{D4av9LySmYf*vv^p_s zfo*6W^CxF5d~qQWRo7=P`1fb-UsgGxcmK?p`+Fx;F55q|b$xx^hSt^%Q|l-+a9}n~ zT43^G_Ur@8DpoXYnK6A!bMuzzGqyBA#)2=QFW-{-!h=P98e^UkhvK>tXFYa`4xR6n zIOLy5oVDzhk?CkOXDV?Hd2oDwEcnS*%S3+(9EMmdHwnHx^o(-=B2NRo!z0pz+(j%_ z=6PgP9E!zCoTKcJXi9Ce#z$sFTeA~u%Zu+`FigGu<$)Ln*~1a_n{;j+MeYg7Q;C}XN$WQg!x6-75qCvC(dUt8Fb#_vmQ z-ZJ=2nBKw;=imZ|S0`v*<%fQHIn2I^bp^7XM%5cbJ#F#mmR~)Q4ZO+Q-Zy)2hS?li z=OFXi>cR2Qkv2g)g+43^r+YQZS`8Wl*D`@KGXm%>u6Xpe1W^*O07^g-bV#5M5y^N7 zKr$B8OCnCJUlL2Gu%rszA_bMQTZ01>vzc{Sg7iqcq+afi3N^@XrLXj;lK9B7kRht( zA%LhG#o)mm@lxvfo&^T#9Wc7$um8Hb=&L>yi@s#0JRpE|>3PzQffSne$w*7iv*pFd zQIwC?bA*M$L}LCY#DDrD7BMgHe+c~34A98tvF$(+f6p^ZI~Y@Rplzf+zp8YJSpTuK ztje$3_lyzd!50g`s4cfT3$2!%Cah-DL{JUO$ULKNYgE`6poL^Ou!^7Nggo>6&IrRo zjq=;b+B0E>)oU2? zBDM!7U$kVJE7w<&gl0G}ETMUF#6Z0{TgCXF){@k(`^J!*_sgvJf2wCpzSo1o_lkic zG*>qy#UndwBzgTk=wufl9G%eGVip7PB|0i3zbeaXHaZsJR#( zz3%lQ^*gwFW?q&i9m*c;>0d1;q+SteU|XT(^_nbu>!l*#(E^ zcs$Xo4=)&-_uavt7&PXw{*3F}hPN^&>jbYd8x>8gI)DlGz3_nd>J*9QZBYTeDemCjr-9lHVuZ$mj zg~$2pEAg-pJjAdR_D}JUk{llk?3lE~Av~bn$HY3R=fUbHKVGh{PEDy)1J+s8nu~_E zQ+$=padpM&in5jERX(QBZwR>vKjFOWH}rW8ukWVgEEG6D)o~6F^AjW;@+Bmlb=Z?M z)Rz$D7ygE%vreD0_sa|8MAVa{LotYDs6XNXaL5jDd`oazq5}9Ns#oDh%Y1jaUl`_l zRFK>Sj?8zL9(y(V+O%fFmoLpxV7x8z%{Jsq@PiUA^7WN>H|pu@%DWq96Ai<`Sk;#= z#;WC>@=i453wSZ$uyA>ZL$;yM%%Syai3ujOOf*>PbGqQDV7(d~9N&7il;l`zpaqBV zHV|P9_WpzmLwN*KF&1D7I<3jTiu4|msSvq!hNiJrn#-^2rW|tqD+*vAQ zC3qJ4L$eALLpUPjV4NcoI9eg45vfBiNv|Vvo6Gs zj+JC6aiB}LY?3k`N`Ec-GQoqv*Uf_-8o%AQ&iE~j)nvYX(39ccW*fdGT{@x52XIyY zmd2RdgMj+?j~cM zATQ3<&XMax&IBVkI%6$GMV0MWVo`3vuV_2i#VOj(nPD;$`3Ri%beyM$;Yd0ZbCGn` zV=dH3Yw2zhbC8k_PRAUEBk52ZlyuhOWVNAsF8LuGNoOsr^iUj0ht{G=I=kHON*qHw zm2?P4(%I$y>o6QihuV&$)5}_h;Yd1!BkA^Pk`9g88TN`p{?sp^4&}E3 zen!A$zBJyF`S!DElBU5{46T=bHftD;pd;q|B%K>EH!xIIf{wtE{NKoK^2d>SjdLZJ zBN`|o^vtAare1@7d)MFClH+0{rH(tfQ~G1*2q^yO)p4<|+8bM;Nin0wFAGf(p_Jyy zmf^Y|k*Y^fCJqizE1)(9{#7e@^Nb9j|5`8EDA68FoxWLnY;m<(9ljYOtc@7L3$>4> zU?32&oR*1Z*;0I&URfpE3}iud^N+7;GvJAEu)0FDtC8AFHpx`d@z)6|kNnnOC;ajq zMJN379YrV92vOgX|50>8wF(@`|1h2K%7NlUlFp`)+bZ}W97$)>sBP7!>({e6QvZgv zRl<=vdOg$ECKzyJoAKF>-LOF;>bmG7B%R%QT-4adOFA^?EZfXB{36rHbO=Y%*~S(O z!;x)|d<98oyT^7I;ux~+5ssv@-D5ipI1T8te73`^?bm(NR=|C>1MuatZyMU>H?Z|1 z%hS;2H{kqDQO05Nq`H&*k5a$NO`?7!|D)Egi1|o5TReJV$V4ImCFPsZG&6Ign9+1_ngZiIYVh-IKmYl*!Ozi>A6DjKnUA2O{tZ-i*pTakQJ^CZHeI6&wSsdIBO__*(-9#FNAMu`?#CbB zJ;>YmHwJ&l(+8Ihx};x)I^H5=XVdNGG5_+w?vNgA5wepwYxS|9u?-@_i2ja=KSO zdRFYwir`xZk8$_lPJYuoC8M|F%5Qr`oe0{ZPO|hmSu?C05{L9z;;eIjG71jKTjKQT zd(({d76Eyq91;iq`QAPh0g)dXJ2532vD_@SPKIH}q=$uCFg`^%7wdu(t9|bXD|w>w zXzyGMUGrr49kW9EO6WvG3Ps~Zbe=*_Vg)qTbvRPu<7n+WMLua_GghoIC@VvV)4TK? z^Fm_Hb0z{z6#Xo*n9Xm^TGFxLk*aa|Q^OX7)y^-f?k-SLO_nMyvZ1)Cb8AByutAn1eHSd(t6&8 zmX-GLWQdZjSy@|2i1$03$In$~~UG_m-Jr)A6eWeC#l|#2+^T9CP?Y zpPRMypQ|(r&Rwe9lO^+~bmT+n9}iEjQYjtzjgrnpI`SPg{dI5tx61q#|NJRk=6|cq z-!HvNrF5D9Na;+Z%lwC@XJg_(FF(uB_O9|t0dsdG1zoNlJd(E;PjE97&nu6w!Sl-H zEAe301^=>sZu`5CzhC)fx|GjtUn8H9(v9*NF&lju_|{ z3%Hcm5d-}y0hjcRaEUMJ8{tw9q&+=~e$iLoK7BfR#RsnvdM4=`;YNM(!0qIRshM8> zcReEMBzWPH|6LFI;8g-&(l^2-9m&53F8#bKUi!VEK0XdejAKWN^Bitx|fB1b~`E2x~PjD%pjehhAF6Co{ zGnL>{KK^j4m;RZQNQ&;Afx(l^2-zN9bUSe1eHtDb=`2#jfg5n2m+^7e#V1>FlNxd!l1!X zRmoXpeN}x028-jy=I5q69rgq{n8dk8V@4Z7U?GOSX2jwU!E!q0!-_NA_QKVTi&8rN%9E8D6=kyrFUxW0 z*r5Z_yv)qJrW@+VB!$$?%yZ^vRyms|!CmK9RW#KNKCh2WQ&KWL{fT-)*t6S3`xxM) zs0yn=Kd>6}hmkCm?Uc12gyUGSPD&0_^cRGnJR|gE3|P}?*rj%1td^%Q)Wq>H`Z(P& zBprh`S~^E-={&=<>ey%ugOU=WQlnF8uewRY?;S?!yVW5*Og?xeJA9SWqKbvdD+X-y z%3C)zG;C@g+mf5xGIm^ZZfEOF*na$hV+P1g!7PJ)?wG|Y!6&1HpGeq2l z`l~|ddkW2$Cnb&vp*;ZJ^IZ^h5W`OyRp5*c)4+Ur3QzG){`t?4`n8(vdhJjkOP>TuoA(;@Az(hXW85ApkS!?Qpkmi8`;w1TZ_ zI_X4f`Mi|=>ud}2$2RBXHIE(Fl9SUC(n2cHoQWUxyb@fOnKM*3q#WS+U@o2Cjq+Qx zHTWGRj~t!=JOM`OxZXyBc_4o0iUm;2BS^kj@S?9c%tVyKj4fd*R-I`YT8q9KFt0UO zEa3C5I;_qe6?263e$^>SiDIo-PEw9EfKo!8hn@5+A+6`7D%wgUZt9!h!b#V=_|eVS;1o3(?rUOm%#RJ$(UOq_RfT*!Hy za;;a+U1}0bW5sMn^|YkK80@yNC0l7hqlGJ^ZK~K$1G$Qo;-r;2y#+H0$F>&aPajt_om_p`Ub00Muto9APUn2Y#wfxTnXp{Zq%0+q>1!rl z8(0-WM7z~_iFnTE%iDny(H-;J71emUg_+ik(k%Llv#@yZi(@7P=|`S-vj{{B)AoZ1hKqa^)J z27Qxoi7(*8ZTTo?HhDZE-4XWL@~DWApn##ayiATD&`WuS8Pr3SVW`2!&RR1OKKdP| zYbF^agKxr?`>c3D#WZQy7fMqO9~h$IYv9ks($1@3bfzIR`Dj=) zO0#P606ywnaomu3I;4X0<0GPqvA#GUAW2{0C${j$TE#%eDm;yCJw1JMgOdUSqRsiG zn>X|CFG-r$tt#CL&mNn!WDtFcCx6<9ORMy~+apHK729y>yb@!sn6~lc_33Vr$BPSB z3fk1CrYWt$zaPu~Dt)!Ec#dBb#fBhq^%dF`L=epY(Y>}*?6Xj@Se8aL7z1HP5QZ{x zPiGe$wM2V5TU<%#`ZD0vVbYG!#TaOGY}z22hGZO|Yl73_{~6pD40mt9b>U&z#29N2Ml0*5-7HMc$f3S-*cuKTtRV?fjV@*M?=S+ zgk_;EWz}uPV9mDiA+Q=eDRn4R7D`s~`=jKZec+O&-Njnk%W zsK+4d%9jnRCiA(uO$7xs?kXr~$`x%u%03z%+$G&lj=;bW%g)5yU=UuQwDe+-xM%cF zG8Fy}B#zUOJIPnb(n#X8`5*&w782JdheyYz`f`f`1o3)W7qjzw$Nd zzy6AJ>Muc`{5)^}M05!bx+B6tZ$!AHvo;CIUjBV_hQlQte|Ws)2kRU6z;6haGpoVA zIYr`)aHz~*hePH53LN3n5YOb(9P#li;8gaJ;KcJ#IK`f2*|$|1$}W5eDZ}A#S#|+O z1FyjVCJOysH0_L6IV=#Zv%#nw#)yWHd9;emv#JVB+!^ik9LwN|Lt#(8SVdxus2PZD z9alNOq00PTg z=>)Et0p8jFq4Mc#SKj2`r|!}~FYK%7;SgtMl*3C;&iWJEM0IQLhW<&#TS1s+^?7~q zM9~+!v3gI)CW%fG!@2S%J`M8G$SUGAF%jvrSWI0A_vN()(w0f-3nZ~5k`ny|1=w_N zK*SoXy0c=CSbO_GM~6{rvniy|KU8p3Rxdvhtfabd1Wp!$lMEv#_`Mv@-%w6;iHhun zR7Jj}x@3KM#s0H-!2==*)8Ej%{G=^%^hjK0YLq&)-x{2s2Aza%zk_n){IvhU%@6+W zC~(x658wSP)t^{f2RdkvYuz)3uH!P`facfYfd0rh;5plm=e^f^c=o_0&%@!8X90(w zfcD59!`e6c-2oiXI!pM5O#U1A#&e#JSlO4+>RV@NIM0W2UODSo zJx7ie)i}FM8)wZ0!p zIMv--2Ks#;OL!H|g2O4bz^4X_d1NpscU{qCzh{IfR< z_0q5N4?fxN#C)aX=SH1Rs>f&nm-KH$!>97fdL%zUmUlPmk>IlK2u}DGZMXXd0sl4V zm_^?y@wd6V1V3W{pCsUt{H5+e=>gWC;0ScGca7WGZ)p+sXsHazZ-FjnVak z#Dmlg8biyxHtD+Y7v!}-jIAYao7@`&ts1wJKZG_cWouF5*{8@vai4QLb$b!X7FA|%h0Atg3fD@p;KoFnz)ON?F= zMZ@M6IjjL+aOAO{y2r>D&{X1UbQ?vdxknTYymh^>fM1^NQI1|QQ)MXbOOVsA1P{?{ z)o?jEFjVjwMfwp4(UrmpQZNS9g=J%^5bffTa7kh@Br$oyfEI0v7BUO)*iWC#$ecx+ z7xh0If&+}K*+sLT^%EPvxJ1Z}>vfyVLRo!vkmqD2Pt8V%{(wfw-I$LQ z<0X_v=WvX{27w@)q!h|S>6AT-j|pNS!dq=PJIPREP(hLR1HwL+%NmOiE*i;F9J-c8 z>Jti!i>(Gq52bPB7mReT;kJnCsJ?#S_uhKo?mwd*eh<3gY}W8H#ei?UKca$(y}9DB zs3=Bm7mfNo2voW-&S<4C%7>M{Gzp27ogT%MLQarpM3IQ~B6_4tZ4hmT7n2=UXy73I z1A;#ec)Ebo;b;V}7WM(WqiqttO^2gxf-CZ&^WZ}Vvz+Qod4{0ZjV8Z#=)MH+If6I@ zCCZs;vDOT{dEmug?|g73eCCON{_Wt|FXlX8pc_K-u^6Hn&JRSs@X^U5Fr1b<>?@dASP;O6Bi z8T(B}Jk#*2_^}p^z)$i84?9ARuw|d3-N-X;(?{_mY6g@~uaK%qe%L?ojmM9GRKDU| zz#@pE5g)HYX^hQAE+^# zk1C6=JTS3a$_m8nw5LEpAQ!&CfcqCi{Y=sk9Vcsa9QPMGPWI?HNWn;jiM*hjYxEd5 z(U)-0H^Msjk93>ZGos!p_>B6c=|<=S!66frh3Jd~CptP@`m20{sIxHAewlUYPJ5@re$CXu{VGSpFqa}H|;ZcNI`N=nMa9P^c6ze5g%Pb~5n z;Y>xny1(X3#UiVJUX7K$%vSXna-%gLUx>W0TAUSDj}_-P;#`kjpL$Rz7U~g(-kDAEU^d2=a<|tIglcz^@c$xPkN620JP9%3(A0FR{;KuqG4wv=eflEKZs~^%& zfK9vXp2)?RO3=4x2gytEgG;>`4wrf(;Ak@r=-DLHx7>d<+MFT~A&fs5g8@$y(a}14mhMqk+tU-@-_9PCdk+hrqh<{8*3p}GviRTE0 zJ!26xv{A4+0sV;{>VU!MhAqX;vDBC-6$hA>}vLa^2__BF%N$sWO*OU%SE-ISRUtLsG ztt8iGW)`%DgNQH5rRD{VrCXnc&xUhq*h6;$;k4n6HpMk1b&j`*%VMpy((yW zMz0Cu*%W#dhyM~`F}(&1G{%U2Z6q3KLy)_EoUuXfHGkDZVFrPNEs{5*SPJG!m3ja$ zR^B)i-XP)IhQb?1z$YI{(pmR+BR;_;opm(W^X5x%Nym$iGcHhXUOM}lbbJA)`j>R} zO&>6R9jp!wg0-FM93Y&C8J~D65;m&*d8yV zy%d8NX8#Z|E7yZ{L4U%qI@NH7FQzA`zY-%wtcs4n^2_+x@RW!YEdC1PVS47C)otRq zreP=hHB8@uWdJi~Y;T#ieY#u~Db~$~G;NLAM(Pp4fwQH=*Y0| z`VHS5_I^kCU~i62?}#59YkYM0Q5xQP%Y(H%I(*lQ2Dq?;lHc9}16;k|i@$Od_^L_| zKFT5NwUn1Ahc{p9S0w#@3Oah>SZkxhZ=__e9-L&!ET45g5i178a>*SG2v>HaLFu7n zI?a&5py*4l6J#=$=c-)m^-IL*dnq;?fu3&5Psxu653;aip6osCg%&mYAE7(iib!3N zRtD1fxjliQ87VpAM^q`ZH7+vy|KjdVz~d^eeDPcN_9k^}X|-CdU265Fed}(ucC}>f zn@Uq$TkUKNahhp z$d20o->JI2NwTq%`R0A!-=J2j?!D)psycP*>}9c*WS0k$T)W$sl2^36G z)XJi*E7r56D5K@|Y{7#`P{$j~SFUGUWS1m+Nl{6DE`|Dd(mc_6w&c?bm$M}gy+?0J zw^0PGPG{pmB_4f7)<|9dy8|E z4;10fW+^o#e>GQ*ybab9=ZQ; zT>Cwd_DiT8^8mi4EMgv9s14C9{ZRy-n2b!PcjVW39I#8oE}|IM`I{Z4?PD zug7jqG+$)Ls7LNf3C~@*C77rnn#T;Oi=+?AF@oa_*+fFUq2L#p!nsO0?H5Bq70v_D zJZU>>=#hxeTXJL2e#*;2bKx>qdb&kYQ(Ayf8lr?~`5;jtEMn17G8j9vWl0oP$GQ1i z8+j_rP~DdN`(n~ro|E71a+irz7LPOZ7v@@;&m!aemwNdQi~+@5{c7N$BJ?|vq$&$T z3_0Z{Xdx?#KhzkZe3CZ>nL%F%qfjV@t(1q+i+C#nQcQR8fgo;y2SoV7iuaS)>P9e} zdOJq+)OQEnm_yy5yg%bA9;l#6_Hm|T=3&Ybyx2rG^`i(A{&GcE5)gaETQM* zOJ_cITm@~t%V}#br!5wyE$S|jjpH998wUxxr=*&2;K|=XHOj-G-=2nSNY1QBeuh{# zUr^)pQXq>n2o9WP@CR5A{h`tfEu}DLqNT*Qk>yK?Z1wSLWyy^gx44xSb6Mu)PF7k< zh`6Jrq%|*#4O<#+$NmdPdW#I8#;pbCgnlD94A1|0j_I8qkpoob?pn-QwwT1Yd{$jc ze~F9>%tH+2^N9EJ)s@1?PQhD(i6}O&{t+%Vj^#zB6T!M^xu|`lVT)T{bQdhHVlx)K z=gV=~{o&=M-j2n3>bv>!lKApE&Fwe{Y5DRpW1J}vZ}~VQA#d48|0aJ+-S9<}Yt^_l z|B>F%uLa+#qExH+p`KYhx@@eu4Tw$1PQ(EB!6rpTsKoH5kv&Ld+G_QqoM47v(&~|~ z<>4Zx<3STHz|LcLgxyWV7RZ{ZL!j2V>HW3#s`@TDue-!K*WHHW6UBRHpsxyF3g&Tw z!v+du8^!mCYmZJ?LgW-HdRWe*;9@2ffwA2PoGsFA{P3wq^$d=H!5sXi1F5i9h(NN) zBLF!C5Gj@gf+~V3dE68zh>oms&<&jFQcrNNDD)G5D^`j|quvB6S?L~3VG0n&sg4#5 zfEpkTf27JC#V{aHx@c_dNoyY;irG0fGTT*5qw#;{xU2=67dyyht!n`bHZK=`K?aMq zQ(!{0osR*(|C6F!)rm3z=PIuA2{;EoE8s-i1)Oj@7%2M`zhA&P_@KBSz8Rtm$Yugg zjL(K)-q0@Kgxia7KjsAO0?yTMa5$*?EU|Mao`l2EYpytnh#L3;qU{7H+WrdezmeZh zaHt)GfpLIuA`YLh4}#ib@d>vVp*>_==j9@IHLGO+NFH>L}Kyz4-BgVI^uF?22WhZF-Riz^g`!veAia4`*%27^*6+t;}B6-Br7xzW+ex26I=b zyR0mGV@IENlWDB0q{{Cs$jj4brjG=w`%3!SOFWg1+`Jq^wq>*)4KxoNUru*KSfEFk z2BYn>m}k*`{>!oLq|1r+gRjQ6lTIMo4@KIoG#-)mYf578kHT5_LAYHTcmLJSa666b zVg$~f;c$CN-2Erw+Qav|HPntMBz&Sy>d75)AAC9`6q{*6)C(H~Ct&EtGrP-GBB-9yVG8d%*R}aplZr8Wd({nM_v<(j(&)KA&xl|+|$!F-&k7Q7--ou z5NvAh>uYZER<{LxjeU2@|2(j}(YvLkX4ICuzO`#6Fwl*kduvxvfd!+=i<6+FeFSvpK~VAoEJ)kc{x0CmLf?_IEFXCOJzs<3YP7F zGR6A~jlu6X?N+{%%`S*uFU-1mw9OmU$I1@#cDf(! z03h16?A)09uO`zwzaQxvG523>741nhPs)V?K5Ufpw;!hHM){$`qK;S+jT66)_pER| z8+=^A75JSvKm5LMyTI>6Te!W2JrRT7C$aGf{94%6G5CG*ZM0*aa7LDFfEyfF z*DL2ozAG(Ty!$%*+|WO23T$s@!=bO&cXla3OjS0XOhtWk!EW~0&F*&{qQ;9Rb!8dUO>|W2JHC=`9Ol)fPPWCfD>tt+%MpS+XWrc{v+VbV_`(_;rp0?6KN+nyj{SFwwDmCMBs#d zeK>DVZ5MD(>{j7N+6A2G{o#2L`0S0vCuSZa?Yv)P%N20q+sU>r;9R~cre6xR3w$E& z91gV$IJ{k@--D=AV3%%DHNsrT`~_I7TvHZ*Xz>T6|3s`x6t_O2tFX7;F+SMa@|B&`kGbKMS!l%INen`NBgUfg6`>!!iB87z7191yd^_k!wEuWXdkKvt=u5zf(tEgF zz**id;6&TQ@CBR*z0+Lr^&#Ly+Lz!H-%j){;6&B|hePcGPNbc~p>}~!d^_3X1)Q+& zoYM}s)eAV0b`FQ`7jReZ6@p0R)?w_LV8;&v$1V*WB|7BriOv-rz`(b~M1Ms)_Ib5^K|03gSKx#F zS#6)k*|96Z*-Pyh2gv`j3HUFs9ltzAJ5oCyu00B()|;Mq;`qfEAAj1bQdsgM zkA!{~`ry$=X?&4aUkSJtX)tI?Hp0OyE7%aiksfKn+(lM{X$`u>13XgHi1t~2QH^F# zO-VArl%UFcBAT5<(?CGXicWWax+m3Clv-7hmh#$#x7~KpZ}YalrPog>+LF>D4C(po zlZ&749p^aJ1E+k%Hm`aN2esklFd~w*G>xpU*r70&lVn6BcMsXh@Lf`7_(h83$5`Rn z1ohB+o8K!?U|IiM`a^ng=ts}Z%*wf;eeC+h?3nlIrKZPt2x0hrN$56qMCvBb8A!r6 zNxqV|(xLO1LsXXeO|??!zzMj(O$n#4J~8PmXKnW5(|%dnoyfFO7juYf8Xh z_#hTOwF~&m+Xeh^yMRyk6MV?*7|jU&BnzwX=QZJWqDyKQ@Rzp>_~CXj=XAe-Kc60k zLu)Pyf6uOPdp!K*?E-$deJT7s7lq+C;dHczW0yJDxH0u)JOLH{34fi+HRU&%LqZNqd|+Uze+U zAN8@4w~P5&-Y(#W+XZ}rBj8`&A05w1k^xlsM^nS?G+)#%;4g0%@Wbt5zUY1d|7c+t z4vi1?P!;~g?}yt7e`*)-m$wV};dX&P-7nx@3^25JnDOx)@SangNdbm>CTCLQg?`8G z3;l}aY-O8fw}kE&eg+Pk&!G?R!kP}^7uLFHr?n;84}K%2ozuQ(-=oIp;JgXKF>?P2 zY6tE)*!Mny{i#gq33lcfk?)slqWXJ-jWH{w6yi#UjR4yg@0X|R(CbLgi3Iu!+NwZ*vP6x9<@J(8fCTySC<6jTY@J$~lq@OBEGi~N&qQ28 zPaM~H>S^8kVm!f!;ZCgE|5 z!{zP0d*6=7MI9MhbMTk59qg$5d)WJnr2PXA75Dojq&Av_V5e;!H@{aX>y1awn6 z?9wo1YLMzkP62S07AnV+gLo-if#9owK{Ng;H*LZTWlc-PAr};Ko0w6?(~qL(yYOfw zE7jf=CwkD~E)O;LUa{AmpI@FhWZvA+Jw9HsD>tLmzs<{bGO$_(#DfBG`qm7&|3@^l585pZ>`xb=<;@YgKIp!QS5LckIG!R!DKLdmQ zpX#>+0$b_>Tj~Ov0~L);<&}+%Y=>{Wv2ol-pPRfJg4H#__Uh`O7+;8u@+9KnwUPl` z!DQfWauPh*z`#SL7)UTr$;N#@+_#ZQqlh+HI*u_F{tmQpL07LM&vu$dkGwQLj>fXO z?27R}KK1iZG28UuJPwz{v7hWCdM~&8@H3!266$lgGay(GP{`>NX3K_jMM%{XJR>tx zAu9Jso?^4jW7g|)0NM*{l&@9xs%KVvt#*H_j3J1Gh}o=xiyJz^hd6gMTpW6-er>fl zr@Crw!+iDCW8w3g$F8oPpEnQfZWm`%x9=V@&l7&x=;Cp%<51oWY-FH$;FcxwLcNk4;UjSubR3oueV!kzu(+d(BZ2aPT6Vdop0$rr>Up^5w>RC8*L-a zc7JnAV}8?yYX7#@*8QuWnh~_)!dO;oL19FlW#k{p>=;%N zkN8Ij6{#nx|ALVdDvbvtA~-p0)eGw%l(eAt1nBH5)s4wq&GUmPGwEY>?W3dZp8V`@ zg`Qzg-@DWS{;#OJx0_$7o(DUY^eSDwNuTtu_>*OEc3s%``jFx^U`=x_mrnKjBtR z3eF^j3=~($3d82!*b%{$S?pH3p2QU4axZI|A4uJ9S?6mV9c?Y^N}XtA*M*+VsU7Is z-O{;WDqW3%sUHirjd=>J?2egl7PX((-Mg;?<5B}WOM#~aUIdIwBKJh09V)11mpUFX z@#fZaY>ipz1=fNjV}gM+`Y?i!k^(q;FM<=&5hBZiRrH@9^!Q)C?hR|ss$DG|=l3-X z4>dLp4V!}J_15q0V&>30y4G_#yUz>G54W@o4YjlkV+;|(kH}6sOAvk}&c~I2EIRG>3IT9H@xu1tbHbS&^vzAZO!( zwISfinl7nxNO45&B0UcM^I9lSHLfp8Eb8a|D4k}meScry`R$m=>W1OrhQ^^GmZfbu zr?Y2IFnC^1!``mYZ`mQ5Jeov-8)7)*0B|!RzWmgDHp#>!l*6c9Uk^z#Ma~DVN^J6)>`)MYnkTTGqN4zgAx#+8A;Cl@8+}h&o-^fZL9ST zfX{Z%HFwT8cJ=%l>s|LoaHJ`g&$jI!4)a+L#&xX%tu!`QjZEoN9u6xCj)jrqUzPBeZFc1jz7c~*54eVROX`6?KT8i78G>&zc zH=?bx(J8?UhCuiBz@)oF|REj*xOR?cb7J7Z)@G&Q0nqEw(adNYiKAd zZ)hlQ?C)=E>g_eP%m!n5ZS~r$youBET39Az2j{hgXUc1Hv(qt;XTobqV20AL_Z3TK z$6QlzZ%^;upvU*U%D{l5$rC*&-Irw9HD}J z0OkdaRd4{W6IGN(!^j>T3zH(4OG8a8CC@0&2fn> zBEcf*HZ{qJoeQ!7?Of#G2#|k+qXhYtR1sBv{a4>Q(F%}BarQUUtji+ALU7(Q8RPNmpTl2sMx<%(u5BD0d@ z9+6bDY$UrUlWQk>=;jhZ6|Z)1L6!XR57(|U4koy5IWC-)VAuB){pSOwOjlc9ai=~| zot>TO$j^0~E#`N7*Cr1)(*Vd)o;ojSz%I%+A-6-_wtQwvdmQvUg;Sk7nJcwb-Wb5N)yH~O{? z^qv7*N+sz|X*w>KVoLbJjmW2QQmNCC2}?_9v7^#inV)Mb$}CDUN*OGJq*BpQA(T=o zGDUylBUT_q?p{PVeWJ3{)s&t&)YLR&vo?=)V_9U-PoB$_msjM_JDQ3*3X`gHYdbn> zbE=c=9o|8v$xXNB0)^5%VLUp~7n&!mUUUK4AJ0d{RY;-4gdlrT z!jzaFN|Ju_Gtf;Sh5JKFHcp>-_yw+Hp!&u;XCxU|KpWHptpf#|K$2)eOYKfnE*o+ zVus*_7{5;7o+IIel2h|SMr6;eV?wW25ZSks6=F=!mKC!0Q}RNL$zI?U&kMo(B+ZpE z%#end4X>oXTUO+StT%=mVpvf;p`G>OJ^2(*i!|IAei+u>RZlAAYfM0UbZF4`g4euSeY5BWF9y>X2{x4#SIyvPJ3CE z{OcImaV3I}a6?NRH|&k!hv?fn(7fP>9l2a4=nKsg>TQAj5eJB<;#j^4Hd35AAg#y~Eq@nJWWA^0itOZO5cYo1bhrkc zV}%-Y4(4U|u_rf$I^=g@VC23!$a6{oo^vbHXz(cKFuI^u#@RdK`pLg2Wh-3Yq+ZX$ z_46L)H_6b@;R_`A8&-IJv-&*Vrrgi3ld+MWpXJYQmZ7oG^MK#H!t)d1 z=W+d-6`r3^pNH(DT+go)T!K#ycfB$p!%+9{@%+IA~D)$8r*buz@0%>8HhCe!#{ z6Jy`-$JmkUME#C9sXHOOS4V6|aZ>jmS|@zIZEbDa=+ocS?DI7>8CG31GIC*O=Y=C9 z7p)qHVR>qD?V2g#S0r=4E+>k;2H*KEYqMEc(VB(yis2emhyk7?lmD5W0G?!Tq*{VeYcY*N*jfz4Rc%SbT%TIF*^r169;?QDMKv`=&gyDI#c*xOP|cIyU^x4+cBEoswcAx)?Q&NW z4Us&49&lQ2zldE3Vh^H)Aoie|*Z;sa|2zB2nl-%aKDeU?eY+FuAqy2DYRFccE@bk^ z9u(es{4us-bk*aggMBK>+%=vW6j*TOxROnDOj|;v!%I!Yq!67-F#lP@nu@`kyt4l4 z>VdNS?4ioF4f$@kG+nNIPi;-H2ZK@8TfVN?++0-B?s5f7i<;6()|K^^u~qKeTsQrE zQ0^=$FE4VI(;5@<`3dyv^fqF_w!k!&*@$V(0?TZ~`dAxr+s%ndm3<|ZYyAGvs_f!V z6*#J^9nR_+F<+~33|_5g$onKqsdBq&YFzFr;;&BWb@0#MDSBlAc>WBLNRs@}&qTgX z8vcG={xz;03}0j6Ygy9Iz_;kRL(8t&0P`CD+y%?772>(a`Lzqf*COvLz;mDE*C<$u z;}Usa9
*C=u(9?x{ZJda;H9KIHL&V%Rf&}AUk6Ks*P1@jq4)3qbRc!`vUT?oZSZ%&x4N`8zZ(2Q;ex2{2*=2ZwfQ*``}eau zFS{(X1IPd#aQPdDXOd9)lFAJBQJ{pHca0S!Q~EQ{y{595yhGY>LFq7-C-#40l_9|4 zF8;gEJPc$(FThnkgnqh}Ph%uJ_7zRD945T*6m4pY?N1mm4>?VjWV{3#TJ#Qb$ETfY z_~4h{w|~E3Mo$BX!wv9WS{G_RK;O3mhwqDZ@qLQWlOl&*Os)`Wfydo zn`q=@so`WX6LjE^c05*Cfb`XH^lSlKR8V9!$0CK$L2QU{jh1lF4c|efYT*WqmU8D6 zxp@`$yc}4n99jn_pqMJ|T#cuG5w+`hXLu?c9o77Y{bOC*)jm+){B_<+(KkK;*P$1s zLFz??F}0$z&Sq~aan&_eXVtIa{Hg&t)PIxT#k}0LWL{{^z9_xJMu1Iz5V2_>_zg4{ zv~nf38ehW;7ula!xG!?@BARA?Jognvr~EU{UjYYX56$sdOswlVXtz(WYv4bl_yFwp z3{lW9!pWq2kD`_{_m?Tcd=c@NU8L3lW*T05I5*FO2Z7%p`vZFcvg*pPM2rK$a>bZJ zY!vWYUq9~kZfx+ct7Wz82W!Xi&Ffw7YZ$NPYw}U{2e}UTe+KSGj{kfZ|5a>1`xe$? zvXmRl;^qAk4E#_w6F3yrgB{LbwDLUxPXN)_)__fK(|aE48#`-a(m|IXs| z#g|`>kDY!J!$DgCjHVZGb3o0A{(~^4q!?fuRpgz?2{NNVGb2xb)o2_;sY$ZY=rn?N z7UbvU;+dT6tW18GE*97ywK50aZl${$k7uBV0p=POz;ky3&o4-u1fHA1cmk#j8_Jo&{C*5fJV!A9btRa} z{29YkGGbujIfD6MJWTXqGw}2PCf;YDKH+a=AOHKo@Zan={O>OqX#K1?d6!HQFf6wZ z>t;Gnzs4WdNu4+^4rBJ_42>C{Zvs6?kWq~i>cG=>&NoCa-_v$*&*&qX6Dy?Pv zQd9Gx;o6$*7j%AR%m2P==EMS5RA1TeG^k zsj2ybfqT|&_?LmMdp3=KribG+$%0r%330GsKf{~g98V`X!{#=p0wrMd^ZW0gxZ#Go zpMvR6`;AvV_~2De3r!~W<&3m+C~U}{d)7u;~e#OFSD_p2X# z@X9wre+&KXDGt8?@Le4KSC+vq0(`R7Iix_)mkmEZL%3uBR5RD~Pq ziVCe3iYJ86!oeJB@QR--;#m8zIui@Ux-Zh%tQm0G=&ia8{LS)*H|FN%=jY~b94;-* zLP99^qnWcBH>3J-#Xr?It>pg2`^0OaaU6$7B{8CoI4Ctu{c=vL=zq$ro6Pl$_{O_JA$oi7AHLYy*!`b;WYkIz(5A^dM>wz*3oXddoD98En zWjJpK&TD|PUV_g9p*g}3t&*|8GFrr$s-RIph3)SjIdZph)y!hs48h+H_-i=)Czipd zG0BO*7nwWTvD?WcEiQx4!!^9-vLi>{zk5c0dgh};Vf=GA{BJCS-z3dp{k^+n{WV3` zU!tvyYiUc?-&}b8{V%x7ux1LdOVhbi@#{~(;p>m!oMQdWEm?mPIHQN;_QVzC_H?_j@X{{opa5oIG#Jtj2;(QHybNgOtiuzLZ3+?q2 z>?e3P+5KbtCtgaugb)$#AB%QMAN|TQMbADGzt~U09gFsm<`sREe#QIf2o^$Xk&xp- z-J?m53USmY;)<4NM<$lx&*=ns10LZW(a8uBU=qfBZY@zH)k%mV2N<$cj6oh^FN2R6 z>5Q{PJ(8m_$b&16JZh{+I-`yv^C<9_Mjm37S8wz3&!=y{{gT^myMcf9KcoJ`nk>d? zSVM9x`1kYDH0|Z`L(^g}7w;eb2j1@rc)T{foqw{r+ip90`|Y9q{8t16&UXlhVUEN1 zmf*l>3|Je-!G+jguy{&JUtwmb&oncl&!V^dEuxRCjl+LIz-Qq;3i!dZfzNwW9PNb) zKgi*~v;@8^ZDGGuZSQ&>$w=!2)J6mhuC|h52wjx^J11p6WhQk#8P97&f1@8xSAZvd z8+65O`4KrnFvzfqVNo9!kK!@V_ZW1S7eL<*QJp$$}ZI-|%q_j19`xiozSy8yPM%T07Vw4Rb< z_O6R2%Irlv!!(mC8jnw3y?q+rWmeI61-`?-sYNZMyW|tf5d1;ez}W-6cYAQsgy=v_ zKQKm3WE7ReC_?Z@sJnhXf$36BvN2I-oKIqjijp{vUx~_8GL(ZvWwfN2PN6L?Ev_!9 z_P7y%ftozI4$=hhh75Bl9rCE7$Zg$j2anweowJ@ZVUqTIXq ztKa@M7^v&ub5n~tw3{(ENOTBVvBLXd7lG>6hw+yVrlrX`*l#QzJIcQ4EuI%9{>uCl zlg$6u$-kMH>oMjIz42J+%}2p6qHrwaIZh=mWcB=tz| zi%Pm_4wk4vS$tgs-rk7QNi?WWN{!n1MpV+E0=lJ`S8zBz!UZ%^qE3@IZ%V-Vqw*9` zrBk^L25B0*8=@t`wOnfu!JDYjCLRkviLLKr9t>8V>KVxZ;09?n_N7Q+9uL}Enwhk! zy}75Qr@pQlJ_481UXX>AfW(w0)|3R5SzAd}NEfd4;UQ7Dwil%LWz(jLdU;3JW!##BU_UW6~ zuDf|^TYt&sYyDkaK7V)j4_nX2BX^wN8r*-|_~d@O!|n)7wKQ*U%FnJ0{jImDW9!Z9 z*WWxjdFzI<;Q*`b3)J;6)*A>w1qbg6ocuiI?GNDpuSu5({(p(!|BBR&c)piGmxZX0 zTqoTu>X}%aHk3Wq_`Erp8m){H>vzyvEC+)Kry~D+vxMJ_g1zS92mLq=v~(h70nze&MaxGb~>y5jWyM+88;U;nrb#S zH;x6&MeFM7*H*zR;T!NyIukuyo-klKyJ+_~`i(Lvn z&22Y)u`P)Kfzs#Zq3c?6*x=$dGh@>huXjt+K`;t0PZ9d)%f!EB)Wf@ry@R>%NQA{;qvT_nPatOfttMWfnJxr+qb20@S^PTw7!axs;Zo=-Gi>89{DD?=F?P2h@Wj>VuLZn+l{CS1?zQbfpI4(7TL7XR6sUQUPOsI?OL_{1&}*;_fVkvw z`~sz6?~*03esV>%HrLnHR28o(Syhmi?y-8Xc#*(h#Ns7oJ$?Zv%br@wkg1d%Mai-? zJzoxlrwF;Bk)nr0N;Z(vOQYA$H#hCNc69YMyPBJKU9-CN+%XWzxvjz7W0jR-yStjU z*7>(JwQoxuO{{VF+uHp0TH|QyHdFIFJu~0jJb%qkvhaZH2=rb%ohm|YVq+zq+o`tTig`VyM-CYNIeCvJqziz$PyTNy$v>_*>so$4h zon$sARkPHth3=jMUAU`zp{v8Y-tVWI@#zh)l=6yvk8yVE*4xrdNoE>{7&`Gwtw-f-RI_Tx#%St*-ezdm#;`^FPbgxZ(u?KO^E9KkeNDZ7$ zD~T@E_++9(iV);s%AiA{!nk;eQ`21}n2{->9C779dHFzh=;cyh8#_L{AuNAvsXDBmcTK#c!u4?pE*-m9sn?61Z3@eN{l3r z_n+*Lehc|lk^I7|L?tVPqpw&^>%_#ws-NRQB&y!WQyT2N@^{ZOn`Hs&N20d6m&WgPOB}}Vvo;U+A54YTI}t~=tLxi(~yIr)TB*_ zQlKp5)mQib;0I62yU%&)rE?a^_a`H->#uSLXet{P4&*)MT2W3Ek_F!l1!>_XiFZz# zz*_|9O=O|ekvx`@q8 zASssOgpl#2Iy|tb;q%av$`&)wq^_}oSMd+SjRAk@Tvkg%9(wWImuSq(PySJH%HNUf zIDLFLIN)=;6s<1Z0tX$U#Wg6wpn(IDfw?jr?aVUd!#NPFq>RHEDdEsz`~kOBWx1m$ zKQAZCOsU;=W;ZNls#bdu88mHNuMBvTWoEA>Gp&a@{oFTr*q0 z_%B*T@7XmrdQNqtV{}*OW%gZ-Y{+jJ3XJV^8I;8O?U(frT)w>?zXuX@&*=4rik8+u zNt=V6ultsgtS_w0Y%NRF8J^aWOpNq3&ArG4cS~e**DG!EFYsFdflBfhFqbw^T|RNw zYKuQ{WA1VBY~0CtOLcT~k_RM_p&edGa zuG_pnc_$j!Q$o+?S~h%!uqXT&{5Bu*B(mI{j=Zc)Yq~krl)#XGxUx+tU&_xWo08T~ z>K$|ppqnp~0O-MS4dhVP!#g0`%%IR?lQ*qfd-LQ-=eYxEyR2&)8`oNQr45|h8G4KP zCfnL3eKVU9=kA}Izke=a(l&3EjTh%CUfc6Z_HNLSKUHO6*$ztzoU< zqZYK53+o5!5!efJGEu52H6@BK&ZEHI%|uuTMwg>%k3ltq%c=rZm|v}=3E@lyX6u5O zI^R9gy~nmaIpA>mQ?}c7_k26(_XoEn4qedKcW5YK>z0Jk=E|ZfL+HMQDo0h*Si)Ae z5Zs!~Hl%FjYau+IE=Zp~X;07wKdYA2)|8hxi*mAU8Hhhlq7z959!dhCWs}{GNqcqR z5?bX-IO1&iu6i`&EjV0wneA=ue8nQ4t`=hX~dM1lQfdrvfi>Q%h%%{NXInoUX?VG zl$)J=E<8xtIYU{Y-*_v#1~<(dt9b0-^xg9*+cq-owgcH4YinDaA=%VfE#_>KqT4RN z#}@ws&S!@%^qYYLPWJ2UYt;EOBgiEI^j1nfYE(f>KwJf)1F~#z{}H1eOa`Cm&t!~z z;R@n6=E=Otx2X&_l$A9BGw_mftep|89S1UNy`+6sR=8c5Wl$tJ^jQjpph(a}QMnApJJc^H z528bIP(}b9G_Cbx$pkP-eve4App_)%%u3vlQ>P6D$B65D#NNxCo36;-o-tHgwRU6u zboCcZ%v-;EE~`I zWm5g88#mYMHpzD7-?eq6&iZ?m7xn()5(LojK4E?Nu)ZkPuSEKaFhM0^)1*=+DDaJw zbi^Ne{GnQ?YM^pr=D3xVL7!p?ur-p*JgzrE*a%lRNK7g@b7`{^~vI}gsa_|}s69CB3W` zVHYXoWyewJr@YkVFsGZ-_$Sp}vY>_ts2ZXO4?$A(YYM&qInY)p!~kg8WKr|vu4ioh zRQl%2N4MWnFrTp%RVp%n`5|K;zHQsp+q%UzUvTU8)mLmzXWAh%D*X+QUeq}^UfSHX zX>geS9va%*)m%D0*Le|qp6C~XV{kUkyQoVAA2Rew7$3DLoX*f0NMsOSM7)|~C;_Kz ziP}s2h+iQ{@#;EUib72W{vYtQ9vT^8Z-;JRNK=09xrJfbJ^!=$1H;7E721aoAT|WP zPN$Bc&VLc#gka<%5_~dF#d&R=?qsYeK*9ZfR}Z;$=U3rf%Ffv)Q=w zvvafe%^5e3>*~j-*xZ2dA)v|{iuI`pHVI{_8quEd0Fq@NEq=N7w3W=Y@mou zLFf?R;j(m0O3)kh35H{kxJ^up8Z>i~F3BkC6Lk7H@cS@P7z|;e$b^iLS(RB;TI_Nb z73Ly1ha@DcBh6_}h8|$?+trjcy+e&q%K&L;LD6>N7G#5gfGBLOfpT`8wX30QAnlT* zp*?LqyIWXF{o+${Fmxaz(%jm+yCsF)Hk{+CY;;#QudVQJZFJ=ie|l&r&so*ru5O{0 zCTF2a8&82YEF>{#F&hS$EEw^XtgvG!2?P!$6dVR0x9GpJ%= z@Q2sE_S(Py>4v}cvEgAh6#6p#42QmiYV2PE7`&5Wn+ic6m9%SEAf9M+veTZIt- zNM8tc!dcwN%2bcvqOui;)|eo1UmQ44DODDy6{V-A6=iZMA3|1?>C(m_c&`I%3Gx=q zHhTOb)|)ST?Yvk|&ymrQ^Q=W zc4VEHts6+c`E#=Txlb3I*jO_$RD~c0v95N3K3r52jC2H8?cmgay%Jgi&d8G!1=B!3 zv{SJ2mJE??-!zfLOeUv^#uOXA(@|tEEWklUPQKiDi8H8$q#DwXuwF(ia#mV<^kcVr zAOOzHH0>E^-myx*Q{U@rUiD@CV|_E9fxPVMo^PsL*N`7*>}+vCaQ+O1=%_fKkNM`g zZ((LjN2_a;WUN2h-mp5c+2Q*!JmDZ0nKB9c8pX(>AxFwiE6EZ^P~(JnKm8!A&8p`= zoL0fbF5QHG3$NgxW$lG|M;(t}#}c#0`G2oI+&a$x`_{<-PlR z6P|oB0lz{=*d=WnO^ZL3?WT=wq05L*5nucPr~M4PyEE9H0nsFr=_PqEk&aML!ucJV zn8g6M311908%k7V*|HEs9=j+a)#+$SkQIr_GhtDfy&j9rkEL<#9T)7y=j|7+U;oD1 z<%@&e^?2w{C`^lg0ykQhX0VDp>CnJK6%a9t;Xc#q60~zBFlu2~7)pc(3nzJ1iVRQ!5 ziq2T=FoWu8p6#>;B+p)z)Yg`C)s8z@p0Ts`uDfbGjiFz#H-?{{-8{T`F7%)Bv5h5F zC#y=a@6dQtpK>KTeBKq(cyPTDdS#N(E9a7-SEfQ$4Eu?I6ji1(!iaSILzT1Yo;IR2TV6SyrxTvTf z=t;_kqgey3vfMh5b#%iWOmTHwDTjW>3gysG?&@%b7TFitYFlp{>}pL)N;0-}4N}*N zi;tR;YK`X?W6nekrYq3DO!N=geNuuVCv1>l#OLBv%!ZqosP@Si-f-;&Iazov(`n0rIz?Jx4nJ2pz0~7;vJtDxi)NTF(dD zH6+maJP3dxxj}}-hGZcKg$8cDGfY5DHmuGGR*NU(V`ut^u-PD96(naSx+^m33d-yZ z(+2wT6RF`7;!&9X7|NU7!qRFwO`+ZFQ^wAk(0g*<{<4I&Hq%wJTTr_%bH1u{xTI=+ zsJfGrAI%H(uM7P{!iuyi7(@&S?b^p62f>VU3GFf@d|C>|O3KQ_ zvVb$rBpE?qi8!^7FYa1?K!MJIf;x02Hn4vO!>bcz<|4W^!ruQV`JvPe6_BT&oC934?YhlIBBEUu7JARa4UUe$8q=@Z@u-_@3524+>Cz*KRI4b z|2;lGe;fZYUjE~+L2aS;DmU}@W`my=N^6266ir!>3;k7wGYPcK%*m-qa2^oL+zCyc zC?agy%FoY12l5N^3v=>vU{)akj?@()BI7fSxQ+sjgNonkey@oYa+hg{G7@>*X^+M?F?|tw2=fmT71pUaM z+--;$Fa}4+W+#XRhc$8Sgf?spU|3*600=BWgeQH(oX{i+loMB>ABX>vYp-4S&*P6g za{QeG*IaYW!cAm)I}m!4xkA@Mins~JLMCmKzRAAGb3zfzfxj6)J>wwMMSgg@0$XQP zX@itb0rvXp!HSB(>Z*ZqRx$9+@*#Yys2HfK9)b~wVERsei=9+lAg2{$$#o)@+{a_d zo0X}L{slBU32()n>=2&OOOReM&0$x-5|jVZ5G2G8L+Iub_9SZxeVa8g&&bHXj*Ss6 zfXg-`r)mA!!$n-=61cK10+*K2I`&z12WV0EWeB)%GxMwfkrHrQ!~A^X{LY5?U5z`} z;Y;IA{Err3(SzsiV_)X@7$wv!pa@!MBINYY!#pcPgCgVR2Cxk+jO<#C7Je@3w83b= zI@RdmP!=mSfv;3AQeRN91#;VWCVs-U{d9s&kB(kBI{JyxQJRZMWM$mRo`7(3{=h?K z>;%}nk!iCRTpeQgzKFIDdZV?vA!6Kze=P?>3Z2kJ_ah6x0NT>$7@y z*sr`dYb3jG*8YjlX4iF(jgNG9kBpDO4$P#j(pL5v_C4fAhR4+(@c6aXtuMXAI=4=( z-!OR<40`eRfz#BMxmczSFpdYyi? z$pnQY#RL|Nr;NlKu*2nm)spPQEiIf>Ui`!-Mz6f`b++w?J4Scl|4Xq{v^cB!&+_A( z4^Y-+72=}a5dNQX6Vt%qo}eM~4~$6qgk4a7*c91v-9yO`dX%Xool$JFI6;)8jQ~Un za5C+&Q#^|efy7(v2poWJDhZ-)DT%uN@ROKgs1DlsbQxWFX?Y{l2HwddXk^Y-w`g&GNb!bCw4KjrmZ16Eh!e(g5VMkHnnRrZP=3_6N)frap-o6ZOW}SxGlp6bdFx zGnjQL(0-upsWa0O9^X?!;B$jBgfTY)jE=x4>ijf?pAXN^N^nl`G-j!3Xs|sPovAgW zgByl6^mGLW+6Ni})onFxrmBlqPE#Oo+9z zlYKk7A0vz$jt8+H-`9QDT|IZ+*>mSzJ@^m5#aF^}0(d%QFJR^@fk}I{7!#67jAZ*< zX|EQ$G`Sm3vrRMbU*h;${APyzq3^Q~Loe)SSMJ&K#LUd|=beYCiyN~%fs68xI%Xsv z^-$lr+;CR%kt)v9+b7vKL#^zaEHE?kK2P()J13<_I_DTjgr1z0h!Ij6IFb3=O(gq5A)K8F=QPOkSLBYAIxYuyy>2F;@c7Wmt zOH??$F_PLid9&~N|LdA|o`0+NyT5f#J9}oXCA%4Y(D+SCqv*?S^u@kpE=gX!sNA8|%C1m1`x-#i zW;}E5Gk^ws&H)@3hvQlThhzr{@2ENpnFL~Uz|V1pN)5c7aMeB@>SB-Ia$w{5fm_cF zy*fd<9b|`d@ZmmN*jz5b#tzuBo4^9RlY_tI+*=QfZw&nr;7Kl_nyH;w4=GgRE|yb7 zXkMkPWy+@ z-?*12i8LrDm0@;e$xs3Z;kAOlQrCw;;r>dnN2um9Vm%;2k3*5v>oj`&rPWQ58DZ4n z;{Q1ex_rp~RP6>PW*9G!4CFw>G{thP*xH*vQsS&BttfO3<>wBTxV)uRc6`lSUADZH zHEb))PqUeG3$_&$q-CV#ouuC}e*?+&(sObJI~N&5;pj8Sei{Uwf#8s7PF0enX&JVC zjWmX8A{KLsDG~a+MzS(1WeHN$ql+V~cSL*P)v-Xs$~o7rojz3ju{ z&&(k41GK-M)u9h>VBX4?&_0u<+5NH|daq9M@aVc+;v+nyK{^fw!x)v&h?L->-dLcA zJ3RX72hMrm$TS{DDc2{y{&ljgZb49X5BoYIT-;JE+3u_JGZUdYk?jFaF)l+U>Jk(v zP?~Z6MS~|`nbb(5#h%<83h(jM7S|&D*q!UnNKZCFOhmwyF;4MCWN}zl)bn6@xGUk) z2SvcA6Okq0-)0uynrehz?H=_^`~7RGYsUQkX^&^R!qb(N)#WMmdfBa|USCOZS7uh% zG^&i$3|EeqR#gty)DBm$s?yTRwe(Tzrb;*N+NzS$DvSmCiE~hu2KXmLt=e_LF$l)2 zrn;~o1%@vT0((I3m>BZ497A#p8T;g8cv7R4H1ik-Mb?f}7=t{8nh!F9jNzO^sc>fz zAm$WXiVX;w^ztwT;nn0p3f6S)s`BV56oXNJ5jny`joluWkukasrJfK++;nbb`Q(_d z1#!V6EqkgeT%|5{xM;Mz4e`XRycM72?$G6qHM9O}Mks!`DBri;e=QFob`%EKLi2nv z`(8#SLXbl@Bc!;kWmj>?mw{?e=+M~7L7oScBQ*vCW_V-L5CIB%KHT@@+5mMTSeS@Y zlo}v!1I27*h*QE)FZd`b7M*ije{9>;B%f(y{w})aHI9&LB!FA#Dr5!bGCDWOO!3M?H%+os` zzn3|_HXC|khJAf1bXb05YB3$p1Wq2H^B)oQyYVqgGC772dP7G_XJVX`Dej}Zs4ycvH5r@)=S1j1fZC`kViOyQhwm=r{uW6d9v^}zz)#rt;Dy~iN5(v> zaxEP*oq6>+$qfTrZk+KCUG~n}&b~<|7Yw*Yx0zO5uzL039&?I+qt9sEkvVkPJ?r+} zHOf-@w_SWVHz(aT&2{<@m9K+mq(FibI{ocpj8CW2mn_rigTCcTI1ifTb^uHV`9hcJ z@@J`%FIBnEMkQyu0G&`12yFEEHhw|gcFE#Brpmgy%E~}Mwu?)38~y%`brpd?1sd6T z_>Ld~#K59GbR$&|WZw-I7YFGlR2qAAbGVu7saOT5-A}(}r~#wz(Q5RCpo- zhP)wGZWS7?tc~N!3Gs$AVKiGumb1}M5YOvjK6an{DX{S~hnYz6AyK7Sz+^rZD0T4`lK7XVx4xKttEV+}tC-2AF4Ie^%d1>QTi0%wX^RXn-c z6=Q#9_s1Hbq33aWdKt9%kJ_JONuFF45&JWHG-`kb4Z{X4y#^cf2QmBA9fFR_!j@;4 zo4KvopzMekp>b>?#1YLDHYw;Dpz1p8Mh2Zh(H)C@3`thH9ZOhi+=FMiVf|0qkbm}f z+K{E!U_*|Mr`WF^6JuHvwH$LhuWBn!j2l@PnK821q{PTJV=qe7C1PZkKdk5ymyK`S z|d^a@4c&E2sN_ju|G|o{Ea-yegqhZ!-ArK$6@r)Ab!)k?_Kr6TeEKx?pXc+(gE0B_8wqk zPc_8gyn?3=4*)Ry5;!l=V@H86Gthr{3f8=*`dG)TV~(};hMr`B>CnASg1rZ@ule{f zwUE+)062$d&zo~^{>l4$cEQW+`B1})7+a3xUci~+IP!7DP=?2~A8(1%ip03u?H)4} zR~xgl--YgR&asZ((9^8e$+k|1p67pXxO%|7fR8IqL!o*ulo^I0Jx+srB{q1Jo~FTt z`9+adSZ0F?@qC8kRF)S27LYqyi+J1 z8Ma@r3cLbwACw^h^;bjcFWN|3q(CXAAu%gONcnkzjQcutX9bSe_1>zIUgR1;3>k=Xw-FBxvwoAgt1c5Ic z@`cWo(relC-eAz1nAkpDS2x{`i6gukswx_0y<1vZw|dp}0Gd!nIXqJuE# zNKEv#wfXp(e9ODFwPlNUwxOb`0fWwIs2TPE3+C7;H3aK0E~Ko}`;WsafYH&w&?L)O zz#^mYX{KTbENpy$6B@}ZC@U>y8O$m?2y)e|+VjvR7Nog#z{c@c{vK2hLhuW(6+i(9 zco`^4eGT5umjd-wL0|DNRZDb)t`c}6B-uoaa8|B*`Re!H3O&W{7hO^3*dkwszJOlC zeL=7+y+d?J1A;x1o_HfYVb9MlzQX4aEOQf09+TE$?#lRkz$e3ffoYl-g5fU%F`cd_ z0MC2Ua@7lqugra{pYY7>thNza99Gar{eyZi+imWF2T9^Dcw#5MjrsT82x2 z$*axjsS5bJ9lQvjtpu7~=l#>0a(ZaZo9|uyB71!3O z6gZ%GBP~qV(ds0yIKHqN#RgD(VD*S7K0uk~_|A(LjLujP zP1O}*bL4d^ymDzhg=Hv=wCzD*jkSB))Zfcc8sQhuBV+J+{3c-JMc;ksy8_(;b5&cW z1;2bGbd()qmzvn6>{tlP8hwf0rQl6JBA(5nC>D$I*C(Gm@zhh_KXKv&TR@Q5 zwV`X+0tcLo+kyLG(8CVEJ#|bM2-bWUmQXs50r}mL`}JfA1q^b*AbJIcG|J%Sr$Eb8 zX_mwifK?zO03iTz+0AwUTAY*n7QaH^Mr3l~Ag&BRiZFh%WDUX~he})6z^FSIAQ`iW zdZIpdh#ivuun4m(<*a{5wPJ8t9d8R`hZVy|f0q9cI?BfyXA0mRJ^F=E<)8^nhTe2A zl>rrton^`Ig{}eyfJX3WUYb;R7}DA@27`1Hf&1tr53mQ6D308FLh-_}f&t$c(P+t)j(xy3j{No>~pYna76#nj$ zAK~2^-dB1zRzIgfFf4Rg^UhH3m zdrL$3;G*VE9@r8npy0rfkt6c4BlrhM7Xs!p%8xiqql8mrA|?xiR*$}ja9@{lI`6v$ zjFbZ82>3g@Z|eOqUZD8yyYCV89USj}^c@hw!teNb-%Yz$ddJ(!OWX#KOlOx7qh^B` z9Gr%YQf83!5}>ov89lHvD=s>m0Zw(vm~2FC3yMlZp*$ER(h$=H!3I5wdEu`Q9_Z{k zaOhXmuZCMjMsE2k?-`bhm=opRe{B4qwNvB*jo+oLCiG2uPv^wMxA^5?Kb=nrfOf?q(!Xr__`u4HjI%Z zrYx#Q;=!w&a@%8%MaK7Sr4ZzJ#{OFf;_%-dIC#aO16`f+vAgfyycwX>v5tckyDsn@ z;xAS_(Y*$A&)I~aeU;_`YtyE?36>c5x0T0%cOpgNBYg`33t&JbmNk&zHJU5%%CPRs zoz7wk5;a&|IuTVHF3qkNuX*ptrDAa@tw)YLNo$MVC1~Vbj6sT2!#SNB!kjqh58?)< zI9wfua!eES*x|56Q(-IW0omSBLpVcC24q!jVi8SBiUz%6rR2 zzqYa&r5iGoVv1Dh-TZ4XY zd%M>k>_Jvkc9zwe#m9ClyHUAELLFHVt2fX?6WQX&GjJ_W=4u{6Wwe9DLG+ zqIyjcwmKt9HzMVXAzx4r@1R~guQSOSjbRGeHK^#E6Qunxa+8GQI0H(5skh=D%{1L_ z(2R`-i%|Xwo<-!B+S1dIR$(&aCFI2fetysJ z8>CO^709|Vp;(6|OPhuFDA>gye}DvRE8zZz-kWwOEyta9>^RJ$YyO`9dE9C9SpoN( zSk2nysIQuscxDOeoQ7|L59#;7{Y>{MycD~gd=o`_5gp#dp5*+F;u9eofx7glj7T2) zIrw|DJTuL8+Q>xOiiw8EA3%av=owZcsN?}2??vx;Se1>=W^V@fBx67As{aQNF?VkAwb|%8E|S57eXw1)a9lU)nX3` z*Gr0?!TX!)oQ(V|Q&w_vT3JThKtSHuWXiFmWomT235FK02i8fk$H-R2gVF!{_F;^R z7e7DWeSP0H{K&^Xhkq(R6Z=Ue?}q~-H#QVlRI!(g)2pZOcA0{FVLU6cI4F0PcZJ96 zWY~}&4fBrv0QQfzR_rIcb@_Ab^{*0rtcTG6%bwXVjl z*SZ?(y6B2)-tUx~dlOj8zPtbbf8Y0?e10=$=9y>unK|>^nK=VTbWQ8#<~_41+suqi zQCqe4>NSXitF^r{_n4$s&kPS3+;`i41GdfHl_f6u=-gI(-ns6_mt&BT6pwt7MTMzM z^S->-zW-0PqlwM1jbRz$G_jgIh2*HtyMIESOx=z=y?T>5DQw;!Am<^w^b-?pAJ{1~ z!pzF&Homv;G1$$uzDHBTyutQA76&17HKe(>#PkQV*J+#)Eznay^tLYF&fR4|cHZa# z*>eY0M~Wv_f7G{6<≥wn^K2`_#hG`4hX+9zoiE&mpIG73*7Cj_>>3BpZ{oGD-K& z;40(pNi(sJD`LN-z3RZ+Hu?3WDbuQk4bLAwaOBYJ{-qyHE*v*Ib41F|#th0GQkm6{ zwlL)m%Rkc=|BNhUcGi5KEcH#YC}q>ySzgn5@lR+YH|9QMhFr)0^3QfW>?i8nFKNSA zryyeLV6|PF8X2DjowA#h>{Pkc<^i~VOxaySs)n$E+WUaX1IbUd^!IBd;vD$M3o~0}=x6sBKgu1C-4x znKXIbrfR#cyao~a-&SJDNX!nQDT4c$=cklj_Lk{Q+MfhdqouH%uLJx{7) zg4!zXGoXJSH)#(U+@Ir-TaPwsrQ|l7&jdY6AjcKt4DvI>c7t}AHh!ELUy;|%_}Zu_ z&d?q+#jV>_jxl8$Q)$b#C-UNh`UB2+juywd;*2q3U#dt+U2XF1clC0ZmK&wTVsoC~ z$&BVm)Q;a5RHPF007S=d4R57}=|{tj%I&R2<_*iu88mwE=%nqzDBezIl;|n;mX@Hx zrDvJT2MuL2Y|eg@wi`5TQ2&hH8T-mfbv?^Hiyz%ertXHBJEUrl=aWnA+f=ohZ}p66 zoMG!_R!C;kCc}qZ&1X%1B{1{bmKS7Q2a?T#Ou_>pw}zCzD?Z_X?+)-Q$tTvV+2g$P z?AaG9$Ew*ry~Ve?F z%bd&GuKHT~cebeu-@myRi7!8HCo7)=SM$Rkmz|m(o-DWY@83VWe|DdNTaONNbb3oY zHlF9u?q_yEAB454f>GUKzLyqLGW)~(?lm>;K&JrVoMV{^> zvVv0`O@AF3Tj@`8Ijjn3iVRZ$_D#4@o;G;@S>p;&}&w>0?$JO zPJ?I@El|6Q8qToP5WW?Y^Zl5O_Q?$Vn#5wl&$qFZ@kT4}H{oyI9Ajf|CAAhYky9Z% zkzTzG(I)1JvAoqJmg3ury#%z9t7XKtQ&;NU(~hUSZP)Yf%iTW2w3PJ9iMc`4ikY|< zlEVgDmO|3c7vn?$XKQEiliVKQXI=4bIo%y8d-pi^#cj%3Pa2JsI62ll%F~KM^%`3% zP1Hp_VN7k0;b)Qp(jO0s!8oy_C?SU>)XKKxVj*vtIx+cfLAO{wVJ3hgsDpoU9%m6x za_#O$ewI?trX@^!&cs{~GBw+XzoA;l zOB-%CE^Ya_=?x40c(vs?j4WjTI_u!XE&K&n<2gz^hJ0jJ65M5jbod8u@9BjQ9O1&( z3^7k;ieK?NZx(B^zGA-YCvFyJ%Kl<&WXivbPEpG~+ktYB*hUVPLu9thk-2iH_%rF% z$zgK1%oC5w5pty5N{*6S%hBR-c6yBwPsnY#27PcuMXo_mlg}1LT3+%5ji9SRNwh$hl%iStIAk`C_cBm34A~ zTqqZbon*aSESJaz)(wraNiGvH=C(scfow)gXDdHaFXyM;m2#C>AP-{{d|DnZo{>jL zt_G9#2X*wP9V?HM$BXCW3GzgFk~~?SB2Sg4$u;s9@^pEIJX4+}&XQ+~TjV+NT=`3} zp3&}OQ7q3BC33AiUtS}Z@0Pz4i{w4>_wruxg1k@O zFCXA6?n82ed{{mr{~#ZgkIBd76Y@#%(ud|v)Zz93(e?eZo0vV29p zDqmx4o`{~YH{_f0Ek^H2;v*RozmsosWBa@EJ^8-;K=r&$6CGo zRDLEumtV-g$S={Yx>0^5zm|WK-^fk!TlshSo$TbB4T~xy(ttB!VU@xOonB%I%aVvn zR~af(^;TJ`kLs)Xss3t!8mIsT!xos|ji%r%ETOoz*U)QSGWGt1?xtDpaMa zLPD)pyQwMSa&`e!F*Z+LwFY z_ZQ9T0Ck}HId^6rtPW9g)Ld1g=BfGYuY|kR0`59rr0UgTaj06N8q`wNsG8I=b*O4q zEvi+uspV<~`|?()!`Lr(IQq?wP)CZtsiV}9jlI0$Ey?6iRvVEvN}bb${xct z>KEL_wTC)GovF@JXRCA6x$2kP$+cFUuP#s*Dzh7Yn!1F&&X=mokZCVhSEwt+a&;AV zcwHk_sCDXEbshJ1-=J<(H;Fd&D|NHFMXguAR=29(sN2--?7zHI-6i%^zg2g$U-};P zdv&k6Pu(x}QV*yH)kA87n64gHkElPWN7ZBMarK0HQvFdy)l+E4c}6{}o>R|rSKbTi zMQ%uaNxZFIRQ(icdR@JNJh-=dOU2aN>K*m2dQZKtK44eJhw3BMp*~ihs87{r z>T~sl`iuIKb8s8gS7N35ntcb~s7>ly=Jr)c=!dKCR3{%WB#Rp@j$jucm)(oQ&_tZ7 zd+{SlM5pTvovC~4EPi6_tNV#7bboQA9-s&6LE_h9A5LF=B4+6!Vz$oKIXYJl)x-2~ zou^0Wk$NjVN^h-4>uvNHy{+C(Z?AXIJL<7|C!H_$)djjxysL}Ex4KxD=u$mSj~Azi z{m`>GQU6R&(mU&2^saicF4N_@LRac4U9EQ$`|BxssyIsTuJ_Q>^qzVzv06{pGxXki zCSN;`(X;eyy|3O+?=Ozl2j~O!&-Fq2V10<5qvz@xJx|ZqwYp9(&zUSLl^`l|D=#u8+`1>ZA10dbK`AAFGek$LkaHiTWfy_8zED z)~D!G^=U|A2kABX7y5M3q0i7~>a+CO`W$_({-wBEpQqRA^YsP#LVc0GSYM(q)tBkZ z^%eR`eU-jiU!&LQYxQ;ddVPbwQQxG0rEk`^==I`Y{cG{QzE%H5-==TZcZmDN1L6{K zslHR+B`#t`(w|?{2J$=OV15hA=4@!L{;j@S|4!edf3NS=_v!of1NuSzklvsl){p2v z=tuQq`f>e)ep3HYNA*+sY5k0TRzIho*MHJ4hc8rZ`YZjl{u>t> z_U0G2Vd6$U1zn}T5hKNwdXsoaf2;p4PSW4;>ttB;)tzEj^C^vG>#gja`VBh>IS?F# zMLEBpab-N~r1T(79KzS8xk0+vCCCtygUq0Jkj1*|VR4(dUECq=6xRoR#0^1Tac|I1 z+!yp`&s3UN7Yqmna-+po!C>}Roy<E*i-xxO#tTvdx>k2W3Fb$ZJ9Vbm?16>_6}x>3&jQEnqVJsKHr}n31$VegMEYj zg8hR7f&+t}2L}ZQ2Zsc6g1JFWFfW)N)CP6If?#2=D5wt>2TOv6U}?}8GzH6oLxbj^ zC1_>s{M%r8up(F)tO^bb4iAn9jtq_pjt*7_#{|a)#|6g+Cj=)3Cj}=5rv#@4rv+<* zUj(NIX9Q;kX9Z^m=LF{lzYNX`)&}PX7X%ju7X=pwmjssvmj#yxR|HoER|QuG*97Z= zYlG{8>w_DD8-tsIUy0L&Sylc*ydm1fTjCY*ns`aPEM6CHhRfzP*DbG0X=|)6s4A;+ zc6q6{^Sxc@?P6z_#qA33_TkIMdv}?!^9%F+`(<(4#)E%hO4-ty`OQs@DP>Iyn;Pqu zq?I+-H!iH1-_}}}QdZ?`o2C5mk&5~C&GXxqE@-G*nO0HT)LJuteqCd$O`)KoI9xfu zhKR75n`*3YK~=ubSH3MzenCY^xXKnYTxA2hTo(9H<-XJvz7!Qcw-vtB6}GhGx;U+> zTk-`}<-Wk>@dB5oRQZD0+!y#L3yM>!TtQvZX3g7MYi-Nv@GcvXW>Uu%}0ntGU9$bkjx!g@ra$vZE+%x2|&bPLMWS54Vl1 zpsFz6yl?ET$l{KoV9LCjW>@UOvdEM~PQ71oc&dF#P2D{*)waBKhNs%9h&ao7Wlc@I zY&~pA3iHR?%wt>6%&E2YblvB4u(@V= zU2*`MQbARPOUWm1-=cfCw^F9M4v_9`_xe=V`sv=bp5dvj^$oRkT)S;7=e4`BiXyuw z3YwKf+lS#jTu^KI#w;qeRZvh=YM&)Le29v1;c2#V!_&H0AitofJeWpJxRxlgofU5J zow~?&>Vm3b$F&6&W#PSC6niB_QC#BQF1B1k=y)vU-haHVYFrqeo;1u5JMJWSZNS zHq^A)LepwhDbtfVw#2_(V$;fJOpHu#X{c#glr$z4`%5O z@?MUCXC|1|*2FfZ2NFwL9zABoV^8}uCieYP;%fC>dCHEwr&aF zxFR&$be1%0b|uAA&(u{3rY@+e_5)hA8_-+}RQVRD@|xHvZoF|; za%{c^#<>~@@8`PjeuF=s!txVG>;wu5ta!SvHbLf+nbaZ2T?Tz|_^Q(aNfA z;ADqoC=((nc=`bn(QWuKDhHV4uU5fMQJr=B(i}LWMP8z0W6>Q zwqX-2-@{$l!%f{Kq^BgBy6f^MyLC1~H_qfwh|EtgM%w(YVJKYNHLtORsPv($jg3%L z8nz-@QN+b%N>dcBbK{P)yqBBk>$*?$1y$VIZs&^v#|v3?i9FaBU2^4qU@A`@ekwf2 zR3!67h3{Pz$wNtn?;jP3UVyaf*}1|E3${Fk`PP%J;XE_zlDl_NT3uJI^iGh;`Se^_ z?szX!*R!XVdp<1h#%;DBBMfiFm%?}gq@dcE9Nc6nmp z$uBIK5ME%y6og%0bXHMhVb|tzh<+eO7A@=aBk zJY+gYQDjk4DU)a$QC1I+cznK@3X`V~=O_x-+cz^PYeQX2OHbE|de%er3GNTqI|g%> zOSC?bBkSS&v+a;{EjLYM)+hJp0>@m1p1BI$tlz7CY(vxhhFLTB$n2uJVuWpcwN$uj ziPU#>aUWfU=Ya~Bq|b+ai+s4ZQtEvd_qL0_-gjJYThDO4lg^xFy;S|;@M8DST2_S0 zFD&w0RAhO>Phieb7+IXCovb9<#?sTHFucV2+ng8pXtAwl`jUmsb#;vmHI23P^TQ1; z8`dfcH`o@6ILkgsqIv8X$65Yy_u-J0rxlxx?NYO>;2cFk1Kp#SG3>K0%J(mq(SoXY zM(wcb95w`l^#s@8MZO7(l6$su6h#{Bvd(9(i!KT;wO-EhDHi)-wK&1IEOZ^;h8taY zYZZkXUDY_tMV_E}?5f6D{&CN$DfUak;^f7=bHwxGIjlID!<-`?!jGTDi9SM(6N4#r zB~8aB8^?sYe5oSr0W_NrUF~EI8hXCvTW=crP8xcrEjE4 zpIoK?kWe|!bCR8bS^e7&33U57+xeNfqB_)+wEFj-8>-^5`B0U1{$`a|kkOR92=i%F zr!+YRb$KiCZ^g+AT#F}Y z9=i_VEdRKxLpX*nC~*vrZ3DPz!#VtrP~b;_g2Y_Fa?(2dx~s&qLP;_!I7d7VFDw=$ zIyrGzM?4NcewMiL({%{vC=9pQa=L0P^-WniF4B@1k6e`(_+~Hl%~|TJymUg?v3t;J zW-DXZ(uP}I4LQqt*@y~C{bX9|^6O*w!*78fe(l&W!85}ISARZ_UPLH$s}}F+OIYek z7;bY}uvSr|%@)ymCDBFUHaAH*%RlatDT=b%5>;Ry_Vln7KvjE*%t<%#2DKbsl-bs8 zI_vKA6)O7{(12p*H)`#F{quXIA6MP$)$4+LU>ug+dht@)l;a=e#fz< zeVW!q()FCs;4J$zlAz^B>!w0YS zEK{A#GS1 z@C$Y4h{x_*v^u#(og*H*eNq%Y%(hb6VO?trH_lBc(hKG+2!T2E)@-o(D4Jlu4(At@ zO-MPcuDNM!>w+-9&Kaw9g>j{}EFr-VvQ6>!=&ZJ?(xil>4(y#$-8iq3U#87P;0=u{urLo}_rQ1?Cx+SuJ zm_40tqx25@e*Sp-g`Hol>?DY7XIN|(Z~l1O4!G?^ifzB5Vq4h=+kTP9wv#FAY4>YI zez|q$=a;)VJ-^(?H_pe0#!8d_{Bb_MaX!9rKE84OefNVczu)?NxseRF51;SD=lk^Y z?bm;vm#d1Iz3W!aZ>U*X+q9x_?EIRRx;}@t)wQ(NH#K(o^jlWfT;Eh{e#YgOx>_4* zU=KgDG^;3^6`9x8&`{TEgQPhr-NczWuV(&|gfp^e)v`r&Jo6}0*I3K%HJ)DDMW-#O zU)V-!Jad&$;47mb-WXP}qf)Cfm(?`0^r>6m((P@X&9+Co#F60Y5|8H@XX0^|aWAQ3 zf$QJz<2@2Vd@J|_$5r)R*j7(5mzq_vf2m)WSK>7rtc7oBgiQ`+y%NDp?DLF_FLW|zA^hs%8*hK4f(n=PKI_>6S=}qT1+z@vg25DW?)Yf8F-#(1bx?Sgx_3~aO7RMJhE=y*_ z%j3GgD~t|1%grzGk5>O9>l$tlMX##BFscEb$4Il)Lf0#4}n+h0RcY5xa0qvton% zB)TApu1KOSvlDil_ZtUY+{;Qy^P85=>t)3fL;2?gCalRbcDeVf7|Y<~{oH(3lpjx{ zA}PGS+_A)4vlYqjK3(Ar9S?8lcz8n>ae7XeOR0LBgLEPtTnH4q8YO3Q zq^M-aqZF61_fd)m`Iqeb+kp9qyj)0jc|V2ujC=<3IfXg`_BM~i9L1hy$$sX^n8*c~ zRcbC~t+@h){l6z+o~lm8T%&HrT+hB!$*xmWuCcfA&(NLhOyr`J;5<%8WwM`eFlP?( zIQuZxoIJE41-S@F_iTL3ZP8L5OiXusU(%!;eR(I17`EelMWIlY)zfB)NewlvjqJVE z^OvVz9;4^`;@QE&_YJmQ695HQbuly+#`bY8Drd;JndtZnXj50 z$gMK^{^b8dGG=u9AC|G*kNr>or2Bujc)G{>qh0A=rhjSU`Jr44&e-yQen!&&kOwnL zI(O7pay3&@W18!{xn~g*TEU1w)lTY@5f1}Z^n%DZ!$ziIOF1s zqcYO%|2vsuGs^A1aho>3ml*m&neIVN;A0eao~BTKaE^DyhCimj^Kar*SRtA zpmS4#PEg4q626|=aWkLq@%Y}DHha&7-g2Hc3*5t_=ewP;9sxvW%=mS7^z`rPPR?^T znhOYdKdJWO?#_)r9IH#Ev)$PV)4a+1NjbAV#!X6{cXviRJIq_IJe}?QM{T;Bl`jz| zCqn+&zqHL?+&s_ZrmNp{EBR0A8_BW6Q>Bf1)NlOB_u5>4@+O>Yq*ljCr-q#8_nS`1ta80*dI7g3kw-Ca4{iODd=X1-k^?d5w3E!UOqSf9v zF_{pFP>HxZudsbKW=&L+yFY4h588IUaoN5erC(c@^*P)1YTnrZ6|<)8<@RX@XAwo` zhNO4fJ0CMH^VhlFzq@fuxp85(oYVL-8_SmaMk2@-_#*L;_zf3(-uC=E+s3<&vQQU1 zwfVPxHtz{{ay*_!qt*}ob-re6im`$ImprP>!0ko|(?Z>Ppz}Arw)M;ylQfDDOBwH4 z{&Vle!<)R=HZ7=Tj zo_SoB2=mWTw45FLH-FpKbw{V0Z+y@6(}aAq&nFZ;QP>tEDllmd+KE#d)lm z&a!K!3+$TdcXrKmk9b79$?2w;yj--Kl@ljtSvhf{m6elx#H^e+Im*h36Qiu0I5o=3 zi8G+AoHzx_%1KQ#D<@7}vU1|&B`YURU$Syi=a@B<&gGs0QNo?SC8-{ldUqx^C9%)? zV`qarAxlPMpAAen14>tNwMX19ZpYs@@s9_)fJ(4Cm?2cjzThA*4{+;6Nh5YEIE?2e z-qqe-gKg4`<9up)5S%3CP})K2sq|i{ceCa+db-q=w1x>2g^t)T5!%ksJjLIHkNBsK z=0*@TMAWKmki%+D6RLywWA^>Hs{_|YuH(E&4AXatYVHQC)%VecDWu*(K05R{ym2mA z3myWD*dmpuck3xOM3fMZ5#ljIJVuDe2=N$a-C~`$i?_i$;9c+@cprSw$>q=>fbL74 zo|A*Y5ReUWKrR^8xn2$jd0+$>3AO^Gz}8?i*rs!R5bAs`2-DBE7cY?Ni@?l&FM*fA zE8tb|8h9PN0p0{}0p?Niw}Jd^Ab%Uk-v;uxf&6VCSL?~udUCa%T&*Wp>&ex6a z^i}5aKLpMh#o0;2LphXWdvxzraH=zp^MWUH^Tw&1UK=mYgqwD@{Io0l^ns|6gXA{i zWOepB}0jOO#QALlb)l>IrK z`H~#K`OH`3KywaL4l-vjz*N zl!9?!JeU9`f}ep&U}vxk*cD6$%*3)BRDeoQ1*!oYBc}lPNA3>x0Mo#pU@tHoAOXm| z!A!6Zm<48oeZhWUe{cXe5d0h*1P%s=fH`0;r~&i9d{7JOzyh!kECTglF<1f`z*5i% zn!qw}C};*PpcS-%;WOTeYzGH^M#0$d5M0#}1;z&da( zxDH$oZU8reo4~KY&EOWW9{d{I3Vs7_1Gj@az@6YO@LO;<_#LDtBG*}Ie0mp*l!13S&a3VMroW{ufG5D1HEfkFTVi*_>^1ui%5^M!3 zKozJ4yMZZSD%c&cCK1!Xo?tI99n1iGgPC9-Fbm8E`-1(z{@?&`G&lxa1}+CzfGfdO z;A(IUSO=~J*MaN74d6y_6ZjRl8QcQagI|MN!EeBA;C65axD(t3ehcmfzXSJx--CO> zec*oZ05CJx!=17JFMItnouA8R!M~yR%kRVt*~xtn0-$e6DWE|BLLdxMKo;l&`htGo ze<0VWtKpt&z&gN)rWnx_Bbs7FQ;cYe5lu0oDMmC!zf|-~MZZ+^OGUp_^h-s*RP;+l zzf|-~MZZ+^OGUp_^h-s*RP;-Af9FQ^0C*5Q1U7(&!6V=g;8E}xcpN+do&n^svbjm_|)TilisABG;*K%qmlc#J7yTa zsYQhX8U!E&!XO2tf?gmEn3YR9$N-t3H^>5gKwr=g^algLKw#EEgTWAx4RXLxRz<_W zaF7Q^fRSJ;PywnyHP{VI0aL;5U=J`2>d|H<$_b0kgnturJsT><!D4ohc>Yu+QfQj6YHT(tcNzS9@@luXcOz9O~~l&$ms3J=O<)-~6f}bt&1J{DF z1^o7cj2=Zsk0PT-k6j?ortd3?l@Dg|#yaHYYuYuRW8{kdw7Knkj z!8_nx@E&*{e23QTPB8~*We(EH9Hf;wNGo%YR^}kB%t2b2gS0XSX=M)5${eJXIY=vW z6f=XG3>eiFqq;(JR+RwhSs^_uq-TZntdO1+(z8N(R?`5|v)T(FJ*ydDZ!i-eJ*!y& z=~*E?E2L+I^sJDc)q&vW;2>}?I0VcAb3qN52j+v?&M51SDC>?W>y9YvjwtJnDC>?W z>y9YvjwtJnDC>?W>y9YvjwtJnDC>?W>y9YvjwtJnDC>?W>y9YvjwtJnDC>?W>y9Yv zjwtJnDC>?W>y9YvjwtJnDC>?W>y9Yvj;J~ToCr=LKPQ7zp-%&Apnm~Q2WNmY!CByJ za1J;Z{1Ti8)`IiF1>iz(5x5v!0xkutBGl#J3UDQ06@jD{MN*3*sYQ|0qDX2{B(*4# zS`8fBa+%iB(;r5Y8#Q%HX^BQL{i&`q_z=B zZ6lJ}MkKY3NNO9A)M7|#F(kDZl3EN&Erz5PLsE+&sl|}gVn}K+B()flS`0}ohNKol zQi~y}#gNouNNO=8wHT6G3`s49q!vR`iy^7Skkn#GYB40W7?N5HNiBw?7DG~tA*scX z)M7|#F(kDZl3EN&Erz5PLsE+&sl|}gVn}K+B()flS`0}ohNKolQi~y}#gNouNNO=8 zwHT6G3`s49q!vR`iy^7Skkn#GYB40W7?N5HNiBw?7DG~tA*scX)M7|#F(kDZl3EN& zErz6Kz8!WTjTs5dNL@zKGSZcisEib4Bqt*+83`$-iwRo-O2IfV9&AZ!n%o&ha_T^G z+NjTgX8hBPdz!ICZvZdy48GSNf)419u|L876#KKzO-NN8NL39;RXN;AJ(Szw1HPtJ zU{>)>Ef7cXpDT{$KS!+QKUW;Xe-2;P9^k3D&nplwa7R=o_eXxf{b7IRKTUkZe;T(v zevJ7k|7qfL{?o)?_)p`uvcF<}#ebUk8~YFsQ z<)&cvlD#k^GJ=V|BTN)OVfK-IFj1C(IY17;L^ecu!Z5!2WpVo^JASx_@*EN2F3P9* z2K)?P0Q++Lg@IH}_To`cw z8hQf7Q1r>9i2+6qMbA%f-5YuQ&H1a9*a6KFvDHVDv zy%jXFD)crQ4Jt-rh2CCo4~^Uky_4Pv8tE0fh&%i=GVFNK-|mg-iwrxNFWF_fj4#~f zx?H52FP>tc`QnMmH%-ik^}}L_xtUH3=5D%2p^Tb1)BnuZ-+(<@+wq%<`34+_9r!gR)%V>>QAr5XgCpWV)(eu`bdSV5ioQEc z94k&DcJsA(5H}Z|f{*!TJV>0uf0q4nJV>0)o;JyieHY<#vA7i4>}Lz;^$(EBgW@4_ z;d=ig;!pH`!vlRS5A^pu@F6#5O3w)$g5N1TKYYT?i_&w&XW}zx#~WXWFQ6TVd?~(! zc6_o?@C$|Kman<3Tza1QMtlS9IOkjOEwtmG@5Fb|j*B4Z-;S3QDr5M#Z8-`x(a?^s z!ZHl)xGPnrLOUKylV*RM59Iahi=o49)cQ2E;n)$D zSC!?}bjz!~Ew83qUhQppH630ZA+q4o(PF4s{fXgb^@q=7Wi+GiuMU7d5RO%LZ()er zMNj0{pOfI&kmc20mRI|5E9fmE&vI;r<<+p|)m+c3j!PYXI?i-F>A2DHq2oZudyeZ2 zzYR9OGl&t~mpKt0WBrIZxd-oMSWer@a@t7CXjqk`8(_IEWVx;{YtO%k(U$ijW(5j2nmvXV~y3wzk z%kT8r6TxIq4W@yA}90092}9bb7{w1+VlU`&OSZ+ z*z9w&PyX+-Dbu;&^dD>gd-Iz^W95XC@^c~d<=`9q_rm_KcCVw2&nMk~wS5zD-U@!I zeJ}59$bLNgY3vuWU(NoX;l9h|hdjCb{HxvnedUc&rVqd;;L9Ij`+gel$Nw@roql*W zJn#c{ZYyC1=M2l~yJh=-pKrNd;`Q~v_4EIB{p5_IeA|Jzoey8_g1Zz<`X}u2oGJGG zAFzpeijhNdW`P59_VV`J|8@VH>tg}&H-Kia@;|_ShyKXAFXzA5HhnX9cVm+FQQ$mq zan6-F*J0nBb6d{w*r(>4xtV{@aQ|Yr$&blbS3ds5@%JoGS9*7o=KbIi@FaK^w1a=- zPkZIO4!Z1|4{g5R`46!_%h{OoE&1km-3AMnwtswgSb0x|EK!r<&MtX zA-6F1zt_(8>Hk>!-cseB%Xy+N*MFD)e{Ox=LEpRwJP02B z5q6X?&x4o2o15E1R^#{H=Kk^U|NGq4&yW+bJNU-?19tqoBEL|fVUM57eq+s>j42DO znQ47mEuCS_A=d0;{ol6q;nv*A`uu@CFvNp|Bc(aBBGH~?Or#oon7c7|vSx-g$MVZE zKGsaN@$6vDt*yDEjkCj;YOxLfsp75+`KhH3wB~iz=Q>LtZt24=H_@e{L_hzLDz)*9wm$n=v!C_p zXX%?PeUqirEuC)Zp@wF+M=fTvG5L+&#NTXdfOV{Kfiy9fJqGR`m>29lFfWU(xBw>= zU9p2@9=~SiTZ~6<>l8Gy?l0%^zeui@%g~>?TE2;9)DO{ydOp8wUx)tEyX5`oB7GVi zq3vQo4R;o)f%7rt9p;`adC&a$OP8t9)|_Z=DU=T`;C?uj-%!7>Mm}n;xsy?AK5xyJ z%`JoS&8FtsMm2014*8zBCQNpio9pEl=AvQwwYghVe%I1AuSEsiTGgV`S_!GLqrLyR-ZuL$On$3veiW^Ds;ADDS9|Ivw967kjIgHT zpT3qJYRxoj+8)N<6BDwJHM6bRTRo4@F!e0vaP>51p7qbPW|lQ`Fm1hAdyqZ%sPWO9 z5~aDk4oMCbdp~@+i^-*8LWRg_3TdaKtud23nzDG-*S;mg2SLj)=WQ|1M;E0G&**#v za}9f7WSFyan4G}FJj{%r>722Jo&?IlWKa!8f=VI#&<^1|>}A-CgbH(}SN=`qLhZ%L z=N$Als_-G?^EL4vx>oPPbr8FNjCN3f>$>nRDWg&j6hU}W_`vYo@B(r#!~4^t>$(3{k3HT$x*qzx6Vr0BaG5JZCXpjVLLv~mW0g1$k&pg-?r^4?|| zQ_+@+PExdF4zzkQ(~>o12GwZEv<-te0P7Qn;B54T=u5p!Ux|*?>(GyS6S`6F(08Hd z^d5Aa-j6=hC(&j4v~CXuqt!DPO`dtd$Y2zjJGTqCt1I*!ny7a|KlV6uV(%&|Jqg7 zUWFdqzUaNpM#Jq$JsN$sW7+?vB9p}lVmI#A+EdIB`=GP^0QNW@BaUZp*u&xv%*9WL zKZ>WsGvYb4OXs7jdp!ENC!>*jik!wMKZ|kxAUPL}+KbSky$p@nE76Xa6)D$!`@1^!e2lIaHVmg?U{`1jF{4lzR zpFjukGw2?E5skyIsW;Iu{2rQxJJ2Zn1)7AvMt|^kZ2t<_W!R4$g*ogV+=`uo+p{aM zh~u;EUkv;5#IW14Fr~)57nBJHlUvzfB2J(o_1UZ%Eh6Pp)sMcq2kcQ(Bx2cXj*7yX#db5q1w>m(6Z3- z&=H|yLnnt$51kvjFm!onUFfFJt)aU@_l7ov9uGYodLi^`C>Hu4^hxN;&^KWb4u{j> z&cWef;Zfo3!ujD+MvC(A6!>+P8!^HS;pXtl@KNF8!>5MN44)UiID94J%FW^1Qm#(9 zDdo15dr~%}Jel%*%Bv~wq;#b2n>sJGG4-(26I0Jly)^ZP)H_li4Bs8TKm16_mnq+- z2C3<({Zn&ON2TtNTAVs5{ABpq)XH#s_;q^AByl?P(Oh)d*P)HR9)0vnMUyxb4fbtf zg;<4jbEN4%jBA_q9y9*27qEkUf1e>af60Enui3lzt0mY-eI?v%czJU^9&6?a`IRyCHP*b89yP{LD$UFa!O50p zjDcQ5eU?XNnpp@<(0t9ZR1Nd9qbl??J8rYjPYvNc#p(R(MJVlSHvPVr){*vw4QGa( z0Nu3jqRaaZOS4B)?x<=FZ$}=*oDz8!b4KJdalh!Kt9sgTR24MvD^hjT*%t-%8b|eof zH!?CZCc;Q2M#=4rsY@|WX7?#3u_$i*F!Z^GmKT|)>?4Lo6T9(whML4w+YpAdO}&yn zcM_5ZYLNYnrdA~L!q)76J%wGXzZ4hA%h~0)ztO+VTM_OZspl@l#sJyL=n}?k30g4Q z0;DdZOBnO;;Bd^NgQGEz3r@s5DL93h`?TP6;^4-GE%uJv^_{_>U2eV%~kG;`j*aw|Y*{T`&m6*!tuf#NF041g~3n(#@ znLu$X4mXpC{lx*8$1x))aU!#VlF!ROVZMmmuH?(|70lNpV}pECzJ>X=d6NPe^=izBCstOQ?rj=8NKY7 zOY}O-8;sN$WCazNeS%8NenB;6f8-P`3y~^{u}hIH#$!)J!kC1;3v$L}>~f@yO6+Q6 zjw#r?BY8~2-V6C-2KG#(kXhLKB8%*geIOFaLD+{Nm(0bUhjdbly#N`78*SubB$Wp2 zM&y-c*v&{St=P+vT~=Zrh6Hm2_EE?&tFezonmHc(L}Z$iu}?*^S%ZDLJVTzzZv6~o z8FNCQ4-$AnBOX09zyPn3Dk8BK4S406QZ4m=gd6 zy3p?a{|$241GsNPI(txP!0g7y-FVkJyRc~7wE(E@zDF|gY`mvxIO`TmOex;(nshMp=awkx?UftPlDc8 z&((|dQQFKkx3K$vir7Q!CH5Ax#C~XwpT`=1fmkFKiw4msmWgK3Dwd0t;xKUpCjw4j z*ZxQB(EpU(_>|wuE-KOqPcd5J8J?dU{zj{bL zq8?LEa_;z9^(WP?UQw^Bx70i8ef6RGSbe7cqBxDNzEz!CZE*~h)L8c#K1!^%^|(Pi zA|4fwizoRq__TOdJpWJB)s^yUxsI|va}W~go{VSH z8N2pooZ5#mX*T0e4ddH<#5`3w@FrK~CV(qq2Wn;49VJ7{9gJ345_Yz$Ud z^DxXqgCnhZ1ZI7J3`&?|tKaKSl(f|Me literal 0 HcmV?d00001 diff --git a/assets/brand/lockups/hub-black.svg b/assets/brand/lockups/hub-black.svg new file mode 100644 index 000000000000..41adbc902041 --- /dev/null +++ b/assets/brand/lockups/hub-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/hub-white.svg b/assets/brand/lockups/hub-white.svg new file mode 100644 index 000000000000..3fb1c659282a --- /dev/null +++ b/assets/brand/lockups/hub-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-black.svg b/assets/brand/lockups/paseo-black.svg new file mode 100644 index 000000000000..104dfefa4496 --- /dev/null +++ b/assets/brand/lockups/paseo-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-hub-black.svg b/assets/brand/lockups/paseo-hub-black.svg new file mode 100644 index 000000000000..849f5fae2440 --- /dev/null +++ b/assets/brand/lockups/paseo-hub-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-hub-white.svg b/assets/brand/lockups/paseo-hub-white.svg new file mode 100644 index 000000000000..0174e895bb86 --- /dev/null +++ b/assets/brand/lockups/paseo-hub-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/lockups/paseo-white.svg b/assets/brand/lockups/paseo-white.svg new file mode 100644 index 000000000000..a14ccab72d02 --- /dev/null +++ b/assets/brand/lockups/paseo-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/brand/marks/paseo-black.svg b/assets/brand/marks/paseo-black.svg new file mode 100644 index 000000000000..b6f1db1f3e57 --- /dev/null +++ b/assets/brand/marks/paseo-black.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-green.svg b/assets/brand/marks/paseo-green.svg new file mode 100644 index 000000000000..51d22edb5b39 --- /dev/null +++ b/assets/brand/marks/paseo-green.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-black.svg b/assets/brand/marks/paseo-hub-black.svg new file mode 100644 index 000000000000..882db41661b5 --- /dev/null +++ b/assets/brand/marks/paseo-hub-black.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-green.svg b/assets/brand/marks/paseo-hub-green.svg new file mode 100644 index 000000000000..6fb1dac7ed2a --- /dev/null +++ b/assets/brand/marks/paseo-hub-green.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-hub-white.svg b/assets/brand/marks/paseo-hub-white.svg new file mode 100644 index 000000000000..1a15ec539c5a --- /dev/null +++ b/assets/brand/marks/paseo-hub-white.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/brand/marks/paseo-white.svg b/assets/brand/marks/paseo-white.svg new file mode 100644 index 000000000000..152c280e8c3d --- /dev/null +++ b/assets/brand/marks/paseo-white.svg @@ -0,0 +1,3 @@ + + + From 7b9c6a7d4a2096716d68f9ce13361609e15ac639 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 20 Nov 2026 16:35:11 +1100 Subject: [PATCH 014/109] feat(providers): bundle goose plugin with multi-provider model selection (#9719) Moves goose into a built-in opt-in provider plugin (`plugins/goose-provider`) and lists models from every provider configured in goose. - Bundles `plugins/goose-provider` with `server_info.features.gooseProvider`, legacy host catalog fallback, legacy `extends: "acp"` config migration, and legacy session handle decoding (`COMPAT(gooseProvider)`). - Adds `context.request(method, params)` and synchronous `config(state, context)` hooks to `@getpaseo/plugin/server/acp`. - Queries goose's provider inventory RPC during discovery to expose `/` entries (falling back to the base catalog if unavailable), switches provider before model on selection, and namespaces session config snapshots. Co-authored-by: James Dumay --- .../e2e/browser/acp-provider-catalog.spec.ts | 51 ++++++- packages/app/src/data/acp-provider-catalog.ts | 1 + .../hooks/use-acp-provider-catalog.test.ts | 18 +++ .../app/src/hooks/use-acp-provider-catalog.ts | 8 +- .../src/server/acp-internal/connection.ts | 40 ++++-- packages/plugin/src/server/acp.test.ts | 132 +++++++++++++++++ packages/plugin/src/server/acp.ts | 7 + .../src/messages.checkout-pr-schema.test.ts | 2 +- packages/protocol/src/messages.ts | 2 + .../src/server/agent/plugin-provider.test.ts | 26 ++++ .../src/server/agent/plugin-provider.ts | 4 + .../src/server/daemon-e2e/goose-fixture.cjs | 88 ++++++++++++ .../src/server/daemon-e2e/models.e2e.test.ts | 57 ++++++++ .../src/server/persisted-config.test.ts | 28 ++++ .../server/src/server/persisted-config.ts | 26 +++- .../src/server/plugins/builtin/index.ts | 1 + .../server/src/server/websocket-server.ts | 2 + plugins/goose-provider/icon.svg | 3 + plugins/goose-provider/index.server.ts | 7 + plugins/goose-provider/paseo-plugin.json | 1 + plugins/goose-provider/server/models.test.ts | 135 ++++++++++++++++++ plugins/goose-provider/server/models.ts | 82 +++++++++++ plugins/goose-provider/server/provider.ts | 17 +++ public-docs/plugins/providers.md | 7 +- public-docs/plugins/providers.zh-CN.md | 7 +- public-docs/plugins/reference.md | 9 +- public-docs/plugins/reference.zh-CN.md | 9 +- public-docs/supported-providers/index.md | 2 +- .../supported-providers/index.zh-CN.md | 2 +- 29 files changed, 747 insertions(+), 27 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/goose-fixture.cjs create mode 100644 plugins/goose-provider/icon.svg create mode 100644 plugins/goose-provider/index.server.ts create mode 100644 plugins/goose-provider/paseo-plugin.json create mode 100644 plugins/goose-provider/server/models.test.ts create mode 100644 plugins/goose-provider/server/models.ts create mode 100644 plugins/goose-provider/server/provider.ts diff --git a/packages/app/e2e/browser/acp-provider-catalog.spec.ts b/packages/app/e2e/browser/acp-provider-catalog.spec.ts index a7eba2a9d21b..b04a73327c5c 100644 --- a/packages/app/e2e/browser/acp-provider-catalog.spec.ts +++ b/packages/app/e2e/browser/acp-provider-catalog.spec.ts @@ -29,7 +29,12 @@ const ACP_PROVIDER = { interface ProviderCatalogDaemonClient { getLastServerInfoMessage(): { - features?: { fxProvider?: boolean; hopliteProvider?: boolean; plugins?: boolean }; + features?: { + gooseProvider?: boolean; + fxProvider?: boolean; + hopliteProvider?: boolean; + plugins?: boolean; + }; } | null; connect(): Promise; close(): Promise; @@ -204,3 +209,47 @@ test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo) await client.close(); } }); + +test("adds bundled goose from the catalog", async ({ page }) => { + const client = await connectDaemonClient({ + clientIdPrefix: "goose-catalog-e2e", + }); + try { + expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true); + await client.patchDaemonConfig({ removeProviders: ["goose"] }); + await gotoAppShell(page); + await addGooseFromSettings(page, getServerId()); + expect((await client.getDaemonConfig()).config.providers?.goose).toEqual({ enabled: true }); + } finally { + await client.patchDaemonConfig({ removeProviders: ["goose"] }); + await client.close(); + } +}); + +test("adds goose through ACP on an older host", async ({ page, outdatedDaemon }) => { + const client = await connectDaemonClient({ + clientIdPrefix: "goose-catalog-old-host", + port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port), + }); + try { + expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(false); + await seedSavedSettingsHosts(page, [outdatedDaemon]); + await page.reload(); + await addGooseFromSettings(page, outdatedDaemon.serverId); + expect((await client.getDaemonConfig()).config.providers?.goose).toMatchObject({ + extends: "acp", + command: ["goose", "acp"], + }); + } finally { + await client.close(); + } +}); + +async function addGooseFromSettings(page: import("@playwright/test").Page, serverId: string) { + await openSettings(page); + await openSettingsHost(page, serverId); + await openSettingsHostSection(page, serverId, "providers"); + await openAddProvider(page); + await installAcpCatalogProvider(page, "goose"); + await expectProviderInstalledInSettings(page, "goose"); +} diff --git a/packages/app/src/data/acp-provider-catalog.ts b/packages/app/src/data/acp-provider-catalog.ts index bfa7ffe3cf2e..0bcc218bbf8d 100644 --- a/packages/app/src/data/acp-provider-catalog.ts +++ b/packages/app/src/data/acp-provider-catalog.ts @@ -224,6 +224,7 @@ const CATALOG_DATA = [ }, { id: "goose", + bundledProvider: { hostFeature: "gooseProvider" }, title: "goose", description: "A local, extensible, open source AI agent that automates engineering tasks", version: "1.33.1", diff --git a/packages/app/src/hooks/use-acp-provider-catalog.test.ts b/packages/app/src/hooks/use-acp-provider-catalog.test.ts index f160630508a6..9713a87cfa7b 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.test.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.test.ts @@ -150,3 +150,21 @@ describe("ACP provider catalog", () => { }); }); }); + +it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => { + const goose = findProvider("goose"); + expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({ + providers: { goose: { enabled: true } }, + }); + expect(buildAcpProviderConfigPatch(goose)).toEqual({ + providers: { + goose: { + extends: "acp", + label: "goose", + description: goose.description, + command: ["goose", "acp"], + env: {}, + }, + }, + }); +}); diff --git a/packages/app/src/hooks/use-acp-provider-catalog.ts b/packages/app/src/hooks/use-acp-provider-catalog.ts index a5d7bdd8bbd8..8bd31c05def9 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.ts @@ -19,12 +19,16 @@ export function buildAcpProviderConfigPatch( hostSupports: (feature: HostFeatureName) => boolean = () => false, ): MutableDaemonConfigPatch { if (entry.bundledProvider) { + const feature = entry.bundledProvider.hostFeature; + if (hostSupports(feature)) { + return { providers: { [entry.id]: { enabled: true } } }; + } + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter. // COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter. // COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter. - if (!hostSupports(entry.bundledProvider.hostFeature)) { + if (feature !== "gooseProvider") { throw new Error(`Update the host to add ${entry.title}.`); } - return { providers: { [entry.id]: { enabled: true } } }; } return { providers: { diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index fa8d14972c23..2a83f6f1a959 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -23,6 +23,8 @@ import { z } from "zod"; import type { AcpConfigAccess, AcpConfigChange, + AcpConfigureContext, + AcpRequest, AcpToolCallSnapshot, AcpTransformer, AcpVendorUpdate, @@ -261,10 +263,10 @@ async function discover( }); try { let catalog = await runtime.discover(input.cwd); - const config = runtime.configAccess(); + const context = runtime.configContext(); for (const transformer of state.options.transformers ?? []) { if (transformer.discover) { - catalog = await transformer.discover(catalog, { sessionId: "catalog", config }); + catalog = await transformer.discover(catalog, context); } } state.emit({ type: "catalog", requestId: input.requestId, catalog }); @@ -902,16 +904,13 @@ class AcpRuntime { this.autoAccept = enableAutoAccept; return; } - const access = this.configAccess(); + const context: AcpConfigureContext = { + ...this.configContext(), + catalog: () => toProviderCatalog(this.modes, this.configOptions), + apply: (nativeChange) => this.applyNativeConfigChange(nativeChange), + }; for (const transformer of this.transformers) { - if ( - (await transformer.configure?.(change, { - sessionId: this.options.boundarySessionId, - config: access, - catalog: () => toProviderCatalog(this.modes, this.configOptions), - apply: (nativeChange) => this.applyNativeConfigChange(nativeChange), - })) === "handled" - ) { + if ((await transformer.configure?.(change, context)) === "handled") { return; } } @@ -951,7 +950,20 @@ class AcpRuntime { this.configOptions = response.configOptions; } - configAccess(): AcpConfigAccess { + configContext() { + return { + sessionId: this.options.boundarySessionId, + config: this.configAccess(), + request: this.request, + }; + } + + private readonly request: AcpRequest = async (method, params) => + jsonValue( + await this.call(this.connection.extMethod(method, params as Record)), + ); + + private configAccess(): AcpConfigAccess { return { read: async () => configValues(this.configOptions), set: async (id, value) => { @@ -989,6 +1001,10 @@ class AcpRuntime { modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }], }; } + const context = { sessionId: this.options.boundarySessionId }; + for (const transformer of this.transformers) { + config = transformer.config?.(config, context) ?? config; + } this.emit({ type: "session.config", sessionId: this.options.boundarySessionId, diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index 4fa16a78eb00..718e96ac1c3f 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -2320,3 +2320,135 @@ describe("ACP session history replay", () => { } }); }); + +it("sends extension requests from discovery and configure and preserves JSON-RPC errors", async () => { + const { connector, instances } = connectorHarness({ + handleRequest(instance, request) { + if (request.method === "_example/catalog") { + instance.respond(request, { model: "vendor-model" }); + return true; + } + if (request.method === "_example/select") { + instance.reject(request, "Vendor rejected the selection"); + return true; + } + return false; + }, + }); + const registration = runAcpProvider({ + id: "extensions", + label: "Extensions", + connector, + transformers: [ + { + async discover(catalog, { request }) { + expect(await request("_example/catalog", { scope: "all" })).toEqual({ + model: "vendor-model", + }); + return { ...catalog, defaultModel: "vendor-model" }; + }, + async configure(change, { request }) { + await expect(request("_example/select", { model: change.value })).rejects.toMatchObject({ + code: -32603, + message: "Vendor rejected the selection", + }); + return "handled"; + }, + }, + ], + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["session.configure"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ type: "catalog", requestId: "catalog" }); + expect( + await waitForEvent( + events, + (event) => event.type === "catalog" || event.type === "request.failed", + ), + ).toMatchObject({ type: "catalog", catalog: { defaultModel: "vendor-model" } }); + expect(instances[1].requests).toContainEqual( + expect.objectContaining({ + method: "_example/catalog", + params: { scope: "all" }, + }), + ); + + const input = openInput(); + await connection.send({ ...input, config: { ...input.config, model: "vendor-model" } }); + expect( + await waitForEvent( + events, + (event) => event.type === "session.ready" || event.type === "request.failed", + ), + ).toMatchObject({ type: "session.ready" }); + expect(instances[2].requests).toContainEqual( + expect.objectContaining({ + method: "_example/select", + params: { model: "vendor-model" }, + }), + ); + } finally { + await connection.close(); + } +}); + +it("rewrites the session-ready, notification and configure-commit config snapshots", async () => { + const modelOption = { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "first", + options: ["first", "second", "third"].map((value) => ({ name: value, value })), + }; + const { connector, instances } = connectorHarness({ configOptions: [modelOption] }); + const registration = runAcpProvider({ + id: "config-transformer", + label: "Config Transformer", + connector, + transformers: [ + { + config(state, { sessionId }) { + return { ...state, model: `${sessionId}/${state.model}` }; + }, + }, + ], + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["session.configure"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + const models = () => + events.flatMap((event) => (event.type === "session.config" ? [event.config.model] : [])); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect(models()).toEqual(["session-1/first"]); + + instances[1].notify("session/update", { + sessionId: "connector-session", + update: { + sessionUpdate: "config_option_update", + configOptions: [{ ...modelOption, currentValue: "second" }], + }, + }); + await expect.poll(models).toEqual(["session-1/first", "session-1/second"]); + + await connection.send({ + type: "session.configure", + requestId: "configure", + sessionId: "session-1", + changes: { model: "third" }, + }); + await expect.poll(models).toEqual(["session-1/first", "session-1/second", "session-1/third"]); + } finally { + await connection.close(); + } +}); diff --git a/packages/plugin/src/server/acp.ts b/packages/plugin/src/server/acp.ts index 3b2cfa6fc779..d3fb394c2572 100644 --- a/packages/plugin/src/server/acp.ts +++ b/packages/plugin/src/server/acp.ts @@ -70,12 +70,17 @@ export interface AcpConfigAccess { set(id: string, value: JsonValue): Promise; } +/** Sends an ACP extension request to the agent. Rejects with the agent's JSON-RPC error. */ +export type AcpRequest = (method: string, params: JsonValue) => Promise; + export interface AcpDiscoveryContext extends AcpContext { config: AcpConfigAccess; + request: AcpRequest; } export interface AcpConfigureContext extends AcpContext { config: AcpConfigAccess; + request: AcpRequest; catalog(): ProviderCatalog; apply(change: AcpConfigChange): Promise; } @@ -117,6 +122,8 @@ export interface AcpTransformer { context: AcpDiscoveryContext, ): Promise | ProviderCatalog; configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">; + /** Rewrites every session config snapshot before Paseo sees it. */ + config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState; notification?( notification: { method: string; params: JsonValue }, context: AcpContext, diff --git a/packages/protocol/src/messages.checkout-pr-schema.test.ts b/packages/protocol/src/messages.checkout-pr-schema.test.ts index db412a831a33..ffdbbb41093b 100644 --- a/packages/protocol/src/messages.checkout-pr-schema.test.ts +++ b/packages/protocol/src/messages.checkout-pr-schema.test.ts @@ -814,7 +814,7 @@ describe("checkout PR schemas", () => { }); test.each( - ["hopliteProvider", "fxProvider"].flatMap((name) => + ["hopliteProvider", "fxProvider", "gooseProvider"].flatMap((name) => [undefined, false, true].map((value) => [name, value] as const), ), )("accepts optional bundled provider capability (%s: %s)", (name, value) => { diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index f7dca4bf7a93..d14299b82edb 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -4151,6 +4151,8 @@ export const ServerInfoStatusPayloadSchema = z hopliteProvider: z.boolean().optional(), // COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter. fxProvider: z.boolean().optional(), + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter. + gooseProvider: z.boolean().optional(), // COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16. importSessionWorkspaceTarget: z.boolean().optional(), // COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02. diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index b95935a515ac..dd0877ed6d76 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -2788,3 +2788,29 @@ test("plugin provider import launches with runtime MCP servers and returns only await registry.shutdown(); } }); + +test("resumes a goose session saved by the generic ACP provider", async () => { + const logger = createTestLogger(); + const harness = createProviderHarness(); + const plugins = new PluginAgentClientRegistry(logger); + plugins.replace([{ ...harness.registration, id: "goose" }]); + const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() }); + const client = registry.goose.createClient(logger); + + try { + const session = await client.resumeSession( + { + provider: "goose", + sessionId: "native-goose-session", + nativeHandle: "native-goose-session", + }, + { provider: "goose", cwd: "/tmp" }, + ); + expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({ + persistence: { version: 1, data: { sessionId: "native-goose-session" } }, + }); + await session.close(); + } finally { + await plugins.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 6a756553648c..f14385bf9c8c 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -2174,6 +2174,10 @@ function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence if (fromMetadata !== undefined) { return ProviderPersistenceSchema.parse(fromMetadata); } + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated. + if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) { + return { version: 1, data: { sessionId: handle.sessionId } }; + } return decodePersistenceId(handle.sessionId); } diff --git a/packages/server/src/server/daemon-e2e/goose-fixture.cjs b/packages/server/src/server/daemon-e2e/goose-fixture.cjs new file mode 100644 index 000000000000..52c5eb052867 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/goose-fixture.cjs @@ -0,0 +1,88 @@ +// Local ACP peer shaped like `goose acp`. +const readline = require("node:readline"); + +const inventory = { + openrouter: { name: "OpenRouter", model: "anthropic/claude-sonnet-4.5" }, + openai: { name: "OpenAI", model: "gpt-4o" }, + anthropic: { name: "Anthropic", model: "sonnet" }, +}; +let provider = "goose"; +let model = inventory.openrouter.model; + +const select = (id, currentValue, values) => ({ + id, + name: id, + ...(id === "model" ? { category: "model" } : {}), + type: "select", + currentValue, + options: values.map((value) => ({ value, name: value })), +}); +const configOptions = () => [ + select("provider", provider, ["goose", ...Object.keys(inventory)]), + select("model", model, [inventory[provider === "goose" ? "openrouter" : provider].model]), +]; +const send = (message) => + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n"); + +readline.createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method, params } = JSON.parse(line); + if (id === undefined) return; + let result; + switch (method) { + case "initialize": + result = { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] }; + break; + case "session/new": + case "session/load": + result = { sessionId: "goose-fixture", configOptions: configOptions() }; + break; + case "_goose/unstable/providers/list": + result = { + entries: Object.entries(inventory).map(([providerId, entry]) => ({ + providerId, + providerName: entry.name, + configured: providerId !== "anthropic", + models: [{ id: entry.model, name: entry.model }], + })), + }; + break; + case "_goose/unstable/config/read": + result = { + value: params.key === "GOOSE_PROVIDER" ? "openrouter" : inventory.openrouter.model, + }; + break; + case "session/set_config_option": + if (params.configId === "provider") { + provider = params.value; + model = inventory[provider === "goose" ? "openrouter" : provider].model; + } else if (params.configId === "model") { + if (params.value !== inventory[provider === "goose" ? "openrouter" : provider].model) { + send({ id, error: { code: -32602, message: "Model unavailable for selected provider" } }); + return; + } + model = params.value; + } + result = { configOptions: configOptions() }; + break; + case "session/prompt": + send({ + method: "session/update", + params: { + sessionId: params.sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `${provider}/${model}` }, + }, + }, + }); + result = { stopReason: "end_turn" }; + break; + case "session/close": + result = {}; + break; + default: + send({ id, error: { code: -32601, message: "Method not found" } }); + return; + } + send({ id, result }); +}); diff --git a/packages/server/src/server/daemon-e2e/models.e2e.test.ts b/packages/server/src/server/daemon-e2e/models.e2e.test.ts index 124e42cd60a5..d6d9b6635b29 100644 --- a/packages/server/src/server/daemon-e2e/models.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/models.e2e.test.ts @@ -519,3 +519,60 @@ test("a provider update outlives the client that started it and a new client rea await daemon.close(); } }, 60000); + +test("bundled goose lists configured providers and switches models across providers", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paseo-goose-models-")); + const daemon = await createTestPaseoDaemon({ + paseoHomeRoot: root, + cleanup: false, + mcpEnabled: false, + builtinPlugins: new BuiltinPluginLoader(undefined, ["goose-provider"]), + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.16.0", + }); + const openRouterModel = "openrouter/anthropic/claude-sonnet-4.5"; + const openAiModel = "openai/gpt-4o"; + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true); + expect( + (await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "goose"), + ).toBe(false); + + await client.patchDaemonConfig({ + providers: { + goose: { + enabled: true, + command: [process.execPath, path.resolve(import.meta.dirname, "goose-fixture.cjs")], + }, + }, + }); + const catalog = await client.listProviderModels("goose", { cwd: root }); + expect(catalog.error).toBeNull(); + expect(catalog.models.map((model) => [model.id, model.isDefault === true])).toEqual([ + [openRouterModel, true], + [openAiModel, false], + ]); + + const agent = await client.createAgent({ provider: "goose", cwd: root, model: openAiModel }); + await client.sendMessage(agent.id, "Which provider and model are you running?"); + expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle"); + await client.setAgentModel(agent.id, openRouterModel); + await client.sendMessage(agent.id, "Which provider and model are you running now?"); + expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle"); + expect((await client.fetchAgent(agent.id))?.agent.model).toBe(openRouterModel); + const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 }); + expect( + timeline.entries.flatMap(({ item }) => + item.type === "assistant_message" ? [item.text] : [], + ), + ).toEqual([openAiModel, openRouterModel]); + } finally { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true }); + } +}, 60_000); diff --git a/packages/server/src/server/persisted-config.test.ts b/packages/server/src/server/persisted-config.test.ts index fb38e4159189..64cc838134e6 100644 --- a/packages/server/src/server/persisted-config.test.ts +++ b/packages/server/src/server/persisted-config.test.ts @@ -1089,3 +1089,31 @@ describe("speech provider config normalization", () => { } }); }); + +test.each([ + ["goose", "acp"], + ["/opt/bin/goose", "acp"], +])( + "migrates the legacy goose entry and preserves command overrides (%s %s)", + (binary, subcommand) => { + const command = [binary, subcommand]; + const overrides = { + enabled: false, + label: "My goose", + env: { GOOSE_PROVIDER: "openai" }, + models: [{ id: "primary", label: "Primary" }], + additionalModels: [{ id: "secondary", label: "Secondary" }], + }; + const parsed = PersistedConfigSchema.parse({ + agents: { + providers: { + goose: { ...overrides, extends: "acp", description: "Old description", command }, + }, + }, + }); + expect(parsed.agents?.providers?.goose).toEqual({ + ...overrides, + ...(command[0] === "goose" ? {} : { command }), + }); + }, +); diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index 3138ec9132c2..7b1f6e86590d 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -199,16 +199,32 @@ function isLegacyProviderEntry(value: unknown): boolean { } function normalizeAgentProviders(value: unknown): unknown { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return value; + if (!isConfigRecord(value)) return value; + + let rawProviders = value; + const goose = configRecord(value.goose); + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy configs have migrated. + if (goose?.extends === "acp") { + const { extends: _base, description: _description, command, ...overrides } = goose; + const usesDefaultCommand = + Array.isArray(command) && + command.length === 2 && + command[0] === "goose" && + command[1] === "acp"; + rawProviders = { + ...value, + goose: { + ...overrides, + ...(command !== undefined && !usesDefaultCommand ? { command } : {}), + }, + }; } - const rawProviders = value as Record; const hasLegacyEntries = Object.values(rawProviders).some((entry) => isLegacyProviderEntry(entry), ); if (!hasLegacyEntries) { - return value; + return rawProviders; } const legacyEntries: Record = {}; @@ -224,7 +240,7 @@ function normalizeAgentProviders(value: unknown): unknown { const parsedLegacyEntries = AgentProviderRuntimeSettingsMapSchema.safeParse(legacyEntries); if (!parsedLegacyEntries.success) { - return value; + return rawProviders; } return { diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index c49eab905ddd..9ffb4cadb4fb 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -9,6 +9,7 @@ export const builtinPlugins = [ "copilot-usage-source", "cursor-usage-source", "fx-provider", + "goose-provider", "grok-usage-source", "hoplite-provider", "kimi-usage-source", diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index ed24eaffeda6..7aabed0d23ae 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2214,6 +2214,8 @@ export class VoiceAssistantWebSocketServer { hopliteProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("hoplite"), // COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter. fxProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("fx"), + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter. + gooseProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("goose"), // COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16. importSessionWorkspaceTarget: true, // COMPAT(importSessionSearch): added in v0.7.3, remove gate after 2027-03-02. diff --git a/plugins/goose-provider/icon.svg b/plugins/goose-provider/icon.svg new file mode 100644 index 000000000000..c4928854263e --- /dev/null +++ b/plugins/goose-provider/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/plugins/goose-provider/index.server.ts b/plugins/goose-provider/index.server.ts new file mode 100644 index 000000000000..2cdf147c5596 --- /dev/null +++ b/plugins/goose-provider/index.server.ts @@ -0,0 +1,7 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { createGooseProvider } from "./server/provider.js"; + +export default function contribute(server: PluginServerContext) { + server.registerProvider(createGooseProvider()); + return () => {}; +} diff --git a/plugins/goose-provider/paseo-plugin.json b/plugins/goose-provider/paseo-plugin.json new file mode 100644 index 000000000000..fedb1fcc84ea --- /dev/null +++ b/plugins/goose-provider/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "goose-provider", "requirements": { "paseo": ">=0.17.0" } } diff --git a/plugins/goose-provider/server/models.test.ts b/plugins/goose-provider/server/models.test.ts new file mode 100644 index 000000000000..65c1c6fb8ae2 --- /dev/null +++ b/plugins/goose-provider/server/models.test.ts @@ -0,0 +1,135 @@ +import type { AcpConfigureContext, AcpRequest } from "@getpaseo/plugin/server/acp"; +import type { ProviderCatalog, ProviderConfigState } from "@getpaseo/plugin/server/provider"; +import { describe, expect, it } from "vitest"; +import { gooseModels } from "./models.js"; + +const routerModel = "anthropic/claude-sonnet-4.5"; +const baseCatalog: ProviderCatalog = { + models: [{ id: routerModel, label: "Sonnet" }], + modes: [], + defaultModel: routerModel, +}; + +const configuredProviders: AcpRequest = async (method, params) => { + if (method === "_goose/unstable/providers/list") { + expect(params).toEqual({ providerIds: [] }); + return { + entries: [ + { + providerId: "openrouter", + providerName: "OpenRouter", + configured: true, + models: [{ id: routerModel, name: "Sonnet" }], + }, + { + providerId: "openai", + providerName: "OpenAI", + configured: true, + models: [{ id: "gpt-4o", name: "GPT-4o" }], + }, + { + providerId: "anthropic", + providerName: "Anthropic", + configured: false, + models: [{ id: "sonnet", name: "Sonnet" }], + }, + ], + }; + } + expect(method).toBe("_goose/unstable/config/read"); + if (params && typeof params === "object" && "key" in params) { + if (params.key === "GOOSE_PROVIDER") return { value: "openrouter" }; + if (params.key === "GOOSE_MODEL") return { value: routerModel }; + } + throw new Error("Unexpected config key"); +}; + +function configContext(request = configuredProviders) { + const writes: Array<[string, unknown]> = []; + const context: AcpConfigureContext = { + sessionId: "goose-session", + request, + config: { + async read() { + return {}; + }, + async set(id, value) { + writes.push([id, value]); + }, + }, + catalog: () => baseCatalog, + apply: async () => {}, + }; + return { context, writes }; +} + +describe("goose model transformer", () => { + it("lists configured providers and keeps slash-delimited model IDs intact", async () => { + const { context } = configContext(); + expect(await gooseModels.discover(baseCatalog, context)).toEqual({ + ...baseCatalog, + models: [ + { id: `openrouter/${routerModel}`, label: "Sonnet", description: "OpenRouter" }, + { id: "openai/gpt-4o", label: "GPT-4o", description: "OpenAI" }, + ], + defaultModel: `openrouter/${routerModel}`, + }); + }); + + it("keeps the base catalog when the RPC is unavailable", async () => { + const { context } = configContext(async () => { + throw new Error("Method not found"); + }); + expect(await gooseModels.discover(baseCatalog, context)).toBe(baseCatalog); + }); + + it("keeps the base catalog when no providers are configured", async () => { + const { context } = configContext(async () => ({ entries: [] })); + expect(await gooseModels.discover(baseCatalog, context)).toBe(baseCatalog); + }); + + it("sets the provider before the model and preserves slashes in the model", async () => { + const { context, writes } = configContext(); + const result = await gooseModels.configure( + { target: "model", value: `openrouter/${routerModel}` }, + context, + ); + expect(result).toBe("handled"); + expect(writes).toEqual([ + ["provider", "openrouter"], + ["model", routerModel], + ]); + }); + + it.each(["gpt-4o", routerModel])("passes the legacy model %s through", async (value) => { + const { context, writes } = configContext(); + expect(await gooseModels.configure({ target: "model", value }, context)).toBe("pass"); + expect(writes).toEqual([]); + }); + + function snapshotFor(provider: string): ProviderConfigState { + return { + model: routerModel, + models: baseCatalog.models, + modes: [], + thinkingOptions: [], + settings: [ + { type: "select", id: "provider", label: "Provider", value: provider, options: [] }, + ], + }; + } + + it("namespaces models in a snapshot for an explicit provider", () => { + const snapshot = snapshotFor("openrouter"); + expect(gooseModels.config(snapshot)).toEqual({ + ...snapshot, + model: `openrouter/${routerModel}`, + models: [{ id: `openrouter/${routerModel}`, label: "Sonnet" }], + }); + }); + + it("keeps the snapshot unchanged while goose Default is selected", () => { + const snapshot = snapshotFor("goose"); + expect(gooseModels.config(snapshot)).toBe(snapshot); + }); +}); diff --git a/plugins/goose-provider/server/models.ts b/plugins/goose-provider/server/models.ts new file mode 100644 index 000000000000..0e80154c4969 --- /dev/null +++ b/plugins/goose-provider/server/models.ts @@ -0,0 +1,82 @@ +import type { AcpRequest, AcpTransformer } from "@getpaseo/plugin/server/acp"; +import { z } from "zod"; + +const inventorySchema = z.object({ + entries: z.array( + z.object({ + providerId: z.string(), + providerName: z.string(), + configured: z.boolean(), + models: z.array(z.object({ id: z.string(), name: z.string() })), + }), + ), +}); +const configValueSchema = z.object({ value: z.string().min(1) }); + +async function configuredProviders(request: AcpRequest) { + // COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once supported goose versions have this RPC. + const response = await request("_goose/unstable/providers/list", { providerIds: [] }).catch( + () => null, + ); + const inventory = inventorySchema.safeParse(response); + return inventory.success ? inventory.data.entries.filter((entry) => entry.configured) : []; +} + +async function readDefault(request: AcpRequest, key: "GOOSE_PROVIDER" | "GOOSE_MODEL") { + const response = await request("_goose/unstable/config/read", { key }).catch(() => null); + const parsed = configValueSchema.safeParse(response); + return parsed.success ? parsed.data.value : undefined; +} + +export const gooseModels = { + async discover(catalog, { request }) { + const providers = await configuredProviders(request); + if (providers.length === 0) return catalog; + + const models = providers.flatMap((provider) => + provider.models.map((model) => ({ + id: `${provider.providerId}/${model.id}`, + label: model.name, + description: provider.providerName, + })), + ); + if (models.length === 0) return catalog; + + const [providerId, modelId] = await Promise.all([ + readDefault(request, "GOOSE_PROVIDER"), + readDefault(request, "GOOSE_MODEL"), + ]); + return { + ...catalog, + models, + defaultModel: providerId && modelId ? `${providerId}/${modelId}` : undefined, + }; + }, + + async configure(change, { config, request }) { + if (change.target !== "model" || !change.value) return "pass"; + const separator = change.value.indexOf("/"); + if (separator <= 0) return "pass"; + + const providerId = change.value.slice(0, separator); + const providers = await configuredProviders(request); + if (!providers.some((provider) => provider.providerId === providerId)) return "pass"; + + await config.set("provider", providerId); + await config.set("model", change.value.slice(separator + 1)); + return "handled"; + }, + + config(state) { + const provider = state.settings?.find((setting) => setting.id === "provider"); + if (provider?.type !== "select" || !provider.value || provider.value === "goose") { + return state; + } + const namespace = (modelId: string) => `${provider.value}/${modelId}`; + return { + ...state, + model: state.model === undefined ? undefined : namespace(state.model), + models: state.models.map((model) => ({ ...model, id: namespace(model.id) })), + }; + }, +} satisfies AcpTransformer; diff --git a/plugins/goose-provider/server/provider.ts b/plugins/goose-provider/server/provider.ts new file mode 100644 index 000000000000..966675d78e75 --- /dev/null +++ b/plugins/goose-provider/server/provider.ts @@ -0,0 +1,17 @@ +import { runAcpProvider } from "@getpaseo/plugin/server/acp"; +import type { ProviderRegistration } from "@getpaseo/plugin/server/provider"; +import { gooseModels } from "./models.js"; + +export function createGooseProvider(): ProviderRegistration { + return { + requiresConfiguration: true, + ...runAcpProvider({ + id: "goose", + label: "goose", + description: "A local, extensible, open source AI agent that automates engineering tasks", + icon: "icon.svg", + command: ["goose", "acp"], + transformers: [gooseModels], + }), + }; +} diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index 83dcf782949f..de4c34cf1e20 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -572,7 +572,12 @@ export default function contribute(server: PluginServerContext) { The shim owns the ACP process, capability mapping, session lifecycle, prompts, permissions, and timeline conversion. Do not copy that machinery into the plugin. -Use `transformers` only for vendor differences ACP cannot describe. Validate vendor payloads with +Use `transformers` for vendor differences ACP cannot describe. The +[goose model transformer](https://github.com/getpaseo/paseo/blob/main/plugins/goose-provider/server/models.ts) +uses `context.request` to read the agent's model inventory and `config` to prefix session model IDs +with the active provider. See the [ACP adapter reference](/docs/plugins/reference#providers). + +Validate vendor payloads with Zod and leave malformed or unrelated values unchanged: ```ts diff --git a/public-docs/plugins/providers.zh-CN.md b/public-docs/plugins/providers.zh-CN.md index d1825d911d1c..ef8ca4443b29 100644 --- a/public-docs/plugins/providers.zh-CN.md +++ b/public-docs/plugins/providers.zh-CN.md @@ -472,7 +472,12 @@ export default function contribute(server: PluginServerContext) { 适配层负责 ACP 进程、能力映射、会话生命周期、提示词、权限和时间线转换。不要把这些机制复制到插件中。 -只在 ACP 无法描述厂商差异时使用 `transformers`。用 Zod 校验厂商负载,并让格式错误或无关的值保持不变: +使用 `transformers` 处理 ACP 无法描述的厂商差异。 +[goose 模型转换器](https://github.com/getpaseo/paseo/blob/main/plugins/goose-provider/server/models.ts) +使用 `context.request` 读取 Agent 的模型列表,并使用 `config` 为会话的模型 ID 添加当前 Provider 前缀。 +参见 [ACP 适配器参考](/docs/plugins/reference#providers)。 + +用 Zod 校验厂商负载,并让格式错误或无关的值保持不变: ```ts import type { AcpTransformer } from "@getpaseo/plugin/server/acp"; diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 7494b3b03228..d95cd0ac7b42 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -433,7 +433,14 @@ Paseo refreshes an agent by closing its current provider session and opening it configuration and persistence. Providers re-read external state during `session.open`. Use `runAcpProvider()` from `@getpaseo/plugin/server/acp` to adapt a command-backed ACP. Add transformer -hooks only for a vendor's discovery, configuration, notification, or tool-call differences. +hooks for vendor behavior. See [Adapt an ACP agent](/docs/plugins/providers#adapt-an-acp-agent). + +In `discover` and `configure`, call `context.request(method, params)` to send an ACP extension +request. The promise returns a JSON value or rejects with the agent's JSON-RPC error. + +Use `config(state, context)` to return the configuration snapshot that Paseo displays. +Paseo calls this synchronous hook for initial, notification, and committed configuration snapshots. +Use `configure` to send changes to the agent. `ProviderRegistration.icon` is a file path relative to the plugin directory, such as `icon.svg`. It must resolve inside that directory to a regular file that follows the diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 465cd70d8494..e6c2b7fd7753 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -363,7 +363,14 @@ Provider 选项是一个记录,即 `session.open` 中的 `ProviderSessionConfi Paseo 刷新 Agent 的方式是关闭它当前的 Provider 会话,再用当前的配置和持久化值打开它。Provider 在 `session.open` 期间重新读取外部状态。 -使用 `@getpaseo/plugin/server/acp` 中的 `runAcpProvider()` 适配一个基于命令的 ACP。只针对厂商在发现、配置、通知或工具调用方面的差异添加转换器钩子。 +使用 `@getpaseo/plugin/server/acp` 中的 `runAcpProvider()` 适配一个基于命令的 ACP。使用转换器钩子处理厂商特有的行为。参见[适配 ACP Agent](/docs/plugins/providers#adapt-an-acp-agent)。 + +在 `discover` 和 `configure` 中,调用 `context.request(method, params)` 发送 ACP 扩展请求。 +Promise 返回 JSON 值,或以 Agent 的 JSON-RPC 错误拒绝。 + +使用 `config(state, context)` 返回 Paseo 显示的配置快照。 +Paseo 在会话就绪、收到配置通知或提交配置更改时调用此同步钩子。 +使用 `configure` 向 Agent 发送更改。 `ProviderRegistration.icon` 是相对于插件目录的文件路径,例如 `icon.svg`。它必须解析到该目录内一个遵循 [SVG 图标规则](#svg-rules)的普通文件。Paseo 在插件启动时读取并校验该文件;这个字符串从不是内联 SVG 或 URL。 diff --git a/public-docs/supported-providers/index.md b/public-docs/supported-providers/index.md index 2c52cc35ac57..b26adeafe627 100644 --- a/public-docs/supported-providers/index.md +++ b/public-docs/supported-providers/index.md @@ -51,7 +51,7 @@ To add one, open **Settings → Hosts → your host → Providers**, select **+ - [Gajae Code](https://gajae-code.com), subscription-based coding agent with plan-before-mutation workflows. - [Gemini CLI](https://geminicli.com), Google's official Gemini CLI. - [GLM Agent](https://github.com/stefandevo/glm-acp-agent), Zhipu AI's GLM coding agent. -- [goose](https://block.github.io/goose/), Block's local open-source AI agent. +- [goose](https://block.github.io/goose/), Block's local open-source AI agent. Paseo lists models from all providers configured in goose when goose supports model inventory discovery. - [Grok](https://docs.x.ai/build/overview), xAI's Grok Build agentic coding CLI. - [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp), Nous Research's self-improving agent. - [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html), JetBrains' coding agent. diff --git a/public-docs/supported-providers/index.zh-CN.md b/public-docs/supported-providers/index.zh-CN.md index b81b815a2bcc..729e2e389757 100644 --- a/public-docs/supported-providers/index.zh-CN.md +++ b/public-docs/supported-providers/index.zh-CN.md @@ -49,7 +49,7 @@ Paseo 可以运行任何使用 [Agent Client Protocol](https://agentclientprotoc - [Gajae Code](https://gajae-code.com):订阅制编程 Agent,采用先规划再修改的工作流。 - [Gemini CLI](https://geminicli.com):Google 官方的 Gemini CLI。 - [GLM Agent](https://github.com/stefandevo/glm-acp-agent):智谱 AI 的 GLM 编程 Agent。 -- [goose](https://block.github.io/goose/):Block 的本地开源 AI Agent。 +- [goose](https://block.github.io/goose/):Block 的本地开源 AI Agent。如果 goose 支持发现模型清单,Paseo 会列出 goose 中所有已配置 Provider 的模型。 - [Grok](https://docs.x.ai/build/overview):xAI 的 Grok Build Agent 编程 CLI。 - [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp):Nous Research 的自我改进型 Agent。 - [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html):JetBrains 的编程 Agent。 From b3d860cce28738d0762e573ee390d4ac4271cfaa Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 13:04:59 +0700 Subject: [PATCH 015/109] feat(website): apply new Paseo and Paseo Hub branding (#10271) Replace the website's legacy Paseo mark and plain-text headers with the canonical Paseo butterfly and Paseo Hub flower marks and Plus Jakarta Sans SemiBold lockups from assets/brand/. Sourcing the website SVG components directly from assets/brand/ keeps mark proportions, 94% butterfly optical balance, and outlined wordmarks aligned with the canonical assets without shipping an extra webfont or duplicating paths across components. --- packages/website/public/favicon.ico | Bin 15086 -> 15086 bytes packages/website/public/favicon.svg | 4 +- packages/website/public/logo.svg | 4 +- .../website/src/components/landing-page.tsx | 7 + .../website/src/components/mockup/icons.tsx | 16 +- .../src/components/mockup/mobile/atoms.tsx | 20 +-- .../src/components/paseo-brand.test.tsx | 74 +++++++++ .../website/src/components/paseo-brand.tsx | 154 ++++++++++++++++++ .../website/src/components/site-header.tsx | 10 +- .../website/src/routes/{-$locale}/docs.tsx | 19 ++- .../website/src/routes/{-$locale}/hub.tsx | 15 +- packages/website/src/types/raw-modules.d.ts | 5 + 12 files changed, 281 insertions(+), 47 deletions(-) create mode 100644 packages/website/src/components/paseo-brand.test.tsx create mode 100644 packages/website/src/components/paseo-brand.tsx diff --git a/packages/website/public/favicon.ico b/packages/website/public/favicon.ico index 936d6640ae6f330c5599e68d94cb6275d44bf86d..045a402611b31836d9b5efa734a34b59898f00f3 100644 GIT binary patch literal 15086 zcmeI32dq^^8h|fFiqb^7sE>t}5<%L6bdVZ^0D+()!iuPfbdVN=7f28lgg`W=5J^EKmUJYv0Sk{ zv6?kwI!}rH>+i8xy;v-klJdvzVzJmET~|!!wD-#!i%r%DRWyz!iTzV2>VZ^^7Xd10 z+&6XFs8fbcH*``tl#rF76S7C>l%i8uD6J9a>2yn{oYFUu9CVqZQz@O|0Yi3Jr$qez ztoGwtw|@kD0QFb@!n#YJp<^A-H!x?8{SW9a-*8mxYR{$l$>?6NU_tfZgAb}adGZL~ zoXlryoq@mU6nd>TYSc(ATC_-IWMn9TTeohh@4x?Ez5DLFs&eJZIrReW+c&YTI<*{|Wmi4%&k zO2j*h?VJyB_seS4s;P??FS=B`apQ*i=%bI+8*jX!o_p>&HFD%g^~D!oDEi)p>({TV zPMtd4%Wp{6`Ujq?`Sa&j`}gm+RZ<%_Zd8vw_L#3uPd@pi+PQP53;*WLo2o;H4lexM zxpS+@lP5d8x^(H{YKu4?fx5$I)TmJ|T|W8b6O}h_-njDayYD_VfBt+I-PNmCRf7f% z4Ba!&JY(AL-o2~ddFLI)H$~JvEeMMCCp|q~6)IFHE{!e!{rBHDv=mOCKCMzx zQXKkb&6>H|_`!V4moHyv{%oOUE8o~)hfleA)`&3HVWQ0ut#UdIDGcmXNE00 z1brtuHf`Ee4Hz&$J^%dks$|KME?my%AAkJO@S-qj(jtXlq z-G(RUk)QspTD4L?{q&Q;qwwpmzdGyQ#;;nns=9pnvcY4`+WSt88a33}vu8~^g{f1g z`pUHV#w&mQ_1A{qvSrIM@nYZi&R;{I3;p}|chPk0*wJ-9FmIlC;t7LOw{G1`bE$Xl z-ljdCu6}K6*RD0{Y~Q}!#fLHHY_h?7c5z;N*Wz1my=9ZApMU;YJ@n8+hBxEMc_F~Q zTct`B)9$BdP~F6d6NQb#Q|2{mYwzB@rj5dsDN`I>UwY{!SN+pZKkbsuJ(WGkhP1Ra z*Lr2#Y}m48i;G8)zTW!!_3PVgoVz7B+!btCxNxE2&z;SNXP?84Zw zV~w7i69V81ZPc8(?FZMcU32FBym|ASb?C(zG-yzuO!l)Nc<;UUoIBR))vFE4jvYG! zc_sQD`gYc=S%z1b0`~?vWBvHgnKQ?*p&z_^*ZK43UE@Au#*C!(7y0aUiQvM83yOY^ zr#t*U{P07=>Z`B5QoVZh3Oq~Lr>j@5o+bUUX>IuKyYJKwKm6dF`v(smRNSjyd+jw< ztXQ#7a%>x6&6+h1O^X&S)R7}cY%z+lku@g$m`px+@L(5Txd$i1i~Z-f-+nXv?7I+m zDfV3K4$cAlY)eL#(0u&y$41_P0|!F&vCw*R^s|9I&Wn@XznLQfAAImZmgI4s3b4o0 z=h>~V&5wJmeJ5dT?e-{T?)x^dS4N>v2ABK04N>hdk;z*fb5DS^`S8OJ-*f#-mo6&uw%!L z398Al9RuWNr5@dngyGBEz74!HU{|mQ`x?%VyiL*)5jSfr8UTWJFUVY^^<1l2%kb8bN(0aeAQ$?L_hy4cd+P81- z+?nlnv*X8)tCcHPI(DS@-6RU{2)N=u(j>8k5$Ig=fqMaO)ydLlfo`6r6)2+%Cv^HV z^hib~zFvI3Hq_HUuIZEvznrAOe_hvB+$z`7+{aMHcY`^m9C5E-lb0(wf%z zBI91=Jp=--B*q z`F}subl6cWmHJ%&&H4F%2=0MYnymgxkbEdFPe$Y}^p4KV5WCrm$rDe46D9}p(zL^8EMJHs54)pn% zM6x-Lv%`OA$)O(@i@0Mz?)W0n0sEIXTAQ9evwa_S zn@{rLe4pfxKKiJOKls>K;;%vn@p)FLP{Hw`oIH6_HEGf$6P;I<-*4=CfVcBn zwQ2?O;Qi^FZ@zJGc{9RK$-9xfDbRmiyLJtv_mfSXyoqkuupuEWeT~ftU|aH=H*M)Z z`X=hT(!PEB9Dd&SKy2?}!-hHbAn`r&PE)gHO*0?xhj3@+ZA-?7H^wOQ^w6P0j(pos z%r|-8(6RaCe$F?FKZ_VP`Vqe?b6SWUqBr;&aQwqXAj~m2?F*Ai9ZVBk)R$sYfL;G z&M)>AiOb@9@wH}?uLWCATj#N}@pO>3MDYuP7c$4z!}bB%=)_w{vf~()4*Lsx(*|@1 z)ejmksyrJXTMv8F4;TyP12$16yF}O7e4>=$#azSIlRno)=lvjmntn-0bzT>!x%ZH& zWuy+sG!P%yhj5D-%L(qBoLIV$MMW+qB zMr;iBqRyQ=duhDC(ZkW1^Mt!0{>Dm`Dmn2a+~u$-xFe*dre@l2g%e^UptbzL)#$^5x4_@#4iDImGf~e}4Mur_TKaThgYJGB%^w2U17QU2F5^%?=H* zM1HZ(+>N*!c<++vfX$NV?gdZmW!tvKc0n#SZ=5~W%z6At_{*>h8FTDBeBs!r_V-w2 yXwCe^ZlK>81Nvh0=+TMpEv&iLIwiY)SbG3G(8GL-F2~auxeje=E?r6zp#2Zd0UtI1 literal 15086 zcmeI3b&M2E7QhF0cVFBk1b2521PBt~fP+Bb4_pJs;oL!R4<6iuySuv_?(R-q|LUmz zs(YtrdS-W#)#EAR@pwW)e*8}8@%+bl zm(Zwb?-14F8D@0IVe~PEcv=~S_Y$)Fuk!IXz0o$tDCdpx-YDWXDewYM@RrUf-k_cF z@`F)+7oMH?U@m{NO`!E3z_)!qtT&LxD8JKQvGeKlo4vw*|F=<``uy(iIS&_uG*uQ_j`1b9au*1`*PsNZSLqx1t zv3|xp-UYJu1qu`p=gyt8v+VWv)vH%U&YU@a#vEMHs9(Rn`1tXoS6<)0e=oj&{~oH1 zZ&9K|30L?7S;s*8mMd3IeERgs!r!f1w?x;jT}4Pph~$rbRiQ!!apJ@YOF!mTy?XUu zHirZW5{Nr@?pS!5I(4du88fC=o?^$2E!M4DXX*dp!-r6Fh#Wbxm@;LGxOVND7&>&Q zh#EDjSA2o4wY~qaVZ$uEOq({%FCBQ9HEWh-9CN5rrHVPWeEIU0_N`mDii8Ohn(cNz zg82;}j~_oa>9A+w#*OQWMx;oQ#DobG%&|PYe*Ib$ELc#E&yXR5c>DIPrTy&Lvm#Zh zRIc#5nNPK9)hzhiw{IU1Zsx%E(&7I7`{tS9zIgE9f!-{xU%xIgWy%x~9jCdB968d& z{rU4}kvMVUfbp`==g*&S;^E=Kg$pJwz5~B?xOwxYNS{7^z_jf1SiE?#iT28sD~|Y> zSLe>11?PIwq)DPdg9ZY=6~5@vql;a;cA2<%*t2JkDFc!wO)8EYIbvytURd|i&Ye3= zoO}1~HTh9|QP-(c$8tv00LJQPg*jfjbV)VKdeNdqCeC>A;)z3t4q4g{95^7DyG}2V z=anm0n)oGzDM3ezn{UsZ*yGoN*oM z)vIU0;ghZ>ZYz z+I}xEhV!cQZtmh|&z_m6HgDeS6_1Y7+jG{eSuOk3MEK*OQ>RW6FZ4Kzx{k{I>U3u` zY0|`wO8#EEcC9H_XV0E(_ThVZIRUm2vVX~v zC1w|NaW}j=_36{6k5?VvBw%|$_d$Pf!e{5-Za?Vf7u4vqPPp8@U$bV7jmywK*~8pv z{&2Qw)5bEmdGqGt(W6I}cj^Z+wrtt5esTJu$y(|%FusPp9#@a^=$57k1lLjmwxZqd-2{;qKkL0vxK}uc&wL-fgmlzKBkm zB}*3RCvVoQnLxio*RsR*?c2lb3ki?;;xF?Sv#|54eq*O&KkB}q@ZcjXIPB*@@v7I% z5#JZSwXo1~IX2+fBmRstXU^y>OWOuNApUC3fJ@q8?MM75==fc_bm>HyGGzolo$&U3 zyPQAqyRk0&hIOqXV*I}h-b0M?@eiB>@#_pm0ooWPBGxA&asFL${@0%l#^ayx9a#7F zf3aRv}w~yy8zu;`3VmmJSg*<6fNQcuHD z3b@E0z%P6I_HDT~hYue%jLEvSi7CdB9(b9|OQfc8c|4XX9@q1_lsE#(rj< z?%lg5-(9?TQN{q>*yL)Bz@dB+_(s)xRg<3*Cr%vG&S!tBxZ>*7tEFvFyLN3E_ks!X zo#080_g53+10OLSJwJza;rI0E)8&5X)~%cLkukT99XpCwuU^Uhg8!R6fL~turSQ>_ zSK^O0?daX)K5))dT$5Neer-Jtz!@OVhP?`J^g@^dX;K76SVKVoD96Mws!2VVJebwY7AoslivY0(!&m)9B`w(Egl%I;T z!G57|R(#Rb+s2I>Cvh=%WH4)s9gTcUk|aqeJe&oU8^hkg9w+X`cYOZ*xr|M@^-mHr zM}`7p$Bvcj41VUQ^Qb>(%a%>RD{>q8KpXP2Ql(0wtRWA$$Myccp4s=xw~UPQ)mOE# z&+(CP-Wadm2UEi{YsMKz=kSLE|D)oU+!SPzzcIerIcwzRamV4`^3|7E1+pI?7pPF7 zLO%QZ!ll}3)TkkK57yGxJxYvtmc!I6jFPtCNz$tEwAB;QMz2Dyaz~Qu!QFz6No)*V0lgW0&B}}rjO?T|rA=i`dg6`)nwn%)B@5kM(`%%y{uvz)O*ctF- zr_FEfd;9}>8}|=7DtD7V-G{tR{r?rv_rb^d+jVN4hI%IN58INxgKj_$!M=U_{KbIH zJ;+{Nuwa4wpCM>+cRS7X2TgU3%sI2xoE`S8w|%B~{ZZ>@(B#9`$Hc9@S9CeQVS@hx DG;4!I diff --git a/packages/website/public/favicon.svg b/packages/website/public/favicon.svg index 0ef308b97b3f..06c329c818f6 100644 --- a/packages/website/public/favicon.svg +++ b/packages/website/public/favicon.svg @@ -1,4 +1,4 @@ - - + + diff --git a/packages/website/public/logo.svg b/packages/website/public/logo.svg index b8ca9396cd07..152c280e8c3d 100644 --- a/packages/website/public/logo.svg +++ b/packages/website/public/logo.svg @@ -1,3 +1,3 @@ - - + + diff --git a/packages/website/src/components/landing-page.tsx b/packages/website/src/components/landing-page.tsx index 8afa87a3ad9f..b84da5ec8ab7 100644 --- a/packages/website/src/components/landing-page.tsx +++ b/packages/website/src/components/landing-page.tsx @@ -89,6 +89,7 @@ import { PiIcon, } from "~/components/agent-icons"; import { DiscordIcon, GitHubIcon, SlackIcon } from "~/components/brand-icons"; +import { PaseoHubMark } from "~/components/paseo-brand"; import { MobileChat, MobileDiff, @@ -515,6 +516,7 @@ function TurnkeySection() { description={t("landing.runAnywhere.teamsDescription")} ctaHref={localize("/hub")} ctaLabel={t("landing.runAnywhere.teamsCta")} + ctaIcon={PASEO_HUB_CTA_ICON} showIntegrationIcons /> @@ -523,12 +525,15 @@ function TurnkeySection() { ); } +const PASEO_HUB_CTA_ICON = ; + function TurnkeyExtensionCard({ icon: Icon, title, description, ctaHref, ctaLabel, + ctaIcon, showIntegrationIcons = false, }: { icon: LucideIcon; @@ -536,6 +541,7 @@ function TurnkeyExtensionCard({ description: string; ctaHref: string; ctaLabel: string; + ctaIcon?: React.ReactNode; showIntegrationIcons?: boolean; }) { return ( @@ -545,6 +551,7 @@ function TurnkeyExtensionCard({ href={ctaHref} className="inline-flex items-center gap-1.5 rounded-full bg-foreground px-2.5 py-1.5 text-xs text-background transition-colors hover:bg-foreground/90" > + {ctaIcon} {ctaLabel} diff --git a/packages/website/src/components/mockup/icons.tsx b/packages/website/src/components/mockup/icons.tsx index 260aeefd091b..3e3094afc696 100644 --- a/packages/website/src/components/mockup/icons.tsx +++ b/packages/website/src/components/mockup/icons.tsx @@ -1,21 +1,11 @@ // Exact SVG paths from packages/app/src/components/icons/ import { OpenCodeIcon as OpenCodeBrandIcon, PiIcon as PiBrandIcon } from "../agent-icons"; +import { PaseoMark as CanonicalPaseoMark } from "../paseo-brand"; -/** The Paseo brand swirl — public/logo.svg, drawn as a small sidebar avatar mark. */ +/** The Paseo butterfly mark, drawn as a small sidebar avatar or tool-call mark. */ export function PaseoMark({ size = 13, className }: { size?: number; className?: string }) { - return ( - - ); + return ; } /** GitHub mark for the toolbar and PR panel. */ diff --git a/packages/website/src/components/mockup/mobile/atoms.tsx b/packages/website/src/components/mockup/mobile/atoms.tsx index 175e58049ea2..56994b45b04d 100644 --- a/packages/website/src/components/mockup/mobile/atoms.tsx +++ b/packages/website/src/components/mockup/mobile/atoms.tsx @@ -1,25 +1,11 @@ -// Small shared bits for the mobile mockups. The Paseo butterfly mark is the -// app icon (packages/website/public/favicon.svg) with the black plate dropped, -// so it can be tinted and placed on any tile. Tile fills are the app's identity +// Small shared bits for the mobile mockups. Tile fills are the app's identity // palette — packages/app/src/styles/identity-colors.ts — surfaced as // `--color-mock-tile-*` tokens in styles.css. -const BUTTERFLY_D = - "M291.495 91.399C333.897 104.892 379.155 135.075 416.229 173.191C453.389 211.394 484.429 259.725 495.708 311.251C497.555 319.693 498.865 328.216 499.586 336.776C509.755 326.554 519.867 317.815 529.89 311.547C540.647 304.821 553.808 299.297 568.641 299.785C584.29 300.299 597.395 307.326 607.747 317.632C632.173 341.947 629.612 372.898 619.872 397.936C610.185 422.833 591.557 447.826 572.732 469.124C553.591 490.78 532.713 510.308 516.779 524.318C508.775 531.355 501.936 537.073 497.07 541.052C494.635 543.043 492.689 544.603 491.334 545.679C490.657 546.217 490.126 546.635 489.756 546.926C489.571 547.071 489.425 547.184 489.321 547.265C489.269 547.305 489.227 547.338 489.196 547.362C489.181 547.374 489.168 547.385 489.157 547.393C489.153 547.397 489.147 547.401 489.144 547.403C489.134 547.4 488.837 547.06 473.001 528.499L489.135 547.411C478.157 555.911 462.033 554.334 453.122 543.89C444.213 533.448 445.887 518.094 456.861 509.592C456.863 509.591 456.865 509.588 456.869 509.586C456.88 509.577 456.902 509.561 456.933 509.536C456.997 509.487 457.101 509.404 457.245 509.292C457.533 509.066 457.979 508.715 458.569 508.247C459.749 507.31 461.506 505.901 463.742 504.073C468.216 500.414 474.589 495.088 482.073 488.508C497.114 475.284 516.315 457.282 533.578 437.75C551.157 417.862 565.26 398.01 571.859 381.048C578.403 364.227 575.681 356.302 570.724 351.367C568.928 349.579 567.744 348.902 567.267 348.676C566.888 348.496 566.811 348.52 566.804 348.52C566.605 348.513 563.971 348.537 557.953 352.3C545.161 360.299 528.815 377.492 506.807 403.867C494.927 418.106 481.871 434.435 467.547 451.957C463.709 457.28 459.503 462.538 454.91 467.717L454.702 467.549C420.808 508.347 380.37 553.856 332.335 593.848C301.853 619.226 262.656 622.597 228.642 614.743C194.834 606.936 162.658 587.448 142.217 561.686C108.054 518.631 100.57 469.801 108.223 427.836C115.56 387.606 137.391 351.005 166.502 331.557C161.248 315.813 156.813 299.49 153.519 283.013C142.593 228.368 143.239 167.031 174.28 119.619C186.922 100.31 205.846 89.1535 227.387 85.2773C248.1 81.5504 270.278 84.648 291.495 91.399ZM378.642 206.356C345.773 172.563 307.463 147.917 275.208 137.654C259.096 132.527 246.171 131.514 236.828 133.195C228.314 134.727 222.227 138.497 217.721 145.38C196.712 177.468 193.858 224.004 203.82 273.827C206.532 287.394 210.127 300.834 214.345 313.817C236.45 310.276 260.156 311.463 281.22 317.11C319.621 327.403 357.501 355.419 357.501 405.654C357.501 435.255 339.111 465.136 307.278 473.815C273.211 483.103 238.854 464.822 213.105 427.541C203.716 413.947 194.443 397.766 185.947 379.89C174.028 392.223 163.08 411.953 158.673 436.118C153.128 466.518 158.514 501.286 183.085 532.253C195.993 548.522 217.742 562.031 240.771 567.349C263.594 572.619 284.147 569.24 298.664 557.154C349.383 514.927 390.709 466.547 426.366 422.952C448.879 390.86 453.195 356.06 445.578 321.265C436.703 280.718 411.425 240.06 378.642 206.356ZM306.296 405.722C306.296 384.769 292.223 370.736 267.284 364.051C256.012 361.03 244.156 360.087 233.095 360.771C240.361 375.935 248.168 389.513 255.897 400.704C275.647 429.298 289.989 427.822 293.247 426.934C298.737 425.437 306.296 418.161 306.296 405.722Z"; +import { PaseoMark as CanonicalPaseoMark } from "../../paseo-brand"; export function PaseoMark({ size = 20, className }: { size?: number; className?: string }) { - return ( - - ); + return ; } /** A hashed identity tile — one letter on a muted identity fill. */ diff --git a/packages/website/src/components/paseo-brand.test.tsx b/packages/website/src/components/paseo-brand.test.tsx new file mode 100644 index 000000000000..483b676068bd --- /dev/null +++ b/packages/website/src/components/paseo-brand.test.tsx @@ -0,0 +1,74 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { HubLockup, PaseoHubLockup, PaseoHubMark, PaseoLockup, PaseoMark } from "./paseo-brand"; + +const REPO_ROOT = path.resolve(import.meta.dirname, "../../../.."); +const BRAND_ROOT = path.join(REPO_ROOT, "assets/brand"); +const WEBSITE_PUBLIC = path.join(REPO_ROOT, "packages/website/public"); + +function extractPathData(svg: string): string[] { + return [...svg.matchAll(/\bd="([^"]+)"/g)].map((m) => m[1]); +} + +describe("paseo brand assets", () => { + it("renders canonical Paseo and Paseo Hub marks with currentColor", () => { + const paseoHtml = renderToStaticMarkup(); + const hubHtml = renderToStaticMarkup(); + const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8"); + const canonicalHub = readFileSync(path.join(BRAND_ROOT, "marks/paseo-hub-white.svg"), "utf8"); + + expect(paseoHtml).toContain('viewBox="0 0 700 700"'); + expect(paseoHtml).toContain('stroke="currentColor"'); + expect(paseoHtml).toContain('stroke-width="50"'); + expect(extractPathData(paseoHtml)).toEqual(extractPathData(canonicalPaseo)); + + expect(hubHtml).toContain('viewBox="0 0 700 700"'); + expect(hubHtml).toContain('stroke="currentColor"'); + expect(hubHtml).toContain('stroke-width="50"'); + expect(extractPathData(hubHtml)).toEqual(extractPathData(canonicalHub)); + }); + + it("renders canonical Paseo, Paseo Hub, and Hub lockups at shared 144-unit height", () => { + const cases = [ + { Component: PaseoLockup, file: "lockups/paseo-white.svg", width: 580 }, + { Component: PaseoHubLockup, file: "lockups/paseo-hub-white.svg", width: 842 }, + { Component: HubLockup, file: "lockups/hub-white.svg", width: 461 }, + ]; + + for (const { Component, file, width } of cases) { + const html = renderToStaticMarkup(); + const canonical = readFileSync(path.join(BRAND_ROOT, file), "utf8"); + + expect(html).toContain(`viewBox="0 0 ${width} 144"`); + expect(html).toContain(`width="${width}"`); + expect(html).toContain('height="144"'); + expect(html).toContain('stroke="currentColor"'); + expect(html).toContain('fill="currentColor"'); + expect(extractPathData(html)).toEqual(extractPathData(canonical)); + } + }); + + it("keeps public/logo.svg and public/favicon.svg aligned with assets/brand", () => { + const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8"); + const publicLogo = readFileSync(path.join(WEBSITE_PUBLIC, "logo.svg"), "utf8"); + const publicFavicon = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.svg"), "utf8"); + + expect(publicLogo).toBe(canonicalPaseo); + expect(publicFavicon).toContain(' { + const ico = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.ico")); + expect(ico.readUInt16LE(0)).toBe(0); + expect(ico.readUInt16LE(2)).toBe(1); + const count = ico.readUInt16LE(4); + const sizes: number[] = []; + for (let i = 0; i < count; i += 1) { + sizes.push(ico[6 + i * 16] || 256); + } + expect(sizes).toEqual([48, 32, 16]); + }); +}); diff --git a/packages/website/src/components/paseo-brand.tsx b/packages/website/src/components/paseo-brand.tsx new file mode 100644 index 000000000000..73c620a83a54 --- /dev/null +++ b/packages/website/src/components/paseo-brand.tsx @@ -0,0 +1,154 @@ +// Canonical Paseo and Paseo Hub brand marks and lockups, sourced directly from +// `assets/brand/` (see `assets/brand/README.md`). + +import type * as React from "react"; +import hubLockupSvg from "../../../../assets/brand/lockups/hub-white.svg?raw"; +import paseoHubLockupSvg from "../../../../assets/brand/lockups/paseo-hub-white.svg?raw"; +import paseoLockupSvg from "../../../../assets/brand/lockups/paseo-white.svg?raw"; +import paseoHubMarkSvg from "../../../../assets/brand/marks/paseo-hub-white.svg?raw"; +import paseoMarkSvg from "../../../../assets/brand/marks/paseo-white.svg?raw"; + +interface ParsedMark { + width: number; + height: number; + viewBox: string; + path: string; + strokeWidth: number; +} + +interface ParsedLockup extends ParsedMark { + wordmarkPath: string; +} + +function readAttr(tag: string, name: string, source: string): string { + const match = tag.match(new RegExp(`${name}="([^"]+)"`)); + if (!match) { + throw new Error(`Missing ${name} attribute in canonical brand SVG (${source})`); + } + return match[1]; +} + +function parseSvgHeader(svg: string, source: string) { + const svgTag = svg.match(/]*>/)?.[0]; + if (!svgTag) { + throw new Error(`Missing root in canonical brand SVG (${source})`); + } + const paths = [...svg.matchAll(/]*\/?>/g)].map((m) => m[0]); + return { + width: Number(readAttr(svgTag, "width", source)), + height: Number(readAttr(svgTag, "height", source)), + viewBox: readAttr(svgTag, "viewBox", source), + paths, + }; +} + +function parseMark(svg: string, source: string): ParsedMark { + const { width, height, viewBox, paths } = parseSvgHeader(svg, source); + if (paths.length !== 1) { + throw new Error(`Expected 1 path in brand mark SVG (${source}), found ${paths.length}`); + } + return { + width, + height, + viewBox, + path: readAttr(paths[0], "d", source), + strokeWidth: Number(readAttr(paths[0], "stroke-width", source)), + }; +} + +function parseLockup(svg: string, source: string): ParsedLockup { + const { width, height, viewBox, paths } = parseSvgHeader(svg, source); + if (paths.length !== 2) { + throw new Error(`Expected 2 paths in brand lockup SVG (${source}), found ${paths.length}`); + } + return { + width, + height, + viewBox, + path: readAttr(paths[0], "d", source), + strokeWidth: Number(readAttr(paths[0], "stroke-width", source)), + wordmarkPath: readAttr(paths[1], "d", source), + }; +} + +const PASEO_MARK = parseMark(paseoMarkSvg, "marks/paseo-white.svg"); +const PASEO_HUB_MARK = parseMark(paseoHubMarkSvg, "marks/paseo-hub-white.svg"); +const PASEO_LOCKUP = parseLockup(paseoLockupSvg, "lockups/paseo-white.svg"); +const PASEO_HUB_LOCKUP = parseLockup(paseoHubLockupSvg, "lockups/paseo-hub-white.svg"); +const HUB_LOCKUP = parseLockup(hubLockupSvg, "lockups/hub-white.svg"); + +function BrandMark({ asset, props }: { asset: ParsedMark; props: React.SVGProps }) { + return ( + + ); +} + +function BrandLockup({ + asset, + props, +}: { + asset: ParsedLockup; + props: React.SVGProps; +}) { + return ( + + ); +} + +/** Canonical Paseo butterfly mark (700x700 viewBox, stroked with currentColor). */ +export function PaseoMark(props: React.SVGProps) { + return ; +} + +/** Canonical Paseo Hub five-petal flower mark (700x700 viewBox, stroked with currentColor). */ +export function PaseoHubMark(props: React.SVGProps) { + return ; +} + +/** Canonical Paseo lockup (butterfly mark at 94% optical scale + Plus Jakarta Sans SemiBold). */ +export function PaseoLockup(props: React.SVGProps) { + return ; +} + +/** Canonical Paseo Hub lockup (flower mark + Plus Jakarta Sans SemiBold). */ +export function PaseoHubLockup(props: React.SVGProps) { + return ; +} + +/** Canonical Hub lockup (flower mark + "Hub"), used where Paseo is already on screen. */ +export function HubLockup(props: React.SVGProps) { + return ; +} diff --git a/packages/website/src/components/site-header.tsx b/packages/website/src/components/site-header.tsx index 249b9ebd8611..3925e72c1b3d 100644 --- a/packages/website/src/components/site-header.tsx +++ b/packages/website/src/components/site-header.tsx @@ -3,6 +3,7 @@ import { PLUGINS_LINKED } from "~/plugins/launch"; import "~/styles.css"; import { DiscordIcon, GitHubIcon } from "~/components/brand-icons"; import { LanguageSelector } from "~/components/language-selector"; +import { PaseoLockup } from "~/components/paseo-brand"; import { useLocalizePath } from "~/i18n"; import { useStars } from "~/routes/__root"; @@ -14,9 +15,12 @@ export function SiteHeader() { const { stars } = useStars(); return (
- -
Paseo - Paseo + +
{PLUGINS_LINKED && ( diff --git a/packages/website/src/routes/{-$locale}/docs.tsx b/packages/website/src/routes/{-$locale}/docs.tsx index 1e6c24a51ee2..3d454f35a0a1 100644 --- a/packages/website/src/routes/{-$locale}/docs.tsx +++ b/packages/website/src/routes/{-$locale}/docs.tsx @@ -9,6 +9,7 @@ import { useTranslation } from "react-i18next"; import { buildDocsNavTree, getDoc, getDocs } from "~/docs"; import { splitLocalePath, useLocale, useLocalizePath } from "~/i18n"; import { LanguageSelector } from "~/components/language-selector"; +import { PaseoLockup } from "~/components/paseo-brand"; import "~/styles.css"; export const Route = createFileRoute("/{-$locale}/docs")({ @@ -35,9 +36,12 @@ function DocsLayout() { {/* Mobile header */}
- - Paseo - Paseo + +
@@ -63,9 +67,12 @@ function DocsLayout() { {/* Desktop sidebar */}
); } diff --git a/packages/website/src/components/site-shell.tsx b/packages/website/src/components/site-shell.tsx index 2c0a38f795e5..a052a50d5584 100644 --- a/packages/website/src/components/site-shell.tsx +++ b/packages/website/src/components/site-shell.tsx @@ -1,4 +1,5 @@ import type { ReactNode } from "react"; +import { PAGE_INSET_CLASS, PAGE_RAIL_CLASS, PageHeaderBand } from "~/components/page-frame"; import { SiteFooter } from "~/components/site-footer"; import { SiteHeader } from "~/components/site-header"; @@ -7,18 +8,26 @@ interface SiteShellProps { width: "default" | "prose" | "wide"; } -const MAIN_CLASSES: Record = { +const MAIN_CLASSES: Record, string> = { prose: "max-w-prose p-6 md:p-12 mx-auto", - default: "max-w-5xl p-6 md:p-20 mx-auto", wide: "max-w-7xl p-6 md:p-20 mx-auto", }; export function SiteShell({ children, width }: SiteShellProps) { - const mainClasses = MAIN_CLASSES[width]; + if (width === "default") { + return ( +
+ +
{children}
+ +
+ ); + } + return (
-
-
+
+
{children} diff --git a/packages/website/src/components/sponsorship.tsx b/packages/website/src/components/sponsorship.tsx index 50a46ccfde1f..7fc8382bf4b4 100644 --- a/packages/website/src/components/sponsorship.tsx +++ b/packages/website/src/components/sponsorship.tsx @@ -1,8 +1,8 @@ import { ArrowRight, Check, ExternalLink, Heart } from "lucide-react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; -import { useLocalizePath } from "~/i18n"; import { BuyMeACoffeeIcon, GitHubIcon, OpenCollectiveIcon } from "~/components/brand-icons"; +import { HairlineGrid, SectionOpener } from "~/components/page-frame"; import { BUY_ME_A_COFFEE_URL, GITHUB_SPONSORS_URL, @@ -14,6 +14,7 @@ import { openSpotCount, sponsorHref, } from "~/data/sponsors"; +import { useLocalizePath } from "~/i18n"; function SectionHeading({ as: Heading, @@ -27,11 +28,13 @@ function SectionHeading({ badge?: string; }) { return ( -
+
- {title} + + {title} + {badge ? ( - + {badge} ) : null} @@ -55,7 +58,7 @@ const MAINTAINER_COMPONENTS = { }; const MAINTAINER_SIGNATURE = ( -

+

); @@ -141,26 +144,28 @@ export function BackingOptions() { [localize, t], ); return ( - + ); } @@ -184,7 +189,7 @@ export function SponsorSpotSection() { ") + if (state.openListTypes.isNotEmpty()) state.openListTypes.removeAt(state.openListTypes.lastIndex) + state.listDepth-- + } + + // Handle list type change at same depth (ul <-> ol) + if (state.listDepth == depth && state.openListTypes.isNotEmpty()) { + if (state.openListTypes.last() != isOrdered) { + html.append(if (state.openListTypes.last()) "" else "") + state.openListTypes.removeAt(state.openListTypes.lastIndex) + state.listDepth-- + } + } + + // Open lists to deeper depth + while (state.listDepth < depth) { + state.listDepth++ + val marginStyle = + if (state.listDepth == 0) { + "margin: 0 0 ${styles.paragraphMarginBottom}px 0; " + } else { + "margin: 0; " + } + + if (isOrdered) { + html + .append("
    ") + state.openListTypes.add(true) + } else { + html + .append("
      ") + state.openListTypes.add(false) + } + } + + html + .append("
    • ") + + if (isTask) { + val size = styles.taskCheckboxSize + val radius = styles.taskCheckboxBorderRadius + if (para.isTaskChecked) { + html + .append("✓ ") + } else { + html + .append(" ") + } + } + + html + .append(content) + .append("
    • ") + + state.previousWasBlockquote = false + state.previousWasCodeBlock = false + } + + private fun handleHeading( + html: StringBuilder, + content: String, + type: Int, + styles: CachedStyles, + state: GeneratorState, + ) { + closeCodeBlockIfOpen(html, state, styles) + closeAllBlockquotes(html, state) + closeListsIfOpen(html, state) + + val level = type // TYPE_H1..TYPE_H6 = 1..6 + val idx = level - 1 + + html + .append("") + .append(content) + .append("') + + state.previousWasBlockquote = false + state.previousWasCodeBlock = false + } + + private fun handleNormalParagraph( + html: StringBuilder, + content: String, + styles: CachedStyles, + state: GeneratorState, + ) { + closeCodeBlockIfOpen(html, state, styles) + closeAllBlockquotes(html, state) + closeListsIfOpen(html, state) + + html + .append("

      ") + .append(content) + .append("

      ") + + state.previousWasBlockquote = false + state.previousWasCodeBlock = false + } + + private fun closeCodeBlockIfOpen( + html: StringBuilder, + state: GeneratorState, + styles: CachedStyles, + ) { + if (state.inCodeBlock) { + state.inCodeBlock = false + outputCodeBlock(html, state.codeBlockLines, styles) + state.codeBlockLines.clear() + } + } + + private fun closeAllBlockquotes( + html: StringBuilder, + state: GeneratorState, + ) { + while (state.blockquoteDepth >= 0) { + html.append("") + state.blockquoteDepth-- + } + state.inBlockquote = false + } + + private fun closeListsIfOpen( + html: StringBuilder, + state: GeneratorState, + ) { + while (state.openListTypes.isNotEmpty()) { + html.append(if (state.openListTypes.last()) "
" else "") + state.openListTypes.removeAt(state.openListTypes.lastIndex) + } + state.listDepth = -1 + } + + private fun closeRemainingContainers( + html: StringBuilder, + state: GeneratorState, + styles: CachedStyles, + ) { + closeCodeBlockIfOpen(html, state, styles) + closeAllBlockquotes(html, state) + closeListsIfOpen(html, state) + } + + private fun generateInlineHTML( + text: Spannable, + start: Int, + end: Int, + styles: CachedStyles, + isCodeBlock: Boolean, + ): String { + val html = StringBuilder(end - start + 32) + var i = start + + while (i < end) { + val char = text[i] + + when { + char == '\n' && i == end - 1 -> { + i++ + } + + char == OBJECT_REPLACEMENT_CHAR -> { + appendReplacementChar(html, text, i, styles) + i++ + } + + else -> { + val segmentEnd = minOf(text.nextSpanTransition(i, end, Any::class.java), end) + val segmentText = text.subSequence(i, segmentEnd).toString() + + if (segmentText.isNotEmpty() && segmentText != "\n") { + appendStyledSegment(html, text, i, segmentEnd, segmentText, styles, isCodeBlock) + } + i = segmentEnd + } + } + } + + return html.toString() + } + + private fun appendReplacementChar( + html: StringBuilder, + text: Spannable, + pos: Int, + styles: CachedStyles, + ) { + val imageSpans = text.getSpans(pos, pos + 1, ImageSpan::class.java) + if (imageSpans.isNotEmpty()) { + val imgSpan = imageSpans[0] + + if (imgSpan.isInline) { + html.append("") + } else { + html + .append("

") + } + return + } + + val mathLatex = extractMathLatex(text, pos, pos + 1) + if (mathLatex != null) { + html + .append("") + escapeHTMLTo(html, mathLatex) + html.append("") + } + } + + private fun appendStyledSegment( + html: StringBuilder, + text: Spannable, + start: Int, + end: Int, + content: String, + styles: CachedStyles, + isCodeBlock: Boolean, + ) { + val strongSpans = text.getSpans(start, end, StrongSpan::class.java) + val styleSpans = text.getSpans(start, end, StyleSpan::class.java) + val emphasisSpans = text.getSpans(start, end, EmphasisSpan::class.java) + val underlineSpans = text.getSpans(start, end, UnderlineSpan::class.java) + val strikethroughSpans = text.getSpans(start, end, StrikethroughSpan::class.java) + val linkSpans = text.getSpans(start, end, LinkSpan::class.java) + val codeSpans = text.getSpans(start, end, CodeSpan::class.java) + val highlightSpans = text.getSpans(start, end, HighlightSpan::class.java) + + val isBold = + strongSpans.isNotEmpty() || + styleSpans.any { it.style == Typeface.BOLD || it.style == Typeface.BOLD_ITALIC } + val isItalic = + emphasisSpans.isNotEmpty() || + styleSpans.any { it.style == Typeface.ITALIC || it.style == Typeface.BOLD_ITALIC } + val isUnderline = underlineSpans.isNotEmpty() + val isStrikethrough = strikethroughSpans.isNotEmpty() + val link = linkSpans.firstOrNull() + val isCode = codeSpans.isNotEmpty() && !isCodeBlock + val isHighlight = highlightSpans.isNotEmpty() + + if (isHighlight) { + html + .append("") + } + + link?.let { + html.append("") + } + + if (isCode) { + html + .append("") + } + + if (isBold) { + if (styles.strongColor != null) { + html.append("") + } else { + html.append("") + } + } + + if (isItalic) { + if (styles.emphasisColor != null) { + html.append("") + } else { + html.append("") + } + } + + if (isStrikethrough) { + if (styles.strikethroughColor != null) { + html.append("") + } else { + html.append("") + } + } + if (isUnderline && link == null) { + if (styles.underlineColor != null) { + html.append("") + } else { + html.append("") + } + } + + escapeHTMLTo(html, content.trimEnd('\n')) + + if (isUnderline && link == null) html.append("") + if (isStrikethrough) html.append("") + if (isItalic) html.append("") + if (isBold) html.append("") + if (isCode) html.append("") + if (link != null) html.append("") + if (isHighlight) html.append("") + } + + private fun collectParagraphs(text: Spannable): ArrayList { + val string = text.toString() + val paragraphs = ArrayList(string.length / 40 + 1) // Estimate + var currentIndex = 0 + + while (currentIndex < string.length) { + var lineEnd = string.indexOf('\n', currentIndex) + if (lineEnd == -1) lineEnd = string.length else lineEnd++ + + val listSpan = innermostListSpan(text, currentIndex) + val type = getParagraphType(text, currentIndex, listSpan) + val depth = getDepthForType(text, currentIndex, type, listSpan) + val isTaskChecked = type == TYPE_TASK_LIST && (listSpan as? TaskListSpan)?.isChecked == true + + paragraphs.add(ParagraphInfo(currentIndex, lineEnd, type, depth, isTaskChecked)) + currentIndex = lineEnd + } + + return paragraphs + } + + /** + * The list span that owns the line starting at [start]. A list item's span covers its nested + * children, so every ancestor is returned here as well - the innermost span is the item that + * actually starts on this line. + */ + private fun innermostListSpan( + text: Spannable, + start: Int, + ): BaseListSpan? = + text + .getSpans(start, minOf(start + 1, text.length), BaseListSpan::class.java) + .maxByOrNull { it.depth } + + private fun getParagraphType( + text: Spannable, + start: Int, + listSpan: BaseListSpan?, + ): Int { + val end = minOf(start + 1, text.length) + + if (text.getSpans(start, end, CodeBlockSpan::class.java).isNotEmpty()) return TYPE_CODE_BLOCK + + val headingSpans = text.getSpans(start, end, HeadingSpan::class.java) + if (headingSpans.isNotEmpty()) return headingSpans[0].level.coerceIn(1, 6) + + if (text.getSpans(start, end, BlockquoteSpan::class.java).isNotEmpty()) return TYPE_BLOCKQUOTE + + return when (listSpan) { + is TaskListSpan -> TYPE_TASK_LIST + is OrderedListSpan -> TYPE_ORDERED_LIST + is UnorderedListSpan -> TYPE_UNORDERED_LIST + else -> TYPE_NORMAL + } + } + + private fun getDepthForType( + text: Spannable, + start: Int, + type: Int, + listSpan: BaseListSpan?, + ): Int = + when (type) { + TYPE_BLOCKQUOTE -> { + text.getSpans(start, start + 1, BlockquoteSpan::class.java).maxOfOrNull { it.depth } ?: 0 + } + + TYPE_ORDERED_LIST, TYPE_UNORDERED_LIST, TYPE_TASK_LIST -> { + listSpan?.depth ?: 0 + } + + else -> { + 0 + } + } + + fun generateTableHTML( + rows: List>>, + style: StyleConfig, + scaledDensity: Float = 1f, + density: Float = 1f, + ): String { + if (rows.isEmpty()) return "" + + val tableStyle = style.tableStyle + val cachedStyles = CachedStyles(style, scaledDensity, density) + + val borderColorCSS = colorToCSS(tableStyle.borderColor) + val borderWidthPx = tableStyle.borderWidth / density + val borderRadiusPx = tableStyle.borderRadius / density + val fontSizePx = tableStyle.fontSize / scaledDensity + val cellPaddingVerticalPx = tableStyle.cellPaddingVertical / density + val cellPaddingHorizontalPx = tableStyle.cellPaddingHorizontal / density + val bodyFontWeight = CachedStyles.fontWeightToCSS(tableStyle.fontWeight) + + return buildString(rows.size * 250) { + append("") + + var hasOpenedBody = false + var bodyRowIndex = 0 + + for (row in rows) { + if (row.isEmpty()) continue + + val isHeaderRow = row.first().second + + if (isHeaderRow) { + append("") + } else if (!hasOpenedBody) { + append("") + hasOpenedBody = true + } + + append("") + + for ((cellText, isHeader, alignment) in row) { + val backgroundColor = + when { + isHeader -> colorToCSS(tableStyle.headerBackgroundColor) + bodyRowIndex % 2 == 0 -> colorToCSS(tableStyle.rowEvenBackgroundColor) + else -> colorToCSS(tableStyle.rowOddBackgroundColor) + } + val textColor = if (isHeader) colorToCSS(tableStyle.headerTextColor) else colorToCSS(tableStyle.color) + val textAlignment = alignmentToCSS(alignment) + val fontWeight = if (isHeader) "bold" else bodyFontWeight + + val htmlTag = if (isHeader) "th" else "td" + append("<$htmlTag style=\"") + append("padding: ${cellPaddingVerticalPx.toInt()}px ${cellPaddingHorizontalPx.toInt()}px; ") + append("text-align: $textAlignment; ") + append("background-color: $backgroundColor; ") + append("color: $textColor; ") + append("border: ${borderWidthPx.toInt()}px solid $borderColorCSS; ") + append("font-weight: $fontWeight;\">") + + if (cellText.isNotEmpty()) { + if (cellText is Spannable) { + append(generateInlineHTML(cellText, 0, cellText.length, cachedStyles, false)) + } else { + escapeHTMLTo(this, cellText.toString()) + } + } + + append("") + } + + append("") + + if (isHeaderRow) { + append("") + } else { + bodyRowIndex++ + } + } + + if (hasOpenedBody) append("") + append("
") + } + } + + private fun alignmentToCSS(alignment: Layout.Alignment): String = + when (alignment) { + Layout.Alignment.ALIGN_CENTER -> "center" + Layout.Alignment.ALIGN_OPPOSITE -> "right" + else -> "left" + } + + private fun colorToCSS(color: Int): String { + if (color == 0) return "inherit" + val alpha = (color shr 24) and 0xFF + val red = (color shr 16) and 0xFF + val green = (color shr 8) and 0xFF + val blue = color and 0xFF + return if (alpha < 255) "rgba($red, $green, $blue, ${alpha / 255f})" else String.format("#%02X%02X%02X", red, green, blue) + } + + /** Fast HTML escape using single-pass character scanning. */ + private fun escapeHTMLTo( + output: StringBuilder, + text: String, + ) { + val len = text.length + + // Fast path: skip if no escaping needed + var needsEscape = false + for (i in 0 until len) { + val c = text[i] + if (c == '&' || c == '<' || c == '>' || c == '"' || c == '\'') { + needsEscape = true + break + } + } + if (!needsEscape) { + output.append(text) + return + } + + for (i in 0 until len) { + when (val c = text[i]) { + '&' -> output.append("&") + '<' -> output.append("<") + '>' -> output.append(">") + '"' -> output.append(""") + '\'' -> output.append("'") + else -> output.append(c) + } + } + } + + private fun extractMathLatex( + text: android.text.Spannable, + start: Int, + end: Int, + ): String? { + return try { + val mathInlineSpanClass = Class.forName("com.swmansion.enriched.markdown.spans.MathInlineSpan") + val spans = text.getSpans(start, end, mathInlineSpanClass) + if (spans.isEmpty()) return null + val latexField = mathInlineSpanClass.getDeclaredField("latex").apply { isAccessible = true } + latexField.get(spans[0]) as? String + } catch (_: Exception) { + null + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor.kt new file mode 100644 index 000000000000..ec5a0347a7c6 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor.kt @@ -0,0 +1,414 @@ +package com.swmansion.enriched.markdown.utils.text.conversion + +import android.text.Spannable +import android.text.style.UnderlineSpan +import android.widget.TextView +import com.swmansion.enriched.markdown.EnrichedMarkdownText +import com.swmansion.enriched.markdown.spans.BaseListSpan +import com.swmansion.enriched.markdown.spans.BaselineShiftSpan +import com.swmansion.enriched.markdown.spans.BlockquoteSpan +import com.swmansion.enriched.markdown.spans.CodeBlockSpan +import com.swmansion.enriched.markdown.spans.CodeSpan +import com.swmansion.enriched.markdown.spans.EmphasisSpan +import com.swmansion.enriched.markdown.spans.HeadingSpan +import com.swmansion.enriched.markdown.spans.HighlightSpan +import com.swmansion.enriched.markdown.spans.ImageSpan +import com.swmansion.enriched.markdown.spans.LinkSpan +import com.swmansion.enriched.markdown.spans.OrderedListSpan +import com.swmansion.enriched.markdown.spans.StrikethroughSpan +import com.swmansion.enriched.markdown.spans.StrongSpan +import com.swmansion.enriched.markdown.spans.TaskListSpan +import com.swmansion.enriched.markdown.spans.ThematicBreakSpan +import com.swmansion.enriched.markdown.spans.UnorderedListSpan + +/** Extracts markdown from styled text (Spannable). */ +object MarkdownExtractor { + /** + * Gets markdown for the current text selection. + * Full selection returns original markdown, partial reconstructs from spans. + */ + fun getMarkdownForSelection(textView: TextView): String? { + val start = textView.selectionStart + val end = textView.selectionEnd + if (start < 0 || end < 0 || start >= end) return null + + val spannable = textView.text as? Spannable ?: return null + + val isFullSelection = start == 0 && end >= textView.text.length - 1 + if (isFullSelection && textView is EnrichedMarkdownText) { + val original = textView.currentMarkdown + if (original.isNotEmpty()) return original + } + + return extractFromSpannable(spannable, start, end) + } + + /** Extracts markdown from a Spannable within a given range. */ + fun extractFromSpannable( + spannable: Spannable, + start: Int, + end: Int, + ): String { + val result = StringBuilder() + val state = ExtractionState() + val headingAccumulator = HeadingAccumulator() + + var i = start + while (i < end) { + val nextTransition = spannable.nextSpanTransition(i, end, Any::class.java) + val segmentText = spannable.subSequence(i, nextTransition).toString() + + val handled = + processSegment( + spannable = spannable, + segmentText = segmentText, + segmentStart = i, + segmentEnd = nextTransition, + result = result, + state = state, + headingAccumulator = headingAccumulator, + ) + + if (!handled) { + // Regular text segment - apply inline formatting and block prefixes + appendFormattedSegment(spannable, segmentText, i, nextTransition, result, state) + } + + i = nextTransition + } + + headingAccumulator.flush(result, state) + return result.toString() + } + + /** Returns true if segment was handled specially. */ + private fun processSegment( + spannable: Spannable, + segmentText: String, + segmentStart: Int, + segmentEnd: Int, + result: StringBuilder, + state: ExtractionState, + headingAccumulator: HeadingAccumulator, + ): Boolean { + // Check for thematic breaks first (uses " \n" as placeholder) + val thematicBreakSpans = spannable.getSpans(segmentStart, segmentEnd, ThematicBreakSpan::class.java) + if (thematicBreakSpans.isNotEmpty()) { + appendThematicBreak(result, state) + return true + } + + if (segmentText == "\uFFFC" || segmentText == "\u200B") { + val imageSpans = spannable.getSpans(segmentStart, segmentEnd, ImageSpan::class.java) + if (imageSpans.isNotEmpty()) { + appendImage(imageSpans[0], result, state) + return true + } + + val mathLatex = extractMathLatex(spannable, segmentStart, segmentEnd) + if (mathLatex != null) { + result.append("$$mathLatex$") + return true + } + } + + if (segmentText.isEmpty()) return true + + if (segmentText == "\n" || segmentText == "\n\n") { + handleNewline(spannable, segmentStart, segmentEnd, result, state) + return true + } + + val headingSpans = spannable.getSpans(segmentStart, segmentEnd, HeadingSpan::class.java) + if (headingSpans.isNotEmpty()) { + headingAccumulator.accumulate(headingSpans[0].level, segmentText, result, state) + return true + } else { + headingAccumulator.flush(result, state) + } + + val codeBlockSpans = spannable.getSpans(segmentStart, segmentEnd, CodeBlockSpan::class.java) + if (codeBlockSpans.isNotEmpty()) { + appendCodeBlock(segmentText, result, state) + return true + } + + return false + } + + private fun appendFormattedSegment( + spannable: Spannable, + segmentText: String, + segmentStart: Int, + segmentEnd: Int, + result: StringBuilder, + state: ExtractionState, + ) { + val blockquotePrefix = detectBlockquote(spannable, segmentStart, segmentEnd, state) + val listPrefix = detectList(spannable, segmentStart, segmentEnd, state) + var segment = applyInlineFormatting(spannable, segmentText, segmentStart, segmentEnd) + + if (result.isAtLineStart() && !segmentText.startsWith("\n")) { + segment = buildBlockPrefix(blockquotePrefix, listPrefix) + segment + } + + if (state.needsBlankLine && result.isNotEmpty()) { + result.ensureBlankLine() + state.needsBlankLine = false + } + + result.append(segment) + } + + private fun appendImage( + img: ImageSpan, + result: StringBuilder, + state: ExtractionState, + ) { + if (img.isInline) { + result.append("![image](${img.imageUrl})") + } else { + result.ensureBlankLine() + result.append("![image](${img.imageUrl})\n") + state.needsBlankLine = true + state.blockquoteDepth = -1 + state.listDepth = -1 + } + } + + private fun appendThematicBreak( + result: StringBuilder, + state: ExtractionState, + ) { + result.ensureBlankLine() + result.append("---\n") + state.needsBlankLine = true + state.blockquoteDepth = -1 + state.listDepth = -1 + } + + private fun handleNewline( + spannable: Spannable, + start: Int, + end: Int, + result: StringBuilder, + state: ExtractionState, + ) { + val inBlockquote = spannable.getSpans(start, end, BlockquoteSpan::class.java).isNotEmpty() + val inList = + spannable.getSpans(start, end, OrderedListSpan::class.java).isNotEmpty() || + spannable.getSpans(start, end, UnorderedListSpan::class.java).isNotEmpty() || + spannable.getSpans(start, end, TaskListSpan::class.java).isNotEmpty() + + when { + !inBlockquote && state.blockquoteDepth >= 0 -> { + result.ensureBlankLine() + state.blockquoteDepth = -1 + } + + !inList && state.listDepth >= 0 -> { + result.ensureBlankLine() + state.listDepth = -1 + } + + inBlockquote || inList -> { + if (!result.endsWith("\n")) result.append("\n") + } + + else -> { + result.ensureBlankLine() + } + } + } + + private fun appendCodeBlock( + text: String, + result: StringBuilder, + state: ExtractionState, + ) { + if (state.needsBlankLine) { + result.ensureBlankLine() + state.needsBlankLine = false + } + + val needsFence = result.isEmpty() || result.endsWith("\n\n") + if (needsFence) result.append("```\n") + + result.append(text) + + if (text.endsWith("\n")) { + result.append("```\n") + state.needsBlankLine = true + } + } + + private fun detectBlockquote( + spannable: Spannable, + start: Int, + end: Int, + state: ExtractionState, + ): String? { + val spans = spannable.getSpans(start, end, BlockquoteSpan::class.java) + val depth = spans.maxOfOrNull { it.depth } ?: -1 + + return if (depth >= 0) { + state.blockquoteDepth = depth + "> ".repeat(depth + 1) + } else { + if (state.blockquoteDepth >= 0) state.blockquoteDepth = -1 + null + } + } + + private fun detectList( + spannable: Spannable, + start: Int, + end: Int, + state: ExtractionState, + ): String? { + // A list item's span covers its nested children, so ancestors are returned here too. The + // innermost span is the item this segment actually belongs to. + val listSpan = + spannable.getSpans(start, end, BaseListSpan::class.java).maxByOrNull { it.depth } + + if (listSpan == null) { + if (state.listDepth >= 0) state.listDepth = -1 + return null + } + + state.listDepth = listSpan.depth + val indent = " ".repeat(listSpan.depth) + + return when (listSpan) { + is TaskListSpan -> "$indent- ${if (listSpan.isChecked) "[x]" else "[ ]"} " + is OrderedListSpan -> "$indent${listSpan.itemNumber}. " + else -> "$indent- " + } + } + + private fun applyInlineFormatting( + spannable: Spannable, + text: String, + start: Int, + end: Int, + ): String { + val hasStrong = spannable.getSpans(start, end, StrongSpan::class.java).isNotEmpty() + val hasEmphasis = spannable.getSpans(start, end, EmphasisSpan::class.java).isNotEmpty() + val hasCode = spannable.getSpans(start, end, CodeSpan::class.java).isNotEmpty() + val hasStrikethrough = spannable.getSpans(start, end, StrikethroughSpan::class.java).isNotEmpty() + val hasUnderline = spannable.getSpans(start, end, UnderlineSpan::class.java).isNotEmpty() + val baselineShiftSpans = spannable.getSpans(start, end, BaselineShiftSpan::class.java) + val hasSuperscript = baselineShiftSpans.any { it.spanType == BaselineShiftSpan.SpanType.SUPERSCRIPT } + val hasSubscript = baselineShiftSpans.any { it.spanType == BaselineShiftSpan.SpanType.SUBSCRIPT } + val linkSpans = spannable.getSpans(start, end, LinkSpan::class.java).filterNot { it.recognizedLink } + val hasHighlight = spannable.getSpans(start, end, HighlightSpan::class.java).isNotEmpty() + + var result = text + + // Innermost first + if (hasCode && linkSpans.isEmpty()) { + result = "`$result`" + } + if (hasStrikethrough) { + result = "~~$result~~" + } + if (hasSubscript) { + result = "~$result~" + } + if (hasSuperscript) { + result = "^$result^" + } + if (hasUnderline && linkSpans.isEmpty()) { + result = "$result" + } + if (hasEmphasis) { + result = "*$result*" + } + if (hasStrong) { + result = "**$result**" + } + if (linkSpans.isNotEmpty()) { + result = "[$result](${linkSpans[0].url})" + } + if (hasHighlight) { + result = "==$result==" + } + + return result + } + + private fun buildBlockPrefix( + blockquotePrefix: String?, + listPrefix: String?, + ): String = + buildString { + blockquotePrefix?.let { append(it) } + listPrefix?.let { append(it) } + } + + private data class ExtractionState( + var blockquoteDepth: Int = -1, + var listDepth: Int = -1, + var needsBlankLine: Boolean = false, + ) + + /** Accumulates heading content across multiple span segments. */ + private class HeadingAccumulator { + private var level: Int? = null + private val content = StringBuilder() + + fun accumulate( + newLevel: Int, + text: String, + result: StringBuilder, + state: ExtractionState, + ) { + if (level != newLevel) { + flush(result, state) + level = newLevel + } + content.append(text.trim('\n')) + } + + fun flush( + result: StringBuilder, + state: ExtractionState, + ) { + val currentLevel = level ?: return + if (content.isEmpty()) return + + result.ensureBlankLine() + result.append("#".repeat(currentLevel)) + result.append(" ") + result.append(content.toString().trim()) + result.append("\n") + + level = null + content.clear() + state.needsBlankLine = true + } + } + + private fun StringBuilder.ensureBlankLine() { + if (isEmpty() || endsWith("\n\n")) return + append(if (endsWith("\n")) "\n" else "\n\n") + } + + private fun StringBuilder.isAtLineStart(): Boolean = isEmpty() || endsWith("\n") + + private fun extractMathLatex( + spannable: Spannable, + start: Int, + end: Int, + ): String? { + return try { + val mathInlineSpanClass = Class.forName("com.swmansion.enriched.markdown.spans.MathInlineSpan") + val spans = spannable.getSpans(start, end, mathInlineSpanClass) + if (spans.isEmpty()) return null + val latexField = mathInlineSpanClass.getDeclaredField("latex").apply { isAccessible = true } + latexField.get(spans[0]) as? String + } catch (_: Exception) { + null + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/ParagraphUtils.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/ParagraphUtils.kt new file mode 100644 index 000000000000..1bedbff4ed03 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/ParagraphUtils.kt @@ -0,0 +1,9 @@ +package com.swmansion.enriched.markdown.utils.text.extensions + +import com.swmansion.enriched.markdown.parser.MarkdownASTNode + +fun MarkdownASTNode.containsBlockImage(): Boolean { + if (type != MarkdownASTNode.NodeType.Paragraph) return false + val firstChild = children.firstOrNull() + return firstChild != null && children.size == 1 && firstChild.type == MarkdownASTNode.NodeType.Image +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/SpannableExtensions.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/SpannableExtensions.kt new file mode 100644 index 000000000000..bab644d8e748 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/SpannableExtensions.kt @@ -0,0 +1,65 @@ +package com.swmansion.enriched.markdown.utils.text.extensions + +import android.content.Context +import android.text.Spannable +import android.text.SpannableStringBuilder +import android.util.Log +import com.swmansion.enriched.markdown.spans.MathMeasureRequest +import com.swmansion.enriched.markdown.spans.MathMetrics +import com.swmansion.enriched.markdown.utils.common.FeatureFlags + +fun SpannableStringBuilder.isInlineImage(): Boolean { + if (isEmpty()) return false + val lastChar = last() + return lastChar != '\n' && lastChar != '\u200B' +} + +/** Swaps MathInlineSpans for MathInlinePlaceholderSpans safe for background-thread measurement. */ +fun Spannable.replaceMathSpansWithPlaceholders(context: Context) { + if (!FeatureFlags.IS_MATH_ENABLED) return + + try { + val spanClass = Class.forName("com.swmansion.enriched.markdown.spans.MathInlineSpan") + val placeholderClass = Class.forName("com.swmansion.enriched.markdown.spans.MathInlinePlaceholderSpan") + + val mathSpans = getSpans(0, length, spanClass) + if (mathSpans.isNullOrEmpty()) return + + val fontSizeField = spanClass.getDeclaredField("fontSize").apply { isAccessible = true } + val latexField = spanClass.getDeclaredField("latex").apply { isAccessible = true } + + val requests = + mathSpans.map { span -> + MathMeasureRequest( + fontSize = fontSizeField.getFloat(span), + latex = latexField.get(span) as String, + ) + } + + val mathMeasureHelperClass = Class.forName("com.swmansion.enriched.markdown.spans.MathMeasureHelper") + val measureMethod = mathMeasureHelperClass.getMethod("measure", Context::class.java, List::class.java) + + @Suppress("UNCHECKED_CAST") + val results = measureMethod.invoke(null, context, requests) as? List ?: return + + val placeholderCtor = placeholderClass.getConstructor(MathMetrics::class.java) + + mathSpans.forEachIndexed { i, oldSpan -> + val metrics = results.getOrNull(i) ?: return@forEachIndexed + + val start = getSpanStart(oldSpan) + val end = getSpanEnd(oldSpan) + val flags = getSpanFlags(oldSpan) + + if (start != -1 && end != -1) { + removeSpan(oldSpan) + val newSpan = placeholderCtor.newInstance(metrics) + setSpan(newSpan, start, end, flags) + } + } + } catch (_: ClassNotFoundException) { + // Expected if the module isn't linked; silent return + } catch (e: Exception) { + Log.e("MathSpan", "Failed to replace math spans", e) + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/TextPaintExtensions.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/TextPaintExtensions.kt new file mode 100644 index 000000000000..f1b9c3a08af1 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/extensions/TextPaintExtensions.kt @@ -0,0 +1,76 @@ +package com.swmansion.enriched.markdown.utils.text.extensions + +import android.content.Context +import android.graphics.Typeface +import android.text.TextPaint +import com.facebook.react.common.ReactConstants +import com.facebook.react.views.text.ReactTypefaceUtils.applyStyles +import com.facebook.react.views.text.ReactTypefaceUtils.parseFontWeight +import com.swmansion.enriched.markdown.renderer.BlockStyle +import com.swmansion.enriched.markdown.styles.CodeBlockStyle + +fun TextPaint.applyColorPreserving( + color: Int, + vararg preserveColors: Int, +) { + if (this.color !in preserveColors) { + this.color = color + } +} + +private val typefaceCache = mutableMapOf() +private val fontWeightCache = mutableMapOf() + +fun TextPaint.applyBlockStyleFont( + blockStyle: BlockStyle, + context: Context, +) { + val cacheKey = "${blockStyle.fontFamily}|${blockStyle.fontWeight}" + + val cachedTypeface = typefaceCache[cacheKey] + if (cachedTypeface != null) { + this.typeface = cachedTypeface + return + } + + val fontWeight = + fontWeightCache.getOrPut(blockStyle.fontWeight) { + parseFontWeight(blockStyle.fontWeight) + } + + // Pass null as base typeface - this matches React Native Text behavior + // applyStyles will use ReactFontManager to load custom fonts from assets + val newTypeface = + applyStyles( + null, // Let applyStyles handle font loading from assets + ReactConstants.UNSET, + fontWeight, + blockStyle.fontFamily.takeIf { it.isNotEmpty() }, + context.assets, + ) + + typefaceCache[cacheKey] = newTypeface + this.typeface = newTypeface +} + +/** + * Code block text sizing and font, shared by both flavors (CodeBlockSpan for + * commonmark, CodeBlockContainerView for github) so the code always renders + * and measures with the same paint. Color is applied by the callers: the span + * needs color preserving, the view colors via the text view. + */ +fun TextPaint.applyCodeBlockTextStyle( + style: CodeBlockStyle, + context: Context, +) { + textSize = style.fontSize + applyBlockStyleFont( + BlockStyle( + fontSize = style.fontSize, + fontFamily = style.fontFamily, + fontWeight = style.fontWeight, + color = style.color, + ), + context, + ) +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/CheckboxTouchHelper.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/CheckboxTouchHelper.kt new file mode 100644 index 000000000000..55c573328a2f --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/CheckboxTouchHelper.kt @@ -0,0 +1,61 @@ +package com.swmansion.enriched.markdown.utils.text.interaction + +import android.view.MotionEvent +import android.view.ViewConfiguration +import android.widget.TextView +import com.swmansion.enriched.markdown.utils.text.interaction.TaskListHitTestResult +import com.swmansion.enriched.markdown.utils.text.interaction.TaskListTapUtils +import kotlin.math.abs + +class CheckboxTouchHelper( + private val textView: TextView, +) { + var onCheckboxTap: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)? = null + + /** + * When false, checkbox taps are ignored: hit-testing is skipped and no + * gesture is consumed, so the tap falls through to the text view unchanged. + */ + var isEnabled: Boolean = true + + private var touchDownX = 0f + private var touchDownY = 0f + private var pendingHit: TaskListHitTestResult? = null + private val touchSlop: Int by lazy { ViewConfiguration.get(textView.context).scaledTouchSlop } + + /** Returns `true` if the event was consumed by a checkbox gesture. */ + fun onTouchEvent(event: MotionEvent): Boolean { + if (!isEnabled) return false + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + val hit = TaskListTapUtils.hitTest(textView, event.x, event.y) ?: return false + touchDownX = event.x + touchDownY = event.y + pendingHit = hit + return true + } + + MotionEvent.ACTION_MOVE -> { + if (pendingHit != null && isExceedingSlop(event)) { + pendingHit = null + } + } + + MotionEvent.ACTION_UP -> { + val hit = pendingHit ?: return false + pendingHit = null + if (!isExceedingSlop(event)) { + onCheckboxTap?.invoke(hit.taskIndex, hit.checked, hit.itemText) + } + return true + } + + MotionEvent.ACTION_CANCEL -> { + pendingHit = null + } + } + return pendingHit != null + } + + private fun isExceedingSlop(event: MotionEvent): Boolean = abs(event.x - touchDownX) > touchSlop || abs(event.y - touchDownY) > touchSlop +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt new file mode 100644 index 000000000000..e70b241678d9 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt @@ -0,0 +1,286 @@ +package com.swmansion.enriched.markdown.utils.text.interaction + +import android.text.Spannable +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.style.ForegroundColorSpan +import android.text.style.StrikethroughSpan +import android.widget.TextView +import com.swmansion.enriched.markdown.renderer.SpanStyleCache +import com.swmansion.enriched.markdown.spans.BaseListSpan +import com.swmansion.enriched.markdown.spans.CodeBlockSpan +import com.swmansion.enriched.markdown.spans.ListMarkerAnchorSpan +import com.swmansion.enriched.markdown.spans.TaskListSpan +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE + +data class TaskListHitTestResult( + val taskIndex: Int, + val checked: Boolean, + val itemText: String, +) + +object TaskListToggleUtils { + private val TASK_PATTERN = Regex("""^([ \t]*[-*+][ \t]+)\[[ xX]]""", RegexOption.MULTILINE) + + fun toggleAtIndex( + markdown: String, + index: Int, + checked: Boolean, + ): String { + val matches = TASK_PATTERN.findAll(markdown).toList() + if (index < 0 || index >= matches.size) return markdown + + val match = matches[index] + val prefix = match.groupValues[1] + + val replacement = "$prefix[${if (checked) "x" else " "}]" + + return markdown.replaceRange(match.range, replacement) + } +} + +object TaskListTapUtils { + fun hitTest( + textView: TextView, + rawX: Float, + rawY: Float, + ): TaskListHitTestResult? = + with(textView) { + val layout = layout ?: return null + val spannable = text as? Spanned ?: return null + + val x = rawX.toInt() - totalPaddingLeft + scrollX + val y = rawY.toInt() - totalPaddingTop + scrollY + + val line = layout.getLineForVertical(y) + + val taskSpan = + spannable + .getSpans( + layout.getLineStart(line), + layout.getLineEnd(line), + TaskListSpan::class.java, + ).maxByOrNull { it.depth } ?: return null + + val isRtl = layout.getParagraphDirection(line) == android.text.Layout.DIR_RIGHT_TO_LEFT + if (isRtl) { + val lineRight = layout.getLineRight(line).toInt() + val indentWidth = lineRight - layout.getParagraphRight(line).toInt() + if (x <= layout.width - indentWidth) return null + } else { + val lineLeft = layout.getLineLeft(line).toInt() + val indentWidth = layout.getParagraphLeft(line).toInt() - lineLeft + if (x >= indentWidth) return null + } + + val spanStart = spannable.getSpanStart(taskSpan) + val spanEnd = spannable.getSpanEnd(taskSpan) + + val itemText = + spannable + .subSequence(spanStart, spanEnd) + .toString() + .substringBefore('\n') + .trim() + + return TaskListHitTestResult( + taskIndex = taskSpan.taskIndex, + checked = taskSpan.isChecked, + itemText = itemText, + ) + } + + fun updateTaskListItemCheckedState( + textView: TextView, + targetIndex: Int, + newChecked: Boolean, + styleConfig: StyleConfig, + ): Boolean { + val text = textView.text + if (text !is Spannable) { + return false + } + + val spannable = SpannableStringBuilder(text) + val targetSpans = + spannable + .getSpans(0, spannable.length, TaskListSpan::class.java) + .filter { it.taskIndex == targetIndex } + if (targetSpans.isEmpty()) { + return false + } + + if (targetSpans.all { it.isChecked == newChecked }) { + return true + } + + val itemDepth = targetSpans.first().depth + val spanStart = targetSpans.minOf { spannable.getSpanStart(it) } + val spanEnd = targetSpans.maxOf { spannable.getSpanEnd(it) } + + val styleCache = SpanStyleCache(styleConfig) + + fun toggledCopy(old: TaskListSpan): TaskListSpan = + TaskListSpan( + taskStyle = styleConfig.taskListStyle, + listStyle = styleConfig.listStyle, + depth = old.depth, + context = textView.context, + styleCache = styleCache, + taskIndex = targetIndex, + isChecked = newChecked, + drawsMarker = old.drawsMarker, + ancestorMarkerOffset = old.ancestorMarkerOffset, + markerExtraWidth = old.markerExtraWidth, + parentMarkerWidth = old.parentMarkerWidth, + ) + + // Layout draws leading margins in insertion order, and a re-added span moves to the end of it. + // Re-add the task's spans and everything attached after them (its ancestors) in their original + // order; the task's own nested items were attached first and stay where they are. + data class ListSpanState( + val span: BaseListSpan, + val start: Int, + val end: Int, + val flags: Int, + ) + + val coveringSpans = spannable.getSpans(spanStart, spanEnd, BaseListSpan::class.java) + val firstTarget = coveringSpans.indexOfFirst { it is TaskListSpan && it.taskIndex == targetIndex } + val listSpans = + coveringSpans.drop(firstTarget).map { + ListSpanState(it, spannable.getSpanStart(it), spannable.getSpanEnd(it), spannable.getSpanFlags(it)) + } + listSpans.forEach { spannable.removeSpan(it.span) } + for ((old, start, end, flags) in listSpans) { + val replacement = if (old is TaskListSpan && old.taskIndex == targetIndex) toggledCopy(old) else old + spannable.setSpan(replacement, start, end, flags) + } + + // The marker may be drawn by an anchor span wrapping an unattached copy + spannable + .getSpans(0, spannable.length, ListMarkerAnchorSpan::class.java) + .filter { (it.marker as? TaskListSpan)?.taskIndex == targetIndex } + .forEach { old -> + val start = spannable.getSpanStart(old) + val end = spannable.getSpanEnd(old) + spannable.removeSpan(old) + spannable.setSpan( + ListMarkerAnchorSpan(toggledCopy(old.marker as TaskListSpan)), + start, + end, + SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, + ) + } + + val taskStyle = styleConfig.taskListStyle + val checkedTextColor = taskStyle.checkedTextColor + val strikethrough = taskStyle.checkedStrikethrough + + val excludedRanges = + ( + spannable.getSpans(spanStart, spanEnd, BaseListSpan::class.java).filter { it.depth > itemDepth } + + spannable.getSpans(spanStart, spanEnd, CodeBlockSpan::class.java).toList() + ).map { spannable.getSpanStart(it) to spannable.getSpanEnd(it) } + .sortedBy { it.first } + + applyDecorationsToRanges( + spannable = spannable, + spanStart = spanStart, + spanEnd = spanEnd, + excludedRanges = excludedRanges, + isChecked = newChecked, + checkedTextColor = checkedTextColor, + strikethrough = strikethrough, + styleConfig = styleConfig, + ) + + val imageSpans = text.getSpans(0, text.length, com.swmansion.enriched.markdown.spans.ImageSpan::class.java).toList() + val originalSpanStarts = imageSpans.associateWith { text.getSpanStart(it) } + + textView.text = spannable + + val newImageSpans = spannable.getSpans(0, spannable.length, com.swmansion.enriched.markdown.spans.ImageSpan::class.java) + imageSpans.forEach { originalSpan -> + val matchingSpan = + newImageSpans.firstOrNull { + it.imageUrl == originalSpan.imageUrl && + spannable.getSpanStart(it) == originalSpanStarts[originalSpan] + } + (matchingSpan ?: originalSpan).registerTextView(textView) + } + + textView.invalidate() + + return true + } + + private fun applyDecorationsToRanges( + spannable: Spannable, + spanStart: Int, + spanEnd: Int, + excludedRanges: List>, + isChecked: Boolean, + checkedTextColor: Int, + strikethrough: Boolean, + styleConfig: StyleConfig, + ) { + var currentPos = spanStart + for ((start, end) in excludedRanges) { + if (start > currentPos) { + if (isChecked) { + applyCheckedSpans(spannable, currentPos, start, checkedTextColor, strikethrough) + } else { + removeCheckedSpans(spannable, currentPos, start, styleConfig) + } + } + currentPos = maxOf(currentPos, end) + } + if (currentPos < spanEnd) { + if (isChecked) { + applyCheckedSpans(spannable, currentPos, spanEnd, checkedTextColor, strikethrough) + } else { + removeCheckedSpans(spannable, currentPos, spanEnd, styleConfig) + } + } + } + + private fun applyCheckedSpans( + spannable: Spannable, + start: Int, + end: Int, + color: Int, + strikethrough: Boolean, + ) { + if (color != 0) { + spannable.setSpan(ForegroundColorSpan(color), start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE) + } + if (strikethrough) { + spannable.setSpan(StrikethroughSpan(), start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE) + } + } + + private fun removeCheckedSpans( + spannable: Spannable, + start: Int, + end: Int, + styleConfig: StyleConfig, + ) { + val strikethroughSpans = spannable.getSpans(start, end, StrikethroughSpan::class.java) + strikethroughSpans.forEach { spannable.removeSpan(it) } + + val colorSpans = spannable.getSpans(start, end, ForegroundColorSpan::class.java) + colorSpans.forEach { spannable.removeSpan(it) } + + val listStyleColor = styleConfig.listStyle.color + if (listStyleColor != 0) { + spannable.setSpan( + ForegroundColorSpan(listStyleColor), + start, + end, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, + ) + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/ApplyLineHeight.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/ApplyLineHeight.kt new file mode 100644 index 000000000000..62ef1fc8587e --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/ApplyLineHeight.kt @@ -0,0 +1,40 @@ +package com.swmansion.enriched.markdown.utils.text.span + +import android.graphics.Paint.FontMetricsInt +import kotlin.math.ceil +import kotlin.math.floor + +/** + * Splits extra leading above and below the line, copied from RN + * CustomLineHeightSpan so we do not depend on React Native internal span types. + * + * Mirrors CustomLineHeightSpan.chooseHeight: + * https://github.com/react/react-native/blob/v0.86.2/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/CustomLineHeightSpan.kt#L44-L57 + * + * Unlike RN, [lineHeight] is a floor, not a clamp: taller content grows the + * line instead of being clipped (e.g. inline code taller than the paragraph, + * https://github.com/software-mansion/enriched-markdown/issues/827). + */ +internal fun applyLineHeight( + fm: FontMetricsInt, + lineHeight: Int, + start: Int, + end: Int, + textLength: Int, +) { + val leading = lineHeight - ((-fm.ascent) + fm.descent) + + // Use lineHeight as a floor: if the default line-height is greater, don't + // override it + if (leading > 0) { + fm.ascent -= ceil(leading / 2.0f).toInt() + fm.descent += floor(leading / 2.0f).toInt() + } + + if (start == 0) { + fm.top = fm.ascent + } + if (end == textLength) { + fm.bottom = fm.descent + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/BlockSpacing.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/BlockSpacing.kt new file mode 100644 index 000000000000..e5baf086f527 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/BlockSpacing.kt @@ -0,0 +1,142 @@ +package com.swmansion.enriched.markdown.utils.text.span + +import android.text.SpannableStringBuilder +import com.swmansion.enriched.markdown.spans.CodeBlockSpan +import com.swmansion.enriched.markdown.spans.ImageSpan +import com.swmansion.enriched.markdown.spans.LineHeightSpan +import com.swmansion.enriched.markdown.spans.LinkPillSpan +import com.swmansion.enriched.markdown.spans.MarginBottomSpan +import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE +import android.text.style.LineHeightSpan as AndroidLineHeightSpan + +fun createLineHeightSpan(lineHeight: Float): AndroidLineHeightSpan = LineHeightSpan(lineHeight) + +/** The line height floor that link pills ask of their paragraph. */ +private class LinkPillLineHeightSpan( + height: Float, +) : AndroidLineHeightSpan by LineHeightSpan(height) + +/** + * Raises the line height of every paragraph in [start]..[end] to the largest + * `pill.lineHeight` among its link pills. A line grows to fit a pill on its own, but only + * that line and only to the pill's box, so pills on consecutive lines touch. A style that + * sets `pill.lineHeight` gets a floor for the whole paragraph instead, which keeps its + * lines even and the pills apart. + * + * Nested blocks set line height over ranges that overlap, so a paragraph that already + * has its floor is left alone. [spanFlags] are those of the block's own line height span: + * line height spans apply in order, and the floor has to come before the spans that add a + * margin to a line, or it would swallow that margin. + */ +fun applyLinkPillLineHeight( + builder: SpannableStringBuilder, + start: Int, + end: Int, + spanFlags: Int = SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, +) { + val heights = HashMap() + for (pill in builder.getSpans(start, end, LinkPillSpan::class.java)) { + val pillStart = builder.getSpanStart(pill) + // getSpans also returns a pill that only touches the range. + if (pill.lineHeight <= 0 || pillStart < start || pillStart >= end) continue + val paragraphStart = builder.lastIndexOf('\n', pillStart - 1).let { if (it < start) start else it + 1 } + heights[paragraphStart] = maxOf(heights[paragraphStart] ?: 0f, pill.lineHeight) + } + for ((paragraphStart, height) in heights) { + val paragraphEnd = builder.indexOf('\n', paragraphStart).let { if (it < 0 || it >= end) end else it + 1 } + // getSpans also returns the floor of a neighbouring paragraph, which only touches this one. + val hasFloor = + builder + .getSpans(paragraphStart, paragraphEnd, LinkPillLineHeightSpan::class.java) + .any { builder.getSpanStart(it) <= paragraphStart && builder.getSpanEnd(it) > paragraphStart } + if (hasFloor) continue + builder.setSpan(LinkPillLineHeightSpan(height), paragraphStart, paragraphEnd, spanFlags) + } +} + +/** + * Applies [LineHeightSpan] to [start]..[end] but skips ranges occupied by + * block [ImageSpan]s (and their trailing '\n') and by [CodeBlockSpan]s — + * both of these apply their own font-metric adjustments that a fixed + * line height would override. + */ +fun applyLineHeightSkippingImages( + builder: SpannableStringBuilder, + start: Int, + end: Int, + lineHeight: Float, + spanFlags: Int = SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, +) { + val blockImageRanges = + builder + .getSpans(start, end, ImageSpan::class.java) + .filter { !it.isInline } + .map { builder.getSpanStart(it) to builder.getSpanEnd(it) } + + val codeBlockRanges = + builder + .getSpans(start, end, CodeBlockSpan::class.java) + .map { builder.getSpanStart(it) to builder.getSpanEnd(it) } + + val excludedRanges = (blockImageRanges + codeBlockRanges).sortedBy { it.first } + + var pos = start + for ((exStart, exEnd) in excludedRanges) { + if (pos < exStart) { + builder.setSpan( + createLineHeightSpan(lineHeight), + pos, + exStart, + spanFlags, + ) + } + val skipEnd = if (exEnd < end && builder[exEnd] == '\n') exEnd + 1 else exEnd + pos = maxOf(pos, skipEnd) + } + if (pos < end) { + builder.setSpan( + createLineHeightSpan(lineHeight), + pos, + end, + spanFlags, + ) + } + applyLinkPillLineHeight(builder, start, end, spanFlags) +} + +fun applyMarginTop( + builder: SpannableStringBuilder, + insertionPoint: Int, + marginTop: Float, +) { + if (marginTop <= 0) return + + // Insert a newline character to act as a vertical spacer + builder.insert(insertionPoint, "\n") + + // Apply MarginBottomSpan to the spacer character to create the gap before the content + builder.setSpan( + MarginBottomSpan(marginTop), + insertionPoint, + insertionPoint + 1, + SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, + ) +} + +fun applyMarginBottom( + builder: SpannableStringBuilder, + marginBottom: Float, +) { + val spacerStart = builder.length + builder.append("\n") + // Always create a MarginBottomSpan, even when marginBottom = 0. + // This ensures removeTrailingMargin can correctly identify the LAST element's + // margin value. Without a span on the last element, it would pick up a previous + // element's span (e.g. blockquote with marginBottom: 16) and use that wrong value. + builder.setSpan( + MarginBottomSpan(marginBottom), + spacerStart, + builder.length, + SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, + ) +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/SpanFlags.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/SpanFlags.kt new file mode 100644 index 000000000000..0da4ad601eff --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/SpanFlags.kt @@ -0,0 +1,43 @@ +package com.swmansion.enriched.markdown.utils.text.span + +import android.text.SpannableString +import android.text.Spanned + +const val SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE = SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE + +/** + * `SPAN_EXCLUSIVE_EXCLUSIVE` with the maximum span priority. + * + * Higher-priority spans are iterated — and therefore applied and drawn — first, + * so lower-priority spans over the same range override them. Use this for a + * block span set after its children that must not override the inline spans + * inside it (e.g. [HeadingSpan]), or for a container background that must sit + * under inline pill/chip backgrounds (e.g. [BlockquoteSpan]). + */ +const val SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE_PRIORITY = + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE or Spanned.SPAN_PRIORITY + +/** + * `SPAN_EXCLUSIVE_EXCLUSIVE` with the maximum span priority, for a block-wide + * LineHeightSpan (e.g. a blockquote's uniform line height) that must be iterated + * BEFORE the per-block [MarginBottomSpan]s it overlaps. LineHeightSpans are + * applied in iteration order and higher priority iterates first, so this span + * sets the base line height and the lower-priority margin span then adds its gap + * on top instead of being normalized away. Without it a line-height pass applied + * after the margins (e.g. in BlockquoteTextRenderer.postProcess) would erase them + * and clip the first line's ascent. + */ +const val SPAN_FLAGS_LINE_HEIGHT_PRIORITY = + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE or Spanned.SPAN_PRIORITY + +/** + * `SPAN_EXCLUSIVE_EXCLUSIVE` with a span priority just above the default. + * + * List item spans are set after the item's children, so at the default + * priority they apply after inline spans such as `CodeSpan` and replace their + * font and size. This priority applies them first, while staying below + * [SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE_PRIORITY] so a blockquote still draws its + * leading margin before a list's. + */ +const val SPAN_FLAGS_LIST_ITEM = + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE or (1 shl Spanned.SPAN_PRIORITY_SHIFT) diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/WidthAwareSpans.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/WidthAwareSpans.kt new file mode 100644 index 000000000000..d43f4794bd0d --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/span/WidthAwareSpans.kt @@ -0,0 +1,30 @@ +package com.swmansion.enriched.markdown.utils.text.span + +import android.text.Spanned +import com.swmansion.enriched.markdown.spans.ImageSpan +import com.swmansion.enriched.markdown.spans.LinkPillSpan + +/** + * Primes every span whose size depends on the layout width (pills, images). Call it + * before building any layout over [text]. [includeImages] is off for a visible text + * view, whose image spans size themselves from the view they are registered with. + * + * Returns true when a pill's width limit changed, i.e. an existing layout is stale. + */ +fun prepareWidthAwareSpans( + text: CharSequence?, + widthPx: Int, + includeImages: Boolean = true, +): Boolean { + val spanned = text as? Spanned ?: return false + // widthPx == 1 is the coerceAtLeast(1) fallback for a not-yet-measured view. Priming + // with it would squeeze pills on screen to a sliver until the next real measure. + if (widthPx <= 1) return false + val pillsChanged = LinkPillSpan.prepareForMeasurement(spanned, widthPx) + if (includeImages) { + spanned + .getSpans(0, spanned.length, ImageSpan::class.java) + .forEach { it.prepareForMeasurement(spanned, widthPx) } + } + return pillsChanged +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/CodeBlockPressHost.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/CodeBlockPressHost.kt new file mode 100644 index 000000000000..7024f3cc70a4 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/CodeBlockPressHost.kt @@ -0,0 +1,15 @@ +package com.swmansion.enriched.markdown.utils.text.view + +/** + * Implemented by the commonmark host view so [LinkLongPressMovementMethod] can + * gate and dispatch taps landing on a code block span. GFM uses a separate + * CodeBlockContainerView, so its host walk resolves to none. + */ +interface CodeBlockPressHost { + val codeBlockPressEnabled: Boolean + + fun emitOnCodeBlockPress( + code: String, + language: String, + ) +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/ImagePressHost.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/ImagePressHost.kt new file mode 100644 index 000000000000..d198671809b2 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/ImagePressHost.kt @@ -0,0 +1,19 @@ +package com.swmansion.enriched.markdown.utils.text.view + +/** + * Implemented by the React-tagged host views (EnrichedMarkdownText and the GFM + * EnrichedMarkdown container) so [LinkLongPressMovementMethod] can gate and + * dispatch image taps without knowing which flavor owns the tapped TextView. + * + * In GFM the tapped TextView is an internal segment child, so the movement + * method walks up to the nearest host - the same routing ImageSpan uses for its + * box-height notifications. + */ +interface ImagePressHost { + val imagePressEnabled: Boolean + + fun emitOnImagePress( + url: String, + altText: String, + ) +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkEvents.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkEvents.kt new file mode 100644 index 000000000000..b524ea722c40 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkEvents.kt @@ -0,0 +1,76 @@ +package com.swmansion.enriched.markdown.utils.text.view + +import android.view.MotionEvent +import android.view.View +import android.widget.TextView +import com.facebook.react.bridge.ReactContext +import com.facebook.react.uimanager.UIManagerHelper +import com.facebook.react.uimanager.events.NativeGestureUtil +import com.swmansion.enriched.markdown.events.ImagePressEvent +import com.swmansion.enriched.markdown.events.LinkLongPressEvent +import com.swmansion.enriched.markdown.events.LinkPressEvent + +fun View.emitLinkPressEvent(url: String, sourceType: String) { + val reactContext = context as? ReactContext ?: return + val surfaceId = UIManagerHelper.getSurfaceId(reactContext) + val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id) + dispatcher?.dispatchEvent(LinkPressEvent(surfaceId, id, url, sourceType)) +} + +fun View.emitImagePressEvent( + url: String, + altText: String, +) { + val reactContext = context as? ReactContext ?: return + val surfaceId = UIManagerHelper.getSurfaceId(reactContext) + val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id) + dispatcher?.dispatchEvent(ImagePressEvent(surfaceId, id, url, altText)) +} + +fun View.emitLinkLongPressEvent(url: String) { + val reactContext = context as? ReactContext ?: return + val surfaceId = UIManagerHelper.getSurfaceId(reactContext) + val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id) + dispatcher?.dispatchEvent(LinkLongPressEvent(surfaceId, id, url)) +} + +/** + * Cancels the JS touch for an active link tap, preventing parent + * Pressable/TouchableOpacity from firing onPress for the same tap. + * + * Also requests that parent ViewGroups do not intercept subsequent touch + * events in this gesture. This is necessary for react-native-gesture-handler's + * Pressable, which intercepts at the native ViewGroup level and would otherwise + * steal the gesture before ACTION_UP reaches the TextView. + */ +fun TextView.cancelJSTouchForLinkTap(event: MotionEvent) { + val currentMovementMethod = movementMethod + if (currentMovementMethod is LinkLongPressMovementMethod && currentMovementMethod.isLinkTouchActive) { + parent?.requestDisallowInterceptTouchEvent(true) + NativeGestureUtil.notifyNativeGestureStarted(this, event) + } +} + +/** + * Re-allows parent ViewGroups to intercept touch events once the link + * touch is no longer active (slop exceeded, gesture ended, or cancelled). + * This restores normal scrolling behavior for parent ScrollView/RecyclerView. + * + * Must be called after [LinkLongPressMovementMethod.onTouchEvent] has + * processed the event, since that is where [isLinkTouchActive] is updated. + */ +fun TextView.reallowParentInterceptIfLinkReleased() { + val currentMovementMethod = movementMethod + if (currentMovementMethod is LinkLongPressMovementMethod && !currentMovementMethod.isLinkTouchActive) { + parent?.requestDisallowInterceptTouchEvent(false) + } +} + +/** + * Cancels the JS touch unconditionally, preventing parent + * Pressable/TouchableOpacity from firing onPress for the same gesture. + */ +fun View.cancelJSTouchForCheckboxTap(event: MotionEvent) { + parent?.requestDisallowInterceptTouchEvent(true) + NativeGestureUtil.notifyNativeGestureStarted(this, event) +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkLongPressMovementMethod.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkLongPressMovementMethod.kt new file mode 100644 index 000000000000..16c125ecc71c --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/LinkLongPressMovementMethod.kt @@ -0,0 +1,303 @@ +package com.swmansion.enriched.markdown.utils.text.view + +import android.os.Handler +import android.os.Looper +import android.text.Spannable +import android.text.method.ArrowKeyMovementMethod +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewParent +import android.widget.TextView +import com.swmansion.enriched.markdown.spans.CodeBlockSpan +import com.swmansion.enriched.markdown.spans.ImageSpan +import com.swmansion.enriched.markdown.spans.LinkSpan +import com.swmansion.enriched.markdown.spans.SpoilerSpan +import com.swmansion.enriched.markdown.spoiler.SpoilerCapable +import kotlin.math.abs + +/** + * Movement method that adds link tap / long-press and spoiler tap handling on + * top of [ArrowKeyMovementMethod], the method [setTextIsSelectable] installs. + * + * Must never mutate the buffer's Selection spans — the platform Editor + * manages them during long-press gestures, and removing or overwriting + * them mid-gesture crashes on some OEM skins. + * See: https://github.com/software-mansion/enriched-markdown/issues/580 + */ +class LinkLongPressMovementMethod : ArrowKeyMovementMethod() { + private val handler = Handler(Looper.getMainLooper()) + private var longPressRunnable: Runnable? = null + + private var startX = 0f + private var startY = 0f + private var pressedLink: LinkSpan? = null + private var pressedImage: ImageSpan? = null + private var pressedCodeBlock: CodeBlockSpan? = null + + var isLinkTouchActive: Boolean = false + private set + private var isTouchWithinTextBounds: Boolean = true + + override fun onTouchEvent( + widget: TextView, + buffer: Spannable, + event: MotionEvent, + ): Boolean { + when (event.action) { + MotionEvent.ACTION_DOWN -> { + startX = event.x + startY = event.y + + pressedLink = findLinkSpan(widget, buffer, event) + pressedImage = + if (pressedLink == null && imagePressHost(widget)?.imagePressEnabled == true) { + findImageSpan(widget, buffer, event) + } else { + null + } + pressedCodeBlock = + if (pressedLink == null && + pressedImage == null && + // Skip while text is selected so the tap clears the selection + // instead of firing the press (matches the web guard). + !widget.hasSelection() && + codeBlockPressHost(widget)?.codeBlockPressEnabled == true + ) { + findCodeBlockSpan(widget, buffer, event) + } else { + null + } + isLinkTouchActive = pressedLink != null || pressedImage != null || pressedCodeBlock != null + isTouchWithinTextBounds = charOffsetAt(widget, event) != null || pressedCodeBlock != null + pressedLink?.let { scheduleLongPress(widget, it) } + } + + MotionEvent.ACTION_MOVE -> { + val config = ViewConfiguration.get(widget.context) + if (abs(event.x - startX) > config.scaledTouchSlop || + abs(event.y - startY) > config.scaledTouchSlop + ) { + cancelLongPress() + isLinkTouchActive = false + pressedLink = null + pressedImage = null + pressedCodeBlock = null + } + } + + MotionEvent.ACTION_UP -> { + cancelLongPress() + val tappedLink = pressedLink + val tappedImage = pressedImage + val tappedCodeBlock = pressedCodeBlock + isLinkTouchActive = false + pressedLink = null + pressedImage = null + pressedCodeBlock = null + + if (handleSpoilerTap(widget, buffer, event)) { + return true + } + + // LinkSpan.onClick itself swallows the click that follows a completed + // long-press (and resets its internal flag), so it is always invoked + // for a tap that started and ended on the same link. + if (tappedLink != null && findLinkSpan(widget, buffer, event) === tappedLink) { + tappedLink.onClick(widget) + return true + } + + if (tappedImage != null && findImageSpan(widget, buffer, event) === tappedImage) { + imagePressHost(widget)?.emitOnImagePress(tappedImage.imageUrl, tappedImage.altText) + return true + } + + if (tappedCodeBlock != null && findCodeBlockSpan(widget, buffer, event) === tappedCodeBlock) { + codeBlockPressHost(widget)?.emitOnCodeBlockPress(tappedCodeBlock.code, tappedCodeBlock.language) + return true + } + } + + MotionEvent.ACTION_CANCEL -> { + cancelLongPress() + isLinkTouchActive = false + pressedLink = null + pressedImage = null + pressedCodeBlock = null + } + } + + // getOffsetForHorizontal snaps to the nearest character, so without this + // guard taps in empty space past the end of a line would still be treated + // as text touches. Let them fall through to the parent (e.g. RNGH + // Pressable) instead. + if (!isTouchWithinTextBounds) { + return false + } + + return super.onTouchEvent(widget, buffer, event) + } + + private fun scheduleLongPress( + widget: TextView, + span: LinkSpan, + ) { + cancelLongPress() + + longPressRunnable = + Runnable { + // Execute the long click logic on the span + if (span.onLongClick(widget)) { + // If consumed, cancel the system's own long-press logic (like context menus) + widget.cancelLongPress() + } + longPressRunnable = null + }.also { + handler.postDelayed(it, ViewConfiguration.getLongPressTimeout().toLong()) + } + } + + private fun cancelLongPress() { + longPressRunnable?.let(handler::removeCallbacks) + longPressRunnable = null + } + + private fun charOffsetAt( + widget: TextView, + event: MotionEvent, + ): Int? { + val x = event.x - widget.totalPaddingLeft + widget.scrollX + val y = event.y - widget.totalPaddingTop + widget.scrollY + val layout = widget.layout ?: return null + + // getLineForVertical clamps to the first/last line for out-of-range + // values, so taps in vertical padding would silently map to a real + // line. Reject them before proceeding. + if (y < 0f || y > layout.height) { + return null + } + + val line = layout.getLineForVertical(y.toInt()) + + // getOffsetForHorizontal snaps to the nearest character even when the + // tap is outside the actual text content (e.g. empty space after the + // last word on a line). Guard against that by checking the tap falls + // within the line's text bounds. + if (x < layout.getLineLeft(line) || x > layout.getLineRight(line)) { + return null + } + + return layout.getOffsetForHorizontal(line, x) + } + + private fun findLinkSpan( + widget: TextView, + buffer: Spannable, + event: MotionEvent, + ): LinkSpan? { + val offset = charOffsetAt(widget, event) ?: return null + return buffer.getSpans(offset, offset, LinkSpan::class.java).firstOrNull() + } + + private fun findImageSpan( + widget: TextView, + buffer: Spannable, + event: MotionEvent, + ): ImageSpan? { + val offset = charOffsetAt(widget, event) ?: return null + return buffer.getSpans(offset, offset, ImageSpan::class.java).firstOrNull() + } + + private fun imagePressHost(widget: View): ImagePressHost? { + if (widget is ImagePressHost) return widget + var parent: ViewParent? = widget.parent + while (parent != null && parent !is ImagePressHost) { + parent = parent.parent + } + return parent as? ImagePressHost + } + + // A code block is a whole-line box, so this matches a tap anywhere on the line + // (ignoring x), unlike charOffsetAt which needs an exact glyph. + private fun findCodeBlockSpan( + widget: TextView, + buffer: Spannable, + event: MotionEvent, + ): CodeBlockSpan? { + val layout = widget.layout ?: return null + val y = event.y - widget.totalPaddingTop + widget.scrollY + if (y < 0f || y > layout.height) return null + val line = layout.getLineForVertical(y.toInt()) + val lineStart = layout.getLineStart(line) + val lineEnd = layout.getLineEnd(line) + return buffer.getSpans(lineStart, lineEnd, CodeBlockSpan::class.java).firstOrNull() + } + + private fun codeBlockPressHost(widget: View): CodeBlockPressHost? { + if (widget is CodeBlockPressHost) return widget + var parent: ViewParent? = widget.parent + while (parent != null && parent !is CodeBlockPressHost) { + parent = parent.parent + } + return parent as? CodeBlockPressHost + } + + private fun handleSpoilerTap( + widget: TextView, + buffer: Spannable, + event: MotionEvent, + ): Boolean { + val offset = charOffsetAt(widget, event) ?: return false + val tappedSpan = + buffer + .getSpans(offset, offset, SpoilerSpan::class.java) + .firstOrNull { !it.revealed && !it.revealing } ?: return false + + val drawer = (widget as? SpoilerCapable)?.spoilerOverlayDrawer ?: return false + val spans = expandContiguousSpoilers(buffer, tappedSpan) + val remaining = intArrayOf(spans.size) + + for (span in spans) { + drawer.revealSpan(span) { + remaining[0]-- + if (remaining[0] <= 0) widget.invalidate() + } + } + widget.invalidate() + return true + } + + private fun expandContiguousSpoilers( + buffer: Spannable, + seed: SpoilerSpan, + ): List { + val allSpans = buffer.getSpans(0, buffer.length, SpoilerSpan::class.java) + if (allSpans.size <= 1) return listOf(seed) + + val result = mutableSetOf(seed) + var rangeStart = buffer.getSpanStart(seed) + var rangeEnd = buffer.getSpanEnd(seed) + var changed = true + while (changed) { + changed = false + for (span in allSpans) { + if (span in result) continue + val spanStart = buffer.getSpanStart(span) + val spanEnd = buffer.getSpanEnd(span) + if (spanEnd >= rangeStart && spanStart <= rangeEnd) { + result.add(span) + if (spanStart < rangeStart) rangeStart = spanStart + if (spanEnd > rangeEnd) rangeEnd = spanEnd + changed = true + } + } + } + return result.sortedBy { buffer.getSpanStart(it) } + } + + companion object { + @JvmStatic + fun createInstance(): LinkLongPressMovementMethod = LinkLongPressMovementMethod() + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/SelectionActionMode.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/SelectionActionMode.kt new file mode 100644 index 000000000000..21bec3bd9834 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/SelectionActionMode.kt @@ -0,0 +1,234 @@ +package com.swmansion.enriched.markdown.utils.text.view + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.text.Spannable +import android.view.ActionMode +import android.view.Menu +import android.view.MenuItem +import android.view.ViewParent +import android.widget.TextView +import com.swmansion.enriched.markdown.EnrichedMarkdown +import com.swmansion.enriched.markdown.EnrichedMarkdownText +import com.swmansion.enriched.markdown.spans.ImageSpan +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.utils.common.layout.isLayoutRTL +import com.swmansion.enriched.markdown.utils.text.conversion.HTMLGenerator +import com.swmansion.enriched.markdown.utils.text.conversion.MarkdownExtractor + +private const val MENU_ITEM_COPY_MARKDOWN = 1000 +private const val MENU_ITEM_COPY_IMAGE_URL = 1001 +private const val MENU_ITEM_CUSTOM_BASE = 2000 +private const val MENU_ITEM_CUSTOM_GROUP = 2001 + +data class SelectionMenuConfig( + val copyAsMarkdown: Boolean = true, + val copyImageUrl: Boolean = true, + val copyLabel: String = "", + val copyAsMarkdownLabel: String = "", + val copyImageUrlLabel: String = "", + val copyImageUrlsLabel: String = "", + // Plural templates indexed by image count (0..100). Empty when no pluralLabels + // are set; counts > 100 use copyImageUrlsLabel (the "other" form). + val copyImageUrlPluralTemplates: List = emptyList(), +) + +/** + * Resolves the "Copy Image URL(s)" menu title for the given image count. Uses the + * precomputed plural templates when present (counts > 100 use the "other" form), + * otherwise the singular/`{count}` templates. All labels are resolved JS-side. + */ +private fun SelectionMenuConfig.imageUrlsTitle(count: Int): String { + val template = + when { + copyImageUrlPluralTemplates.isNotEmpty() && count in 0..100 -> copyImageUrlPluralTemplates[count] + count == 1 -> copyImageUrlLabel + else -> copyImageUrlsLabel + } + return template.replace("{count}", count.toString()) +} + +/** + * Creates an ActionMode.Callback that adds custom copy options and + * overrides the default "Copy" action to include HTML for rich text support. + */ +fun createSelectionActionModeCallback( + textView: TextView, + getCustomItemTexts: () -> List = { emptyList() }, + getSelectionMenuConfig: () -> SelectionMenuConfig = { SelectionMenuConfig() }, + onCustomItemPress: (itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit = + { _, _, _, _ -> }, +): ActionMode.Callback = + object : ActionMode.Callback { + override fun onCreateActionMode( + mode: ActionMode?, + menu: Menu?, + ): Boolean = true + + override fun onPrepareActionMode( + mode: ActionMode?, + menu: Menu?, + ): Boolean { + if (menu == null) return false + + menu.removeItem(MENU_ITEM_COPY_MARKDOWN) + menu.removeItem(MENU_ITEM_COPY_IMAGE_URL) + menu.removeGroup(MENU_ITEM_CUSTOM_GROUP) + + val selectionMenuConfig = getSelectionMenuConfig() + + // The system Copy item is added by the platform; relabel it so it + // matches the rest of the localized menu (iOS rebuilds the menu so + // gets this for free; Android only intercepts the click). + if (selectionMenuConfig.copyLabel.isNotEmpty()) { + menu.findItem(android.R.id.copy)?.title = selectionMenuConfig.copyLabel + } + + if ( + selectionMenuConfig.copyAsMarkdown && + textView.selectionStart >= 0 && + textView.selectionEnd > textView.selectionStart + ) { + menu.add( + Menu.NONE, + MENU_ITEM_COPY_MARKDOWN, + Menu.NONE, + selectionMenuConfig.copyAsMarkdownLabel, + ) + } + + if (textView.selectionStart >= 0 && textView.selectionEnd > textView.selectionStart) { + val customItems = getCustomItemTexts() + customItems.forEachIndexed { index, text -> + menu + .add(MENU_ITEM_CUSTOM_GROUP, MENU_ITEM_CUSTOM_BASE + index, index, text) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) + } + } + + val imageUrls = + if (selectionMenuConfig.copyImageUrl) { + textView.getImageUrlsInSelection() + } else { + emptyList() + } + if (imageUrls.isNotEmpty()) { + val title = selectionMenuConfig.imageUrlsTitle(imageUrls.size) + menu.add(Menu.NONE, MENU_ITEM_COPY_IMAGE_URL, Menu.NONE, title) + } + + return true + } + + override fun onActionItemClicked( + mode: ActionMode?, + item: MenuItem?, + ): Boolean { + val itemId = item?.itemId ?: return false + + when (itemId) { + android.R.id.copy -> { + textView.copyWithHTML() + mode?.finish() + return true + } + + MENU_ITEM_COPY_MARKDOWN -> { + textView.copyMarkdownToClipboard() + mode?.finish() + return true + } + + MENU_ITEM_COPY_IMAGE_URL -> { + textView.copyImageUrlsToClipboard() + mode?.finish() + return true + } + } + + val customItems = getCustomItemTexts() + val customIndex = itemId - MENU_ITEM_CUSTOM_BASE + if (customIndex in customItems.indices) { + val start = textView.selectionStart + val end = textView.selectionEnd + val selectedText = if (start >= 0 && end > start) textView.text.substring(start, end) else "" + onCustomItemPress(customItems[customIndex], selectedText, start, end) + mode?.finish() + return true + } + + return false + } + + override fun onDestroyActionMode(mode: ActionMode?) {} + } + +/** Copies selection as both plain text and HTML with inline styles. */ +private fun TextView.copyWithHTML() { + val start = selectionStart + val end = selectionEnd + if (start < 0 || end < 0 || start >= end) return + + val spannable = text as? Spannable ?: return + val selectedText = spannable.subSequence(start, end) + val plainText = selectedText.toString() + + val styleConfig = + (this as? EnrichedMarkdownText)?.markdownStyle + ?: findParentMarkdownStyle() + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + + if (styleConfig != null && selectedText is Spannable) { + // Density values convert device pixels back to CSS pixels + val displayMetrics = context.resources.displayMetrics + val isRTL = context.resources.isLayoutRTL() + val html = + HTMLGenerator.generateHTML( + selectedText, + styleConfig, + displayMetrics.scaledDensity, + displayMetrics.density, + isRTL, + ) + clipboard.setPrimaryClip(ClipData.newHtmlText("EnrichedMarkdown", plainText, html)) + } else { + clipboard.setPrimaryClip(ClipData.newPlainText("Text", plainText)) + } +} + +private fun TextView.copyMarkdownToClipboard() { + val markdown = MarkdownExtractor.getMarkdownForSelection(this) ?: return + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText("Markdown", markdown)) +} + +/** Returns remote image URLs (http/https only) from the current selection. */ +private fun TextView.getImageUrlsInSelection(): List { + val start = selectionStart + val end = selectionEnd + if (start < 0 || end < 0 || start >= end) return emptyList() + + val spannable = text as? Spannable ?: return emptyList() + return spannable + .getSpans(start, end, ImageSpan::class.java) + .mapNotNull { it.imageUrl } + .filter { it.startsWith("http://") || it.startsWith("https://") } +} + +private fun TextView.copyImageUrlsToClipboard() { + val urls = getImageUrlsInSelection() + if (urls.isEmpty()) return + + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText("Image URLs", urls.joinToString("\n"))) +} + +private fun TextView.findParentMarkdownStyle(): StyleConfig? { + var current: ViewParent? = parent + while (current != null) { + if (current is EnrichedMarkdown) return current.markdownStyle + current = current.parent + } + return null +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextSelectionColors.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextSelectionColors.kt new file mode 100644 index 000000000000..1a6d724249ca --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextSelectionColors.kt @@ -0,0 +1,48 @@ +package com.swmansion.enriched.markdown.utils.text.view + +import android.graphics.drawable.Drawable +import android.os.Build +import android.util.Log +import android.widget.TextView +import androidx.annotation.ColorInt +import androidx.core.graphics.drawable.DrawableCompat + +private const val TAG = "TextSelectionColors" + +private typealias HandleGetter = (TextView) -> Drawable? +private typealias HandleSetter = (TextView, Drawable) -> Unit + +/** + * Applies selection highlight and (where supported) handle tinting to a [TextView]. + * + * Handle drawables are only tinted on API 29+ where the framework exposes getters; + * on older versions the handle theme defaults remain unchanged. + */ +fun TextView.applySelectionColors( + selectionColor: Int?, + selectionHandleColor: Int?, +) { + selectionColor?.let { highlightColor = it } + selectionHandleColor?.let { applySelectionHandleTint(it) } +} + +private fun TextView.applySelectionHandleTint( + @ColorInt color: Int, +) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return + + val handles: List> = + listOf( + TextView::getTextSelectHandleLeft to { tv, d -> tv.setTextSelectHandleLeft(d) }, + TextView::getTextSelectHandle to { tv, d -> tv.setTextSelectHandle(d) }, + TextView::getTextSelectHandleRight to { tv, d -> tv.setTextSelectHandleRight(d) }, + ) + + handles.forEach { (getter, setter) -> + try { + getter(this)?.mutate()?.also { DrawableCompat.setTint(it, color) }?.let { setter(this, it) } + } catch (e: LinkageError) { + Log.w(TAG, "Selection handle tint skipped: ${e.message}") + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt new file mode 100644 index 000000000000..8742c0cee579 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt @@ -0,0 +1,122 @@ +package com.swmansion.enriched.markdown.utils.text.view + +import android.graphics.Color +import android.os.Build +import android.text.GetChars +import android.text.Spannable +import android.text.SpannableString +import android.text.SpannableStringBuilder +import android.view.textclassifier.TextClassifier +import androidx.appcompat.widget.AppCompatTextView +import androidx.core.view.ViewCompat +import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView + +internal fun wrapForInsertionOrderedLayout(source: CharSequence): CharSequence = + if (source is SpannableStringBuilder) InsertionOrderedSpannable(source) else source + +/** + * Adopts the renderer's buffer instead of copying it: the default factory's copy is + * quadratic in span count. Safe because each segment's buffer is owned by one view. + */ +private object NoCopySpannableFactory : Spannable.Factory() { + override fun newSpannable(source: CharSequence): Spannable = + when (source) { + is SpannableStringBuilder -> InsertionOrderedSpannable(source) + is Spannable -> source + else -> SpannableString(source) + } +} + +/** + * Hides that [buffer] is a `SpannableStringBuilder`. Layout reads a builder's paragraph + * spans in position order rather than insertion order, which paints nested list margins + * outer-first and pushes nested checkboxes an indent right. + * + * Hiding the type has a price, and it is deliberate: every paragraph-span query from + * `Layout` now goes through the builder's sorted `getSpans` instead of the unsorted fast + * path the framework reserves for builders. The `layout` benchmark in the example app's + * `display-benchmark` covers that cost, so it is already accounted for. Do not + * "optimise" this wrapper away. + */ +private class InsertionOrderedSpannable( + private val buffer: SpannableStringBuilder, +) : Spannable, + GetChars { + override val length: Int get() = buffer.length + + override fun get(index: Int): Char = buffer[index] + + override fun subSequence( + startIndex: Int, + endIndex: Int, + ): CharSequence = buffer.subSequence(startIndex, endIndex) + + override fun getChars( + start: Int, + end: Int, + dest: CharArray, + destoff: Int, + ) = buffer.getChars(start, end, dest, destoff) + + override fun getSpans( + start: Int, + end: Int, + type: Class, + ): Array = buffer.getSpans(start, end, type) + + override fun getSpanStart(tag: Any): Int = buffer.getSpanStart(tag) + + override fun getSpanEnd(tag: Any): Int = buffer.getSpanEnd(tag) + + override fun getSpanFlags(tag: Any): Int = buffer.getSpanFlags(tag) + + override fun nextSpanTransition( + start: Int, + limit: Int, + type: Class<*>?, + ): Int = buffer.nextSpanTransition(start, limit, type) + + override fun setSpan( + what: Any, + start: Int, + end: Int, + flags: Int, + ) = buffer.setSpan(what, start, end, flags) + + override fun removeSpan(what: Any) = buffer.removeSpan(what) + + override fun toString(): String = buffer.toString() +} + +fun AccessibleMarkdownTextView.setupAsMarkdownTextView() { + setBackgroundColor(Color.TRANSPARENT) + setSpannableFactory(NoCopySpannableFactory) + includeFontPadding = false + movementMethod = LinkLongPressMovementMethod.createInstance() + setTextIsSelectable(true) + customSelectionActionModeCallback = createSelectionActionModeCallback(this) + // SmartSelectSprite crashes with "Center point is not inside any of the + // rectangles!" when Layout.getSelection returns empty rects near an + // ImageSpan (ReplacementSpan). NO_OP makes skipTextClassification() return + // true, bypassing the entire SmartSelectSprite code path. Regular text + // selection (long-press, handles, copy/paste) still works; only automatic + // entity detection (phone numbers, addresses) is disabled. + // + // TODO: Add an Android-only `enableSmartTextSelection` prop that skips this + // NO_OP override. This would let users who don't render images opt in to + // entity detection. The prop should default to false and its docs should + // warn that enabling it with markdown containing images will crash. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + setTextClassifier(TextClassifier.NO_OP) + } + isVerticalScrollBarEnabled = false + isHorizontalScrollBarEnabled = false + ViewCompat.setAccessibilityDelegate(this, accessibilityHelper) +} + +fun AppCompatTextView.applySelectableState(selectable: Boolean) { + if (isTextSelectable == selectable) return + setTextIsSelectable(selectable) + movementMethod = LinkLongPressMovementMethod.createInstance() + if (!selectable && !isClickable) isClickable = true +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ClaimingHorizontalScrollView.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ClaimingHorizontalScrollView.kt new file mode 100644 index 000000000000..d80ecbd42299 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ClaimingHorizontalScrollView.kt @@ -0,0 +1,41 @@ +package com.swmansion.enriched.markdown.views + +import android.content.Context +import android.view.MotionEvent +import android.view.ViewConfiguration +import android.widget.HorizontalScrollView +import kotlin.math.abs + +/** Claims overflowing blocks before ancestor gesture handlers can activate. */ +internal class ClaimingHorizontalScrollView(context: Context) : HorizontalScrollView(context) { + private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop + private var downX = 0f + private var downY = 0f + private var claimed = false + + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + downX = event.x + downY = event.y + claimed = canScrollHorizontally(-1) || canScrollHorizontally(1) + if (claimed) parent.requestDisallowInterceptTouchEvent(true) + } + + val handled = super.dispatchTouchEvent(event) + when (event.actionMasked) { + MotionEvent.ACTION_MOVE -> { + if (claimed) { + val dx = abs(event.x - downX) + val dy = abs(event.y - downY) + if (dy > dx && dy > touchSlop) { + // Release after native dispatch, which can itself disallow interception. + parent.requestDisallowInterceptTouchEvent(false) + claimed = false + } + } + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> claimed = false + } + return handled + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ContextMenuPopup.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ContextMenuPopup.kt new file mode 100644 index 000000000000..37082b467555 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/ContextMenuPopup.kt @@ -0,0 +1,217 @@ +package com.swmansion.enriched.markdown.views + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.ColorFilter +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.RectF +import android.graphics.Typeface +import android.graphics.drawable.ColorDrawable +import android.graphics.drawable.Drawable +import android.graphics.drawable.GradientDrawable +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.View.MeasureSpec +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.PopupWindow +import android.widget.TextView +import kotlin.math.roundToInt + +object ContextMenuPopup { + private var activePopup: PopupWindow? = null + + fun dismiss() { + activePopup?.dismiss() + } + + enum class Icon { COPY, DOCUMENT } + + class Builder internal constructor() { + internal val items = mutableListOf() + + fun item( + icon: Icon, + label: String, + onClick: () -> Unit, + ) { + items.add(MenuItem(icon, label, onClick)) + } + } + + internal data class MenuItem( + val icon: Icon, + val label: String, + val onClick: () -> Unit, + ) + + private var density = 1f + private val Float.dp get() = (this * density).roundToInt() + + fun show( + anchor: View, + parent: View, + block: Builder.() -> Unit, + ) { + activePopup?.dismiss() + + val context = anchor.context + density = context.resources.displayMetrics.density + val builder = Builder().apply(block) + if (builder.items.isEmpty()) return + + val container = + LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + elevation = 12f.dp.toFloat() + setPadding(4f.dp, 12f.dp, 4f.dp, 12f.dp) + background = + GradientDrawable().apply { + setColor(Color.WHITE) + cornerRadius = 14f.dp.toFloat() + } + } + + builder.items.forEachIndexed { index, item -> + if (index > 0) container.addView(createDivider(context)) + container.addView(createMenuItemView(context, item)) + } + + val popup = + PopupWindow( + container, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + true, + ).apply { + elevation = 24f.dp.toFloat() + isOutsideTouchable = true + setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) + setOnDismissListener { + activePopup = null + } + } + + container.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) + + val location = IntArray(2).also { anchor.getLocationOnScreen(it) } + val centerX = location[0] + anchor.width / 2 + val topY = location[1] + + val screenW = context.resources.displayMetrics.widthPixels + val margin = 8f.dp + + val x = + (centerX - container.measuredWidth / 2) + .coerceIn(margin, screenW - container.measuredWidth - margin) + val y = + (topY - container.measuredHeight - margin) + .coerceAtLeast(margin) + + activePopup = popup + popup.showAtLocation(parent, Gravity.NO_GRAVITY, x, y) + } + + private fun createMenuItemView( + context: Context, + item: MenuItem, + ) = LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(16f.dp, 0, 16f.dp, 0) + minimumHeight = 48f.dp + isClickable = true + isFocusable = true + + val outValue = TypedValue() + context.theme.resolveAttribute(android.R.attr.selectableItemBackground, outValue, true) + foreground = context.getDrawable(outValue.resourceId) + + addView( + ImageView(context).apply { + setImageDrawable(createIconDrawable(item.icon)) + setColorFilter(Color.parseColor("#333333")) + }, + LinearLayout.LayoutParams(20f.dp, 20f.dp), + ) + + addView( + TextView(context).apply { + text = item.label + textSize = 16f + setTextColor(Color.parseColor("#1C1C1E")) + typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) + }, + LinearLayout + .LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ).apply { marginStart = 12f.dp }, + ) + + setOnClickListener { + item.onClick() + dismiss() + } + } + + private fun createDivider(context: Context) = + View(context).apply { + setBackgroundColor(Color.parseColor("#E5E5EA")) + layoutParams = + LinearLayout + .LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 1f.dp.coerceAtLeast(1), + ).apply { + setMargins(16f.dp, 0, 16f.dp, 0) + } + } + + private fun createIconDrawable(icon: Icon): Drawable = + object : Drawable() { + private val paint = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = 1.5f * density + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + color = Color.parseColor("#333333") + } + + private val copyGlyph = CopyGlyph() + + // COPY mirrors SF Symbol doc.on.doc, DOCUMENT mirrors doc.text; the copy + // glyph is shared with the header button in CodeBlockContainerView. + override fun draw(canvas: Canvas) { + val u = bounds.width() / 24f + if (icon == Icon.COPY) { + copyGlyph.draw(canvas, bounds.width().toFloat(), paint) + } else { + canvas.drawRoundRect(RectF(5 * u, 3 * u, 19 * u, 21 * u), 2.5f * u, 2.5f * u, paint) + canvas.drawLine(8.5f * u, 9 * u, 15.5f * u, 9 * u, paint) + canvas.drawLine(8.5f * u, 12.5f * u, 15.5f * u, 12.5f * u, paint) + canvas.drawLine(8.5f * u, 16 * u, 13 * u, 16 * u, paint) + } + } + + override fun getIntrinsicWidth() = 24f.dp + + override fun getIntrinsicHeight() = 24f.dp + + override fun setAlpha(alpha: Int) { + paint.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + paint.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity() = PixelFormat.TRANSLUCENT + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/CopyGlyph.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/CopyGlyph.kt new file mode 100644 index 000000000000..b1a4df01517b --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/views/CopyGlyph.kt @@ -0,0 +1,101 @@ +package com.swmansion.enriched.markdown.views + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.graphics.PorterDuff +import android.graphics.PorterDuffXfermode + +/** + * Draws the copy glyph so Android matches the SF Symbol doc.on.doc rendered on + * iOS: two portrait document pages with a folded (dog-eared) top-right corner, + * a front page in the lower-left laid over a back page in the upper-right. + * + * The back page is punched out where the front page (plus a hairline of + * clearance) covers it, so the front reads as sitting on top exactly as the SF + * Symbol does, instead of both outlines crossing. The clear is done inside an + * offscreen layer so the punched region reveals whatever background the drawable + * sits on, without the glyph needing to know that color. + * + * One instance is held per drawable rather than shared: the paths and clear + * paint are reused across draws to keep draw() allocation-free, and two drawables + * of different sizes must not share those buffers. All coordinates use a 24-unit + * grid scaled to the drawable width, matching the grid the iOS symbol is authored + * on. + */ +internal class CopyGlyph { + private val back = Path() + private val front = Path() + private val backFold = Path() + private val frontFold = Path() + + // Color and colorFilter are irrelevant under PorterDuff.CLEAR; only the + // widened stroke (set per draw) matters, so this is configured once. + private val clearPaint = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.FILL_AND_STROKE + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) + } + + fun draw( + canvas: Canvas, + width: Float, + stroke: Paint, + ) { + val u = width / 24f + val fold = 4f * u + val corner = 2f * u + + buildPage(back, 9 * u, 1 * u, 20 * u, 17 * u, fold, corner) + buildPage(front, 3 * u, 7 * u, 14 * u, 23 * u, fold, corner) + buildFold(backFold, 20 * u, 1 * u, fold) + buildFold(frontFold, 14 * u, 7 * u, fold) + clearPaint.strokeWidth = stroke.strokeWidth * 3f + + val saved = canvas.saveLayer(0f, 0f, width, width, null) + canvas.drawPath(back, stroke) + canvas.drawPath(backFold, stroke) + canvas.drawPath(front, clearPaint) + canvas.drawPath(front, stroke) + canvas.drawPath(frontFold, stroke) + canvas.restoreToCount(saved) + } + + // A page outline whose top-right corner is cut back by fold, with the other + // three corners rounded by corner. + private fun buildPage( + path: Path, + l: Float, + t: Float, + r: Float, + b: Float, + fold: Float, + corner: Float, + ) { + path.rewind() + path.moveTo(l, t + corner) + path.quadTo(l, t, l + corner, t) + path.lineTo(r - fold, t) + path.lineTo(r, t + fold) + path.lineTo(r, b - corner) + path.quadTo(r, b, r - corner, b) + path.lineTo(l + corner, b) + path.quadTo(l, b, l, b - corner) + path.close() + } + + // The two inner edges of the folded-over corner, at the page's top-right. + private fun buildFold( + path: Path, + r: Float, + t: Float, + fold: Float, + ) { + path.rewind() + path.moveTo(r - fold, t) + path.lineTo(r - fold, t + fold) + path.lineTo(r, t + fold) + } +} diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/CMakeLists.txt b/packages/react-native-enriched-markdown/android/src/main/jni/CMakeLists.txt new file mode 100644 index 000000000000..2bdaa07a014d --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/CMakeLists.txt @@ -0,0 +1,137 @@ +cmake_minimum_required(VERSION 3.13) +set(CMAKE_VERBOSE_MAKEFILE ON) + +set(LIB_LITERAL EnrichedMarkdownTextSpec) +set(LIB_TARGET_NAME react_codegen_${LIB_LITERAL}) + +set(LIB_ANDROID_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..) +set(LIB_ANDROID_GENERATED_JNI_DIR ${LIB_ANDROID_DIR}/generated/jni) +set(LIB_ANDROID_GENERATED_COMPONENTS_DIR ${LIB_ANDROID_GENERATED_JNI_DIR}/react/renderer/components/${LIB_LITERAL}) + +# cpp/ is a symlink to packages/core/cpp in the monorepo; published tarballs +# ship real files (materialized at prepack). Use paths relative to this file — +# Android's cross-compile CMake pass cannot access absolute paths outside the +# module via symlinks or REALPATH. +set(CPP_IN_PACKAGE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../cpp") +set(CPP_IN_MONOREPO "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../core/cpp") + +if(EXISTS "${CPP_IN_PACKAGE}/md4c/md4c.c") + set(CPP_ROOT "${CPP_IN_PACKAGE}") +elseif(EXISTS "${CPP_IN_MONOREPO}/md4c/md4c.c") + set(CPP_ROOT "${CPP_IN_MONOREPO}") +else() + message(FATAL_ERROR "EnrichedMarkdown C++ sources not found. Expected cpp/ or packages/core/cpp.") +endif() + +set(ANDROID_CPP_DIR "${LIB_ANDROID_DIR}/src/main/cpp") + +# Optional tree-sitter code highlighting. build.gradle writes this config during +# configuration (enable flag, selected languages, generated registry dir); absent +# on a bare CMake invocation, in which case highlighting stays compiled out. +set(HIGHLIGHT_CONFIG "${LIB_ANDROID_DIR}/build/generated/highlight/highlight-config.cmake") +if(EXISTS "${HIGHLIGHT_CONFIG}") + include("${HIGHLIGHT_CONFIG}") +endif() + +file(GLOB MD4C_SOURCES "${CPP_ROOT}/md4c/*.c") +file(GLOB PARSER_SOURCES "${CPP_ROOT}/parser/*.cpp") +file(GLOB HIGHLIGHT_SOURCES "${CPP_ROOT}/highlight/*.cpp") + +# md4c is C code, build as separate static library with C flags +add_library(md4c_lib STATIC ${MD4C_SOURCES}) +target_include_directories(md4c_lib PUBLIC ${CPP_ROOT}/md4c) +target_compile_definitions(md4c_lib PRIVATE MD4C_USE_UTF8=1) +set_target_properties(md4c_lib PROPERTIES + C_STANDARD 11 + C_STANDARD_REQUIRED ON +) + +file(GLOB LIB_CODEGEN_SRCS CONFIGURE_DEPENDS ${LIB_ANDROID_GENERATED_JNI_DIR}/*.cpp ${LIB_ANDROID_GENERATED_COMPONENTS_DIR}/*.cpp) +file(GLOB LIB_CUSTOM_JNI_SRCS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/react/renderer/components/${LIB_LITERAL}/*.cpp) + +add_library( + ${LIB_TARGET_NAME} + SHARED + ${LIB_CODEGEN_SRCS} + ${LIB_CUSTOM_JNI_SRCS} + ${PARSER_SOURCES} + ${HIGHLIGHT_SOURCES} + ${ANDROID_CPP_DIR}/jni-adapter.cpp +) + +target_include_directories( + ${LIB_TARGET_NAME} + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/react/renderer/components/${LIB_LITERAL} + ${LIB_ANDROID_GENERATED_JNI_DIR} + ${LIB_ANDROID_GENERATED_COMPONENTS_DIR} + ${CPP_ROOT}/md4c + ${CPP_ROOT}/parser + ${CPP_ROOT}/highlight +) + +target_compile_definitions(${LIB_TARGET_NAME} PRIVATE MD4C_USE_UTF8=1) + +find_package(fbjni REQUIRED CONFIG) +find_package(ReactAndroid REQUIRED CONFIG) +find_library(LOG_LIB log) + +target_link_libraries( + ${LIB_TARGET_NAME} + ${LOG_LIB} + md4c_lib + fbjni::fbjni + ReactAndroid::jsi + ReactAndroid::reactnative +) + +target_include_directories( + ${CMAKE_PROJECT_NAME} + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} +) + +target_compile_reactnative_options(${LIB_TARGET_NAME} PRIVATE) + +# --- Code-block syntax highlighting (tree-sitter) --- +# CodeBlockHighlighter.cpp / CodeBlockLanguages.cpp are already in the target via +# HIGHLIGHT_SOURCES; without the define below CodeBlockHighlighter.cpp is the stub. +# When enabled we add the runtime, the generated registry, and one OBJECT lib per +# selected grammar (each isolated to its own dir so grammar parser.h files never +# collide), then define ENRICHED_MARKDOWN_CODE_HIGHLIGHT so the real seam compiles. +if(ENRICHED_MARKDOWN_CODE_HIGHLIGHT) + set(TS_VENDOR "${CPP_ROOT}/highlight/vendor") + + add_library(tree_sitter_runtime STATIC "${TS_VENDOR}/tree-sitter/src/lib.c") + target_include_directories(tree_sitter_runtime + PRIVATE "${TS_VENDOR}/tree-sitter/src" + PUBLIC "${TS_VENDOR}/tree-sitter/include") + set_target_properties(tree_sitter_runtime PROPERTIES + C_STANDARD 11 C_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON) + target_compile_options(tree_sitter_runtime PRIVATE -fvisibility=hidden) + + set(GRAMMAR_OBJECTS "") + foreach(lang IN LISTS ENRICHED_MARKDOWN_HIGHLIGHT_LANGUAGES) + set(gdir "${TS_VENDOR}/grammars/${lang}") + set(gsrcs "${gdir}/parser.c") + if(EXISTS "${gdir}/scanner.c") + list(APPEND gsrcs "${gdir}/scanner.c") + endif() + add_library(ts_grammar_${lang} OBJECT ${gsrcs}) + target_include_directories(ts_grammar_${lang} PRIVATE "${gdir}") + set_target_properties(ts_grammar_${lang} PROPERTIES + C_STANDARD 11 C_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON) + target_compile_options(ts_grammar_${lang} PRIVATE -fvisibility=hidden) + list(APPEND GRAMMAR_OBJECTS $) + endforeach() + + target_sources(${LIB_TARGET_NAME} PRIVATE + "${ENRICHED_MARKDOWN_HIGHLIGHT_GENERATED_DIR}/generated_registry.cpp" + ${GRAMMAR_OBJECTS}) + target_include_directories(${LIB_TARGET_NAME} PRIVATE + "${TS_VENDOR}/tree-sitter/include" + "${ENRICHED_MARKDOWN_HIGHLIGHT_GENERATED_DIR}") + target_compile_definitions(${LIB_TARGET_NAME} PRIVATE ENRICHED_MARKDOWN_CODE_HIGHLIGHT=1) + target_link_libraries(${LIB_TARGET_NAME} tree_sitter_runtime) +endif() diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.cpp new file mode 100644 index 000000000000..09fecc63d1d9 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.cpp @@ -0,0 +1,21 @@ +/** + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. + * + * @generated by codegen project: GenerateModuleJniCpp.js + */ + +#include "EnrichedMarkdownTextSpec.h" + +namespace facebook::react { + +std::shared_ptr EnrichedMarkdownTextSpec_ModuleProvider(const std::string &moduleName, + const JavaTurboModule::InitParams ¶ms) { + + return nullptr; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.h b/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.h new file mode 100644 index 000000000000..abceb3dadcd7 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/EnrichedMarkdownTextSpec.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include +#include + +#include + +namespace facebook::react { + +JSI_EXPORT +std::shared_ptr EnrichedMarkdownTextSpec_ModuleProvider(const std::string &moduleName, + const JavaTurboModule::InitParams ¶ms); + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/ComponentDescriptors.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/ComponentDescriptors.h new file mode 100644 index 000000000000..137568773922 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/ComponentDescriptors.h @@ -0,0 +1,67 @@ +#pragma once + +#include "MarkdownContainerMeasurementManager.h" +#include "MarkdownContainerShadowNode.h" +#include "MarkdownTextInputMeasurementManager.h" +#include "MarkdownTextInputShadowNode.h" +#include "MarkdownTextMeasurementManager.h" +#include "MarkdownTextShadowNode.h" + +#include +#include + +namespace facebook::react { + +class EnrichedMarkdownComponentDescriptor final : public ConcreteComponentDescriptor { +public: + EnrichedMarkdownComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters), + measurementsManager_(std::make_shared(contextContainer_)) {} + + void adopt(ShadowNode &shadowNode) const override { + ConcreteComponentDescriptor::adopt(shadowNode); + auto &containerShadowNode = static_cast(shadowNode); + containerShadowNode.setMeasurementsManager(measurementsManager_); + } + +private: + const std::shared_ptr measurementsManager_; +}; + +class EnrichedMarkdownTextComponentDescriptor final : public ConcreteComponentDescriptor { +public: + EnrichedMarkdownTextComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters), + measurementsManager_(std::make_shared(contextContainer_)) {} + + void adopt(ShadowNode &shadowNode) const override { + ConcreteComponentDescriptor::adopt(shadowNode); + auto &markdownTextShadowNode = static_cast(shadowNode); + markdownTextShadowNode.setMeasurementsManager(measurementsManager_); + } + +private: + const std::shared_ptr measurementsManager_; +}; + +class EnrichedMarkdownTextInputComponentDescriptor final + : public ConcreteComponentDescriptor { +public: + EnrichedMarkdownTextInputComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters), + measurementsManager_(std::make_shared(contextContainer_)) {} + + void adopt(ShadowNode &shadowNode) const override { + ConcreteComponentDescriptor::adopt(shadowNode); + auto &inputShadowNode = static_cast(shadowNode); + inputShadowNode.setMeasurementsManager(measurementsManager_); + } + +private: + const std::shared_ptr measurementsManager_; +}; + +void EnrichedMarkdownTextSpec_registerComponentDescriptorsFromCodegen( + std::shared_ptr registry); + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerComponentDescriptor.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerComponentDescriptor.h new file mode 100644 index 000000000000..bf466eeb8711 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerComponentDescriptor.h @@ -0,0 +1,26 @@ +#pragma once + +#include "MarkdownContainerMeasurementManager.h" +#include "MarkdownContainerShadowNode.h" + +#include + +namespace facebook::react { + +class MarkdownContainerComponentDescriptor final : public ConcreteComponentDescriptor { +public: + MarkdownContainerComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters), + measurementsManager_(std::make_shared(contextContainer_)) {} + + void adopt(ShadowNode &shadowNode) const override { + ConcreteComponentDescriptor::adopt(shadowNode); + auto &containerShadowNode = static_cast(shadowNode); + containerShadowNode.setMeasurementsManager(measurementsManager_); + } + +private: + const std::shared_ptr measurementsManager_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.cpp new file mode 100644 index 000000000000..89f446ff1899 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.cpp @@ -0,0 +1,45 @@ +#include "MarkdownContainerMeasurementManager.h" +#include "conversions.h" + +#include +#include +#include + +using namespace facebook::jni; + +namespace facebook::react { + +Size MarkdownContainerMeasurementManager::measure(SurfaceId surfaceId, int viewTag, const EnrichedMarkdownProps &props, + LayoutConstraints layoutConstraints) const { + const jni::global_ref &fabricUIManager = contextContainer_->at>("FabricUIManager"); + + static const auto measure = + facebook::jni::findClassStatic("com/facebook/react/fabric/FabricUIManager") + ->getMethod("measure"); + + auto minimumSize = layoutConstraints.minimumSize; + auto maximumSize = layoutConstraints.maximumSize; + + local_ref componentName = make_jstring("EnrichedMarkdown"); + + // Prepare extraData map with viewTag + folly::dynamic extraData = folly::dynamic::object(); + extraData["viewTag"] = viewTag; + local_ref extraDataRNM = ReadableNativeMap::newObjectCxxArgs(extraData); + local_ref extraDataRM = + make_local(reinterpret_cast(extraDataRNM.get())); + + // Serialize props for measurement + auto serializedProps = toDynamic(props); + local_ref propsRNM = ReadableNativeMap::newObjectCxxArgs(serializedProps); + local_ref propsRM = make_local(reinterpret_cast(propsRNM.get())); + + auto measurement = yogaMeassureToSize(measure(fabricUIManager, surfaceId, componentName.get(), extraDataRM.get(), + propsRM.get(), nullptr, minimumSize.width, maximumSize.width, + minimumSize.height, maximumSize.height)); + + return measurement; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.h new file mode 100644 index 000000000000..dd69dd50ff2f --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerMeasurementManager.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace facebook::react { + +class MarkdownContainerMeasurementManager { +public: + MarkdownContainerMeasurementManager(const std::shared_ptr &contextContainer) + : contextContainer_(contextContainer) {} + + Size measure(SurfaceId surfaceId, int viewTag, const EnrichedMarkdownProps &props, + LayoutConstraints layoutConstraints) const; + +private: + const std::shared_ptr contextContainer_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp new file mode 100644 index 000000000000..b30a0177424a --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.cpp @@ -0,0 +1,38 @@ +#include "MarkdownContainerShadowNode.h" + +#include + +namespace facebook::react { + +extern const char MarkdownContainerComponentName[] = "EnrichedMarkdown"; + +void MarkdownContainerShadowNode::setMeasurementsManager( + const std::shared_ptr &measurementsManager) { + ensureUnsealed(); + measurementsManager_ = measurementsManager; +} + +void MarkdownContainerShadowNode::dirtyLayoutIfNeeded() { + const auto state = this->getStateData(); + const auto counter = state.getForceHeightRecalculationCounter(); + + if (forceHeightRecalculationCounter_ != counter) { + forceHeightRecalculationCounter_ = counter; + dirtyLayout(); + } +} + +// Only new props change the rendered markdown. When a parent is cloned, React Native's adoptYogaChild +// re-clones its children without new props, and dirtying those clones re-measures every settled message +// whenever the list above grows. +bool MarkdownContainerShadowNode::shouldNewRevisionDirtyMeasurement(const ShadowNode & /*sourceShadowNode*/, + const ShadowNodeFragment &fragment) const { + return fragment.props != nullptr; +} + +Size MarkdownContainerShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const { + return measurementsManager_->measure(getSurfaceId(), getTag(), getConcreteProps(), layoutConstraints); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h new file mode 100644 index 000000000000..6c4bd204a1e3 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownContainerShadowNode.h @@ -0,0 +1,49 @@ +#pragma once + +#include "MarkdownContainerMeasurementManager.h" +#include "MarkdownTextState.h" + +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char MarkdownContainerComponentName[]; + +class MarkdownContainerShadowNode final + : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + MarkdownContainerShadowNode(ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) { + forceHeightRecalculationCounter_ = + static_cast(sourceShadowNode).forceHeightRecalculationCounter_; + dirtyLayoutIfNeeded(); + } + + static ShadowNodeTraits BaseTraits() { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + + void setMeasurementsManager(const std::shared_ptr &measurementsManager); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + +protected: + bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) const override; + +private: + int forceHeightRecalculationCounter_{0}; + std::shared_ptr measurementsManager_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextComponentDescriptor.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextComponentDescriptor.h new file mode 100644 index 000000000000..defb75a46b9c --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextComponentDescriptor.h @@ -0,0 +1,29 @@ +#pragma once + +#include "MarkdownTextMeasurementManager.h" +#include "MarkdownTextShadowNode.h" + +#include + +namespace facebook::react { + +class MarkdownTextComponentDescriptor final : public ConcreteComponentDescriptor { +public: + MarkdownTextComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters), + measurementsManager_(std::make_shared(contextContainer_)) {} + + void adopt(ShadowNode &shadowNode) const override { + ConcreteComponentDescriptor::adopt(shadowNode); + auto &markdownTextShadowNode = static_cast(shadowNode); + + // MarkdownTextShadowNode uses MarkdownTextMeasurementManager + // to provide measurements to Yoga. + markdownTextShadowNode.setMeasurementsManager(measurementsManager_); + } + +private: + const std::shared_ptr measurementsManager_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.cpp new file mode 100644 index 000000000000..29026f7ab4e5 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.cpp @@ -0,0 +1,44 @@ +#include "MarkdownTextInputMeasurementManager.h" +#include "conversions.h" + +#include +#include +#include + +using namespace facebook::jni; + +namespace facebook::react { + +Size MarkdownTextInputMeasurementManager::measure(SurfaceId surfaceId, int viewTag, + const EnrichedMarkdownTextInputProps &props, + LayoutConstraints layoutConstraints) const { + const jni::global_ref &fabricUIManager = contextContainer_->at>("FabricUIManager"); + + static const auto measure = + facebook::jni::findClassStatic("com/facebook/react/fabric/FabricUIManager") + ->getMethod("measure"); + + auto minimumSize = layoutConstraints.minimumSize; + auto maximumSize = layoutConstraints.maximumSize; + + local_ref componentName = make_jstring("EnrichedMarkdownTextInput"); + + folly::dynamic extraData = folly::dynamic::object(); + extraData["viewTag"] = viewTag; + local_ref extraDataRNM = ReadableNativeMap::newObjectCxxArgs(extraData); + local_ref extraDataRM = + make_local(reinterpret_cast(extraDataRNM.get())); + + auto serializedProps = toDynamic(props); + local_ref propsRNM = ReadableNativeMap::newObjectCxxArgs(serializedProps); + local_ref propsRM = make_local(reinterpret_cast(propsRNM.get())); + + auto measurement = yogaMeassureToSize(measure(fabricUIManager, surfaceId, componentName.get(), extraDataRM.get(), + propsRM.get(), nullptr, minimumSize.width, maximumSize.width, + minimumSize.height, maximumSize.height)); + + return measurement; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.h new file mode 100644 index 000000000000..5eadd0bbade3 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputMeasurementManager.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace facebook::react { + +class MarkdownTextInputMeasurementManager { +public: + MarkdownTextInputMeasurementManager(const std::shared_ptr &contextContainer) + : contextContainer_(contextContainer) {} + + Size measure(SurfaceId surfaceId, int viewTag, const EnrichedMarkdownTextInputProps &props, + LayoutConstraints layoutConstraints) const; + +private: + const std::shared_ptr contextContainer_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.cpp new file mode 100644 index 000000000000..ac18fda9b682 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.cpp @@ -0,0 +1,30 @@ +#include "MarkdownTextInputShadowNode.h" + +#include + +namespace facebook::react { + +extern const char MarkdownTextInputComponentName[] = "EnrichedMarkdownTextInput"; + +void MarkdownTextInputShadowNode::setMeasurementsManager( + const std::shared_ptr &measurementsManager) { + ensureUnsealed(); + measurementsManager_ = measurementsManager; +} + +void MarkdownTextInputShadowNode::dirtyLayoutIfNeeded() { + const auto state = this->getStateData(); + const auto counter = state.getForceHeightRecalculationCounter(); + + if (forceHeightRecalculationCounter_ != counter) { + forceHeightRecalculationCounter_ = counter; + dirtyLayout(); + } +} + +Size MarkdownTextInputShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const { + return measurementsManager_->measure(getSurfaceId(), getTag(), getConcreteProps(), layoutConstraints); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.h new file mode 100644 index 000000000000..22cabef6199f --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputShadowNode.h @@ -0,0 +1,43 @@ +#pragma once + +#include "MarkdownTextInputMeasurementManager.h" +#include "MarkdownTextInputState.h" + +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char MarkdownTextInputComponentName[]; + +class MarkdownTextInputShadowNode final + : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + MarkdownTextInputShadowNode(ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) { + dirtyLayoutIfNeeded(); + } + + static ShadowNodeTraits BaseTraits() { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + + void setMeasurementsManager(const std::shared_ptr &measurementsManager); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + +private: + int forceHeightRecalculationCounter_{0}; + std::shared_ptr measurementsManager_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.cpp new file mode 100644 index 000000000000..fdbd2292283f --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.cpp @@ -0,0 +1,9 @@ +#include "MarkdownTextInputState.h" + +namespace facebook::react { + +int MarkdownTextInputState::getForceHeightRecalculationCounter() const { + return forceHeightRecalculationCounter_; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.h new file mode 100644 index 000000000000..537e9622b63e --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextInputState.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace facebook::react { + +class MarkdownTextInputState { +public: + MarkdownTextInputState() : forceHeightRecalculationCounter_(0) {} + + MarkdownTextInputState(MarkdownTextInputState const &previousState, folly::dynamic data) + : forceHeightRecalculationCounter_((int)data["forceHeightRecalculationCounter"].getInt()) {} + + folly::dynamic getDynamic() const { + return {}; + } + + int getForceHeightRecalculationCounter() const; + +private: + const int forceHeightRecalculationCounter_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.cpp new file mode 100644 index 000000000000..248a6b5abd4d --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.cpp @@ -0,0 +1,45 @@ +#include "MarkdownTextMeasurementManager.h" +#include "conversions.h" + +#include +#include +#include + +using namespace facebook::jni; + +namespace facebook::react { + +Size MarkdownTextMeasurementManager::measure(SurfaceId surfaceId, int viewTag, const EnrichedMarkdownTextProps &props, + LayoutConstraints layoutConstraints) const { + const jni::global_ref &fabricUIManager = contextContainer_->at>("FabricUIManager"); + + static const auto measure = + facebook::jni::findClassStatic("com/facebook/react/fabric/FabricUIManager") + ->getMethod("measure"); + + auto minimumSize = layoutConstraints.minimumSize; + auto maximumSize = layoutConstraints.maximumSize; + + local_ref componentName = make_jstring("EnrichedMarkdownText"); + + // Prepare extraData map with viewTag + folly::dynamic extraData = folly::dynamic::object(); + extraData["viewTag"] = viewTag; + local_ref extraDataRNM = ReadableNativeMap::newObjectCxxArgs(extraData); + local_ref extraDataRM = + make_local(reinterpret_cast(extraDataRNM.get())); + + // Prepare layout metrics affecting props + auto serializedProps = toDynamic(props); + local_ref propsRNM = ReadableNativeMap::newObjectCxxArgs(serializedProps); + local_ref propsRM = make_local(reinterpret_cast(propsRNM.get())); + + auto measurement = yogaMeassureToSize(measure(fabricUIManager, surfaceId, componentName.get(), extraDataRM.get(), + propsRM.get(), nullptr, minimumSize.width, maximumSize.width, + minimumSize.height, maximumSize.height)); + + return measurement; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.h new file mode 100644 index 000000000000..a3dd6796132d --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextMeasurementManager.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace facebook::react { + +class MarkdownTextMeasurementManager { +public: + MarkdownTextMeasurementManager(const std::shared_ptr &contextContainer) + : contextContainer_(contextContainer) {} + + Size measure(SurfaceId surfaceId, int viewTag, const EnrichedMarkdownTextProps &props, + LayoutConstraints layoutConstraints) const; + +private: + const std::shared_ptr contextContainer_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp new file mode 100644 index 000000000000..ab51055c83f4 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.cpp @@ -0,0 +1,38 @@ +#include "MarkdownTextShadowNode.h" + +#include + +namespace facebook::react { + +extern const char MarkdownTextComponentName[] = "EnrichedMarkdownText"; + +void MarkdownTextShadowNode::setMeasurementsManager( + const std::shared_ptr &measurementsManager) { + ensureUnsealed(); + measurementsManager_ = measurementsManager; +} + +void MarkdownTextShadowNode::dirtyLayoutIfNeeded() { + const auto state = this->getStateData(); + const auto counter = state.getForceHeightRecalculationCounter(); + + if (forceHeightRecalculationCounter_ != counter) { + forceHeightRecalculationCounter_ = counter; + dirtyLayout(); + } +} + +// Only new props change the rendered markdown. When a parent is cloned, React Native's adoptYogaChild +// re-clones its children without new props, and dirtying those clones re-measures every settled message +// whenever the list above grows. +bool MarkdownTextShadowNode::shouldNewRevisionDirtyMeasurement(const ShadowNode & /*sourceShadowNode*/, + const ShadowNodeFragment &fragment) const { + return fragment.props != nullptr; +} + +Size MarkdownTextShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const { + return measurementsManager_->measure(getSurfaceId(), getTag(), getConcreteProps(), layoutConstraints); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h new file mode 100644 index 000000000000..05a02eb9faf6 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextShadowNode.h @@ -0,0 +1,53 @@ +#pragma once + +#include "MarkdownTextMeasurementManager.h" +#include "MarkdownTextState.h" + +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char MarkdownTextComponentName[]; + +/* + * `ShadowNode` for component. + */ +class MarkdownTextShadowNode final + : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + MarkdownTextShadowNode(ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) { + forceHeightRecalculationCounter_ = + static_cast(sourceShadowNode).forceHeightRecalculationCounter_; + dirtyLayoutIfNeeded(); + } + + static ShadowNodeTraits BaseTraits() { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + + // Associates a shared `MarkdownTextMeasurementManager` with the node. + void setMeasurementsManager(const std::shared_ptr &measurementsManager); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + +protected: + bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) const override; + +private: + int forceHeightRecalculationCounter_{0}; + std::shared_ptr measurementsManager_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.cpp b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.cpp new file mode 100644 index 000000000000..4ebdaaa98677 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.cpp @@ -0,0 +1,9 @@ +#include "MarkdownTextState.h" + +namespace facebook::react { + +int MarkdownTextState::getForceHeightRecalculationCounter() const { + return forceHeightRecalculationCounter_; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.h new file mode 100644 index 000000000000..fe6b316f10f4 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/MarkdownTextState.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace facebook::react { + +class MarkdownTextState { +public: + MarkdownTextState() : forceHeightRecalculationCounter_(0) {} + + MarkdownTextState(MarkdownTextState const &previousState, folly::dynamic data) + : forceHeightRecalculationCounter_((int)data["forceHeightRecalculationCounter"].getInt()) {} + + folly::dynamic getDynamic() const { + return {}; + } + + int getForceHeightRecalculationCounter() const; + +private: + const int forceHeightRecalculationCounter_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/conversions.h b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/conversions.h new file mode 100644 index 000000000000..d4961d13cb28 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/main/jni/react/renderer/components/EnrichedMarkdownTextSpec/conversions.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include + +namespace facebook::react { + +#ifdef RN_SERIALIZABLE_STATE +inline folly::dynamic toDynamic(const EnrichedMarkdownTextProps &props) { + folly::dynamic serializedProps = folly::dynamic::object(); + serializedProps["markdown"] = props.markdown; + serializedProps["markdownStyle"] = toDynamic(props.markdownStyle); + serializedProps["md4cFlags"] = toDynamic(props.md4cFlags); + serializedProps["allowFontScaling"] = props.allowFontScaling; + serializedProps["maxFontSizeMultiplier"] = props.maxFontSizeMultiplier; + serializedProps["allowTrailingMargin"] = props.allowTrailingMargin; + serializedProps["streamingAnimation"] = props.streamingAnimation; + serializedProps["numberOfLines"] = props.numberOfLines; + serializedProps["ellipsizeMode"] = props.ellipsizeMode; + + folly::dynamic imageRequestHeaders = folly::dynamic::array(); + for (const auto &header : props.imageRequestHeaders) { + imageRequestHeaders.push_back(toDynamic(header)); + } + serializedProps["imageRequestHeaders"] = std::move(imageRequestHeaders); + + // Pill labels change text width, so measurement needs the same content the view renders. + folly::dynamic linkPillContent = folly::dynamic::array(); + for (const auto &content : props.linkPillContent) { + linkPillContent.push_back(toDynamic(content)); + } + serializedProps["linkPillContent"] = std::move(linkPillContent); + + // Recognition changes line wrapping, so measurement must parse with the view's patterns. + serializedProps["linkRecognition"] = toDynamic(props.linkRecognition); + + return serializedProps; +} + +inline folly::dynamic toDynamic(const EnrichedMarkdownProps &props) { + folly::dynamic serializedProps = folly::dynamic::object(); + serializedProps["markdown"] = props.markdown; + serializedProps["markdownStyle"] = toDynamic(props.markdownStyle); + serializedProps["md4cFlags"] = toDynamic(props.md4cFlags); + serializedProps["allowFontScaling"] = props.allowFontScaling; + serializedProps["maxFontSizeMultiplier"] = props.maxFontSizeMultiplier; + serializedProps["allowTrailingMargin"] = props.allowTrailingMargin; + serializedProps["streamingAnimation"] = props.streamingAnimation; + + folly::dynamic imageRequestHeaders = folly::dynamic::array(); + for (const auto &header : props.imageRequestHeaders) { + imageRequestHeaders.push_back(toDynamic(header)); + } + serializedProps["imageRequestHeaders"] = std::move(imageRequestHeaders); + + // Pill labels change text width, so measurement needs the same content the view renders. + folly::dynamic linkPillContent = folly::dynamic::array(); + for (const auto &content : props.linkPillContent) { + linkPillContent.push_back(toDynamic(content)); + } + serializedProps["linkPillContent"] = std::move(linkPillContent); + + // Recognition changes line wrapping, so measurement must parse with the view's patterns. + serializedProps["linkRecognition"] = toDynamic(props.linkRecognition); + + return serializedProps; +} + +inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputProps &props) { + folly::dynamic serializedProps = folly::dynamic::object(); + serializedProps["defaultValue"] = props.defaultValue; + serializedProps["placeholder"] = props.placeholder; + serializedProps["fontSize"] = props.fontSize; + serializedProps["fontWeight"] = props.fontWeight; + serializedProps["fontFamily"] = props.fontFamily; + serializedProps["lineHeight"] = props.lineHeight; + + return serializedProps; +} +#endif + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/renderer/MathInlineRenderer.kt b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/renderer/MathInlineRenderer.kt new file mode 100644 index 000000000000..430ccf9a912b --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/renderer/MathInlineRenderer.kt @@ -0,0 +1,55 @@ +package com.swmansion.enriched.markdown.renderer + +import android.content.Context +import android.text.SpannableStringBuilder +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.spans.MathInlineSpan +import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE +import io.ratex.RaTeXFontLoader + +class MathInlineRenderer( + private val config: RendererConfig, + private val context: Context, +) : NodeRenderer { + override fun render( + node: MarkdownASTNode, + builder: SpannableStringBuilder, + onLinkPress: ((String) -> Unit)?, + onLinkLongPress: ((String) -> Unit)?, + factory: RendererFactory, + ) { + RaTeXFontLoader.ensureLoaded(context) + + val latex = extractLatex(node) + if (latex.isEmpty()) return + + val fontSize = + factory.blockStyleContext.currentBlockStyleOrNull()?.fontSize + ?: config.style.mathStyle.fontSize + + val start = builder.length + builder.append("\uFFFC") + val end = builder.length + + val span = + MathInlineSpan( + context = context, + latex = latex, + fontSize = fontSize, + textColor = config.style.inlineMathStyle.color, + onLatexError = config.onLatexError, + ) + + builder.setSpan(span, start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE) + } + + private fun extractLatex(node: MarkdownASTNode): String { + if (node.content.isNotEmpty()) return node.content + return node.children.joinToString("") { child -> + when (child.type) { + MarkdownASTNode.NodeType.SoftBreak, MarkdownASTNode.NodeType.LineBreak -> " " + else -> child.content + } + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/segments/MathContainerView.kt b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/segments/MathContainerView.kt new file mode 100644 index 000000000000..c937222bc213 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/segments/MathContainerView.kt @@ -0,0 +1,200 @@ +package com.swmansion.enriched.markdown.segments + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.util.Log +import android.view.Gravity +import android.view.View +import android.view.ViewGroup.LayoutParams.MATCH_PARENT +import android.view.ViewGroup.LayoutParams.WRAP_CONTENT +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels +import com.swmansion.enriched.markdown.math.LatexErrorReporter +import com.swmansion.enriched.markdown.spans.MathMeasureHelper +import com.swmansion.enriched.markdown.spans.MathMeasureRequest +import com.swmansion.enriched.markdown.spans.MathRenderMode +import com.swmansion.enriched.markdown.styles.MathStyle +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.views.ContextMenuPopup +import io.ratex.RaTeXEngine +import io.ratex.RaTeXFontLoader +import io.ratex.RaTeXRenderer +import kotlin.math.ceil + +class MathContainerView( + context: Context, + styleConfig: StyleConfig, +) : FrameLayout(context), + BlockSegmentView { + private val mathStyle: MathStyle = styleConfig.mathStyle + private val scrollView = HorizontalScrollView(context) + private var cachedLatex: String = "" + + var accessibilityLabels: AccessibilityLabels = AccessibilityLabels() + set(value) { + field = value + updateAccessibilityLabel() + } + var dynamicProps: DynamicBlockProps = DynamicBlockProps() + var onLatexError: LatexErrorReporter? = null + + override val segmentMarginTop: Int get() = mathStyle.marginTop.toInt() + override val segmentMarginBottom: Int get() = mathStyle.marginBottom.toInt() + + private val mathGravity = + when (mathStyle.textAlign) { + "left" -> Gravity.START + "right" -> Gravity.END + else -> Gravity.CENTER_HORIZONTAL + } + + private val mathView = RaTeXCanvasView(context) + + init { + setBackgroundColor(mathStyle.backgroundColor) + + val paddingPx = mathStyle.padding.toInt() + + RaTeXFontLoader.ensureLoaded(context) + + val mathLayoutParams = + FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { + gravity = mathGravity + } + + val mathWrapper = + FrameLayout(context).apply { + setPadding(paddingPx, paddingPx, paddingPx, paddingPx) + } + mathWrapper.addView(mathView, mathLayoutParams) + + scrollView.apply { + isHorizontalScrollBarEnabled = true + overScrollMode = View.OVER_SCROLL_NEVER + isFillViewport = true + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + addView(mathWrapper, LayoutParams(WRAP_CONTENT, WRAP_CONTENT)) + } + + addView(scrollView, LayoutParams(MATCH_PARENT, WRAP_CONTENT)) + + isFocusable = true + isScreenReaderFocusable = true + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES + updateAccessibilityLabel() + + setOnLongClickListener { view -> showContextMenu(view) } + mathView.setOnLongClickListener { view -> showContextMenu(view) } + } + + fun applyLatex(latex: String) { + cachedLatex = latex + try { + val displayList = RaTeXEngine.parseBlocking(latex, displayMode = true, color = mathStyle.color) + mathView.renderer = RaTeXRenderer(displayList, mathStyle.fontSize) { RaTeXFontLoader.getTypeface(it) } + mathView.fallbackText = null + } catch (e: Exception) { + Log.e(TAG, "Failed to render LaTeX", e) + mathView.renderer = null + mathView.fallbackText = "\$\$" + latex + "\$\$" + mathView.fallbackColor = mathStyle.color + mathView.fallbackFontSize = mathStyle.fontSize + onLatexError?.report(latex, e.message, true) + } + mathView.requestLayout() + mathView.invalidate() + updateAccessibilityLabel() + } + + private fun updateAccessibilityLabel() { + contentDescription = accessibilityLabels.mathEquation.replace("{latex}", cachedLatex) + } + + private fun showContextMenu(anchor: View): Boolean { + if (!dynamicProps.enableBlockContextMenu) return false + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + ContextMenuPopup.show(anchor, this) { + item(ContextMenuPopup.Icon.COPY, dynamicProps.copyLabel) { + clipboard.setPrimaryClip(ClipData.newPlainText("Math", cachedLatex)) + } + item(ContextMenuPopup.Icon.DOCUMENT, dynamicProps.copyAsMarkdownLabel) { + clipboard.setPrimaryClip(ClipData.newPlainText("Math", "$$\n$cachedLatex\n$$")) + } + } + return true + } + + private class RaTeXCanvasView( + context: Context, + ) : View(context) { + var renderer: RaTeXRenderer? = null + + var fallbackText: String? = null + var fallbackColor: Int = 0 + var fallbackFontSize: Float = 0f + private val fallbackPaint = Paint(Paint.ANTI_ALIAS_FLAG) + + override fun onMeasure( + widthMeasureSpec: Int, + heightMeasureSpec: Int, + ) { + val currentRenderer = renderer + if (currentRenderer != null) { + setMeasuredDimension( + ceil(currentRenderer.widthPx).toInt().coerceAtLeast(1), + ceil(currentRenderer.totalHeightPx).toInt().coerceAtLeast(1), + ) + return + } + + val fallback = fallbackText + if (fallback != null) { + fallbackPaint.textSize = fallbackFontSize + val metrics = fallbackPaint.fontMetrics + setMeasuredDimension( + ceil(fallbackPaint.measureText(fallback)).toInt().coerceAtLeast(1), + ceil(metrics.descent - metrics.ascent).toInt().coerceAtLeast(1), + ) + return + } + + setMeasuredDimension(0, 0) + } + + override fun onDraw(canvas: Canvas) { + val currentRenderer = renderer + if (currentRenderer != null) { + currentRenderer.draw(canvas) + return + } + + val fallback = fallbackText ?: return + fallbackPaint.textSize = fallbackFontSize + fallbackPaint.color = fallbackColor + canvas.drawText(fallback, 0f, -fallbackPaint.fontMetrics.ascent, fallbackPaint) + } + } + + companion object { + fun measureMathHeight( + latex: String, + mathStyle: MathStyle, + context: Context, + ): Float { + val request = + MathMeasureRequest( + fontSize = mathStyle.fontSize, + latex = latex, + mode = MathRenderMode.Display, + ) + val metrics = MathMeasureHelper.measure(context, listOf(request)).first() + return ceil(metrics.ascent + metrics.descent).toInt() + (mathStyle.padding * 2) + } + + private const val TAG = "MathContainerView" + } +} diff --git a/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlinePlaceholderSpan.kt b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlinePlaceholderSpan.kt new file mode 100644 index 000000000000..d93081286a42 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlinePlaceholderSpan.kt @@ -0,0 +1,41 @@ +package com.swmansion.enriched.markdown.spans + +import android.graphics.Canvas +import android.graphics.Paint +import android.text.style.ReplacementSpan +import kotlin.math.roundToInt + +/** Holds pre-computed math metrics for background-thread measurement. */ +class MathInlinePlaceholderSpan( + private val metrics: MathMetrics, +) : ReplacementSpan() { + override fun getSize( + paint: Paint, + text: CharSequence?, + start: Int, + end: Int, + fm: Paint.FontMetricsInt?, + ): Int { + fm?.apply { + ascent = -metrics.ascent.roundToInt() + top = ascent + descent = metrics.descent.roundToInt() + bottom = descent + } + return metrics.width + } + + override fun draw( + canvas: Canvas, + text: CharSequence?, + start: Int, + end: Int, + x: Float, + top: Int, + y: Int, + bottom: Int, + paint: Paint, + ) { + // Never displayed — measurement only. + } +} diff --git a/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlineSpan.kt b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlineSpan.kt new file mode 100644 index 000000000000..17864cbd03b8 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathInlineSpan.kt @@ -0,0 +1,117 @@ +package com.swmansion.enriched.markdown.spans + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.text.style.ReplacementSpan +import com.swmansion.enriched.markdown.math.LatexErrorReporter +import io.ratex.RaTeXEngine +import io.ratex.RaTeXFontLoader +import io.ratex.RaTeXRenderer +import kotlin.math.ceil + +class MathInlineSpan( + private val context: Context, + internal val latex: String, + internal val fontSize: Float, + private val textColor: Int, + private val onLatexError: LatexErrorReporter? = null, +) : ReplacementSpan() { + private var cachedBitmap: Bitmap? = null + private var cachedWidth = 0 + private var mathAscent = 0f + private var mathDescent = 0f + private var renderFailed = false + + private var fallbackText: String? = null + + private fun prepareResources() { + if (cachedBitmap != null && !cachedBitmap!!.isRecycled) return + if (renderFailed) return + + try { + val displayList = RaTeXEngine.parseBlocking(latex, displayMode = false, color = textColor) + val renderer = RaTeXRenderer(displayList, fontSize) { RaTeXFontLoader.getTypeface(it) } + + cachedWidth = renderer.widthPx.toInt().coerceAtLeast(1) + mathAscent = renderer.heightPx + mathDescent = renderer.depthPx + + val bitmap = + Bitmap.createBitmap( + cachedWidth, + ceil(renderer.totalHeightPx).toInt().coerceAtLeast(1), + Bitmap.Config.ARGB_8888, + ) + + renderer.draw(Canvas(bitmap)) + cachedBitmap = bitmap + } catch (e: Exception) { + renderFailed = true + fallbackText = "\$" + latex + "\$" + onLatexError?.report(latex, e.message, false) + } + } + + override fun getSize( + paint: Paint, + text: CharSequence?, + start: Int, + end: Int, + fm: Paint.FontMetricsInt?, + ): Int { + prepareResources() + + val fallback = fallbackText + if (fallback != null) { + cachedWidth = ceil(paint.measureText(fallback)).toInt().coerceAtLeast(1) + fm?.apply { + val paintFm = paint.fontMetricsInt + ascent = paintFm.ascent + top = paintFm.top + descent = paintFm.descent + bottom = paintFm.bottom + } + return cachedWidth + } + + fm?.apply { + val ascentPx = ceil(mathAscent).toInt() + ascent = -ascentPx + top = ascent + descent = (cachedBitmap?.height ?: ceil(mathAscent + mathDescent).toInt()) - ascentPx + bottom = descent + } + + return cachedWidth + } + + override fun draw( + canvas: Canvas, + text: CharSequence?, + start: Int, + end: Int, + x: Float, + top: Int, + y: Int, + bottom: Int, + paint: Paint, + ) { + prepareResources() + + val bitmap = cachedBitmap + if (bitmap != null) { + val bitmapY = y - ceil(mathAscent) + canvas.drawBitmap(bitmap, x, bitmapY, paint) + return + } + + fallbackText?.let { fallback -> + val originalColor = paint.color + paint.color = textColor + canvas.drawText(fallback, x, y.toFloat(), paint) + paint.color = originalColor + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathMeasureHelper.kt b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathMeasureHelper.kt new file mode 100644 index 000000000000..d0eda85e5e9b --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/math/java/com/swmansion/enriched/markdown/spans/MathMeasureHelper.kt @@ -0,0 +1,57 @@ +package com.swmansion.enriched.markdown.spans + +import android.content.Context +import android.util.Log +import io.ratex.RaTeXEngine +import io.ratex.RaTeXFontLoader +import io.ratex.RaTeXRenderer + +object MathMeasureHelper { + @JvmStatic + fun measure( + context: Context, + requests: List, + ): List { + if (requests.isEmpty()) return emptyList() + + RaTeXFontLoader.ensureLoaded(context) + + return requests.map { request -> + runCatching { measureSingle(context, request) }.getOrElse { estimateFallback(request) } + } + } + + private fun measureSingle( + context: Context, + request: MathMeasureRequest, + ): MathMetrics { + val displayList = + RaTeXEngine.parseBlocking( + request.latex, + displayMode = request.mode == MathRenderMode.Display, + ) + + val renderer = + RaTeXRenderer(displayList, request.fontSize) { + RaTeXFontLoader.getTypeface(it) + } + + return MathMetrics( + renderer.widthPx.toInt(), + renderer.heightPx, + renderer.depthPx, + ) + } + + private fun estimateFallback(request: MathMeasureRequest): MathMetrics { + val h = request.fontSize * 1.4f + return MathMetrics( + width = + (request.fontSize * request.latex.length * 0.5f) + .coerceIn(request.fontSize, request.fontSize * 20f) + .toInt(), + ascent = h * 0.7f, + descent = h * 0.3f, + ) + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/InlineCodeFormattingTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/InlineCodeFormattingTest.kt new file mode 100644 index 000000000000..77c9b43e77c1 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/InlineCodeFormattingTest.kt @@ -0,0 +1,89 @@ +package com.swmansion.enriched.markdown + +import android.text.TextPaint +import com.facebook.react.bridge.JavaOnlyMap +import com.swmansion.enriched.markdown.renderer.BlockStyle +import com.swmansion.enriched.markdown.renderer.SpanStyleCache +import com.swmansion.enriched.markdown.spans.CodeSpan +import com.swmansion.enriched.markdown.spans.StrongSpan +import com.swmansion.enriched.markdown.spans.EmphasisSpan +import com.swmansion.enriched.markdown.styles.StyleConfig +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@org.robolectric.annotation.GraphicsMode(org.robolectric.annotation.GraphicsMode.Mode.NATIVE) +@Config(manifest = Config.NONE, sdk = [34]) +class InlineCodeFormattingTest { + private fun cache(): SpanStyleCache { + com.facebook.react.uimanager.DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(RuntimeEnvironment.getApplication()) + val common = JavaOnlyMap.of( + "fontFamily", "", "fontWeight", "bold", "fontStyle", "italic", + "fontSize", 12.0, "color", -16777216.0, "backgroundColor", 0.0, + "borderColor", 0.0, "underline", false, + "marginTop", 0.0, "marginBottom", 0.0, "lineHeight", 20.0, "textAlign", "left", + "checkedColor", 0.0, "checkmarkColor", 0.0, "checkedTextColor", 0.0, + "checkboxSize", 18.0, "checkboxBorderRadius", 2.0, "checkedStrikethrough", false, + "particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0), + "solid", JavaOnlyMap.of("borderRadius", 0.0), + "fontScale", 0.7, "baselineOffsetScale", 0.3, + ) + val styles = JavaOnlyMap() + listOf("paragraph", "strong", "em", "strikethrough", "link", "code", "taskList", + "spoiler", "superscript", "subscript", "highlight").forEach { styles.putMap(it, common) } + styles.putMap("code", JavaOnlyMap.of("fontFamily", "", "fontSize", 0.0, "fontScale", 0.75, "color", -16777216.0, "backgroundColor", 0.0, "borderColor", 0.0)) + return SpanStyleCache(StyleConfig(styles, RuntimeEnvironment.getApplication(), false, 1f)) + } + + @Test fun boldPreservesInlineCodeSizeInMeasurementAndDrawing() { + val cache = cache() + for (blockSize in listOf(16f, 28f)) { + val block = BlockStyle(blockSize, "", "normal", -16777216) + for (draw in listOf(false, true)) { + for (boldFirst in listOf(false, true)) { + val paint = TextPaint().apply { textSize = blockSize } + val code = CodeSpan(cache, block) + val bold = StrongSpan(cache, block) + val spans = if (boldFirst) listOf(bold, code) else listOf(code, bold) + spans.forEach { if (draw) it.updateDrawState(paint) else it.updateMeasureState(paint) } + assertEquals("Inline code size must survive bold in either span order", blockSize * 0.75f, paint.textSize, 0f) + assertTrue(paint.typeface.isBold) + } + } + } + } + + @Test fun boldPreservesExistingSizeAndItalic() { + val cache = cache() + val block = BlockStyle(28f, "", "normal", -16777216) + val paint = TextPaint().apply { textSize = 16f } + EmphasisSpan(cache, block).updateMeasureState(paint) + StrongSpan(cache, block).updateMeasureState(paint) + assertEquals(16f, paint.textSize, 0f) + assertTrue(paint.typeface.isBold) + assertTrue(paint.typeface.isItalic) + } + + @Test fun linksPreserveCodeAndEmphasizedProseFonts() { + val cache = cache() + val block = BlockStyle(28f, "", "normal", -16777216) + for (code in listOf(false, true)) { + val paint = TextPaint().apply { textSize = 16f } + if (code) CodeSpan(cache, block).updateDrawState(paint) + EmphasisSpan(cache, block).updateDrawState(paint) + StrongSpan(cache, block).updateDrawState(paint) + val size = paint.textSize + val font = paint.typeface + com.swmansion.enriched.markdown.spans.LinkSpan( + "https://example.com", null, null, cache, block, RuntimeEnvironment.getApplication(), + ).updateDrawState(paint) + assertEquals(size, paint.textSize, 0f) + assertEquals(font, paint.typeface) + } + } + +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt new file mode 100644 index 000000000000..6115a30630da --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt @@ -0,0 +1,244 @@ +package com.swmansion.enriched.markdown + +import android.graphics.Paint +import android.text.Layout +import android.text.SpannableStringBuilder +import android.text.style.LineHeightSpan as AndroidLineHeightSpan +import android.util.TypedValue +import android.view.View.MeasureSpec +import com.facebook.react.bridge.JavaOnlyArray +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType +import com.swmansion.enriched.markdown.renderer.Renderer +import com.swmansion.enriched.markdown.segments.SegmentHeightMeasurer +import com.swmansion.enriched.markdown.spans.LineHeightSpan +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(manifest = Config.NONE, sdk = [34]) +class ListBlockquoteMeasurementTest { + private fun styleConfig(): StyleConfig { + val context = RuntimeEnvironment.getApplication() + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context) + val base = + JavaOnlyMap.of( + "fontFamily", "", + "fontWeight", "normal", + "fontStyle", "normal", + "fontSize", 16.0, + "lineHeight", 22.0, + "color", -16777216.0, + "backgroundColor", 0.0, + "borderColor", 0.0, + "borderWidth", 3.0, + "borderRadius", 0.0, + "padding", 12.0, + "gapWidth", 8.0, + "marginTop", 0.0, + "marginBottom", 12.0, + "marginLeft", 20.0, + "itemSpacing", 4.0, + "bulletColor", -16777216.0, + "bulletSize", 6.0, + "markerMinWidth", 0.0, + "markerColor", -16777216.0, + "markerFontWeight", "normal", + "textAlign", "left", + "underline", false, + "checkedColor", 0.0, + "checkmarkColor", 0.0, + "checkedTextColor", 0.0, + "checkboxSize", 18.0, + "checkboxBorderRadius", 2.0, + "checkedStrikethrough", false, + "particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0), + "solid", JavaOnlyMap.of("borderRadius", 0.0), + "fontScale", 0.7, + "baselineOffsetScale", 0.3, + ) + val styles = JavaOnlyMap() + listOf( + "paragraph", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "strong", + "em", + "strikethrough", + "underline", + "link", + "code", + "blockquote", + "list", + "codeBlock", + "thematicBreak", + "image", + "inlineImage", + "video", + "table", + "taskList", + "math", + "inlineMath", + "spoiler", + "superscript", + "subscript", + "highlight", + ).forEach { styles.putMap(it, base) } + styles.putArray("linkVariants", JavaOnlyArray()) + return StyleConfig(styles, context, allowFontScaling = false, maxFontSizeMultiplier = 1f) + } + + private fun measureTextView( + text: CharSequence, + fontSizePx: Float, + widthPx: Int, + ): EnrichedMarkdownInternalText { + val context = RuntimeEnvironment.getApplication() + return EnrichedMarkdownInternalText(context).apply { + setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx) + breakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY + applyStyledText(text) + measure( + MeasureSpec.makeMeasureSpec(widthPx, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), + ) + } + } + + @Test + fun listNestedBlockquotesMatchMeasurementAndKeepSpacerHeights() { + val context = RuntimeEnvironment.getApplication() + val style = styleConfig() + val widthPx = 640 + val fontSizePx = style.paragraphStyle.fontSize + + val ast = + MarkdownASTNode( + NodeType.Document, + children = + listOf( + MarkdownASTNode( + NodeType.OrderedList, + attributes = mapOf("start" to "1"), + children = + listOf( + MarkdownASTNode( + NodeType.ListItem, + children = + listOf( + MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First item"))), + MarkdownASTNode( + NodeType.Blockquote, + children = + listOf( + MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First quote"))), + ), + ), + ), + ), + MarkdownASTNode( + NodeType.ListItem, + children = + listOf( + MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second item"))), + MarkdownASTNode( + NodeType.Blockquote, + children = + listOf( + MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second quote"))), + ), + ), + ), + ), + ), + ), + MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Trailing paragraph"))), + ), + ) + + val renderer = Renderer().apply { configure(style, context) } + val rendered = renderer.renderDocument(ast) + + val storeLayout = MeasurementStore.createStaticLayout(rendered, fontSizePx, widthPx, null) + val segmentLayout = + SegmentHeightMeasurer.createStaticLayout(rendered, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY) + val textView = measureTextView(rendered, fontSizePx, widthPx) + + assertEquals("MeasurementStore and TextView must agree on height", textView.measuredHeight, storeLayout.height) + assertEquals("SegmentHeightMeasurer and TextView must agree on height", textView.measuredHeight, segmentLayout.height) + + // Verify blockquote top-padding and bottom-margin spacer lines keep their configured + // heights instead of being inflated to list.lineHeight (22dp). + val paddingPx = style.blockquoteStyle.padding.toInt() + val marginBottomPx = style.blockquoteStyle.marginBottom.toInt() + val itemSpacingPx = style.listStyle.itemSpacing.toInt() + val spacerLineHeights = + (0 until storeLayout.lineCount) + .filter { line -> + val start = storeLayout.getLineStart(line) + val end = storeLayout.getLineEnd(line) + end - start == 1 && rendered[start] == '\n' + }.map { line -> storeLayout.getLineBottom(line) - storeLayout.getLineTop(line) } + + assertEquals( + listOf(paddingPx, marginBottomPx + itemSpacingPx, paddingPx, marginBottomPx, marginBottomPx), + spacerLineHeights, + ) + } + + @Test + fun measurementStaticLayoutUsesInsertionOrderLikeTextView() { + val context = RuntimeEnvironment.getApplication() + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context) + val widthPx = 400 + val fontSizePx = 16f + + // Inner priority-0 spacer inserted before outer priority-0 LineHeightSpan: + // SpannableStringBuilder's unsorted fast path orders by start offset (outer first), + // while InsertionOrderedSpannable orders by insertion order (inner first, so outer inflates it). + val builder = SpannableStringBuilder("first\n\nsecond") + builder.setSpan( + object : AndroidLineHeightSpan { + override fun chooseHeight( + text: CharSequence, + start: Int, + end: Int, + spanstartv: Int, + v: Int, + fm: Paint.FontMetricsInt, + ) { + fm.top = 0 + fm.ascent = 0 + fm.descent = 12 + fm.bottom = 12 + } + }, + 6, + 7, + SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE, + ) + builder.setSpan(LineHeightSpan(40f), 0, builder.length, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE) + + val storeLayout = MeasurementStore.createStaticLayout(builder, fontSizePx, widthPx, null) + val segmentLayout = + SegmentHeightMeasurer.createStaticLayout(builder, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY) + val textView = measureTextView(builder, fontSizePx, widthPx) + + assertEquals(textView.measuredHeight, storeLayout.height) + assertEquals(textView.measuredHeight, segmentLayout.height) + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt new file mode 100644 index 000000000000..9cc404ff5f6e --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt @@ -0,0 +1,460 @@ +package com.swmansion.enriched.markdown + +import android.graphics.Typeface +import android.text.SpannableString +import android.text.StaticLayout +import android.text.TextPaint +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.spans.BaseListSpan +import com.swmansion.enriched.markdown.spans.ListMarkerAnchorSpan +import com.swmansion.enriched.markdown.spans.OrderedListSpan +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.render +import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.styleConfig +import com.swmansion.enriched.markdown.test.MarkerCanvas +import com.swmansion.enriched.markdown.test.MarkerGeometry +import com.swmansion.enriched.markdown.test.TestAstFactory.listItem +import com.swmansion.enriched.markdown.test.TestAstFactory.orderedList +import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph +import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem +import com.swmansion.enriched.markdown.test.TestAstFactory.text +import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import kotlin.math.ceil + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class ListRenderingTest { + @Test + fun shortListsKeepTheirIndentAndLongListsShareTheirWidestGutter() { + val style = listStyle() + val paint = + TextPaint().apply { + textSize = style.listStyle.fontSize + typeface = Typeface.create("monospace", Typeface.NORMAL) + } + val baseline = paint.measureText("99.") + val gap = style.listStyle.gapWidth + val short = orderedSpans(style, numbered(1, 99)) + short.forEach { assertEquals((baseline + gap).toInt(), it.getLeadingMargin(false)) } + for ((start, count) in listOf(1 to 250, 98 to 4, 998 to 4, 12345 to 4, 0 to 101)) { + val spans = orderedSpans(style, numbered(start, count)) + val widest = maxOf(baseline, spans.maxOf { paint.measureText("${it.itemNumber}.") }) + spans.forEach { assertEquals((baseline + ceil(widest - baseline) + gap).toInt(), it.getLeadingMargin(false)) } + assertTrue(spans.first().getLeadingMargin(false) > short.first().getLeadingMargin(false)) + } + } + + @Test + fun nestedAndFollowingListsRestoreTheirOwnGutters() { + val style = listStyle() + val spans = orderedSpans(style, withChild(numbered(98, 4), 0, numbered(9998, 4)), numbered(1, 1)) + val parent = spans.filter { it.depth == 0 && it.itemNumber != 1 } + assertEquals(4, parent.size) + parent.forEach { assertEquals(parent.first().getLeadingMargin(false), it.getLeadingMargin(false)) } + spans.filter { it.depth == 1 }.forEach { assertTrue(it.getLeadingMargin(false) > style.listStyle.marginLeft) } + val following = spans.single { it.depth == 0 && it.itemNumber == 1 } + assertTrue(following.getLeadingMargin(false) < parent.first().getLeadingMargin(false)) + } + + @Test + fun markerMinimumWidthRemainsAFloor() { + val style = listStyle(minWidth = 200.0) + orderedSpans(style, numbered(998, 4)).forEach { + assertEquals((style.listStyle.markerMinWidth + style.listStyle.gapWidth).toInt(), it.getLeadingMargin(false)) + } + } + + @Test + fun drawnMarkersStayInsideTheGutterAndAttachedToTheirParagraphs() { + val style = listStyle() + for (start in listOf(1, 98, 9998)) { + val threeLevels = withChild(numbered(1, 1), 0, numbered(1, 1)) + assertDrawnMarkerPositions(style, withChild(numbered(start, 4), 2, threeLevels)) + } + } + + @Test + fun nestedBulletColumnsKeepTheirGapUnderWideParents() { + val style = listStyle() + + fun tree(start: Int) = withChild(numbered(start, 4), 2, unorderedList(item(), item())) + for (start in listOf(98, 9998)) { + assertNestedMarkerGapsUnchanged(style, tree(1), tree(start)) + } + } + + @Test + fun tasksMoveWithTheirWideNumberedSiblings() { + val style = listStyle() + + fun tree(start: Int): MarkdownASTNode { + val items = numbered(start, 3).children.toMutableList() + items[1] = taskListItem(checked = false, paragraph(text("item")), numbered(1, 1)) + items[2] = listItem(paragraph(text("item")), numbered(1, 1)) + return orderedList(*items.toTypedArray(), start = start) + } + assertEveryRowShiftsTogether(style, tree(1), tree(12345)) + } + + @Test + fun nestedTasksKeepTheirGapUnderWideNumericParents() { + val style = listStyle() + + fun tree(start: Int) = withChild(numbered(start, 4), 2, orderedList(taskListItem(checked = false, paragraph(text("item"))))) + for (start in listOf(98, 9998)) { + assertNestedMarkerGapsUnchanged(style, tree(1), tree(start)) + } + } + + @Test + fun sameTypeBulletAndTaskNestsKeepTheirMarkerGap() { + val style = listStyle() + val bullet = unorderedList(item()) + val task = orderedList(taskListItem(checked = false, paragraph(text("item")))) + for (parent in listOf(bullet, task)) { + assertDrawnMarkerPositions(style, withChild(parent, 0, parent)) + } + } + + @Test + fun mixedNestsStartTheirTextFromTheirOwnMarkerColumn() { + val style = mixedStyle() + // Each child's text sits one marginLeft plus its own column and gap in: 24 + (3, 22 or 14) + 6. + val indents = mapOf(Kind.BULLET to 33f, Kind.ORDERED to 52f, Kind.TASK to 44f) + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val markers = drawMarkers(style, list(parent, list(child, checked = checked), checked)) + assertEquals(listOf(0, 1), markers.map { it.depth }) + assertEquals("$child under $parent", indents.getValue(child), markers.last().paragraphLeft, 0f) + assertMixedGaps(markers, "$child under $parent, checked=$checked") + } + } + } + } + + @Test + fun topLevelAndSameTypeNestsKeepTheirGeometry() { + val style = mixedStyle() + for (kind in Kind.entries) { + val column = columnOf(style, kind) + val markers = drawMarkers(style, list(kind, list(kind, list(kind)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $kind at depth ${it.depth}", (column + MIXED_GAP).toInt() + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(column + it.depth * 24f, it.marker.right, 0.01f) + } + } + } + + @Test + fun mixedColumnsUseAbsoluteIndentsWithoutFractionalDrift() { + val alternating = listOf(Kind.BULLET, Kind.ORDERED, Kind.BULLET, Kind.TASK) + val sameTypeRun = List(5) { Kind.BULLET } + Kind.TASK + for (margin in listOf(24.0, 24.5, 4.0)) { + val style = mixedStyle(bulletSize = 6.5, marginLeft = margin) + for (kinds in listOf(alternating, sameTypeRun)) { + val columns = kinds.map { columnOf(style, it) } + val tree = kinds.dropLast(1).foldRight(list(kinds.last())) { kind, child -> list(kind, child) } + val markers = drawMarkers(style, tree) + assertEquals(kinds.indices.toList(), markers.map { it.depth }) + markers.forEach { + val expected = (it.depth * margin + columns[it.depth] + MIXED_GAP).toInt().toFloat() + assertEquals("absolute indent at depth ${it.depth} of $kinds, margin $margin", expected, it.paragraphLeft, 0f) + assertEquals(it.paragraphLeft - MIXED_GAP, it.marker.right, 0.99f) + } + } + } + } + + @Test + fun mixedAncestorsAndFollowingSiblingsRestoreTheirOwnColumns() { + val style = mixedStyle() + for (parent in Kind.entries) { + val tree = list(parent).copy(children = Kind.entries.map { child -> item(parent, list(child, list(parent))) }) + assertMixedGaps(drawMarkers(style, tree, list(Kind.BULLET), list(Kind.ORDERED), list(Kind.TASK)), "under $parent") + } + } + + @Test + fun mixedNestsAroundWideNumberedListsKeepTheirMarkerGap() { + val style = mixedStyle() + val wide = numbered(12345, 2) + val wideWithTask = orderedList(item(), item(Kind.TASK, list(Kind.BULLET)), start = 998) + val shapes = + listOf( + withChild(wide, 0, list(Kind.BULLET)), + withChild(wide, 1, list(Kind.TASK, list(Kind.BULLET))), + list(Kind.BULLET, wide), + list(Kind.TASK, wide), + withChild(numbered(998, 4), 3, withChild(wide, 0, list(Kind.BULLET))), + list(Kind.BULLET, withChild(wide, 1, list(Kind.TASK))), + withChild(wideWithTask, 0, list(Kind.BULLET)), + ) + for ((index, shape) in shapes.withIndex()) { + assertMixedGaps(drawMarkers(style, shape), "shape $index") + } + } + + @Test + fun wrappedLinesKeepTheChildsOwnColumn() { + val style = mixedStyle() + val wrapped = orderedList(listItem(paragraph(text("wrapped child text ".repeat(12))))) + val text = SpannableString(render(style, list(Kind.BULLET, wrapped))) + val layout = StaticLayout.Builder.obtain(text, 0, text.length, TextPaint(), 180).build() + val span = text.getSpans(0, text.length, OrderedListSpan::class.java).single() + val firstLine = layout.getLineForOffset(text.getSpanStart(span)) + val lastLine = layout.getLineForOffset(text.getSpanEnd(span) - 1) + assertTrue(lastLine > firstLine) + val column = columnOf(style, Kind.ORDERED) + for (line in firstLine..lastLine) { + assertEquals((24f + column + MIXED_GAP).toInt(), layout.getParagraphLeft(line)) + } + val markers = MarkerCanvas.drawMarkers(layout) + assertEquals(2, markers.size) + assertEquals(24f + column, markers.last().right, 0.01f) + } + + @Test + fun rtlMixedNestsKeepTheirMarkerGapAtEveryDepth() { + fun rtl(node: MarkdownASTNode): MarkdownASTNode { + if (node.type == MarkdownASTNode.NodeType.Text) return node.copy(content = "\u05e4\u05e8\u05d9\u05d8") + return node.copy(children = node.children.map { rtl(it) }) + } + + val style = mixedStyle() + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val tree = list(parent, list(child, list(parent, checked = checked), checked), checked) + val text = SpannableString(render(style, rtl(tree))) + val markers = MarkerCanvas.markerGeometry(text, MarkerCanvas.layout(text, style.listStyle.fontSize, rtl = true)) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("RTL paragraph at depth ${it.depth}", -1, it.direction) + // Bullets are centered on the column edge, so their recorded right is that edge in both directions. + val kind = if (it.depth == 1) child else parent + val edge = if (kind == Kind.BULLET) it.marker.right else it.marker.left + assertEquals("$child under $parent, checked=$checked, depth ${it.depth}", it.paragraphRight + MIXED_GAP, edge, 0.01f) + } + } + } + } + } + + @Test + fun equalMinimumColumnsKeepTheirGeometryForMixedNests() { + val style = mixedStyle(markerMinWidth = 40.0) + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + val markers = drawMarkers(style, list(parent, list(child, list(parent)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $child under $parent at depth ${it.depth}", 46f + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(40f + it.depth * 24f, it.marker.right, 0.01f) + } + } + } + } + + @Test + fun markersAnchoredOnANestedListKeepTheirAncestorsOffset() { + val style = listStyle() + // The middle item opens with its sublist, so its marker is drawn by an anchor span. + val middle = orderedList(listItem(numbered(1, 1)), start = 1) + val text = SpannableString(render(style, withChild(numbered(12345, 1), 0, middle))) + assertEquals(1, text.getSpans(0, text.length, ListMarkerAnchorSpan::class.java).size) + val markers = MarkerCanvas.drawMarkers(MarkerCanvas.layout(text, style.listStyle.fontSize)) + assertEquals(3, markers.size) + val (root, anchored, leaf) = markers.sortedBy { it.right } + assertEquals(root.right + style.listStyle.marginLeft, anchored.right, 0.01f) + assertEquals(anchored.right + style.listStyle.marginLeft, leaf.right, 0.01f) + assertTrue(markers.all { it.left >= 0f }) + } + + @Test + fun inheritedMarkerOffsetsFollowTheRtlDirection() { + val style = listStyle() + val text = SpannableString(render(style, withChild(numbered(12345, 1), 0, numbered(1, 1)))) + val layout = MarkerCanvas.layout(text, style.listStyle.fontSize, rtl = true) + val markers = MarkerCanvas.drawMarkers(layout) + assertEquals(2, markers.size) + markers.forEach { marker -> + val line = layout.getLineForVertical(marker.baseline.toInt()) + assertEquals(-1, layout.getParagraphDirection(line)) + assertEquals(layout.getParagraphRight(line) + style.listStyle.gapWidth, marker.left, 0.01f) + assertTrue(marker.right <= layout.width) + } + } + + private fun assertMixedGaps( + markers: List, + shape: String, + ) { + assertTrue(markers.isNotEmpty()) + markers.forEach { + assertEquals("marker gap at depth ${it.depth}, $shape", it.paragraphLeft - MIXED_GAP, it.marker.right, 0.01f) + } + } + + private fun assertDrawnMarkerPositions( + style: StyleConfig, + vararg lists: MarkdownASTNode, + ) { + drawMarkers(style, *lists).forEach { geometry -> + assertEquals( + "marker right at depth ${geometry.depth}", + geometry.paragraphLeft - style.listStyle.gapWidth, + geometry.marker.right, + 0.01f, + ) + } + } + + /** The rows [wide] shares with [short], tasks and their children included, all sit [wide]'s widening further right. */ + private fun assertEveryRowShiftsTogether( + style: StyleConfig, + short: MarkdownASTNode, + wide: MarkdownASTNode, + ) { + val shortRows = drawMarkers(style, short) + val wideRows = drawMarkers(style, wide).take(shortRows.size) + assertEquals(shortRows.size, wideRows.size) + val shift = wideRows.first().paragraphLeft - shortRows.first().paragraphLeft + assertTrue(shift > 0f) + wideRows.zip(shortRows).forEach { (actual, control) -> + assertEquals(control.depth, actual.depth) + assertEquals("text shift at depth ${actual.depth}", shift, actual.paragraphLeft - control.paragraphLeft, 0.01f) + assertEquals( + "marker gap at depth ${actual.depth}", + control.paragraphLeft - control.marker.right, + actual.paragraphLeft - actual.marker.right, + 0.01f, + ) + } + } + + private fun assertNestedMarkerGapsUnchanged( + style: StyleConfig, + short: MarkdownASTNode, + wide: MarkdownASTNode, + ) { + val shortMarkers = drawMarkers(style, short).filter { it.depth > 0 } + val wideMarkers = drawMarkers(style, wide).filter { it.depth > 0 } + assertTrue(shortMarkers.isNotEmpty()) + assertEquals(shortMarkers.size, wideMarkers.size) + shortMarkers.zip(wideMarkers).forEach { (control, actual) -> + assertEquals(control.depth, actual.depth) + assertEquals( + "nested marker gap at depth ${actual.depth}", + control.paragraphLeft - control.marker.right, + actual.paragraphLeft - actual.marker.right, + 0.01f, + ) + } + } + + private fun drawMarkers( + style: StyleConfig, + vararg lists: MarkdownASTNode, + ): List { + // SpannableString reports spans in insertion order, as the text view does. + val text = SpannableString(render(style, *lists)) + val geometry = MarkerCanvas.markerGeometry(text, MarkerCanvas.layout(text, style.listStyle.fontSize)) + assertEquals(text.getSpans(0, text.length, BaseListSpan::class.java).count { it.drawsMarker }, geometry.size) + geometry.forEach { assertTrue("marker left ${it.marker.left} at depth ${it.depth}", it.marker.left >= 0f) } + return geometry + } + + private fun orderedSpans( + style: StyleConfig, + vararg lists: MarkdownASTNode, + ): List { + val text = render(style, *lists) + return text + .getSpans(0, text.length, OrderedListSpan::class.java) + .sortedWith(compareBy({ text.getSpanStart(it) }, { it.depth })) + } + + private fun item(): MarkdownASTNode = listItem(paragraph(text("item"))) + + private fun numbered( + start: Int, + count: Int, + ): MarkdownASTNode = orderedList(*Array(count) { item() }, start = start) + + private fun withChild( + list: MarkdownASTNode, + index: Int, + child: MarkdownASTNode, + ): MarkdownASTNode { + val items = list.children.toMutableList() + items[index] = items[index].copy(children = items[index].children + child) + return list.copy(children = items) + } + + private fun listStyle(minWidth: Double = 0.0): StyleConfig = + styleConfig(list = mapOf("fontFamily" to "monospace", "markerMinWidth" to minWidth)) + + private enum class Kind { ORDERED, BULLET, TASK } + + private fun list( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val item = item(kind, child, checked) + return if (kind == Kind.ORDERED) orderedList(item) else unorderedList(item) + } + + private fun item( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val children = listOfNotNull(paragraph(text("item")), child).toTypedArray() + return if (kind == Kind.TASK) taskListItem(checked, *children) else listItem(*children) + } + + private fun checkedStates( + parent: Kind, + child: Kind, + ) = if (parent == Kind.TASK || child == Kind.TASK) listOf(false, true) else listOf(false) + + /** The marker column [kind] reserves before any widening, read from a rendered top-level item. */ + private fun columnOf( + style: StyleConfig, + kind: Kind, + ): Float { + val text = render(style, list(kind)) + return text.getSpans(0, text.length, BaseListSpan::class.java).single().baselineMarkerWidth + } + + private fun mixedStyle( + markerMinWidth: Double = 0.0, + bulletSize: Double = 6.0, + marginLeft: Double = 24.0, + ): StyleConfig = + styleConfig( + list = + mapOf( + "bulletSize" to bulletSize, + "markerMinWidth" to markerMinWidth, + "gapWidth" to MIXED_GAP.toDouble(), + "marginLeft" to marginLeft, + ), + taskList = mapOf("checkboxSize" to 14.0), + ) + + private companion object { + const val MIXED_GAP = 6f + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MarkdownRenderDispatchTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MarkdownRenderDispatchTest.kt new file mode 100644 index 000000000000..2959e2902d3e --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MarkdownRenderDispatchTest.kt @@ -0,0 +1,46 @@ +package com.swmansion.enriched.markdown + +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.junit.Assert.* +import org.junit.Test + +class MarkdownRenderDispatchTest { + @Test fun populatedViewUpdatesBeforeReturningEvenWithBusyWorker() { + val executor = Executors.newSingleThreadExecutor() + val release = CountDownLatch(1) + val started = CountDownLatch(1) + try { + executor.execute { started.countDown(); release.await() } + assertTrue(started.await(5, TimeUnit.SECONDS)) + val caller = Thread.currentThread() + var rendered = false + dispatchMarkdownRender(true, executor) { + assertSame(caller, Thread.currentThread()) + rendered = true + } + assertTrue(rendered) + } finally { + release.countDown() + executor.shutdownNow() + } + } + + @Test fun firstMountPreparesOnWorker() { + val executor = Executors.newSingleThreadExecutor() + val finished = CountDownLatch(1) + val caller = Thread.currentThread() + var worker: Thread? = null + try { + dispatchMarkdownRender(false, executor) { + worker = Thread.currentThread() + finished.countDown() + } + assertTrue(finished.await(5, TimeUnit.SECONDS)) + assertNotSame(caller, worker) + } finally { + executor.shutdownNow() + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt new file mode 100644 index 000000000000..b3394c4fc60a --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt @@ -0,0 +1,51 @@ +package com.swmansion.enriched.markdown + +import org.junit.Assert.* +import org.junit.Test + +class MeasurementSizeCacheTest { + private fun key(markdown: String = "hello", propsHash: Int = 1, width: Float = 320f) = + MeasurementSizeCache.Key(markdown, propsHash, width, true) + + @Test fun reusesSizeAcrossIndependentEqualKeys() { + val cache = MeasurementSizeCache(2) + cache.put(key(), 42L) + assertEquals(42L, cache.get(key())) + assertNull(cache.get(key(propsHash = 2))) + assertNull(cache.get(key(width = 321f))) + assertNull(cache.get(key().copy(splitTableSegments = false))) + } + + @Test fun comparesMarkdownEvenWhenItsHashCollides() { + val cache = MeasurementSizeCache(2) + assertEquals("Aa".hashCode(), "BB".hashCode()) + cache.put(key("Aa"), 42L) + assertNull(cache.get(key("BB"))) + } + + @Test fun evictsLeastRecentlyUsedSize() { + val cache = MeasurementSizeCache(2) + cache.put(key("one"), 1L) + cache.put(key("two"), 2L) + assertEquals(1L, cache.get(key("one"))) + cache.put(key("three"), 3L) + assertNull(cache.get(key("two"))) + assertEquals(1L, cache.get(key("one"))) + assertEquals(3L, cache.get(key("three"))) + } + + @Test fun invalidatesAllWidthsAndPropsForChangedContent() { + val cache = MeasurementSizeCache(4) + cache.put(key(), 1L) + cache.put(key(width = 640f), 2L) + cache.put(key(propsHash = 2), 3L) + cache.put(key("other"), 4L) + cache.removeMatchingMarkdown("hello") + assertNull(cache.get(key())) + assertNull(cache.get(key(width = 640f))) + assertNull(cache.get(key(propsHash = 2))) + assertEquals(4L, cache.get(key("other"))) + cache.clear() + assertNull(cache.get(key("other"))) + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt new file mode 100644 index 000000000000..4ade5adce9a2 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt @@ -0,0 +1,119 @@ +package com.swmansion.enriched.markdown + +import android.text.Spanned +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.spans.BaseListSpan +import com.swmansion.enriched.markdown.spans.ListMarkerAnchorSpan +import com.swmansion.enriched.markdown.spans.TaskListSpan +import com.swmansion.enriched.markdown.test.DrawnMarker +import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.render +import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.styleConfig +import com.swmansion.enriched.markdown.test.MarkerCanvas +import com.swmansion.enriched.markdown.test.TestAstFactory.listItem +import com.swmansion.enriched.markdown.test.TestAstFactory.orderedList +import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph +import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem +import com.swmansion.enriched.markdown.test.TestAstFactory.text +import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList +import com.swmansion.enriched.markdown.utils.text.interaction.TaskListTapUtils +import com.swmansion.enriched.markdown.utils.text.view.setupAsMarkdownTextView +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class TaskListInteractionTest { + private val context = RuntimeEnvironment.getApplication() + + @Test + fun togglingATaskUnderAWideParentKeepsEveryMarginAndMarkerPosition() { + assertTaskToggleKeepsGeometry(wideParentTree(opensWithSublist = false), anchors = 0, markers = 4) + } + + @Test + fun togglingAnAnchoredTaskUnderAWideParentKeepsEveryMarginAndMarkerPosition() { + assertTaskToggleKeepsGeometry(wideParentTree(opensWithSublist = true), anchors = 1, markers = 4) + } + + @Test + fun togglingATaskInAMixedNestKeepsEveryMarginAndMarkerPosition() { + // The task's indent depends on its parent's marker column, so the toggled copy has to keep it. + val tasks = unorderedList(taskListItem(checked = false, paragraph(text("item")), numbered(1))) + val parent = listItem(paragraph(text("item")), tasks) + for (tree in listOf(unorderedList(parent), orderedList(parent))) { + assertTaskToggleKeepsGeometry(tree, anchors = 0, markers = 3) + } + } + + private fun wideParentTree(opensWithSublist: Boolean): MarkdownASTNode { + val taskChildren = if (opensWithSublist) arrayOf(numbered(1)) else arrayOf(paragraph(text("item")), numbered(1)) + val task = taskListItem(checked = false, *taskChildren) + return orderedList(listItem(paragraph(text("item")), unorderedList(task)), item(), start = 100) + } + + // Layout draws leading margins in span insertion order, so a toggle that re-adds only the + // task's span would move its checkbox by its ancestors' margins. + private fun assertTaskToggleKeepsGeometry( + tree: MarkdownASTNode, + anchors: Int, + markers: Int, + ) { + val style = styleConfig(list = mapOf("fontFamily" to "monospace")) + val textView = + object : AccessibleMarkdownTextView(context) {}.apply { + layoutParams = ViewGroup.LayoutParams(MarkerCanvas.LAYOUT_WIDTH, ViewGroup.LayoutParams.WRAP_CONTENT) + setupAsMarkdownTextView() + } + textView.setText(render(style, tree), TextView.BufferType.SPANNABLE) + val initialText = textView.text as Spanned + val taskIndex = initialText.getSpans(0, initialText.length, TaskListSpan::class.java).single().taskIndex + assertEquals(anchors, initialText.getSpans(0, initialText.length, ListMarkerAnchorSpan::class.java).size) + val initialMargins = listMargins(initialText) + val initialMarkers = drawTextViewMarkers(textView) + assertEquals(markers, initialMarkers.size) + + for (checked in listOf(true, false)) { + assertTrue(TaskListTapUtils.updateTaskListItemCheckedState(textView, taskIndex, checked, style)) + val text = textView.text as Spanned + val tasks = text.getSpans(0, text.length, TaskListSpan::class.java) + assertTrue(tasks.isNotEmpty()) + tasks.forEach { assertEquals(checked, it.isChecked) } + text.getSpans(0, text.length, ListMarkerAnchorSpan::class.java).forEach { + assertEquals(checked, (it.marker as TaskListSpan).isChecked) + } + assertEquals("list margins after checked=$checked", initialMargins, listMargins(text)) + assertEquals("drawn markers after checked=$checked", initialMarkers, drawTextViewMarkers(textView)) + } + } + + private fun listMargins(text: Spanned): List> = + text + .getSpans(0, text.length, BaseListSpan::class.java) + .sortedWith(compareBy({ text.getSpanStart(it) }, { it.depth }, { text.getSpanEnd(it) })) + .map { listOf(text.getSpanStart(it), text.getSpanEnd(it), it.depth, it.getLeadingMargin(true), it.getLeadingMargin(false)) } + + private fun drawTextViewMarkers(textView: TextView): List { + textView.forceLayout() + textView.measure( + View.MeasureSpec.makeMeasureSpec(MarkerCanvas.LAYOUT_WIDTH, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), + ) + textView.layout(0, 0, textView.measuredWidth, textView.measuredHeight) + return MarkerCanvas.drawMarkers(textView.layout) + } + + private fun item(): MarkdownASTNode = listItem(paragraph(text("item"))) + + private fun numbered(count: Int): MarkdownASTNode = orderedList(*Array(count) { item() }, start = 1) +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt new file mode 100644 index 000000000000..7d925cc12c60 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt @@ -0,0 +1,121 @@ +package com.swmansion.enriched.markdown.test + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Rect +import android.graphics.RectF +import android.text.Layout +import android.text.Spanned +import android.text.StaticLayout +import android.text.TextDirectionHeuristics +import android.text.TextPaint +import com.swmansion.enriched.markdown.spans.BaseListSpan + +/** A list marker as the layout drew it: a number, a bullet, or a checkbox. */ +data class DrawnMarker( + val left: Float, + val right: Float, + val baseline: Float, +) + +/** A drawn marker with the text edges, direction and list depth of the paragraph it belongs to. */ +data class MarkerGeometry( + val marker: DrawnMarker, + val paragraphLeft: Float, + val depth: Int, + val paragraphRight: Float, + val direction: Int, +) + +/** Records the list markers a layout draws instead of painting them. */ +class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.ARGB_8888)) { + val markers = mutableListOf() + + // Layout draws only the lines inside the clip; report one tall enough for every list. + override fun getClipBounds(bounds: Rect): Boolean { + bounds.set(0, 0, LAYOUT_WIDTH, Int.MAX_VALUE / 2) + return true + } + + override fun drawCircle( + cx: Float, + cy: Float, + radius: Float, + paint: Paint, + ) { + // Bullets are centered on the reserved column edge, matching the iOS drawer. + val outerRadius = radius + paint.strokeWidth / 2f + markers += DrawnMarker(cx - outerRadius, cx, cy) + super.drawCircle(cx, cy, radius, paint) + } + + override fun drawRect( + left: Float, + top: Float, + right: Float, + bottom: Float, + paint: Paint, + ) { + // Bullets from depth 2 on are squares, centered like the round ones. + markers += DrawnMarker(left, (left + right) / 2f, (top + bottom) / 2f) + super.drawRect(left, top, right, bottom, paint) + } + + override fun drawRoundRect( + rect: RectF, + rx: Float, + ry: Float, + paint: Paint, + ) { + val halfStroke = if (paint.style == Paint.Style.STROKE) paint.strokeWidth / 2f else 0f + markers += DrawnMarker(rect.left - halfStroke, rect.right + halfStroke, rect.centerY()) + super.drawRoundRect(rect, rx, ry, paint) + } + + override fun drawText( + text: String, + x: Float, + y: Float, + paint: Paint, + ) { + if (text.matches(Regex("(?:[0-9]+\\.|\\.[0-9]+)"))) markers += DrawnMarker(x, x + paint.measureText(text), y) + super.drawText(text, x, y, paint) + } + + companion object { + const val LAYOUT_WIDTH = 2000 + + fun layout( + text: CharSequence, + textSize: Float, + rtl: Boolean = false, + ): StaticLayout = + StaticLayout.Builder + .obtain(text, 0, text.length, TextPaint().apply { this.textSize = textSize }, LAYOUT_WIDTH) + .apply { if (rtl) setTextDirection(TextDirectionHeuristics.RTL) } + .build() + + /** The markers [layout] draws, top to bottom. */ + fun drawMarkers(layout: Layout): List = + MarkerCanvas().also(layout::draw).markers.sortedWith(compareBy({ it.baseline }, { it.left })) + + /** Every marker [layout] draws, with the text edges, direction and depth of its paragraph. */ + fun markerGeometry( + text: Spanned, + layout: Layout, + ): List = + drawMarkers(layout).map { marker -> + val line = layout.getLineForVertical(marker.baseline.toInt()) + val start = layout.getLineStart(line) + val depth = text.getSpans(start, start + 1, BaseListSpan::class.java).maxOf { it.depth } + MarkerGeometry( + marker, + layout.getParagraphLeft(line).toFloat(), + depth, + layout.getParagraphRight(line).toFloat(), + layout.getParagraphDirection(line), + ) + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt new file mode 100644 index 000000000000..645ce339d58d --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt @@ -0,0 +1,126 @@ +package com.swmansion.enriched.markdown.test + +import android.content.Context +import android.graphics.Color +import android.text.Spannable +import com.facebook.react.bridge.JavaOnlyArray +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.renderer.Renderer +import com.swmansion.enriched.markdown.styles.StyleConfig +import org.robolectric.RuntimeEnvironment + +object MarkdownRenderTestSupport { + // Resolved per call, not cached: a @Config qualifier applies to the current test's context. + private val context: Context + get() = RuntimeEnvironment.getApplication() + + fun render( + style: StyleConfig, + vararg blocks: MarkdownASTNode, + ): Spannable { + val renderer = Renderer() + renderer.configure(style, context) + return renderer.renderContent(blocks.toList()) + } + + /** + * The style map the JS side sends, with [list] and [taskList] entries replacing the defaults. + * Sizes are Double, colors Int, as in a ReadableMap. + */ + fun styleConfig( + list: Map = emptyMap(), + taskList: Map = emptyMap(), + ): StyleConfig { + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context) + val style = JavaOnlyMap() + listOf("paragraph", "strong", "em", "strikethrough", "code", "superscript", "subscript", "highlight") + .forEach { style.putMap(it, textElement()) } + style.putMap("link", textElement().apply { putString("fontFamily", "serif") }) + style.putArray( + "linkVariants", + JavaOnlyArray.of( + textElement().apply { + putString("pattern", "^ref:") + putString("fontFamily", "monospace") + putInt("color", Color.BLUE) + }, + ), + ) + style.putMap( + "spoiler", + textElement().apply { + putMap("particles", JavaOnlyMap.of("density", 0.5, "speed", 1.0)) + putMap("solid", JavaOnlyMap.of("borderRadius", 0.0)) + }, + ) + style.putMap("taskList", JavaOnlyMap().apply { putAll(defaultTaskList + taskList) }) + style.putMap("list", textElement().apply { putAll(defaultList + list) }) + return StyleConfig(style, context, false, 0f) + } + + private val defaultList: Map = + mapOf( + "fontFamily" to "", + "bulletColor" to Color.BLACK, + "markerColor" to Color.BLACK, + "bulletSize" to 6.0, + "markerMinWidth" to 0.0, + "gapWidth" to 8.0, + "marginLeft" to 24.0, + "itemSpacing" to 0.0, + ) + + private val defaultTaskList: Map = + mapOf( + "checkedColor" to Color.BLACK, + "borderColor" to Color.BLACK, + "checkmarkColor" to Color.BLACK, + "checkedTextColor" to Color.BLACK, + "checkboxSize" to 16.0, + "checkboxBorderRadius" to 0.0, + "checkedStrikethrough" to false, + ) + + private fun textElement(): JavaOnlyMap = + JavaOnlyMap.of( + "fontFamily", + "", + "fontWeight", + "normal", + "fontSize", + 16.0, + "lineHeight", + 0.0, + "marginTop", + 0.0, + "marginBottom", + 0.0, + "color", + Color.BLACK, + "backgroundColor", + Color.TRANSPARENT, + "borderColor", + Color.TRANSPARENT, + "underline", + false, + "fontScale", + 0.8, + "baselineOffsetScale", + 0.5, + ) + + private fun JavaOnlyMap.putAll(values: Map) { + for ((key, value) in values) { + when (value) { + is String -> putString(key, value) + is Boolean -> putBoolean(key, value) + is Int -> putInt(key, value) + is Double -> putDouble(key, value) + is Float -> putDouble(key, value.toDouble()) + else -> error("Unsupported style value for $key: $value") + } + } + } +} diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/TestAstFactory.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/TestAstFactory.kt new file mode 100644 index 000000000000..1808c3414cb5 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/TestAstFactory.kt @@ -0,0 +1,36 @@ +package com.swmansion.enriched.markdown.test + +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType + +object TestAstFactory { + fun paragraph(vararg children: MarkdownASTNode): MarkdownASTNode = MarkdownASTNode(NodeType.Paragraph, children = children.toList()) + + fun text(content: String): MarkdownASTNode = MarkdownASTNode(NodeType.Text, content = content) + + /** An ordered list; [start] is the first number, as md4c reports it. */ + fun orderedList( + vararg items: MarkdownASTNode, + start: Int? = null, + ): MarkdownASTNode = + MarkdownASTNode( + type = NodeType.OrderedList, + attributes = start?.let { mapOf("start" to it.toString()) }.orEmpty(), + children = items.toList(), + ) + + fun unorderedList(vararg items: MarkdownASTNode): MarkdownASTNode = MarkdownASTNode(NodeType.UnorderedList, children = items.toList()) + + fun listItem(vararg children: MarkdownASTNode): MarkdownASTNode = MarkdownASTNode(NodeType.ListItem, children = children.toList()) + + /** A GFM task-list item, what md4c produces for `- [ ]` / `- [x]`. */ + fun taskListItem( + checked: Boolean, + vararg children: MarkdownASTNode, + ): MarkdownASTNode = + MarkdownASTNode( + type = NodeType.ListItem, + attributes = mapOf("isTask" to "true", "taskChecked" to checked.toString()), + children = children.toList(), + ) +} diff --git a/packages/react-native-enriched-markdown/android/src/video/java/com/swmansion/enriched/markdown/segments/VideoContainerView.kt b/packages/react-native-enriched-markdown/android/src/video/java/com/swmansion/enriched/markdown/segments/VideoContainerView.kt new file mode 100644 index 000000000000..975df1338881 --- /dev/null +++ b/packages/react-native-enriched-markdown/android/src/video/java/com/swmansion/enriched/markdown/segments/VideoContainerView.kt @@ -0,0 +1,115 @@ +package com.swmansion.enriched.markdown.segments + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.net.Uri +import android.widget.FrameLayout +import androidx.media3.common.MediaItem +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.ui.PlayerView +import com.swmansion.enriched.markdown.parser.MarkdownASTNode +import com.swmansion.enriched.markdown.styles.StyleConfig +import com.swmansion.enriched.markdown.views.ContextMenuPopup +import kotlin.math.roundToInt + +class VideoContainerView( + context: Context, + private val styleConfig: StyleConfig, +) : FrameLayout(context), + BlockSegmentView { + private val playerView = PlayerView(context) + private var player: ExoPlayer? = null + private var currentUrl: String? = null + var dynamicProps: DynamicBlockProps = DynamicBlockProps() + + override val segmentMarginTop: Int get() = styleConfig.videoStyle.marginTop.toInt() + override val segmentMarginBottom: Int get() = styleConfig.videoStyle.marginBottom.toInt() + + init { + val videoStyle = styleConfig.videoStyle + setBackgroundColor(videoStyle.backgroundColor) + clipToOutline = true + outlineProvider = RoundedOutlineProvider(videoStyle.borderRadius) + + playerView.apply { + clipToOutline = true + outlineProvider = RoundedOutlineProvider(videoStyle.borderRadius) + } + + addView(playerView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + + isLongClickable = true + setOnLongClickListener { view -> showContextMenu(view) } + + playerView.isLongClickable = true + playerView.setOnLongClickListener { showContextMenu(it) } + } + + fun applyVideoNode(node: MarkdownASTNode) { + val url = node.getAttribute("url") ?: return + if (url == currentUrl) return + + releasePlayer() + currentUrl = url + + val exoPlayer = ExoPlayer.Builder(context).build() + exoPlayer.playWhenReady = false + exoPlayer.setMediaItem(MediaItem.fromUri(Uri.parse(url))) + exoPlayer.prepare() + player = exoPlayer + playerView.player = exoPlayer + } + + override fun onMeasure( + widthMeasureSpec: Int, + heightMeasureSpec: Int, + ) { + val width = MeasureSpec.getSize(widthMeasureSpec) + val height = (width / styleConfig.videoStyle.resolvedAspectRatio).roundToInt() + super.onMeasure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY), + ) + } + + override fun onDetachedFromWindow() { + super.onDetachedFromWindow() + releasePlayer() + } + + private fun showContextMenu(anchor: android.view.View): Boolean { + val url = currentUrl ?: return false + if (!dynamicProps.enableBlockContextMenu || url.isEmpty()) return false + ContextMenuPopup.show(anchor, this) { + item(ContextMenuPopup.Icon.COPY, dynamicProps.copyLabel) { copyToClipboard(url) } + item(ContextMenuPopup.Icon.DOCUMENT, dynamicProps.copyAsMarkdownLabel) { copyToClipboard(videoMarkdown(url)) } + } + return true + } + + private fun videoMarkdown(url: String): String = if (url.contains('"')) "

--languages a,b,c --out +// +// Writes /generated_queries.h and /generated_registry.cpp referencing +// only the selected grammars, so the link step stays valid no matter how many +// grammars are vendored. `; inherits:` directives are resolved by inlining the +// parent grammar's highlights (parents come first, child overrides). + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +const LOG_PREFIX = '[react-native-enriched-markdown]'; +const log = (message) => console.log(`${LOG_PREFIX} ${message}`); +const warn = (message) => console.warn(`${LOG_PREFIX} ${message}`); +const fail = (message) => { + console.error(`${LOG_PREFIX} ${message}`); + process.exit(1); +}; + +function parseArgs(argv) { + const args = { vendorDir: null, languages: [], out: null, manifest: path.join(here, 'grammar-versions.json') }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--vendor-dir') args.vendorDir = argv[++i]; + else if (a === '--languages') args.languages = argv[++i].split(',').map((s) => s.trim()).filter(Boolean); + else if (a === '--out') args.out = argv[++i]; + else if (a === '--manifest') args.manifest = argv[++i]; + } + if (!args.vendorDir || !args.out) { + fail('usage: --vendor-dir --languages a,b --out '); + } + return args; +} + +function identifier(id) { + return id.replace(/[^A-Za-z0-9]/g, '_'); +} + +function grammarFunction(id, manifest) { + const spec = manifest.grammars?.[id]; + return spec?.function ?? `tree_sitter_${identifier(id)}`; +} + +function highlightsPath(vendorDir, id) { + return path.join(vendorDir, 'grammars', id, 'highlights.scm'); +} + +const INHERITS_RE = /^[ \t]*;+[ \t]*inherits[ \t]*:[ \t]*([^\n]+)$/m; + +// Reads a grammar's highlights.scm and inlines any `; inherits:` parents that +// are also vendored. Cycle-guarded; a missing parent is skipped with a warning. +function resolveHighlights(vendorDir, id, seen = new Set()) { + const file = highlightsPath(vendorDir, id); + if (!fs.existsSync(file)) { + fail(`missing vendored highlights for '${id}': ${file}`); + } + if (seen.has(id)) return ''; + seen.add(id); + + const raw = fs.readFileSync(file, 'utf8'); + const match = raw.match(INHERITS_RE); + let inherited = ''; + if (match) { + for (const parent of match[1].split(',').map((s) => s.trim()).filter(Boolean)) { + if (fs.existsSync(highlightsPath(vendorDir, parent))) { + inherited += resolveHighlights(vendorDir, parent, seen) + '\n'; + } else { + warn(`${id} inherits '${parent}' which is not vendored; skipping inheritance`); + } + } + } + const body = raw.replace(INHERITS_RE, ''); + return inherited + body; +} + +function toCStringLines(text) { + const lines = text.split('\n'); + return lines + .map((line, i) => { + // Escape backslashes, quotes, and every '?' so sequences like "??=" in a + // query never form a C trigraph. + const escaped = line.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\?/g, '\\?'); + const newline = i < lines.length - 1 ? '\\n' : ''; + return ` "${escaped}${newline}"`; + }) + .join('\n'); +} + +function main() { + const args = parseArgs(process.argv.slice(2)); + const manifest = JSON.parse(fs.readFileSync(args.manifest, 'utf8')); + fs.mkdirSync(args.out, { recursive: true }); + + const entries = args.languages.map((id) => ({ + id, + ident: identifier(id), + fn: grammarFunction(id, manifest), + query: resolveHighlights(args.vendorDir, id), + })); + + const queriesHeader = + '#pragma once\n' + + '// Generated by vendor/gen-registry.mjs. Do not edit.\n\n' + + 'namespace Markdown {\n\n' + + entries + .map((e) => `static const char kHighlightsQuery_${e.ident}[] =\n${toCStringLines(e.query)};\n`) + .join('\n') + + '\n} // namespace Markdown\n'; + + const header = + '// Generated by vendor/gen-registry.mjs. Do not edit.\n\n' + + '#include "HighlightGrammars.hpp"\n' + + '#include "generated_queries.h"\n\n' + + '#include \n\n'; + + let registryCpp; + if (entries.length === 0) { + registryCpp = + header + + 'namespace Markdown {\n\n' + + 'const GrammarEntry *findGrammar(const char * /*canonicalId*/) {\n return nullptr;\n}\n\n' + + '} // namespace Markdown\n'; + } else { + registryCpp = + header + + 'extern "C" {\n' + + entries.map((e) => `const TSLanguage *${e.fn}(void);`).join('\n') + + '\n}\n\n' + + 'namespace Markdown {\nnamespace {\n\n' + + 'constexpr GrammarEntry kGrammars[] = {\n' + + entries.map((e) => ` {"${e.id}", ${e.fn}, kHighlightsQuery_${e.ident}},`).join('\n') + + '\n};\n\n' + + '} // namespace\n\n' + + 'const GrammarEntry *findGrammar(const char *canonicalId) {\n' + + ' if (canonicalId == nullptr) {\n return nullptr;\n }\n' + + ' for (const GrammarEntry &entry : kGrammars) {\n' + + ' if (std::strcmp(entry.canonicalId, canonicalId) == 0) {\n return &entry;\n }\n }\n' + + ' return nullptr;\n}\n\n' + + '} // namespace Markdown\n'; + } + + fs.writeFileSync(path.join(args.out, 'generated_queries.h'), queriesHeader); + fs.writeFileSync(path.join(args.out, 'generated_registry.cpp'), registryCpp); + log(`wrote ${entries.length} grammar(s) to ${args.out}`); +} + +main(); diff --git a/packages/react-native-enriched-markdown/cpp/highlight/grammar-versions.json b/packages/react-native-enriched-markdown/cpp/highlight/grammar-versions.json new file mode 100644 index 000000000000..5633b06e7204 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/highlight/grammar-versions.json @@ -0,0 +1,159 @@ +{ + "$comment": "Pins the tree-sitter runtime and every supported grammar for vendor-grammars.mjs. Grammars marked default:true form the curated set compiled unless a consumer overrides the language list. Each grammar package is a devDependency of react-native-enriched-markdown and is never shipped; only the copied .c/.h/.scm files are vendored. Versions must generate an ABI in [13,15] to match the runtime. Re-pin and re-run vendor-grammars.mjs to upgrade. The postinstall script downloads grammar sources from the npm registry using the 'package' and 'version' fields.", + "runtime": { + "$comment": "tree-sitter runtime C amalgamation. Fetched at install/prepack from the pinned GitHub release tarball (lib/src + lib/include) into the gitignored vendor/tree-sitter/; WASM is compiled out by leaving TREE_SITTER_FEATURE_WASM undefined (never strip wasm_store.c, it provides the no-op stubs parser.c/language.c call). To re-pin: bump ref, run `node vendor/vendor-grammars.mjs --force`, and paste the sha256 it prints on mismatch. tarball is optional; when absent it is derived from ref.", + "package": "tree-sitter", + "ref": "v0.26.3", + "tarball": "https://github.com/tree-sitter/tree-sitter/archive/refs/tags/v0.26.3.tar.gz", + "sha256": "7f4a7cf0a2cd217444063fe2a4d800bc9d21ed609badc2ac20c0841d67166550", + "abi": { "version": 15, "minCompatible": 13 } + }, + "grammars": { + "json": { + "package": "tree-sitter-json", + "version": "0.24.8", + "scanner": false, + "default": true, + "size": "27 KB" + }, + "html": { + "package": "tree-sitter-html", + "version": "0.23.2", + "scanner": true, + "default": true, + "size": "76 KB" + }, + "css": { + "package": "tree-sitter-css", + "version": "0.23.2", + "scanner": true, + "default": true, + "size": "0.5 MB" + }, + "markdown": { + "package": "@tree-sitter-grammars/tree-sitter-markdown", + "version": "0.3.2", + "subPath": "tree-sitter-markdown", + "scanner": true, + "default": true, + "size": "1.5 MB", + "$comment": "Multi-grammar package; the block grammar (tree-sitter-markdown/) is vendored. The inline sub-grammar is not linked." + }, + "yaml": { + "package": "@tree-sitter-grammars/tree-sitter-yaml", + "version": "0.7.1", + "scanner": true, + "default": true, + "size": "1 MB" + }, + "go": { + "package": "tree-sitter-go", + "version": "0.23.4", + "scanner": false, + "default": true, + "size": "1 MB" + }, + "java": { + "package": "tree-sitter-java", + "version": "0.23.5", + "scanner": false, + "default": true, + "size": "2.5 MB" + }, + "javascript": { + "package": "tree-sitter-javascript", + "version": "0.23.1", + "scanner": true, + "default": true, + "size": "2.8 MB" + }, + "python": { + "package": "tree-sitter-python", + "version": "0.23.6", + "scanner": true, + "default": true, + "size": "3.4 MB" + }, + "c": { + "package": "tree-sitter-c", + "version": "0.23.5", + "scanner": false, + "default": true, + "size": "3.8 MB" + }, + "rust": { + "package": "tree-sitter-rust", + "version": "0.23.2", + "scanner": true, + "default": true, + "size": "6.3 MB" + }, + "bash": { + "package": "tree-sitter-bash", + "version": "0.23.3", + "scanner": true, + "default": true, + "size": "9.7 MB" + }, + + "typescript": { + "package": "tree-sitter-typescript", + "version": "0.23.2", + "subPath": "typescript", + "scanner": true, + "sharedSrc": ["../../common/scanner.h"], + "inherits": ["javascript"], + "default": true, + "size": "17 MB" + }, + "tsx": { + "package": "tree-sitter-typescript", + "version": "0.23.2", + "subPath": "tsx", + "scanner": true, + "sharedSrc": ["../../common/scanner.h"], + "inherits": ["javascript"], + "default": true, + "size": "17 MB" + }, + "cpp": { + "package": "tree-sitter-cpp", + "version": "0.23.4", + "scanner": true, + "inherits": ["c"], + "default": false, + "size": "17 MB" + }, + "swift": { + "package": "tree-sitter-swift", + "version": "0.7.0", + "scanner": true, + "default": false, + "size": "18 MB" + }, + "php": { + "package": "tree-sitter-php", + "version": "0.24.2", + "subPath": "php", + "scanner": true, + "sharedSrc": ["../../common/scanner.h"], + "default": false, + "size": "14 MB" + }, + "ruby": { + "package": "tree-sitter-ruby", + "version": "0.23.1", + "scanner": true, + "default": false, + "size": "15 MB" + }, + "c-sharp": { + "package": "tree-sitter-c-sharp", + "version": "0.23.1", + "scanner": true, + "function": "tree_sitter_c_sharp", + "default": false, + "size": "29 MB" + } + } +} diff --git a/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_queries.h b/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_queries.h new file mode 100644 index 000000000000..27eea65c2a4a --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_queries.h @@ -0,0 +1,1665 @@ +#pragma once +// Generated by vendor/gen-registry.mjs. Do not edit. + +namespace Markdown { + +static const char kHighlightsQuery_json[] = + "(pair\n" + " key: (_) @string.special.key)\n" + "\n" + "(string) @string\n" + "\n" + "(number) @number\n" + "\n" + "[\n" + " (null)\n" + " (true)\n" + " (false)\n" + "] @constant.builtin\n" + "\n" + "(escape_sequence) @escape\n" + "\n" + "(comment) @comment\n" + ""; + +static const char kHighlightsQuery_html[] = + "(tag_name) @tag\n" + "(erroneous_end_tag_name) @tag.error\n" + "(doctype) @constant\n" + "(attribute_name) @attribute\n" + "(attribute_value) @string\n" + "(comment) @comment\n" + "\n" + "[\n" + " \"<\"\n" + " \">\"\n" + " \"\"\n" + "] @punctuation.bracket\n" + ""; + +static const char kHighlightsQuery_css[] = + "(comment) @comment\n" + "\n" + "(tag_name) @tag\n" + "(nesting_selector) @tag\n" + "(universal_selector) @tag\n" + "\n" + "\"~\" @operator\n" + "\">\" @operator\n" + "\"+\" @operator\n" + "\"-\" @operator\n" + "\"*\" @operator\n" + "\"/\" @operator\n" + "\"=\" @operator\n" + "\"^=\" @operator\n" + "\"|=\" @operator\n" + "\"~=\" @operator\n" + "\"$=\" @operator\n" + "\"*=\" @operator\n" + "\n" + "\"and\" @operator\n" + "\"or\" @operator\n" + "\"not\" @operator\n" + "\"only\" @operator\n" + "\n" + "(attribute_selector (plain_value) @string)\n" + "(pseudo_element_selector (tag_name) @attribute)\n" + "(pseudo_class_selector (class_name) @attribute)\n" + "\n" + "(class_name) @property\n" + "(id_name) @property\n" + "(namespace_name) @property\n" + "(property_name) @property\n" + "(feature_name) @property\n" + "\n" + "(attribute_name) @attribute\n" + "\n" + "(function_name) @function\n" + "\n" + "((property_name) @variable\n" + " (#match\? @variable \"^--\"))\n" + "((plain_value) @variable\n" + " (#match\? @variable \"^--\"))\n" + "\n" + "\"@media\" @keyword\n" + "\"@import\" @keyword\n" + "\"@charset\" @keyword\n" + "\"@namespace\" @keyword\n" + "\"@supports\" @keyword\n" + "\"@keyframes\" @keyword\n" + "(at_keyword) @keyword\n" + "(to) @keyword\n" + "(from) @keyword\n" + "(important) @keyword\n" + "\n" + "(string_value) @string\n" + "(color_value) @string.special\n" + "\n" + "(integer_value) @number\n" + "(float_value) @number\n" + "(unit) @type\n" + "\n" + "\"#\" @punctuation.delimiter\n" + "\",\" @punctuation.delimiter\n" + "\":\" @punctuation.delimiter\n" + ""; + +static const char kHighlightsQuery_markdown[] = + ";From nvim-treesitter/nvim-treesitter\n" + "(atx_heading (inline) @text.title)\n" + "(setext_heading (paragraph) @text.title)\n" + "\n" + "[\n" + " (atx_h1_marker)\n" + " (atx_h2_marker)\n" + " (atx_h3_marker)\n" + " (atx_h4_marker)\n" + " (atx_h5_marker)\n" + " (atx_h6_marker)\n" + " (setext_h1_underline)\n" + " (setext_h2_underline)\n" + "] @punctuation.special\n" + "\n" + "[\n" + " (link_title)\n" + " (indented_code_block)\n" + " (fenced_code_block)\n" + "] @text.literal\n" + "\n" + "[\n" + " (fenced_code_block_delimiter)\n" + "] @punctuation.delimiter\n" + "\n" + "(code_fence_content) @none\n" + "\n" + "[\n" + " (link_destination)\n" + "] @text.uri\n" + "\n" + "[\n" + " (link_label)\n" + "] @text.reference\n" + "\n" + "[\n" + " (list_marker_plus)\n" + " (list_marker_minus)\n" + " (list_marker_star)\n" + " (list_marker_dot)\n" + " (list_marker_parenthesis)\n" + " (thematic_break)\n" + "] @punctuation.special\n" + "\n" + "[\n" + " (block_continuation)\n" + " (block_quote_marker)\n" + "] @punctuation.special\n" + "\n" + "[\n" + " (backslash_escape)\n" + "] @string.escape\n" + ""; + +static const char kHighlightsQuery_yaml[] = + "(boolean_scalar) @boolean\n" + "\n" + "(null_scalar) @constant.builtin\n" + "\n" + "[\n" + " (double_quote_scalar)\n" + " (single_quote_scalar)\n" + " (block_scalar)\n" + " (string_scalar)\n" + "] @string\n" + "\n" + "[\n" + " (integer_scalar)\n" + " (float_scalar)\n" + "] @number\n" + "\n" + "(comment) @comment\n" + "\n" + "[\n" + " (anchor_name)\n" + " (alias_name)\n" + "] @label\n" + "\n" + "(tag) @type\n" + "\n" + "[\n" + " (yaml_directive)\n" + " (tag_directive)\n" + " (reserved_directive)\n" + "] @attribute\n" + "\n" + "(block_mapping_pair\n" + " key: (flow_node\n" + " [\n" + " (double_quote_scalar)\n" + " (single_quote_scalar)\n" + " ] @property))\n" + "\n" + "(block_mapping_pair\n" + " key: (flow_node\n" + " (plain_scalar\n" + " (string_scalar) @property)))\n" + "\n" + "(flow_mapping\n" + " (_\n" + " key: (flow_node\n" + " [\n" + " (double_quote_scalar)\n" + " (single_quote_scalar)\n" + " ] @property)))\n" + "\n" + "(flow_mapping\n" + " (_\n" + " key: (flow_node\n" + " (plain_scalar\n" + " (string_scalar) @property))))\n" + "\n" + "[\n" + " \",\"\n" + " \"-\"\n" + " \":\"\n" + " \">\"\n" + " \"\?\"\n" + " \"|\"\n" + "] @punctuation.delimiter\n" + "\n" + "[\n" + " \"[\"\n" + " \"]\"\n" + " \"{\"\n" + " \"}\"\n" + "] @punctuation.bracket\n" + "\n" + "[\n" + " \"*\"\n" + " \"&\"\n" + " \"---\"\n" + " \"...\"\n" + "] @punctuation.special\n" + ""; + +static const char kHighlightsQuery_go[] = + "; Function calls\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "\n" + "(call_expression\n" + " function: (identifier) @function.builtin\n" + " (#match\? @function.builtin \"^(append|cap|close|complex|copy|delete|imag|len|make|new|panic|print|println|real|recover)$\"))\n" + "\n" + "(call_expression\n" + " function: (selector_expression\n" + " field: (field_identifier) @function.method))\n" + "\n" + "; Function definitions\n" + "\n" + "(function_declaration\n" + " name: (identifier) @function)\n" + "\n" + "(method_declaration\n" + " name: (field_identifier) @function.method)\n" + "\n" + "; Identifiers\n" + "\n" + "(type_identifier) @type\n" + "(field_identifier) @property\n" + "(identifier) @variable\n" + "\n" + "; Operators\n" + "\n" + "[\n" + " \"--\"\n" + " \"-\"\n" + " \"-=\"\n" + " \":=\"\n" + " \"!\"\n" + " \"!=\"\n" + " \"...\"\n" + " \"*\"\n" + " \"*\"\n" + " \"*=\"\n" + " \"/\"\n" + " \"/=\"\n" + " \"&\"\n" + " \"&&\"\n" + " \"&=\"\n" + " \"%\"\n" + " \"%=\"\n" + " \"^\"\n" + " \"^=\"\n" + " \"+\"\n" + " \"++\"\n" + " \"+=\"\n" + " \"<-\"\n" + " \"<\"\n" + " \"<<\"\n" + " \"<<=\"\n" + " \"<=\"\n" + " \"=\"\n" + " \"==\"\n" + " \">\"\n" + " \">=\"\n" + " \">>\"\n" + " \">>=\"\n" + " \"|\"\n" + " \"|=\"\n" + " \"||\"\n" + " \"~\"\n" + "] @operator\n" + "\n" + "; Keywords\n" + "\n" + "[\n" + " \"break\"\n" + " \"case\"\n" + " \"chan\"\n" + " \"const\"\n" + " \"continue\"\n" + " \"default\"\n" + " \"defer\"\n" + " \"else\"\n" + " \"fallthrough\"\n" + " \"for\"\n" + " \"func\"\n" + " \"go\"\n" + " \"goto\"\n" + " \"if\"\n" + " \"import\"\n" + " \"interface\"\n" + " \"map\"\n" + " \"package\"\n" + " \"range\"\n" + " \"return\"\n" + " \"select\"\n" + " \"struct\"\n" + " \"switch\"\n" + " \"type\"\n" + " \"var\"\n" + "] @keyword\n" + "\n" + "; Literals\n" + "\n" + "[\n" + " (interpreted_string_literal)\n" + " (raw_string_literal)\n" + " (rune_literal)\n" + "] @string\n" + "\n" + "(escape_sequence) @escape\n" + "\n" + "[\n" + " (int_literal)\n" + " (float_literal)\n" + " (imaginary_literal)\n" + "] @number\n" + "\n" + "[\n" + " (true)\n" + " (false)\n" + " (nil)\n" + " (iota)\n" + "] @constant.builtin\n" + "\n" + "(comment) @comment\n" + ""; + +static const char kHighlightsQuery_java[] = + "; Variables\n" + "\n" + "(identifier) @variable\n" + "\n" + "; Methods\n" + "\n" + "(method_declaration\n" + " name: (identifier) @function.method)\n" + "(method_invocation\n" + " name: (identifier) @function.method)\n" + "(super) @function.builtin\n" + "\n" + "; Annotations\n" + "\n" + "(annotation\n" + " name: (identifier) @attribute)\n" + "(marker_annotation\n" + " name: (identifier) @attribute)\n" + "\n" + "\"@\" @operator\n" + "\n" + "; Types\n" + "\n" + "(type_identifier) @type\n" + "\n" + "(interface_declaration\n" + " name: (identifier) @type)\n" + "(class_declaration\n" + " name: (identifier) @type)\n" + "(enum_declaration\n" + " name: (identifier) @type)\n" + "\n" + "((field_access\n" + " object: (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((scoped_identifier\n" + " scope: (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((method_invocation\n" + " object: (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((method_reference\n" + " . (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "\n" + "(constructor_declaration\n" + " name: (identifier) @type)\n" + "\n" + "[\n" + " (boolean_type)\n" + " (integral_type)\n" + " (floating_point_type)\n" + " (floating_point_type)\n" + " (void_type)\n" + "] @type.builtin\n" + "\n" + "; Constants\n" + "\n" + "((identifier) @constant\n" + " (#match\? @constant \"^_*[A-Z][A-Z\\\\d_]+$\"))\n" + "\n" + "; Builtins\n" + "\n" + "(this) @variable.builtin\n" + "\n" + "; Literals\n" + "\n" + "[\n" + " (hex_integer_literal)\n" + " (decimal_integer_literal)\n" + " (octal_integer_literal)\n" + " (decimal_floating_point_literal)\n" + " (hex_floating_point_literal)\n" + "] @number\n" + "\n" + "[\n" + " (character_literal)\n" + " (string_literal)\n" + "] @string\n" + "(escape_sequence) @string.escape\n" + "\n" + "[\n" + " (true)\n" + " (false)\n" + " (null_literal)\n" + "] @constant.builtin\n" + "\n" + "[\n" + " (line_comment)\n" + " (block_comment)\n" + "] @comment\n" + "\n" + "; Keywords\n" + "\n" + "[\n" + " \"abstract\"\n" + " \"assert\"\n" + " \"break\"\n" + " \"case\"\n" + " \"catch\"\n" + " \"class\"\n" + " \"continue\"\n" + " \"default\"\n" + " \"do\"\n" + " \"else\"\n" + " \"enum\"\n" + " \"exports\"\n" + " \"extends\"\n" + " \"final\"\n" + " \"finally\"\n" + " \"for\"\n" + " \"if\"\n" + " \"implements\"\n" + " \"import\"\n" + " \"instanceof\"\n" + " \"interface\"\n" + " \"module\"\n" + " \"native\"\n" + " \"new\"\n" + " \"non-sealed\"\n" + " \"open\"\n" + " \"opens\"\n" + " \"package\"\n" + " \"permits\"\n" + " \"private\"\n" + " \"protected\"\n" + " \"provides\"\n" + " \"public\"\n" + " \"requires\"\n" + " \"record\"\n" + " \"return\"\n" + " \"sealed\"\n" + " \"static\"\n" + " \"strictfp\"\n" + " \"switch\"\n" + " \"synchronized\"\n" + " \"throw\"\n" + " \"throws\"\n" + " \"to\"\n" + " \"transient\"\n" + " \"transitive\"\n" + " \"try\"\n" + " \"uses\"\n" + " \"volatile\"\n" + " \"when\"\n" + " \"while\"\n" + " \"with\"\n" + " \"yield\"\n" + "] @keyword\n" + ""; + +static const char kHighlightsQuery_javascript[] = + "; Variables\n" + ";----------\n" + "\n" + "(identifier) @variable\n" + "\n" + "; Properties\n" + ";-----------\n" + "\n" + "(property_identifier) @property\n" + "\n" + "; Function and method definitions\n" + ";--------------------------------\n" + "\n" + "(function_expression\n" + " name: (identifier) @function)\n" + "(function_declaration\n" + " name: (identifier) @function)\n" + "(method_definition\n" + " name: (property_identifier) @function.method)\n" + "\n" + "(pair\n" + " key: (property_identifier) @function.method\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (member_expression\n" + " property: (property_identifier) @function.method)\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "(variable_declarator\n" + " name: (identifier) @function\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (identifier) @function\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "; Function and method calls\n" + ";--------------------------\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "\n" + "(call_expression\n" + " function: (member_expression\n" + " property: (property_identifier) @function.method))\n" + "\n" + "; Special identifiers\n" + ";--------------------\n" + "\n" + "((identifier) @constructor\n" + " (#match\? @constructor \"^[A-Z]\"))\n" + "\n" + "([\n" + " (identifier)\n" + " (shorthand_property_identifier)\n" + " (shorthand_property_identifier_pattern)\n" + " ] @constant\n" + " (#match\? @constant \"^[A-Z_][A-Z\\\\d_]+$\"))\n" + "\n" + "((identifier) @variable.builtin\n" + " (#match\? @variable.builtin \"^(arguments|module|console|window|document)$\")\n" + " (#is-not\? local))\n" + "\n" + "((identifier) @function.builtin\n" + " (#eq\? @function.builtin \"require\")\n" + " (#is-not\? local))\n" + "\n" + "; Literals\n" + ";---------\n" + "\n" + "(this) @variable.builtin\n" + "(super) @variable.builtin\n" + "\n" + "[\n" + " (true)\n" + " (false)\n" + " (null)\n" + " (undefined)\n" + "] @constant.builtin\n" + "\n" + "(comment) @comment\n" + "\n" + "[\n" + " (string)\n" + " (template_string)\n" + "] @string\n" + "\n" + "(regex) @string.special\n" + "(number) @number\n" + "\n" + "; Tokens\n" + ";-------\n" + "\n" + "[\n" + " \";\"\n" + " (optional_chain)\n" + " \".\"\n" + " \",\"\n" + "] @punctuation.delimiter\n" + "\n" + "[\n" + " \"-\"\n" + " \"--\"\n" + " \"-=\"\n" + " \"+\"\n" + " \"++\"\n" + " \"+=\"\n" + " \"*\"\n" + " \"*=\"\n" + " \"**\"\n" + " \"**=\"\n" + " \"/\"\n" + " \"/=\"\n" + " \"%\"\n" + " \"%=\"\n" + " \"<\"\n" + " \"<=\"\n" + " \"<<\"\n" + " \"<<=\"\n" + " \"=\"\n" + " \"==\"\n" + " \"===\"\n" + " \"!\"\n" + " \"!=\"\n" + " \"!==\"\n" + " \"=>\"\n" + " \">\"\n" + " \">=\"\n" + " \">>\"\n" + " \">>=\"\n" + " \">>>\"\n" + " \">>>=\"\n" + " \"~\"\n" + " \"^\"\n" + " \"&\"\n" + " \"|\"\n" + " \"^=\"\n" + " \"&=\"\n" + " \"|=\"\n" + " \"&&\"\n" + " \"||\"\n" + " \"\?\?\"\n" + " \"&&=\"\n" + " \"||=\"\n" + " \"\?\?=\"\n" + "] @operator\n" + "\n" + "[\n" + " \"(\"\n" + " \")\"\n" + " \"[\"\n" + " \"]\"\n" + " \"{\"\n" + " \"}\"\n" + "] @punctuation.bracket\n" + "\n" + "(template_substitution\n" + " \"${\" @punctuation.special\n" + " \"}\" @punctuation.special) @embedded\n" + "\n" + "[\n" + " \"as\"\n" + " \"async\"\n" + " \"await\"\n" + " \"break\"\n" + " \"case\"\n" + " \"catch\"\n" + " \"class\"\n" + " \"const\"\n" + " \"continue\"\n" + " \"debugger\"\n" + " \"default\"\n" + " \"delete\"\n" + " \"do\"\n" + " \"else\"\n" + " \"export\"\n" + " \"extends\"\n" + " \"finally\"\n" + " \"for\"\n" + " \"from\"\n" + " \"function\"\n" + " \"get\"\n" + " \"if\"\n" + " \"import\"\n" + " \"in\"\n" + " \"instanceof\"\n" + " \"let\"\n" + " \"new\"\n" + " \"of\"\n" + " \"return\"\n" + " \"set\"\n" + " \"static\"\n" + " \"switch\"\n" + " \"target\"\n" + " \"throw\"\n" + " \"try\"\n" + " \"typeof\"\n" + " \"var\"\n" + " \"void\"\n" + " \"while\"\n" + " \"with\"\n" + " \"yield\"\n" + "] @keyword\n" + ""; + +static const char kHighlightsQuery_python[] = + "; Identifier naming conventions\n" + "\n" + "(identifier) @variable\n" + "\n" + "((identifier) @constructor\n" + " (#match\? @constructor \"^[A-Z]\"))\n" + "\n" + "((identifier) @constant\n" + " (#match\? @constant \"^[A-Z][A-Z_]*$\"))\n" + "\n" + "; Function calls\n" + "\n" + "(decorator) @function\n" + "(decorator\n" + " (identifier) @function)\n" + "\n" + "(call\n" + " function: (attribute attribute: (identifier) @function.method))\n" + "(call\n" + " function: (identifier) @function)\n" + "\n" + "; Builtin functions\n" + "\n" + "((call\n" + " function: (identifier) @function.builtin)\n" + " (#match\?\n" + " @function.builtin\n" + " \"^(abs|all|any|ascii|bin|bool|breakpoint|bytearray|bytes|callable|chr|classmethod|compile|complex|delattr|dict|dir|divmod|enumerate|eval|exec|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|isinstance|issubclass|iter|len|list|locals|map|max|memoryview|min|next|object|oct|open|ord|pow|print|property|range|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|vars|zip|__import__)$\"))\n" + "\n" + "; Function definitions\n" + "\n" + "(function_definition\n" + " name: (identifier) @function)\n" + "\n" + "(attribute attribute: (identifier) @property)\n" + "(type (identifier) @type)\n" + "\n" + "; Literals\n" + "\n" + "[\n" + " (none)\n" + " (true)\n" + " (false)\n" + "] @constant.builtin\n" + "\n" + "[\n" + " (integer)\n" + " (float)\n" + "] @number\n" + "\n" + "(comment) @comment\n" + "(string) @string\n" + "(escape_sequence) @escape\n" + "\n" + "(interpolation\n" + " \"{\" @punctuation.special\n" + " \"}\" @punctuation.special) @embedded\n" + "\n" + "[\n" + " \"-\"\n" + " \"-=\"\n" + " \"!=\"\n" + " \"*\"\n" + " \"**\"\n" + " \"**=\"\n" + " \"*=\"\n" + " \"/\"\n" + " \"//\"\n" + " \"//=\"\n" + " \"/=\"\n" + " \"&\"\n" + " \"&=\"\n" + " \"%\"\n" + " \"%=\"\n" + " \"^\"\n" + " \"^=\"\n" + " \"+\"\n" + " \"->\"\n" + " \"+=\"\n" + " \"<\"\n" + " \"<<\"\n" + " \"<<=\"\n" + " \"<=\"\n" + " \"<>\"\n" + " \"=\"\n" + " \":=\"\n" + " \"==\"\n" + " \">\"\n" + " \">=\"\n" + " \">>\"\n" + " \">>=\"\n" + " \"|\"\n" + " \"|=\"\n" + " \"~\"\n" + " \"@=\"\n" + " \"and\"\n" + " \"in\"\n" + " \"is\"\n" + " \"not\"\n" + " \"or\"\n" + " \"is not\"\n" + " \"not in\"\n" + "] @operator\n" + "\n" + "[\n" + " \"as\"\n" + " \"assert\"\n" + " \"async\"\n" + " \"await\"\n" + " \"break\"\n" + " \"class\"\n" + " \"continue\"\n" + " \"def\"\n" + " \"del\"\n" + " \"elif\"\n" + " \"else\"\n" + " \"except\"\n" + " \"exec\"\n" + " \"finally\"\n" + " \"for\"\n" + " \"from\"\n" + " \"global\"\n" + " \"if\"\n" + " \"import\"\n" + " \"lambda\"\n" + " \"nonlocal\"\n" + " \"pass\"\n" + " \"print\"\n" + " \"raise\"\n" + " \"return\"\n" + " \"try\"\n" + " \"while\"\n" + " \"with\"\n" + " \"yield\"\n" + " \"match\"\n" + " \"case\"\n" + "] @keyword\n" + ""; + +static const char kHighlightsQuery_c[] = + "(identifier) @variable\n" + "\n" + "((identifier) @constant\n" + " (#match\? @constant \"^[A-Z][A-Z\\\\d_]*$\"))\n" + "\n" + "\"break\" @keyword\n" + "\"case\" @keyword\n" + "\"const\" @keyword\n" + "\"continue\" @keyword\n" + "\"default\" @keyword\n" + "\"do\" @keyword\n" + "\"else\" @keyword\n" + "\"enum\" @keyword\n" + "\"extern\" @keyword\n" + "\"for\" @keyword\n" + "\"if\" @keyword\n" + "\"inline\" @keyword\n" + "\"return\" @keyword\n" + "\"sizeof\" @keyword\n" + "\"static\" @keyword\n" + "\"struct\" @keyword\n" + "\"switch\" @keyword\n" + "\"typedef\" @keyword\n" + "\"union\" @keyword\n" + "\"volatile\" @keyword\n" + "\"while\" @keyword\n" + "\n" + "\"#define\" @keyword\n" + "\"#elif\" @keyword\n" + "\"#else\" @keyword\n" + "\"#endif\" @keyword\n" + "\"#if\" @keyword\n" + "\"#ifdef\" @keyword\n" + "\"#ifndef\" @keyword\n" + "\"#include\" @keyword\n" + "(preproc_directive) @keyword\n" + "\n" + "\"--\" @operator\n" + "\"-\" @operator\n" + "\"-=\" @operator\n" + "\"->\" @operator\n" + "\"=\" @operator\n" + "\"!=\" @operator\n" + "\"*\" @operator\n" + "\"&\" @operator\n" + "\"&&\" @operator\n" + "\"+\" @operator\n" + "\"++\" @operator\n" + "\"+=\" @operator\n" + "\"<\" @operator\n" + "\"==\" @operator\n" + "\">\" @operator\n" + "\"||\" @operator\n" + "\n" + "\".\" @delimiter\n" + "\";\" @delimiter\n" + "\n" + "(string_literal) @string\n" + "(system_lib_string) @string\n" + "\n" + "(null) @constant\n" + "(number_literal) @number\n" + "(char_literal) @number\n" + "\n" + "(field_identifier) @property\n" + "(statement_identifier) @label\n" + "(type_identifier) @type\n" + "(primitive_type) @type\n" + "(sized_type_specifier) @type\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "(call_expression\n" + " function: (field_expression\n" + " field: (field_identifier) @function))\n" + "(function_declarator\n" + " declarator: (identifier) @function)\n" + "(preproc_function_def\n" + " name: (identifier) @function.special)\n" + "\n" + "(comment) @comment\n" + ""; + +static const char kHighlightsQuery_rust[] = + "; Identifiers\n" + "\n" + "(type_identifier) @type\n" + "(primitive_type) @type.builtin\n" + "(field_identifier) @property\n" + "\n" + "; Identifier conventions\n" + "\n" + "; Assume all-caps names are constants\n" + "((identifier) @constant\n" + " (#match\? @constant \"^[A-Z][A-Z\\\\d_]+$'\"))\n" + "\n" + "; Assume uppercase names are enum constructors\n" + "((identifier) @constructor\n" + " (#match\? @constructor \"^[A-Z]\"))\n" + "\n" + "; Assume that uppercase names in paths are types\n" + "((scoped_identifier\n" + " path: (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((scoped_identifier\n" + " path: (scoped_identifier\n" + " name: (identifier) @type))\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((scoped_type_identifier\n" + " path: (identifier) @type)\n" + " (#match\? @type \"^[A-Z]\"))\n" + "((scoped_type_identifier\n" + " path: (scoped_identifier\n" + " name: (identifier) @type))\n" + " (#match\? @type \"^[A-Z]\"))\n" + "\n" + "; Assume all qualified names in struct patterns are enum constructors. (They're\n" + "; either that, or struct names; highlighting both as constructors seems to be\n" + "; the less glaring choice of error, visually.)\n" + "(struct_pattern\n" + " type: (scoped_type_identifier\n" + " name: (type_identifier) @constructor))\n" + "\n" + "; Function calls\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "(call_expression\n" + " function: (field_expression\n" + " field: (field_identifier) @function.method))\n" + "(call_expression\n" + " function: (scoped_identifier\n" + " \"::\"\n" + " name: (identifier) @function))\n" + "\n" + "(generic_function\n" + " function: (identifier) @function)\n" + "(generic_function\n" + " function: (scoped_identifier\n" + " name: (identifier) @function))\n" + "(generic_function\n" + " function: (field_expression\n" + " field: (field_identifier) @function.method))\n" + "\n" + "(macro_invocation\n" + " macro: (identifier) @function.macro\n" + " \"!\" @function.macro)\n" + "\n" + "; Function definitions\n" + "\n" + "(function_item (identifier) @function)\n" + "(function_signature_item (identifier) @function)\n" + "\n" + "(line_comment) @comment\n" + "(block_comment) @comment\n" + "\n" + "(line_comment (doc_comment)) @comment.documentation\n" + "(block_comment (doc_comment)) @comment.documentation\n" + "\n" + "\"(\" @punctuation.bracket\n" + "\")\" @punctuation.bracket\n" + "\"[\" @punctuation.bracket\n" + "\"]\" @punctuation.bracket\n" + "\"{\" @punctuation.bracket\n" + "\"}\" @punctuation.bracket\n" + "\n" + "(type_arguments\n" + " \"<\" @punctuation.bracket\n" + " \">\" @punctuation.bracket)\n" + "(type_parameters\n" + " \"<\" @punctuation.bracket\n" + " \">\" @punctuation.bracket)\n" + "\n" + "\"::\" @punctuation.delimiter\n" + "\":\" @punctuation.delimiter\n" + "\".\" @punctuation.delimiter\n" + "\",\" @punctuation.delimiter\n" + "\";\" @punctuation.delimiter\n" + "\n" + "(parameter (identifier) @variable.parameter)\n" + "\n" + "(lifetime (identifier) @label)\n" + "\n" + "\"as\" @keyword\n" + "\"async\" @keyword\n" + "\"await\" @keyword\n" + "\"break\" @keyword\n" + "\"const\" @keyword\n" + "\"continue\" @keyword\n" + "\"default\" @keyword\n" + "\"dyn\" @keyword\n" + "\"else\" @keyword\n" + "\"enum\" @keyword\n" + "\"extern\" @keyword\n" + "\"fn\" @keyword\n" + "\"for\" @keyword\n" + "\"gen\" @keyword\n" + "\"if\" @keyword\n" + "\"impl\" @keyword\n" + "\"in\" @keyword\n" + "\"let\" @keyword\n" + "\"loop\" @keyword\n" + "\"macro_rules!\" @keyword\n" + "\"match\" @keyword\n" + "\"mod\" @keyword\n" + "\"move\" @keyword\n" + "\"pub\" @keyword\n" + "\"raw\" @keyword\n" + "\"ref\" @keyword\n" + "\"return\" @keyword\n" + "\"static\" @keyword\n" + "\"struct\" @keyword\n" + "\"trait\" @keyword\n" + "\"type\" @keyword\n" + "\"union\" @keyword\n" + "\"unsafe\" @keyword\n" + "\"use\" @keyword\n" + "\"where\" @keyword\n" + "\"while\" @keyword\n" + "\"yield\" @keyword\n" + "(crate) @keyword\n" + "(mutable_specifier) @keyword\n" + "(use_list (self) @keyword)\n" + "(scoped_use_list (self) @keyword)\n" + "(scoped_identifier (self) @keyword)\n" + "(super) @keyword\n" + "\n" + "(self) @variable.builtin\n" + "\n" + "(char_literal) @string\n" + "(string_literal) @string\n" + "(raw_string_literal) @string\n" + "\n" + "(boolean_literal) @constant.builtin\n" + "(integer_literal) @constant.builtin\n" + "(float_literal) @constant.builtin\n" + "\n" + "(escape_sequence) @escape\n" + "\n" + "(attribute_item) @attribute\n" + "(inner_attribute_item) @attribute\n" + "\n" + "\"*\" @operator\n" + "\"&\" @operator\n" + "\"'\" @operator\n" + ""; + +static const char kHighlightsQuery_bash[] = + "[\n" + " (string)\n" + " (raw_string)\n" + " (heredoc_body)\n" + " (heredoc_start)\n" + "] @string\n" + "\n" + "(command_name) @function\n" + "\n" + "(variable_name) @property\n" + "\n" + "[\n" + " \"case\"\n" + " \"do\"\n" + " \"done\"\n" + " \"elif\"\n" + " \"else\"\n" + " \"esac\"\n" + " \"export\"\n" + " \"fi\"\n" + " \"for\"\n" + " \"function\"\n" + " \"if\"\n" + " \"in\"\n" + " \"select\"\n" + " \"then\"\n" + " \"unset\"\n" + " \"until\"\n" + " \"while\"\n" + "] @keyword\n" + "\n" + "(comment) @comment\n" + "\n" + "(function_definition name: (word) @function)\n" + "\n" + "(file_descriptor) @number\n" + "\n" + "[\n" + " (command_substitution)\n" + " (process_substitution)\n" + " (expansion)\n" + "]@embedded\n" + "\n" + "[\n" + " \"$\"\n" + " \"&&\"\n" + " \">\"\n" + " \">>\"\n" + " \"<\"\n" + " \"|\"\n" + "] @operator\n" + "\n" + "(\n" + " (command (_) @constant)\n" + " (#match\? @constant \"^-\")\n" + ")\n" + ""; + +static const char kHighlightsQuery_typescript[] = + "; Variables\n" + ";----------\n" + "\n" + "(identifier) @variable\n" + "\n" + "; Properties\n" + ";-----------\n" + "\n" + "(property_identifier) @property\n" + "\n" + "; Function and method definitions\n" + ";--------------------------------\n" + "\n" + "(function_expression\n" + " name: (identifier) @function)\n" + "(function_declaration\n" + " name: (identifier) @function)\n" + "(method_definition\n" + " name: (property_identifier) @function.method)\n" + "\n" + "(pair\n" + " key: (property_identifier) @function.method\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (member_expression\n" + " property: (property_identifier) @function.method)\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "(variable_declarator\n" + " name: (identifier) @function\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (identifier) @function\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "; Function and method calls\n" + ";--------------------------\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "\n" + "(call_expression\n" + " function: (member_expression\n" + " property: (property_identifier) @function.method))\n" + "\n" + "; Special identifiers\n" + ";--------------------\n" + "\n" + "((identifier) @constructor\n" + " (#match\? @constructor \"^[A-Z]\"))\n" + "\n" + "([\n" + " (identifier)\n" + " (shorthand_property_identifier)\n" + " (shorthand_property_identifier_pattern)\n" + " ] @constant\n" + " (#match\? @constant \"^[A-Z_][A-Z\\\\d_]+$\"))\n" + "\n" + "((identifier) @variable.builtin\n" + " (#match\? @variable.builtin \"^(arguments|module|console|window|document)$\")\n" + " (#is-not\? local))\n" + "\n" + "((identifier) @function.builtin\n" + " (#eq\? @function.builtin \"require\")\n" + " (#is-not\? local))\n" + "\n" + "; Literals\n" + ";---------\n" + "\n" + "(this) @variable.builtin\n" + "(super) @variable.builtin\n" + "\n" + "[\n" + " (true)\n" + " (false)\n" + " (null)\n" + " (undefined)\n" + "] @constant.builtin\n" + "\n" + "(comment) @comment\n" + "\n" + "[\n" + " (string)\n" + " (template_string)\n" + "] @string\n" + "\n" + "(regex) @string.special\n" + "(number) @number\n" + "\n" + "; Tokens\n" + ";-------\n" + "\n" + "[\n" + " \";\"\n" + " (optional_chain)\n" + " \".\"\n" + " \",\"\n" + "] @punctuation.delimiter\n" + "\n" + "[\n" + " \"-\"\n" + " \"--\"\n" + " \"-=\"\n" + " \"+\"\n" + " \"++\"\n" + " \"+=\"\n" + " \"*\"\n" + " \"*=\"\n" + " \"**\"\n" + " \"**=\"\n" + " \"/\"\n" + " \"/=\"\n" + " \"%\"\n" + " \"%=\"\n" + " \"<\"\n" + " \"<=\"\n" + " \"<<\"\n" + " \"<<=\"\n" + " \"=\"\n" + " \"==\"\n" + " \"===\"\n" + " \"!\"\n" + " \"!=\"\n" + " \"!==\"\n" + " \"=>\"\n" + " \">\"\n" + " \">=\"\n" + " \">>\"\n" + " \">>=\"\n" + " \">>>\"\n" + " \">>>=\"\n" + " \"~\"\n" + " \"^\"\n" + " \"&\"\n" + " \"|\"\n" + " \"^=\"\n" + " \"&=\"\n" + " \"|=\"\n" + " \"&&\"\n" + " \"||\"\n" + " \"\?\?\"\n" + " \"&&=\"\n" + " \"||=\"\n" + " \"\?\?=\"\n" + "] @operator\n" + "\n" + "[\n" + " \"(\"\n" + " \")\"\n" + " \"[\"\n" + " \"]\"\n" + " \"{\"\n" + " \"}\"\n" + "] @punctuation.bracket\n" + "\n" + "(template_substitution\n" + " \"${\" @punctuation.special\n" + " \"}\" @punctuation.special) @embedded\n" + "\n" + "[\n" + " \"as\"\n" + " \"async\"\n" + " \"await\"\n" + " \"break\"\n" + " \"case\"\n" + " \"catch\"\n" + " \"class\"\n" + " \"const\"\n" + " \"continue\"\n" + " \"debugger\"\n" + " \"default\"\n" + " \"delete\"\n" + " \"do\"\n" + " \"else\"\n" + " \"export\"\n" + " \"extends\"\n" + " \"finally\"\n" + " \"for\"\n" + " \"from\"\n" + " \"function\"\n" + " \"get\"\n" + " \"if\"\n" + " \"import\"\n" + " \"in\"\n" + " \"instanceof\"\n" + " \"let\"\n" + " \"new\"\n" + " \"of\"\n" + " \"return\"\n" + " \"set\"\n" + " \"static\"\n" + " \"switch\"\n" + " \"target\"\n" + " \"throw\"\n" + " \"try\"\n" + " \"typeof\"\n" + " \"var\"\n" + " \"void\"\n" + " \"while\"\n" + " \"with\"\n" + " \"yield\"\n" + "] @keyword\n" + "\n" + "\n" + "; Types\n" + "\n" + "(type_identifier) @type\n" + "(predefined_type) @type.builtin\n" + "\n" + "((identifier) @type\n" + " (#match\? @type \"^[A-Z]\"))\n" + "\n" + "(type_arguments\n" + " \"<\" @punctuation.bracket\n" + " \">\" @punctuation.bracket)\n" + "\n" + "; Variables\n" + "\n" + "(required_parameter (identifier) @variable.parameter)\n" + "(optional_parameter (identifier) @variable.parameter)\n" + "\n" + "; Keywords\n" + "\n" + "[ \"abstract\"\n" + " \"declare\"\n" + " \"enum\"\n" + " \"export\"\n" + " \"implements\"\n" + " \"interface\"\n" + " \"keyof\"\n" + " \"namespace\"\n" + " \"private\"\n" + " \"protected\"\n" + " \"public\"\n" + " \"type\"\n" + " \"readonly\"\n" + " \"override\"\n" + " \"satisfies\"\n" + "] @keyword\n" + ""; + +static const char kHighlightsQuery_tsx[] = + "; Variables\n" + ";----------\n" + "\n" + "(identifier) @variable\n" + "\n" + "; Properties\n" + ";-----------\n" + "\n" + "(property_identifier) @property\n" + "\n" + "; Function and method definitions\n" + ";--------------------------------\n" + "\n" + "(function_expression\n" + " name: (identifier) @function)\n" + "(function_declaration\n" + " name: (identifier) @function)\n" + "(method_definition\n" + " name: (property_identifier) @function.method)\n" + "\n" + "(pair\n" + " key: (property_identifier) @function.method\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (member_expression\n" + " property: (property_identifier) @function.method)\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "(variable_declarator\n" + " name: (identifier) @function\n" + " value: [(function_expression) (arrow_function)])\n" + "\n" + "(assignment_expression\n" + " left: (identifier) @function\n" + " right: [(function_expression) (arrow_function)])\n" + "\n" + "; Function and method calls\n" + ";--------------------------\n" + "\n" + "(call_expression\n" + " function: (identifier) @function)\n" + "\n" + "(call_expression\n" + " function: (member_expression\n" + " property: (property_identifier) @function.method))\n" + "\n" + "; Special identifiers\n" + ";--------------------\n" + "\n" + "((identifier) @constructor\n" + " (#match\? @constructor \"^[A-Z]\"))\n" + "\n" + "([\n" + " (identifier)\n" + " (shorthand_property_identifier)\n" + " (shorthand_property_identifier_pattern)\n" + " ] @constant\n" + " (#match\? @constant \"^[A-Z_][A-Z\\\\d_]+$\"))\n" + "\n" + "((identifier) @variable.builtin\n" + " (#match\? @variable.builtin \"^(arguments|module|console|window|document)$\")\n" + " (#is-not\? local))\n" + "\n" + "((identifier) @function.builtin\n" + " (#eq\? @function.builtin \"require\")\n" + " (#is-not\? local))\n" + "\n" + "; Literals\n" + ";---------\n" + "\n" + "(this) @variable.builtin\n" + "(super) @variable.builtin\n" + "\n" + "[\n" + " (true)\n" + " (false)\n" + " (null)\n" + " (undefined)\n" + "] @constant.builtin\n" + "\n" + "(comment) @comment\n" + "\n" + "[\n" + " (string)\n" + " (template_string)\n" + "] @string\n" + "\n" + "(regex) @string.special\n" + "(number) @number\n" + "\n" + "; Tokens\n" + ";-------\n" + "\n" + "[\n" + " \";\"\n" + " (optional_chain)\n" + " \".\"\n" + " \",\"\n" + "] @punctuation.delimiter\n" + "\n" + "[\n" + " \"-\"\n" + " \"--\"\n" + " \"-=\"\n" + " \"+\"\n" + " \"++\"\n" + " \"+=\"\n" + " \"*\"\n" + " \"*=\"\n" + " \"**\"\n" + " \"**=\"\n" + " \"/\"\n" + " \"/=\"\n" + " \"%\"\n" + " \"%=\"\n" + " \"<\"\n" + " \"<=\"\n" + " \"<<\"\n" + " \"<<=\"\n" + " \"=\"\n" + " \"==\"\n" + " \"===\"\n" + " \"!\"\n" + " \"!=\"\n" + " \"!==\"\n" + " \"=>\"\n" + " \">\"\n" + " \">=\"\n" + " \">>\"\n" + " \">>=\"\n" + " \">>>\"\n" + " \">>>=\"\n" + " \"~\"\n" + " \"^\"\n" + " \"&\"\n" + " \"|\"\n" + " \"^=\"\n" + " \"&=\"\n" + " \"|=\"\n" + " \"&&\"\n" + " \"||\"\n" + " \"\?\?\"\n" + " \"&&=\"\n" + " \"||=\"\n" + " \"\?\?=\"\n" + "] @operator\n" + "\n" + "[\n" + " \"(\"\n" + " \")\"\n" + " \"[\"\n" + " \"]\"\n" + " \"{\"\n" + " \"}\"\n" + "] @punctuation.bracket\n" + "\n" + "(template_substitution\n" + " \"${\" @punctuation.special\n" + " \"}\" @punctuation.special) @embedded\n" + "\n" + "[\n" + " \"as\"\n" + " \"async\"\n" + " \"await\"\n" + " \"break\"\n" + " \"case\"\n" + " \"catch\"\n" + " \"class\"\n" + " \"const\"\n" + " \"continue\"\n" + " \"debugger\"\n" + " \"default\"\n" + " \"delete\"\n" + " \"do\"\n" + " \"else\"\n" + " \"export\"\n" + " \"extends\"\n" + " \"finally\"\n" + " \"for\"\n" + " \"from\"\n" + " \"function\"\n" + " \"get\"\n" + " \"if\"\n" + " \"import\"\n" + " \"in\"\n" + " \"instanceof\"\n" + " \"let\"\n" + " \"new\"\n" + " \"of\"\n" + " \"return\"\n" + " \"set\"\n" + " \"static\"\n" + " \"switch\"\n" + " \"target\"\n" + " \"throw\"\n" + " \"try\"\n" + " \"typeof\"\n" + " \"var\"\n" + " \"void\"\n" + " \"while\"\n" + " \"with\"\n" + " \"yield\"\n" + "] @keyword\n" + "\n" + "\n" + "; Types\n" + "\n" + "(type_identifier) @type\n" + "(predefined_type) @type.builtin\n" + "\n" + "((identifier) @type\n" + " (#match\? @type \"^[A-Z]\"))\n" + "\n" + "(type_arguments\n" + " \"<\" @punctuation.bracket\n" + " \">\" @punctuation.bracket)\n" + "\n" + "; Variables\n" + "\n" + "(required_parameter (identifier) @variable.parameter)\n" + "(optional_parameter (identifier) @variable.parameter)\n" + "\n" + "; Keywords\n" + "\n" + "[ \"abstract\"\n" + " \"declare\"\n" + " \"enum\"\n" + " \"export\"\n" + " \"implements\"\n" + " \"interface\"\n" + " \"keyof\"\n" + " \"namespace\"\n" + " \"private\"\n" + " \"protected\"\n" + " \"public\"\n" + " \"type\"\n" + " \"readonly\"\n" + " \"override\"\n" + " \"satisfies\"\n" + "] @keyword\n" + ""; + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_registry.cpp b/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_registry.cpp new file mode 100644 index 000000000000..37f595c0f1fb --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/highlight/vendor/generated/generated_registry.cpp @@ -0,0 +1,59 @@ +// Generated by vendor/gen-registry.mjs. Do not edit. + +#include "HighlightGrammars.hpp" +#include "generated_queries.h" + +#include + +extern "C" { +const TSLanguage *tree_sitter_json(void); +const TSLanguage *tree_sitter_html(void); +const TSLanguage *tree_sitter_css(void); +const TSLanguage *tree_sitter_markdown(void); +const TSLanguage *tree_sitter_yaml(void); +const TSLanguage *tree_sitter_go(void); +const TSLanguage *tree_sitter_java(void); +const TSLanguage *tree_sitter_javascript(void); +const TSLanguage *tree_sitter_python(void); +const TSLanguage *tree_sitter_c(void); +const TSLanguage *tree_sitter_rust(void); +const TSLanguage *tree_sitter_bash(void); +const TSLanguage *tree_sitter_typescript(void); +const TSLanguage *tree_sitter_tsx(void); +} + +namespace Markdown { +namespace { + +constexpr GrammarEntry kGrammars[] = { + {"json", tree_sitter_json, kHighlightsQuery_json}, + {"html", tree_sitter_html, kHighlightsQuery_html}, + {"css", tree_sitter_css, kHighlightsQuery_css}, + {"markdown", tree_sitter_markdown, kHighlightsQuery_markdown}, + {"yaml", tree_sitter_yaml, kHighlightsQuery_yaml}, + {"go", tree_sitter_go, kHighlightsQuery_go}, + {"java", tree_sitter_java, kHighlightsQuery_java}, + {"javascript", tree_sitter_javascript, kHighlightsQuery_javascript}, + {"python", tree_sitter_python, kHighlightsQuery_python}, + {"c", tree_sitter_c, kHighlightsQuery_c}, + {"rust", tree_sitter_rust, kHighlightsQuery_rust}, + {"bash", tree_sitter_bash, kHighlightsQuery_bash}, + {"typescript", tree_sitter_typescript, kHighlightsQuery_typescript}, + {"tsx", tree_sitter_tsx, kHighlightsQuery_tsx}, +}; + +} // namespace + +const GrammarEntry *findGrammar(const char *canonicalId) { + if (canonicalId == nullptr) { + return nullptr; + } + for (const GrammarEntry &entry : kGrammars) { + if (std::strcmp(entry.canonicalId, canonicalId) == 0) { + return &entry; + } + } + return nullptr; +} + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/md4c/md4c.c b/packages/react-native-enriched-markdown/cpp/md4c/md4c.c new file mode 100644 index 000000000000..5bc55296e00d --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/md4c/md4c.c @@ -0,0 +1,7397 @@ +/* + * MD4C: Markdown parser for C + * (https://github.com/mity/md4c) + * + * Copyright (c) 2016-2026 Martin Mitáš + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "md4c.h" + + +/***************************** + *** Miscellaneous Stuff *** + *****************************/ + +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199409L + /* C89/90 or old compilers in general may not understand "inline". */ + #if defined __GNUC__ + #define inline __inline__ + #elif defined _MSC_VER + #define inline __inline + #else + #define inline + #endif +#endif + +/* Make the UTF-8 support the default. */ +#if !defined MD4C_USE_ASCII && !defined MD4C_USE_UTF8 && !defined MD4C_USE_UTF16 + #define MD4C_USE_UTF8 +#endif + +/* Magic for making wide literals with MD4C_USE_UTF16. */ +#ifdef _T + #undef _T +#endif +#if defined MD4C_USE_UTF16 + #define _T(x) L##x +#else + #define _T(x) x +#endif + +/* Misc. macros. */ +#define SIZEOF_ARRAY(a) (sizeof(a) / sizeof(a[0])) + +#define STRINGIZE_(x) #x +#define STRINGIZE(x) STRINGIZE_(x) + +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + +#define MD_LOG(msg) \ + do { \ + if(ctx->parser.debug_log != NULL) \ + ctx->parser.debug_log((msg), ctx->userdata); \ + } while(0) + +#ifdef DEBUG + #define MD_ASSERT(cond) \ + do { \ + if(!(cond)) { \ + MD_LOG(__FILE__ ":" STRINGIZE(__LINE__) ": " \ + "Assertion '" STRINGIZE(cond) "' failed."); \ + exit(1); \ + } \ + } while(0) + + #define MD_UNREACHABLE() MD_ASSERT(1 == 0) +#else + #ifdef __GNUC__ + #define MD_ASSERT(cond) do { if(!(cond)) __builtin_unreachable(); } while(0) + #define MD_UNREACHABLE() do { __builtin_unreachable(); } while(0) + #elif defined _MSC_VER && _MSC_VER > 120 + #define MD_ASSERT(cond) do { __assume(cond); } while(0) + #define MD_UNREACHABLE() do { __assume(0); } while(0) + #else + #define MD_ASSERT(cond) do {} while(0) + #define MD_UNREACHABLE() do {} while(0) + #endif +#endif + +/* For falling through case labels in switch statements. */ +#if defined __clang__ && __clang_major__ >= 12 + #define MD_FALLTHROUGH() __attribute__((fallthrough)) +#elif defined __GNUC__ && __GNUC__ >= 7 + #define MD_FALLTHROUGH() __attribute__((fallthrough)) +#else + #define MD_FALLTHROUGH() ((void)0) +#endif + +/* Suppress "unused parameter" warnings. */ +#define MD_UNUSED(x) ((void)x) + + +/****************************** + *** Some internal limits *** + ******************************/ + +/* We limit code span marks to lower than 32 backticks. This solves the + * pathologic case of too many openers, each of different length: Their + * resolving would be then O(n^2). */ +#define CODESPAN_MARK_MAXLEN 32 + + +/************************ + *** Internal Types *** + ************************/ + +/* These are omnipresent so lets save some typing. */ +#define CHAR MD_CHAR +#define SZ MD_SIZE +#define OFF MD_OFFSET + +typedef struct MD_MARK_tag MD_MARK; +typedef struct MD_BLOCK_tag MD_BLOCK; +typedef struct MD_CONTAINER_tag MD_CONTAINER; +typedef struct MD_REF_DEF_tag MD_REF_DEF; +typedef struct MD_FOOTNOTE_DEF_tag MD_FOOTNOTE_DEF; + +/* Forward declaration; full definition is below with MD_LINE_tag. */ +typedef struct MD_LINE_tag MD_LINE; + +typedef struct MD_LABEL_HASH_ENTRY_tag MD_LABEL_HASH_ENTRY; +struct MD_LABEL_HASH_ENTRY_tag { + const CHAR* label; + SZ label_size; + unsigned hash; +}; + +typedef struct MD_LABEL_HASH_TABLE_tag MD_LABEL_HASH_TABLE; +struct MD_LABEL_HASH_TABLE_tag { + /* Flat array of all records. */ + union { + void* defs; + MD_REF_DEF* ref_defs; + MD_FOOTNOTE_DEF* footnote_defs; + }; + unsigned def_size; + unsigned n_defs; + unsigned alloc_defs; + + /* The hashtable itself, where the actual entries are pointers into the + * array defs[] above. */ + void** buckets; + unsigned n_buckets; +}; + + +/* During analyzes of inline marks, we need to manage stacks of unresolved + * openers of the given type. + * The stack connects the marks via MD_MARK::next; + */ +typedef struct MD_MARKSTACK_tag MD_MARKSTACK; +struct MD_MARKSTACK_tag { + int top; /* -1 if empty. */ +}; + +/* Context propagated through all the parsing. */ +typedef struct MD_CTX_tag MD_CTX; +struct MD_CTX_tag { + /* Immutable stuff (parameters of md_parse()). */ + const CHAR* text; + SZ size; + MD_PARSER parser; + void* userdata; + + /* When this is true, it allows some optimizations. */ + int doc_ends_with_newline; + + /* Helper temporary growing buffer. */ + CHAR* buffer; + unsigned alloc_buffer; + + /* Reference definitions. */ + MD_LABEL_HASH_TABLE ref_def_hashtable; + SZ max_ref_def_output; + + /* Footnote definitions. */ + MD_LABEL_HASH_TABLE footnote_hashtable; + unsigned next_footnote_index; /* 1-based counter for sequential numbering */ + + /* Stack of inline/span markers. + * This is only used for parsing a single block contents but by storing it + * here we may reuse the stack for subsequent blocks; i.e. we have fewer + * (re)allocations. */ + MD_MARK* marks; + int n_marks; + int alloc_marks; + +#if defined MD4C_USE_UTF16 + char mark_char_map[128]; +#else + char mark_char_map[256]; +#endif + + /* For resolving of inline spans. */ + MD_MARKSTACK opener_stacks[20]; +#define ASTERISK_OPENERS_oo_mod3_0 (ctx->opener_stacks[0]) /* Opener-only */ +#define ASTERISK_OPENERS_oo_mod3_1 (ctx->opener_stacks[1]) +#define ASTERISK_OPENERS_oo_mod3_2 (ctx->opener_stacks[2]) +#define ASTERISK_OPENERS_oc_mod3_0 (ctx->opener_stacks[3]) /* Both opener and closer candidate */ +#define ASTERISK_OPENERS_oc_mod3_1 (ctx->opener_stacks[4]) +#define ASTERISK_OPENERS_oc_mod3_2 (ctx->opener_stacks[5]) +#define UNDERSCORE_OPENERS_oo_mod3_0 (ctx->opener_stacks[6]) /* Opener-only */ +#define UNDERSCORE_OPENERS_oo_mod3_1 (ctx->opener_stacks[7]) +#define UNDERSCORE_OPENERS_oo_mod3_2 (ctx->opener_stacks[8]) +#define UNDERSCORE_OPENERS_oc_mod3_0 (ctx->opener_stacks[9]) /* Both opener and closer candidate */ +#define UNDERSCORE_OPENERS_oc_mod3_1 (ctx->opener_stacks[10]) +#define UNDERSCORE_OPENERS_oc_mod3_2 (ctx->opener_stacks[11]) +#define TILDE_OPENERS_1 (ctx->opener_stacks[12]) +#define TILDE_OPENERS_2 (ctx->opener_stacks[13]) +#define BRACKET_OPENERS (ctx->opener_stacks[14]) +#define DOLLAR_OPENERS (ctx->opener_stacks[15]) +#define PIPE_OPENERS (ctx->opener_stacks[16]) +#define CARET_OPENERS (ctx->opener_stacks[17]) +#define EQUAL_OPENERS (ctx->opener_stacks[18]) +#define PLUS_OPENERS (ctx->opener_stacks[19]) + + /* Stack of dummies which need to call free() for pointers stored in them. + * These are constructed during inline parsing and freed after all the block + * is processed (i.e. all callbacks referring those strings are called). */ + MD_MARKSTACK ptr_stack; + + /* For resolving table rows. */ + int n_table_cell_boundaries; + int table_cell_boundaries_head; + int table_cell_boundaries_tail; + + /* For resolving links. */ + int unresolved_link_head; + int unresolved_link_tail; + + /* For resolving raw HTML. */ + OFF html_comment_horizon; + OFF html_proc_instr_horizon; + OFF html_decl_horizon; + OFF html_cdata_horizon; + + /* For resolving permissive autolinks. */ + OFF permissive_autolink_tail_horizon; + + /* For block analysis. + * Notes: + * -- It holds MD_BLOCK as well as MD_LINE structures. After each + * MD_BLOCK, its (multiple) MD_LINE(s) follow. + * -- For MD_BLOCK_HTML and MD_BLOCK_CODE, MD_VERBATIMLINE(s) are used + * instead of MD_LINE(s). + */ + void* block_bytes; + MD_BLOCK* current_block; + int n_block_bytes; + int alloc_block_bytes; + + /* Pending count of blank lines not yet reported as MD_BLOCK_BLANK. + * Used only with MD_FLAG_PRESERVEBLANKLINES. */ + unsigned n_blank_lines; + + /* For container block analysis. */ + MD_CONTAINER* containers; + int n_containers; + int alloc_containers; + + /* Minimal indentation to call the block "indented code block". */ + unsigned code_indent_offset; + + /* Contextual info for line analysis. */ + SZ code_fence_length; /* For checking closing fence length. */ + int html_block_type; /* For checking closing raw HTML condition. */ + int last_line_has_list_loosening_effect; + int last_list_item_starts_with_two_blank_lines; +}; + +enum MD_LINETYPE_tag { + MD_LINE_BLANK, + MD_LINE_HR, + MD_LINE_ATXHEADER, + MD_LINE_SETEXTHEADER, + MD_LINE_SETEXTUNDERLINE, + MD_LINE_INDENTEDCODE, + MD_LINE_FENCEDCODE, + MD_LINE_HTML, + MD_LINE_TEXT, + MD_LINE_TABLE, + MD_LINE_TABLEUNDERLINE +}; +typedef enum MD_LINETYPE_tag MD_LINETYPE; + +typedef struct MD_LINE_ANALYSIS_tag MD_LINE_ANALYSIS; +struct MD_LINE_ANALYSIS_tag { + MD_LINETYPE type; + unsigned data; + int enforce_new_block; + OFF beg; + OFF end; + unsigned indent; /* Indentation level. */ +}; + +struct MD_LINE_tag { + OFF beg; + OFF end; +}; + +typedef struct MD_VERBATIMLINE_tag MD_VERBATIMLINE; +struct MD_VERBATIMLINE_tag { + OFF beg; + OFF end; + OFF indent; +}; + + +/***************** + *** Helpers *** + *****************/ + +/* Character accessors. */ +#define CH(off) (ctx->text[(off)]) +#define STR(off) (ctx->text + (off)) + +/* Character classification. + * Note we assume ASCII compatibility of code points < 128 here. */ +#define ISIN_(ch, ch_min, ch_max) ((ch_min) <= (unsigned)(ch) && (unsigned)(ch) <= (ch_max)) +#define ISANYOF_(ch, palette) ((ch) != _T('\0') && md_strchr((palette), (ch)) != NULL) +#define ISANYOF2_(ch, ch1, ch2) ((ch) == (ch1) || (ch) == (ch2)) +#define ISANYOF3_(ch, ch1, ch2, ch3) ((ch) == (ch1) || (ch) == (ch2) || (ch) == (ch3)) +#define ISASCII_(ch) ((unsigned)(ch) <= 127) +#define ISBLANK_(ch) (ISANYOF2_((ch), _T(' '), _T('\t'))) +#define ISNEWLINE_(ch) (ISANYOF2_((ch), _T('\r'), _T('\n'))) +#define ISWHITESPACE_(ch) (ISBLANK_(ch) || ISANYOF2_((ch), _T('\v'), _T('\f'))) +#define ISCNTRL_(ch) ((unsigned)(ch) <= 31 || (unsigned)(ch) == 127) +#define ISPUNCT_(ch) (ISIN_(ch, 33, 47) || ISIN_(ch, 58, 64) || ISIN_(ch, 91, 96) || ISIN_(ch, 123, 126)) +#define ISUPPER_(ch) (ISIN_(ch, _T('A'), _T('Z'))) +#define ISLOWER_(ch) (ISIN_(ch, _T('a'), _T('z'))) +#define ISALPHA_(ch) (ISUPPER_(ch) || ISLOWER_(ch)) +#define ISDIGIT_(ch) (ISIN_(ch, _T('0'), _T('9'))) +#define ISXDIGIT_(ch) (ISDIGIT_(ch) || ISIN_(ch, _T('A'), _T('F')) || ISIN_(ch, _T('a'), _T('f'))) +#define ISALNUM_(ch) (ISALPHA_(ch) || ISDIGIT_(ch)) + +#define ISANYOF(off, palette) ISANYOF_(CH(off), (palette)) +#define ISANYOF2(off, ch1, ch2) ISANYOF2_(CH(off), (ch1), (ch2)) +#define ISANYOF3(off, ch1, ch2, ch3) ISANYOF3_(CH(off), (ch1), (ch2), (ch3)) +#define ISASCII(off) ISASCII_(CH(off)) +#define ISBLANK(off) ISBLANK_(CH(off)) +#define ISNEWLINE(off) ISNEWLINE_(CH(off)) +#define ISWHITESPACE(off) ISWHITESPACE_(CH(off)) +#define ISCNTRL(off) ISCNTRL_(CH(off)) +#define ISPUNCT(off) ISPUNCT_(CH(off)) +#define ISUPPER(off) ISUPPER_(CH(off)) +#define ISLOWER(off) ISLOWER_(CH(off)) +#define ISALPHA(off) ISALPHA_(CH(off)) +#define ISDIGIT(off) ISDIGIT_(CH(off)) +#define ISXDIGIT(off) ISXDIGIT_(CH(off)) +#define ISALNUM(off) ISALNUM_(CH(off)) + + +#if defined MD4C_USE_UTF16 + #define md_strchr wcschr + #define md_strlen wcslen +#else + #define md_strchr strchr + #define md_strlen strlen +#endif + + +/* Case insensitive check of string equality. */ +static inline int +md_ascii_case_eq(const CHAR* s1, const CHAR* s2, SZ n) +{ + OFF i; + for(i = 0; i < n; i++) { + CHAR ch1 = s1[i]; + CHAR ch2 = s2[i]; + + if(ISLOWER_(ch1)) + ch1 += ('A'-'a'); + if(ISLOWER_(ch2)) + ch2 += ('A'-'a'); + if(ch1 != ch2) + return false; + } + return true; +} + +static inline int +md_ascii_eq(const CHAR* s1, const CHAR* s2, SZ n) +{ + return memcmp(s1, s2, n * sizeof(CHAR)) == 0; +} + +static int +md_text_with_null_replacement(MD_CTX* ctx, MD_TEXTTYPE type, const CHAR* str, SZ size) +{ + OFF off = 0; + int ret = 0; + + while(1) { + while(off < size && str[off] != _T('\0')) + off++; + + if(off > 0) { + ret = ctx->parser.text(type, str, off, ctx->userdata); + if(ret != 0) + return ret; + + str += off; + size -= off; + off = 0; + } + + if(off >= size) + return 0; + + ret = ctx->parser.text(MD_TEXT_NULLCHAR, _T(""), 1, ctx->userdata); + if(ret != 0) + return ret; + off++; + } +} + + +#define MD_CHECK(func) \ + do { \ + ret = (func); \ + if(ret != 0) \ + goto abort; \ + } while(0) + + +#define MD_TEMP_BUFFER(sz) \ + do { \ + if(sz > ctx->alloc_buffer) { \ + CHAR* new_buffer; \ + SZ new_size = ((sz) + (sz) / 2 + 128) & ~127; \ + \ + new_buffer = realloc(ctx->buffer, new_size); \ + if(new_buffer == NULL) { \ + MD_LOG("realloc() failed."); \ + ret = -1; \ + goto abort; \ + } \ + \ + ctx->buffer = new_buffer; \ + ctx->alloc_buffer = new_size; \ + } \ + } while(0) + + +#define MD_ENTER_BLOCK(type, arg) \ + do { \ + ret = ctx->parser.enter_block((type), (arg), ctx->userdata); \ + if(ret != 0) { \ + MD_LOG("Aborted from enter_block() callback."); \ + goto abort; \ + } \ + } while(0) + +#define MD_LEAVE_BLOCK(type, arg) \ + do { \ + ret = ctx->parser.leave_block((type), (arg), ctx->userdata); \ + if(ret != 0) { \ + MD_LOG("Aborted from leave_block() callback."); \ + goto abort; \ + } \ + } while(0) + +#define MD_ENTER_SPAN(type, arg) \ + do { \ + ret = ctx->parser.enter_span((type), (arg), ctx->userdata); \ + if(ret != 0) { \ + MD_LOG("Aborted from enter_span() callback."); \ + goto abort; \ + } \ + } while(0) + +#define MD_LEAVE_SPAN(type, arg) \ + do { \ + ret = ctx->parser.leave_span((type), (arg), ctx->userdata); \ + if(ret != 0) { \ + MD_LOG("Aborted from leave_span() callback."); \ + goto abort; \ + } \ + } while(0) + +#define MD_TEXT(type, str, size) \ + do { \ + if(size > 0) { \ + ret = ctx->parser.text((type), (str), (size), ctx->userdata); \ + if(ret != 0) { \ + MD_LOG("Aborted from text() callback."); \ + goto abort; \ + } \ + } \ + } while(0) + +#define MD_TEXT_INSECURE(type, str, size) \ + do { \ + if(size > 0) { \ + ret = md_text_with_null_replacement(ctx, type, str, size); \ + if(ret != 0) { \ + MD_LOG("Aborted from text() callback."); \ + goto abort; \ + } \ + } \ + } while(0) + + +/* If the offset falls into a gap between line, we return the following + * line. */ +static const MD_LINE* +md_lookup_line(OFF off, const MD_LINE* lines, MD_SIZE n_lines, MD_SIZE* p_line_index) +{ + MD_SIZE lo, hi; + MD_SIZE pivot; + const MD_LINE* line; + + lo = 0; + hi = n_lines - 1; + while(lo <= hi) { + pivot = (lo + hi) / 2; + line = &lines[pivot]; + + if(off < line->beg) { + if(hi == 0 || lines[hi-1].end < off) { + if(p_line_index != NULL) + *p_line_index = pivot; + return line; + } + hi = pivot - 1; + } else if(off > line->end) { + lo = pivot + 1; + } else { + if(p_line_index != NULL) + *p_line_index = pivot; + return line; + } + } + + return NULL; +} + + +/************************* + *** Unicode Support *** + *************************/ + +typedef struct MD_UNICODE_FOLD_INFO_tag MD_UNICODE_FOLD_INFO; +struct MD_UNICODE_FOLD_INFO_tag { + unsigned codepoints[3]; + unsigned n_codepoints; +}; + + +#if defined MD4C_USE_UTF16 || defined MD4C_USE_UTF8 + /* Binary search over sorted "map" of codepoints. Consecutive sequences + * of codepoints may be encoded in the map by just using the + * (MIN_CODEPOINT | 0x40000000) and (MAX_CODEPOINT | 0x80000000). + * + * Returns index of the found record in the map (in the case of ranges, + * the minimal value is used); or -1 on failure. */ + static int + md_unicode_bsearch__(unsigned codepoint, const unsigned* map, size_t map_size) + { + int beg, end; + int pivot_beg, pivot_end; + + beg = 0; + end = (int) map_size-1; + while(beg <= end) { + /* Pivot may be a range, not just a single value. */ + pivot_beg = pivot_end = (beg + end) / 2; + if(map[pivot_end] & 0x40000000) + pivot_end++; + if(map[pivot_beg] & 0x80000000) + pivot_beg--; + + if(codepoint < (map[pivot_beg] & 0x00ffffff)) + end = pivot_beg - 1; + else if(codepoint > (map[pivot_end] & 0x00ffffff)) + beg = pivot_end + 1; + else + return pivot_beg; + } + + return -1; + } + + static int + md_is_unicode_whitespace__(unsigned codepoint) + { +#define R(cp_min, cp_max) ((cp_min) | 0x40000000), ((cp_max) | 0x80000000) +#define S(cp) (cp) + /* Unicode "Zs" category. + * (generated by scripts/build_whitespace_map.py) */ + static const unsigned WHITESPACE_MAP[] = { + S(0x0020), S(0x00a0), S(0x1680), R(0x2000,0x200a), S(0x202f), S(0x205f), S(0x3000) + }; +#undef R +#undef S + + /* The ASCII ones are the most frequently used ones, also CommonMark + * specification requests few more in this range. */ + if(codepoint <= 0x7f) + return ISWHITESPACE_(codepoint); + + return (md_unicode_bsearch__(codepoint, WHITESPACE_MAP, SIZEOF_ARRAY(WHITESPACE_MAP)) >= 0); + } + + static int + md_is_unicode_punct__(unsigned codepoint) + { +#define R(cp_min, cp_max) ((cp_min) | 0x40000000), ((cp_max) | 0x80000000) +#define S(cp) (cp) + /* Unicode general "P" and "S" categories. + * (generated by scripts/build_punct_map.py) */ + static const unsigned PUNCT_MAP[] = { + R(0x0021,0x002f), R(0x003a,0x0040), R(0x005b,0x0060), R(0x007b,0x007e), R(0x00a1,0x00a9), + R(0x00ab,0x00ac), R(0x00ae,0x00b1), S(0x00b4), R(0x00b6,0x00b8), S(0x00bb), S(0x00bf), S(0x00d7), + S(0x00f7), R(0x02c2,0x02c5), R(0x02d2,0x02df), R(0x02e5,0x02eb), S(0x02ed), R(0x02ef,0x02ff), S(0x0375), + S(0x037e), R(0x0384,0x0385), S(0x0387), S(0x03f6), S(0x0482), R(0x055a,0x055f), R(0x0589,0x058a), + R(0x058d,0x058f), S(0x05be), S(0x05c0), S(0x05c3), S(0x05c6), R(0x05f3,0x05f4), R(0x0606,0x060f), + S(0x061b), R(0x061d,0x061f), R(0x066a,0x066d), S(0x06d4), S(0x06de), S(0x06e9), R(0x06fd,0x06fe), + R(0x0700,0x070d), R(0x07f6,0x07f9), R(0x07fe,0x07ff), R(0x0830,0x083e), S(0x085e), S(0x0888), + R(0x0964,0x0965), S(0x0970), R(0x09f2,0x09f3), R(0x09fa,0x09fb), S(0x09fd), S(0x0a76), R(0x0af0,0x0af1), + S(0x0b70), R(0x0bf3,0x0bfa), S(0x0c77), S(0x0c7f), S(0x0c84), S(0x0d4f), S(0x0d79), S(0x0df4), S(0x0e3f), + S(0x0e4f), R(0x0e5a,0x0e5b), R(0x0f01,0x0f17), R(0x0f1a,0x0f1f), S(0x0f34), S(0x0f36), S(0x0f38), + R(0x0f3a,0x0f3d), S(0x0f85), R(0x0fbe,0x0fc5), R(0x0fc7,0x0fcc), R(0x0fce,0x0fda), R(0x104a,0x104f), + R(0x109e,0x109f), S(0x10fb), R(0x1360,0x1368), R(0x1390,0x1399), S(0x1400), R(0x166d,0x166e), + R(0x169b,0x169c), R(0x16eb,0x16ed), R(0x1735,0x1736), R(0x17d4,0x17d6), R(0x17d8,0x17db), + R(0x1800,0x180a), S(0x1940), R(0x1944,0x1945), R(0x19de,0x19ff), R(0x1a1e,0x1a1f), R(0x1aa0,0x1aa6), + R(0x1aa8,0x1aad), R(0x1b4e,0x1b4f), R(0x1b5a,0x1b6a), R(0x1b74,0x1b7f), R(0x1bfc,0x1bff), + R(0x1c3b,0x1c3f), R(0x1c7e,0x1c7f), R(0x1cc0,0x1cc7), S(0x1cd3), S(0x1fbd), R(0x1fbf,0x1fc1), + R(0x1fcd,0x1fcf), R(0x1fdd,0x1fdf), R(0x1fed,0x1fef), R(0x1ffd,0x1ffe), R(0x2010,0x2027), + R(0x2030,0x205e), R(0x207a,0x207e), R(0x208a,0x208e), R(0x20a0,0x20c4), R(0x2100,0x2101), + R(0x2103,0x2106), R(0x2108,0x2109), S(0x2114), R(0x2116,0x2118), R(0x211e,0x2123), S(0x2125), S(0x2127), + S(0x2129), S(0x212e), R(0x213a,0x213b), R(0x2140,0x2144), R(0x214a,0x214d), S(0x214f), R(0x218a,0x218b), + R(0x2190,0x2429), R(0x2440,0x244a), R(0x249c,0x24e9), R(0x2500,0x2775), R(0x2794,0x2b73), + R(0x2b76,0x2bff), R(0x2ce5,0x2cea), R(0x2cf9,0x2cfc), R(0x2cfe,0x2cff), S(0x2d70), R(0x2e00,0x2e2e), + R(0x2e30,0x2e5d), R(0x2e60,0x2e63), R(0x2e80,0x2e99), R(0x2e9b,0x2ef3), R(0x2f00,0x2fd5), + R(0x2ff0,0x2fff), R(0x3001,0x3004), R(0x3008,0x3020), S(0x3030), R(0x3036,0x3037), R(0x303d,0x303f), + R(0x309b,0x309c), S(0x30a0), S(0x30fb), R(0x3190,0x3191), R(0x3196,0x319f), R(0x31c0,0x31e5), S(0x31ef), + R(0x3200,0x321e), R(0x322a,0x3247), S(0x3250), R(0x3260,0x327f), R(0x328a,0x32b0), R(0x32c0,0x33ff), + R(0x4dc0,0x4dff), R(0xa490,0xa4c6), R(0xa4fe,0xa4ff), R(0xa60d,0xa60f), S(0xa673), S(0xa67e), + R(0xa6f2,0xa6f7), R(0xa700,0xa716), R(0xa720,0xa721), R(0xa789,0xa78a), R(0xa828,0xa82b), + R(0xa836,0xa839), R(0xa874,0xa877), R(0xa8ce,0xa8cf), R(0xa8f8,0xa8fa), S(0xa8fc), R(0xa92e,0xa92f), + S(0xa95f), R(0xa9c1,0xa9cd), R(0xa9de,0xa9df), R(0xaa5c,0xaa5f), R(0xaa77,0xaa79), R(0xaade,0xaadf), + R(0xaaf0,0xaaf1), S(0xab5b), R(0xab6a,0xab6b), S(0xabeb), S(0xfb29), R(0xfbb2,0xfbd2), R(0xfd3e,0xfd4f), + R(0xfd90,0xfd91), R(0xfdc8,0xfdcf), R(0xfdfc,0xfdff), R(0xfe10,0xfe19), R(0xfe30,0xfe52), + R(0xfe54,0xfe66), R(0xfe68,0xfe6b), R(0xff01,0xff0f), R(0xff1a,0xff20), R(0xff3b,0xff40), + R(0xff5b,0xff65), R(0xffe0,0xffe6), R(0xffe8,0xffee), R(0xfffc,0xfffd), R(0x10100,0x10102), + R(0x10137,0x1013f), R(0x10179,0x10189), R(0x1018c,0x1018e), R(0x10190,0x1019c), S(0x101a0), + R(0x101d0,0x101fc), S(0x1039f), S(0x103d0), S(0x1056f), S(0x10857), R(0x10877,0x10878), S(0x1091f), + S(0x1093f), R(0x10a50,0x10a58), S(0x10a7f), S(0x10ac8), R(0x10af0,0x10af6), R(0x10b39,0x10b3f), + R(0x10b99,0x10b9c), S(0x10d6e), R(0x10d8e,0x10d8f), S(0x10ead), R(0x10ec9,0x10eca), R(0x10ed0,0x10ed8), + R(0x10f55,0x10f59), R(0x10f86,0x10f89), R(0x11047,0x1104d), R(0x110bb,0x110bc), R(0x110be,0x110c1), + R(0x11140,0x11143), R(0x11174,0x11175), R(0x111c5,0x111c8), S(0x111cd), S(0x111db), R(0x111dd,0x111df), + R(0x11238,0x1123d), S(0x112a9), R(0x113d4,0x113d5), R(0x113d7,0x113d8), R(0x1144b,0x1144f), + R(0x1145a,0x1145b), S(0x1145d), S(0x114c6), R(0x115c1,0x115d7), R(0x11641,0x11643), R(0x11660,0x1166c), + S(0x116b9), R(0x1173c,0x1173f), S(0x1183b), R(0x11944,0x11946), S(0x119e2), R(0x11a3f,0x11a46), + R(0x11a9a,0x11a9c), R(0x11a9e,0x11aa2), R(0x11b00,0x11b09), S(0x11be1), R(0x11c41,0x11c45), + R(0x11c70,0x11c71), R(0x11ef7,0x11ef8), R(0x11f43,0x11f4f), R(0x11fd5,0x11ff1), S(0x11fff), + R(0x12470,0x12474), R(0x12ff1,0x12ff2), R(0x16a6e,0x16a6f), S(0x16af5), R(0x16b37,0x16b3f), + R(0x16b44,0x16b45), R(0x16d6d,0x16d6f), R(0x16e97,0x16e9a), S(0x16fe2), S(0x1bc9c), S(0x1bc9f), + R(0x1cc00,0x1ccef), R(0x1ccfa,0x1ccfc), R(0x1cd00,0x1ceb3), R(0x1ceba,0x1ced0), R(0x1ced2,0x1ced4), + R(0x1cedd,0x1cefd), R(0x1cf50,0x1cfc3), R(0x1d000,0x1d0f5), R(0x1d100,0x1d126), R(0x1d129,0x1d164), + R(0x1d16a,0x1d16c), R(0x1d183,0x1d184), R(0x1d18c,0x1d1a9), R(0x1d1ae,0x1d241), S(0x1d245), + R(0x1d253,0x1d25a), R(0x1d25d,0x1d25e), R(0x1d260,0x1d27f), R(0x1d300,0x1d356), S(0x1d6c1), S(0x1d6db), + S(0x1d6fb), S(0x1d715), S(0x1d735), S(0x1d74f), S(0x1d76f), S(0x1d789), S(0x1d7a9), S(0x1d7c3), + R(0x1d800,0x1d9ff), R(0x1da37,0x1da3a), R(0x1da6d,0x1da74), R(0x1da76,0x1da83), R(0x1da85,0x1da8b), + R(0x1db00,0x1db1c), S(0x1e14f), S(0x1e2ff), S(0x1e5ff), R(0x1e95e,0x1e95f), S(0x1ecac), S(0x1ecb0), + S(0x1ed2e), R(0x1eef0,0x1eef1), R(0x1f000,0x1f02b), R(0x1f030,0x1f093), R(0x1f0a0,0x1f0ae), + R(0x1f0b1,0x1f0bf), R(0x1f0c1,0x1f0cf), R(0x1f0d1,0x1f0f5), R(0x1f10d,0x1f1ae), R(0x1f1e6,0x1f202), + R(0x1f210,0x1f23b), R(0x1f240,0x1f248), R(0x1f250,0x1f251), R(0x1f260,0x1f265), R(0x1f300,0x1f6d9), + R(0x1f6dc,0x1f6ec), R(0x1f6f0,0x1f6fc), R(0x1f700,0x1f7db), R(0x1f7e0,0x1f7eb), R(0x1f7f0,0x1f80b), + R(0x1f810,0x1f847), R(0x1f850,0x1f859), R(0x1f860,0x1f887), R(0x1f890,0x1f8ad), R(0x1f8b0,0x1f8bb), + R(0x1f8c0,0x1f8c1), R(0x1f8d0,0x1f8d8), R(0x1f900,0x1fa57), R(0x1fa60,0x1fa6d), R(0x1fa70,0x1fa7c), + R(0x1fa80,0x1fac6), S(0x1fac8), R(0x1facc,0x1fadd), R(0x1fadf,0x1faeb), R(0x1faef,0x1fafa), + R(0x1fb00,0x1fb92), R(0x1fb94,0x1fbef), S(0x1fbfa) + }; +#undef R +#undef S + + /* The ASCII ones are the most frequently used ones, also CommonMark + * specification requests few more in this range. */ + if(codepoint <= 0x7f) + return ISPUNCT_(codepoint); + + return (md_unicode_bsearch__(codepoint, PUNCT_MAP, SIZEOF_ARRAY(PUNCT_MAP)) >= 0); + } + + static void + md_get_unicode_fold_info(unsigned codepoint, MD_UNICODE_FOLD_INFO* info) + { +#define R(cp_min, cp_max) ((cp_min) | 0x40000000), ((cp_max) | 0x80000000) +#define S(cp) (cp) + /* Unicode "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps" categories. + * (generated by scripts/build_folding_map.py) */ + static const unsigned FOLD_MAP_1[] = { + R(0x0041,0x005a), S(0x00b5), R(0x00c0,0x00d6), R(0x00d8,0x00de), R(0x0100,0x012e), R(0x0132,0x0136), + R(0x0139,0x0147), R(0x014a,0x0176), S(0x0178), R(0x0179,0x017d), S(0x017f), S(0x0181), S(0x0182), + S(0x0184), S(0x0186), S(0x0187), S(0x0189), S(0x018a), S(0x018b), S(0x018e), S(0x018f), S(0x0190), + S(0x0191), S(0x0193), S(0x0194), S(0x0196), S(0x0197), S(0x0198), S(0x019c), S(0x019d), S(0x019f), + R(0x01a0,0x01a4), S(0x01a6), S(0x01a7), S(0x01a9), S(0x01ac), S(0x01ae), S(0x01af), S(0x01b1), S(0x01b2), + S(0x01b3), S(0x01b5), S(0x01b7), S(0x01b8), S(0x01bc), S(0x01c4), S(0x01c5), S(0x01c7), S(0x01c8), + S(0x01ca), R(0x01cb,0x01db), R(0x01de,0x01ee), S(0x01f1), S(0x01f2), S(0x01f4), S(0x01f6), S(0x01f7), + R(0x01f8,0x021e), S(0x0220), R(0x0222,0x0232), S(0x023a), S(0x023b), S(0x023d), S(0x023e), S(0x0241), + S(0x0243), S(0x0244), S(0x0245), R(0x0246,0x024e), S(0x0345), S(0x0370), S(0x0372), S(0x0376), S(0x037f), + S(0x0386), R(0x0388,0x038a), S(0x038c), S(0x038e), S(0x038f), R(0x0391,0x03a1), R(0x03a3,0x03ab), + S(0x03c2), S(0x03cf), S(0x03d0), S(0x03d1), S(0x03d5), S(0x03d6), R(0x03d8,0x03ee), S(0x03f0), S(0x03f1), + S(0x03f4), S(0x03f5), S(0x03f7), S(0x03f9), S(0x03fa), R(0x03fd,0x03ff), R(0x0400,0x040f), + R(0x0410,0x042f), R(0x0460,0x0480), R(0x048a,0x04be), S(0x04c0), R(0x04c1,0x04cd), R(0x04d0,0x052e), + R(0x0531,0x0556), R(0x10a0,0x10c5), S(0x10c7), S(0x10cd), R(0x13f8,0x13fd), S(0x1c80), S(0x1c81), + S(0x1c82), S(0x1c83), S(0x1c84), S(0x1c85), S(0x1c86), S(0x1c87), S(0x1c88), S(0x1c89), R(0x1c90,0x1cba), + R(0x1cbd,0x1cbf), R(0x1e00,0x1e94), S(0x1e9b), R(0x1ea0,0x1efe), R(0x1f08,0x1f0f), R(0x1f18,0x1f1d), + R(0x1f28,0x1f2f), R(0x1f38,0x1f3f), R(0x1f48,0x1f4d), S(0x1f59), S(0x1f5b), S(0x1f5d), S(0x1f5f), + R(0x1f68,0x1f6f), S(0x1fb8), S(0x1fb9), S(0x1fba), S(0x1fbb), S(0x1fbe), R(0x1fc8,0x1fcb), S(0x1fd8), + S(0x1fd9), S(0x1fda), S(0x1fdb), S(0x1fe8), S(0x1fe9), S(0x1fea), S(0x1feb), S(0x1fec), S(0x1ff8), + S(0x1ff9), S(0x1ffa), S(0x1ffb), S(0x2126), S(0x212a), S(0x212b), S(0x2132), R(0x2160,0x216f), S(0x2183), + R(0x24b6,0x24cf), R(0x2c00,0x2c2f), S(0x2c60), S(0x2c62), S(0x2c63), S(0x2c64), R(0x2c67,0x2c6b), + S(0x2c6d), S(0x2c6e), S(0x2c6f), S(0x2c70), S(0x2c72), S(0x2c75), S(0x2c7e), S(0x2c7f), R(0x2c80,0x2ce2), + S(0x2ceb), S(0x2ced), S(0x2cf2), R(0xa640,0xa66c), R(0xa680,0xa69a), R(0xa722,0xa72e), R(0xa732,0xa76e), + S(0xa779), S(0xa77b), S(0xa77d), R(0xa77e,0xa786), S(0xa78b), S(0xa78d), S(0xa790), S(0xa792), + R(0xa796,0xa7a8), S(0xa7aa), S(0xa7ab), S(0xa7ac), S(0xa7ad), S(0xa7ae), S(0xa7b0), S(0xa7b1), S(0xa7b2), + S(0xa7b3), R(0xa7b4,0xa7c2), S(0xa7c4), S(0xa7c5), S(0xa7c6), S(0xa7c7), S(0xa7c9), S(0xa7cb), + R(0xa7cc,0xa7da), S(0xa7dc), S(0xa7dd), S(0xa7e2), S(0xa7f5), S(0xab6c), S(0xab6d), R(0xab70,0xabbf), + R(0xff21,0xff3a), R(0x10400,0x10427), R(0x104b0,0x104d3), R(0x10570,0x1057a), R(0x1057c,0x1058a), + R(0x1058c,0x10592), S(0x10594), S(0x10595), R(0x10c80,0x10cb2), R(0x10d50,0x10d65), R(0x118a0,0x118bf), + R(0x16e40,0x16e5f), R(0x16ea0,0x16eb8), S(0x1df40), S(0x1df48), S(0x1df4a), S(0x1df4d), S(0x1df51), + R(0x1df68,0x1df6e), R(0x1df72,0x1df7e), R(0x1e900,0x1e921) + }; + static const unsigned FOLD_MAP_1_DATA[] = { + 0x0061, 0x007a, 0x03bc, 0x00e0, 0x00f6, 0x00f8, 0x00fe, 0x0101, 0x012f, 0x0133, 0x0137, 0x013a, 0x0148, + 0x014b, 0x0177, 0x00ff, 0x017a, 0x017e, 0x0073, 0x0253, 0x0183, 0x0185, 0x0254, 0x0188, 0x0256, 0x0257, + 0x018c, 0x01dd, 0x0259, 0x025b, 0x0192, 0x0260, 0x0263, 0x0269, 0x0268, 0x0199, 0x026f, 0x0272, 0x0275, + 0x01a1, 0x01a5, 0x0280, 0x01a8, 0x0283, 0x01ad, 0x0288, 0x01b0, 0x028a, 0x028b, 0x01b4, 0x01b6, 0x0292, + 0x01b9, 0x01bd, 0x01c6, 0x01c6, 0x01c9, 0x01c9, 0x01cc, 0x01cc, 0x01dc, 0x01df, 0x01ef, 0x01f3, 0x01f3, + 0x01f5, 0x0195, 0x01bf, 0x01f9, 0x021f, 0x019e, 0x0223, 0x0233, 0x2c65, 0x023c, 0x019a, 0x2c66, 0x0242, + 0x0180, 0x0289, 0x028c, 0x0247, 0x024f, 0x03b9, 0x0371, 0x0373, 0x0377, 0x03f3, 0x03ac, 0x03ad, 0x03af, + 0x03cc, 0x03cd, 0x03ce, 0x03b1, 0x03c1, 0x03c3, 0x03cb, 0x03c3, 0x03d7, 0x03b2, 0x03b8, 0x03c6, 0x03c0, + 0x03d9, 0x03ef, 0x03ba, 0x03c1, 0x03b8, 0x03b5, 0x03f8, 0x03f2, 0x03fb, 0x037b, 0x037d, 0x0450, 0x045f, + 0x0430, 0x044f, 0x0461, 0x0481, 0x048b, 0x04bf, 0x04cf, 0x04c2, 0x04ce, 0x04d1, 0x052f, 0x0561, 0x0586, + 0x2d00, 0x2d25, 0x2d27, 0x2d2d, 0x13f0, 0x13f5, 0x0432, 0x0434, 0x043e, 0x0441, 0x0442, 0x0442, 0x044a, + 0x0463, 0xa64b, 0x1c8a, 0x10d0, 0x10fa, 0x10fd, 0x10ff, 0x1e01, 0x1e95, 0x1e61, 0x1ea1, 0x1eff, 0x1f00, + 0x1f07, 0x1f10, 0x1f15, 0x1f20, 0x1f27, 0x1f30, 0x1f37, 0x1f40, 0x1f45, 0x1f51, 0x1f53, 0x1f55, 0x1f57, + 0x1f60, 0x1f67, 0x1fb0, 0x1fb1, 0x1f70, 0x1f71, 0x03b9, 0x1f72, 0x1f75, 0x1fd0, 0x1fd1, 0x1f76, 0x1f77, + 0x1fe0, 0x1fe1, 0x1f7a, 0x1f7b, 0x1fe5, 0x1f78, 0x1f79, 0x1f7c, 0x1f7d, 0x03c9, 0x006b, 0x00e5, 0x214e, + 0x2170, 0x217f, 0x2184, 0x24d0, 0x24e9, 0x2c30, 0x2c5f, 0x2c61, 0x026b, 0x1d7d, 0x027d, 0x2c68, 0x2c6c, + 0x0251, 0x0271, 0x0250, 0x0252, 0x2c73, 0x2c76, 0x023f, 0x0240, 0x2c81, 0x2ce3, 0x2cec, 0x2cee, 0x2cf3, + 0xa641, 0xa66d, 0xa681, 0xa69b, 0xa723, 0xa72f, 0xa733, 0xa76f, 0xa77a, 0xa77c, 0x1d79, 0xa77f, 0xa787, + 0xa78c, 0x0265, 0xa791, 0xa793, 0xa797, 0xa7a9, 0x0266, 0x025c, 0x0261, 0x026c, 0x026a, 0x029e, 0x0287, + 0x029d, 0xab53, 0xa7b5, 0xa7c3, 0xa794, 0x0282, 0x1d8e, 0xa7c8, 0xa7ca, 0x0264, 0xa7cd, 0xa7db, 0x019b, + 0x0277, 0x027c, 0xa7f6, 0xab4b, 0xab4c, 0x13a0, 0x13ef, 0xff41, 0xff5a, 0x10428, 0x1044f, 0x104d8, + 0x104fb, 0x10597, 0x105a1, 0x105a3, 0x105b1, 0x105b3, 0x105b9, 0x105bb, 0x105bc, 0x10cc0, 0x10cf2, + 0x10d70, 0x10d85, 0x118c0, 0x118df, 0x16e60, 0x16e7f, 0x16ebb, 0x16ed3, 0x1df41, 0x1df49, 0x1df4b, + 0x1df4e, 0x1df52, 0x1df69, 0x1df6f, 0x1df73, 0x1df7f, 0x1e922, 0x1e943 + }; + static const unsigned FOLD_MAP_2[] = { + S(0x00df), S(0x0130), S(0x0149), S(0x01f0), S(0x0587), S(0x1e96), S(0x1e97), S(0x1e98), S(0x1e99), + S(0x1e9a), S(0x1e9e), S(0x1f50), R(0x1f80,0x1f87), R(0x1f88,0x1f8f), R(0x1f90,0x1f97), R(0x1f98,0x1f9f), + R(0x1fa0,0x1fa7), R(0x1fa8,0x1faf), S(0x1fb2), S(0x1fb3), S(0x1fb4), S(0x1fb6), S(0x1fbc), S(0x1fc2), + S(0x1fc3), S(0x1fc4), S(0x1fc6), S(0x1fcc), S(0x1fd6), S(0x1fe4), S(0x1fe6), S(0x1ff2), S(0x1ff3), + S(0x1ff4), S(0x1ff6), S(0x1ffc), S(0xfb00), S(0xfb01), S(0xfb02), S(0xfb05), S(0xfb06), S(0xfb13), + S(0xfb14), S(0xfb15), S(0xfb16), S(0xfb17), S(0x1df95) + }; + static const unsigned FOLD_MAP_2_DATA[] = { + 0x0073,0x0073, 0x0069,0x0307, 0x02bc,0x006e, 0x006a,0x030c, 0x0565,0x0582, 0x0068,0x0331, 0x0074,0x0308, + 0x0077,0x030a, 0x0079,0x030a, 0x0061,0x02be, 0x0073,0x0073, 0x03c5,0x0313, 0x1f00,0x03b9, 0x1f07,0x03b9, + 0x1f00,0x03b9, 0x1f07,0x03b9, 0x1f20,0x03b9, 0x1f27,0x03b9, 0x1f20,0x03b9, 0x1f27,0x03b9, 0x1f60,0x03b9, + 0x1f67,0x03b9, 0x1f60,0x03b9, 0x1f67,0x03b9, 0x1f70,0x03b9, 0x03b1,0x03b9, 0x03ac,0x03b9, 0x03b1,0x0342, + 0x03b1,0x03b9, 0x1f74,0x03b9, 0x03b7,0x03b9, 0x03ae,0x03b9, 0x03b7,0x0342, 0x03b7,0x03b9, 0x03b9,0x0342, + 0x03c1,0x0313, 0x03c5,0x0342, 0x1f7c,0x03b9, 0x03c9,0x03b9, 0x03ce,0x03b9, 0x03c9,0x0342, 0x03c9,0x03b9, + 0x0066,0x0066, 0x0066,0x0069, 0x0066,0x006c, 0x0073,0x0074, 0x0073,0x0074, 0x0574,0x0576, 0x0574,0x0565, + 0x0574,0x056b, 0x057e,0x0576, 0x0574,0x056d, 0x0073,0x0073 + }; + static const unsigned FOLD_MAP_3[] = { + S(0x0390), S(0x03b0), S(0x1f52), S(0x1f54), S(0x1f56), S(0x1fb7), S(0x1fc7), S(0x1fd2), S(0x1fd3), + S(0x1fd7), S(0x1fe2), S(0x1fe3), S(0x1fe7), S(0x1ff7), S(0xfb03), S(0xfb04) + }; + static const unsigned FOLD_MAP_3_DATA[] = { + 0x03b9,0x0308,0x0301, 0x03c5,0x0308,0x0301, 0x03c5,0x0313,0x0300, 0x03c5,0x0313,0x0301, + 0x03c5,0x0313,0x0342, 0x03b1,0x0342,0x03b9, 0x03b7,0x0342,0x03b9, 0x03b9,0x0308,0x0300, + 0x03b9,0x0308,0x0301, 0x03b9,0x0308,0x0342, 0x03c5,0x0308,0x0300, 0x03c5,0x0308,0x0301, + 0x03c5,0x0308,0x0342, 0x03c9,0x0342,0x03b9, 0x0066,0x0066,0x0069, 0x0066,0x0066,0x006c + }; +#undef R +#undef S + static const struct { + const unsigned* map; + const unsigned* data; + size_t map_size; + unsigned n_codepoints; + } FOLD_MAP_LIST[] = { + { FOLD_MAP_1, FOLD_MAP_1_DATA, SIZEOF_ARRAY(FOLD_MAP_1), 1 }, + { FOLD_MAP_2, FOLD_MAP_2_DATA, SIZEOF_ARRAY(FOLD_MAP_2), 2 }, + { FOLD_MAP_3, FOLD_MAP_3_DATA, SIZEOF_ARRAY(FOLD_MAP_3), 3 } + }; + + int i; + + /* Fast path for ASCII characters. */ + if(codepoint <= 0x7f) { + info->codepoints[0] = codepoint; + if(ISUPPER_(codepoint)) + info->codepoints[0] += 'a' - 'A'; + info->n_codepoints = 1; + return; + } + + /* Try to locate the codepoint in any of the maps. */ + for(i = 0; i < (int) SIZEOF_ARRAY(FOLD_MAP_LIST); i++) { + int index; + + index = md_unicode_bsearch__(codepoint, FOLD_MAP_LIST[i].map, FOLD_MAP_LIST[i].map_size); + if(index >= 0) { + /* Found the mapping. */ + unsigned n_codepoints = FOLD_MAP_LIST[i].n_codepoints; + const unsigned* map = FOLD_MAP_LIST[i].map; + const unsigned* codepoints = FOLD_MAP_LIST[i].data + (index * n_codepoints); + + memcpy(info->codepoints, codepoints, sizeof(unsigned) * n_codepoints); + info->n_codepoints = n_codepoints; + + if(FOLD_MAP_LIST[i].map[index] != codepoint) { + /* The found mapping maps whole range of codepoints, + * i.e. we have to offset info->codepoints[0] accordingly. */ + if((map[index] & 0x00ffffff)+1 == codepoints[0]) { + /* Alternating type of the range. */ + info->codepoints[0] = codepoint + ((codepoint & 0x1) == (map[index] & 0x1) ? 1 : 0); + } else { + /* Range to range kind of mapping. */ + info->codepoints[0] += (codepoint - (map[index] & 0x00ffffff)); + } + } + + return; + } + } + + /* No mapping found. Map the codepoint to itself. */ + info->codepoints[0] = codepoint; + info->n_codepoints = 1; + } +#endif + + +#if defined MD4C_USE_UTF16 + #define IS_UTF16_SURROGATE_HI(word) (((WORD)(word) & 0xfc00) == 0xd800) + #define IS_UTF16_SURROGATE_LO(word) (((WORD)(word) & 0xfc00) == 0xdc00) + #define UTF16_DECODE_SURROGATE(hi, lo) (0x10000 + ((((unsigned)(hi) & 0x3ff) << 10) | (((unsigned)(lo) & 0x3ff) << 0))) + + static unsigned + md_decode_utf16le__(const CHAR* str, SZ str_size, SZ* p_size) + { + if(IS_UTF16_SURROGATE_HI(str[0])) { + if(1 < str_size && IS_UTF16_SURROGATE_LO(str[1])) { + if(p_size != NULL) + *p_size = 2; + return UTF16_DECODE_SURROGATE(str[0], str[1]); + } + } + + if(p_size != NULL) + *p_size = 1; + return str[0]; + } + + static unsigned + md_decode_utf16le_before__(MD_CTX* ctx, OFF off) + { + if(off > 2 && IS_UTF16_SURROGATE_HI(CH(off-2)) && IS_UTF16_SURROGATE_LO(CH(off-1))) + return UTF16_DECODE_SURROGATE(CH(off-2), CH(off-1)); + + return CH(off-1); + } + + /* No whitespace uses surrogates, so no decoding needed here. */ + #define ISUNICODEWHITESPACE_(codepoint) md_is_unicode_whitespace__(codepoint) + #define ISUNICODEWHITESPACE(off) md_is_unicode_whitespace__(CH(off)) + #define ISUNICODEWHITESPACEBEFORE(off) md_is_unicode_whitespace__(CH((off)-1)) + + #define ISUNICODEPUNCT(off) md_is_unicode_punct__(md_decode_utf16le__(STR(off), ctx->size - (off), NULL)) + #define ISUNICODEPUNCTBEFORE(off) md_is_unicode_punct__(md_decode_utf16le_before__(ctx, off)) + + static inline int + md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_char_size) + { + return md_decode_utf16le__(str+off, str_size-off, p_char_size); + } +#elif defined MD4C_USE_UTF8 + #define IS_UTF8_LEAD1(byte) ((unsigned char)(byte) <= 0x7f) + #define IS_UTF8_LEAD2(byte) (((unsigned char)(byte) & 0xe0) == 0xc0) + #define IS_UTF8_LEAD3(byte) (((unsigned char)(byte) & 0xf0) == 0xe0) + #define IS_UTF8_LEAD4(byte) (((unsigned char)(byte) & 0xf8) == 0xf0) + #define IS_UTF8_TAIL(byte) (((unsigned char)(byte) & 0xc0) == 0x80) + + static unsigned + md_decode_utf8__(const CHAR* str, SZ str_size, SZ* p_size) + { + if(!IS_UTF8_LEAD1(str[0])) { + if(IS_UTF8_LEAD2(str[0])) { + if(1 < str_size && IS_UTF8_TAIL(str[1])) { + if(p_size != NULL) + *p_size = 2; + + return (((unsigned int)str[0] & 0x1f) << 6) | + (((unsigned int)str[1] & 0x3f) << 0); + } + } else if(IS_UTF8_LEAD3(str[0])) { + if(2 < str_size && IS_UTF8_TAIL(str[1]) && IS_UTF8_TAIL(str[2])) { + if(p_size != NULL) + *p_size = 3; + + return (((unsigned int)str[0] & 0x0f) << 12) | + (((unsigned int)str[1] & 0x3f) << 6) | + (((unsigned int)str[2] & 0x3f) << 0); + } + } else if(IS_UTF8_LEAD4(str[0])) { + if(3 < str_size && IS_UTF8_TAIL(str[1]) && IS_UTF8_TAIL(str[2]) && IS_UTF8_TAIL(str[3])) { + if(p_size != NULL) + *p_size = 4; + + return (((unsigned int)str[0] & 0x07) << 18) | + (((unsigned int)str[1] & 0x3f) << 12) | + (((unsigned int)str[2] & 0x3f) << 6) | + (((unsigned int)str[3] & 0x3f) << 0); + } + } + } + + if(p_size != NULL) + *p_size = 1; + return (unsigned) str[0]; + } + + static unsigned + md_decode_utf8_before__(MD_CTX* ctx, OFF off) + { + if(!IS_UTF8_LEAD1(CH(off-1))) { + if(off > 1 && IS_UTF8_LEAD2(CH(off-2)) && IS_UTF8_TAIL(CH(off-1))) + return (((unsigned int)CH(off-2) & 0x1f) << 6) | + (((unsigned int)CH(off-1) & 0x3f) << 0); + + if(off > 2 && IS_UTF8_LEAD3(CH(off-3)) && IS_UTF8_TAIL(CH(off-2)) && IS_UTF8_TAIL(CH(off-1))) + return (((unsigned int)CH(off-3) & 0x0f) << 12) | + (((unsigned int)CH(off-2) & 0x3f) << 6) | + (((unsigned int)CH(off-1) & 0x3f) << 0); + + if(off > 3 && IS_UTF8_LEAD4(CH(off-4)) && IS_UTF8_TAIL(CH(off-3)) && IS_UTF8_TAIL(CH(off-2)) && IS_UTF8_TAIL(CH(off-1))) + return (((unsigned int)CH(off-4) & 0x07) << 18) | + (((unsigned int)CH(off-3) & 0x3f) << 12) | + (((unsigned int)CH(off-2) & 0x3f) << 6) | + (((unsigned int)CH(off-1) & 0x3f) << 0); + } + + return (unsigned) CH(off-1); + } + + #define ISUNICODEWHITESPACE_(codepoint) md_is_unicode_whitespace__(codepoint) + #define ISUNICODEWHITESPACE(off) md_is_unicode_whitespace__(md_decode_utf8__(STR(off), ctx->size - (off), NULL)) + #define ISUNICODEWHITESPACEBEFORE(off) md_is_unicode_whitespace__(md_decode_utf8_before__(ctx, off)) + + #define ISUNICODEPUNCT(off) md_is_unicode_punct__(md_decode_utf8__(STR(off), ctx->size - (off), NULL)) + #define ISUNICODEPUNCTBEFORE(off) md_is_unicode_punct__(md_decode_utf8_before__(ctx, off)) + + static inline unsigned + md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_char_size) + { + return md_decode_utf8__(str+off, str_size-off, p_char_size); + } +#else + #define ISUNICODEWHITESPACE_(codepoint) ISWHITESPACE_(codepoint) + #define ISUNICODEWHITESPACE(off) ISWHITESPACE(off) + #define ISUNICODEWHITESPACEBEFORE(off) ISWHITESPACE((off)-1) + + #define ISUNICODEPUNCT(off) ISPUNCT(off) + #define ISUNICODEPUNCTBEFORE(off) ISPUNCT((off)-1) + + static inline void + md_get_unicode_fold_info(unsigned codepoint, MD_UNICODE_FOLD_INFO* info) + { + info->codepoints[0] = codepoint; + if(ISUPPER_(codepoint)) + info->codepoints[0] += 'a' - 'A'; + info->n_codepoints = 1; + } + + static inline unsigned + md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_size) + { + MD_UNUSED(str_size); + *p_size = 1; + return (unsigned) str[off]; + } +#endif + + +/************************************* + *** Helper string manipulations *** + *************************************/ + +/* Fill buffer with copy of the string between 'beg' and 'end' but replace any + * line breaks with given replacement character. + * + * NOTE: Caller is responsible to make sure the buffer is large enough. + * (Given the output is always shorter than input, (end - beg) is good idea + * what the caller should allocate.) + */ +static void +md_merge_lines(MD_CTX* ctx, OFF beg, OFF end, const MD_LINE* lines, MD_SIZE n_lines, + CHAR line_break_replacement_char, CHAR* buffer, SZ* p_size) +{ + CHAR* ptr = buffer; + int line_index = 0; + OFF off = beg; + + MD_UNUSED(n_lines); + + while(1) { + const MD_LINE* line = &lines[line_index]; + OFF line_end = line->end; + if(end < line_end) + line_end = end; + + while(off < line_end) { + *ptr = CH(off); + ptr++; + off++; + } + + if(off >= end) { + *p_size = (MD_SIZE)(ptr - buffer); + return; + } + + *ptr = line_break_replacement_char; + ptr++; + + line_index++; + off = lines[line_index].beg; + } +} + +/* Wrapper of md_merge_lines() which allocates new buffer for the output string. + */ +static int +md_merge_lines_alloc(MD_CTX* ctx, OFF beg, OFF end, const MD_LINE* lines, MD_SIZE n_lines, + CHAR line_break_replacement_char, CHAR** p_str, SZ* p_size) +{ + CHAR* buffer; + + buffer = (CHAR*) malloc(sizeof(CHAR) * (end - beg)); + if(buffer == NULL) { + MD_LOG("malloc() failed."); + return -1; + } + + md_merge_lines(ctx, beg, end, lines, n_lines, + line_break_replacement_char, buffer, p_size); + + *p_str = buffer; + return 0; +} + +static OFF +md_skip_unicode_whitespace(const CHAR* label, OFF off, SZ size) +{ + SZ char_size; + unsigned codepoint; + + while(off < size) { + codepoint = md_decode_unicode(label, off, size, &char_size); + if(!ISUNICODEWHITESPACE_(codepoint) && !ISNEWLINE_(label[off])) + break; + off += char_size; + } + + return off; +} + + +/****************************** + *** Recognizing raw HTML *** + ******************************/ + +/* md_is_html_tag() may be called when processing inlines (inline raw HTML) + * or when breaking document to blocks (checking for start of HTML block type 7). + * + * When breaking document to blocks, we do not yet know line boundaries, but + * in that case the whole tag has to live on a single line. We distinguish this + * by n_lines == 0. + */ +static int +md_is_html_tag(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + int attr_state; + OFF off = beg; + OFF line_end = (n_lines > 0) ? lines[0].end : ctx->size; + MD_SIZE line_index = 0; + + MD_ASSERT(CH(beg) == _T('<')); + + if(off + 1 >= line_end) + return false; + off++; + + /* For parsing attributes, we need a little state automaton below. + * State -1: no attributes are allowed. + * State 0: attribute could follow after some whitespace. + * State 1: after a whitespace (attribute name may follow). + * State 2: after attribute name ('=' MAY follow). + * State 3: after '=' (value specification MUST follow). + * State 41: in middle of unquoted attribute value. + * State 42: in middle of single-quoted attribute value. + * State 43: in middle of double-quoted attribute value. + */ + attr_state = 0; + + if(CH(off) == _T('/')) { + /* Closer tag "". No attributes may be present. */ + attr_state = -1; + off++; + } + + /* Tag name */ + if(off >= line_end || !ISALPHA(off)) + return false; + off++; + while(off < line_end && (ISALNUM(off) || CH(off) == _T('-'))) + off++; + + /* (Optional) attributes (if not closer), (optional) '/' (if not closer) + * and final '>'. */ + while(1) { + while(off < line_end && !ISNEWLINE(off)) { + if(attr_state > 40) { + if(attr_state == 41 && (ISBLANK(off) || ISANYOF(off, _T("\"'=<>`")))) { + attr_state = 0; + off--; /* Put the char back for re-inspection in the new state. */ + } else if(attr_state == 42 && CH(off) == _T('\'')) { + attr_state = 0; + } else if(attr_state == 43 && CH(off) == _T('"')) { + attr_state = 0; + } + off++; + } else if(ISWHITESPACE(off)) { + if(attr_state == 0) + attr_state = 1; + off++; + } else if(attr_state <= 2 && CH(off) == _T('>')) { + /* End. */ + goto done; + } else if(attr_state <= 2 && CH(off) == _T('/') && off+1 < line_end && CH(off+1) == _T('>')) { + /* End with digraph '/>' */ + off++; + goto done; + } else if((attr_state == 1 || attr_state == 2) && (ISALPHA(off) || CH(off) == _T('_') || CH(off) == _T(':'))) { + off++; + /* Attribute name */ + while(off < line_end && (ISALNUM(off) || ISANYOF(off, _T("_.:-")))) + off++; + attr_state = 2; + } else if(attr_state == 2 && CH(off) == _T('=')) { + /* Attribute assignment sign */ + off++; + attr_state = 3; + } else if(attr_state == 3) { + /* Expecting start of attribute value. */ + if(CH(off) == _T('"')) + attr_state = 43; + else if(CH(off) == _T('\'')) + attr_state = 42; + else if(!ISANYOF(off, _T("\"'=<>`")) && !ISNEWLINE(off)) + attr_state = 41; + else + return false; + off++; + } else { + /* Anything unexpected. */ + return false; + } + } + + /* We have to be on a single line. See definition of start condition + * of HTML block, type 7. */ + if(n_lines == 0) + return false; + + line_index++; + if(line_index >= n_lines) + return false; + + off = lines[line_index].beg; + line_end = lines[line_index].end; + + if(attr_state == 0 || attr_state == 41) + attr_state = 1; + + if(off >= max_end) + return false; + } + +done: + if(off >= max_end) + return false; + + *p_end = off+1; + return true; +} + +static int +md_scan_for_html_closer(MD_CTX* ctx, const MD_CHAR* str, MD_SIZE len, + const MD_LINE* lines, MD_SIZE n_lines, + OFF beg, OFF max_end, OFF* p_end, + OFF* p_scan_horizon) +{ + OFF off = beg; + MD_SIZE line_index = 0; + + if(off < *p_scan_horizon && *p_scan_horizon >= max_end - len) { + /* We have already scanned the range up to the max_end so we know + * there is nothing to see. */ + return false; + } + + while(true) { + while(off + len <= lines[line_index].end && off + len <= max_end) { + if(md_ascii_eq(STR(off), str, len)) { + /* Success. */ + *p_end = off + len; + return true; + } + off++; + } + + line_index++; + if(off >= max_end || line_index >= n_lines) { + /* Failure. */ + *p_scan_horizon = off; + return false; + } + + off = lines[line_index].beg; + } +} + +static int +md_is_html_comment(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + + MD_ASSERT(CH(beg) == _T('<')); + + if(off + 4 >= lines[0].end) + return false; + if(CH(off+1) != _T('!') || CH(off+2) != _T('-') || CH(off+3) != _T('-')) + return false; + + /* Skip only "" or "" */ + off += 2; + + /* Scan for ordinary comment closer "-->". */ + return md_scan_for_html_closer(ctx, _T("-->"), 3, + lines, n_lines, off, max_end, p_end, &ctx->html_comment_horizon); +} + +static int +md_is_html_processing_instruction(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + + if(off + 2 >= lines[0].end) + return false; + if(CH(off+1) != _T('?')) + return false; + off += 2; + + return md_scan_for_html_closer(ctx, _T("?>"), 2, + lines, n_lines, off, max_end, p_end, &ctx->html_proc_instr_horizon); +} + +static int +md_is_html_declaration(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + + if(off + 2 >= lines[0].end) + return false; + if(CH(off+1) != _T('!')) + return false; + off += 2; + + /* Declaration name. */ + if(off >= lines[0].end || !ISALPHA(off)) + return false; + off++; + while(off < lines[0].end && ISALPHA(off)) + off++; + + return md_scan_for_html_closer(ctx, _T(">"), 1, + lines, n_lines, off, max_end, p_end, &ctx->html_decl_horizon); +} + +static int +md_is_html_cdata(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + static const CHAR open_str[] = _T("= lines[0].end) + return false; + if(memcmp(STR(off), open_str, open_size * sizeof(CHAR)) != 0) + return false; + off += open_size; + + return md_scan_for_html_closer(ctx, _T("]]>"), 3, + lines, n_lines, off, max_end, p_end, &ctx->html_cdata_horizon); +} + +static int +md_is_html_any(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end) +{ + MD_ASSERT(CH(beg) == _T('<')); + return (md_is_html_tag(ctx, lines, n_lines, beg, max_end, p_end) || + md_is_html_comment(ctx, lines, n_lines, beg, max_end, p_end) || + md_is_html_processing_instruction(ctx, lines, n_lines, beg, max_end, p_end) || + md_is_html_declaration(ctx, lines, n_lines, beg, max_end, p_end) || + md_is_html_cdata(ctx, lines, n_lines, beg, max_end, p_end)); +} + + +/**************************** + *** Recognizing Entity *** + ****************************/ + +static int +md_is_hex_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + MD_UNUSED(ctx); + + while(off < max_end && ISXDIGIT_(text[off]) && off - beg <= 8) + off++; + + if(1 <= off - beg && off - beg <= 6) { + *p_end = off; + return true; + } else { + return false; + } +} + +static int +md_is_dec_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + MD_UNUSED(ctx); + + while(off < max_end && ISDIGIT_(text[off]) && off - beg <= 8) + off++; + + if(1 <= off - beg && off - beg <= 7) { + *p_end = off; + return true; + } else { + return false; + } +} + +static int +md_is_named_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg; + MD_UNUSED(ctx); + + if(off < max_end && ISALPHA_(text[off])) + off++; + else + return false; + + while(off < max_end && ISALNUM_(text[off]) && off - beg <= 48) + off++; + + if(2 <= off - beg && off - beg <= 48) { + *p_end = off; + return true; + } else { + return false; + } +} + +static int +md_is_entity_str(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end) +{ + int is_contents; + OFF off = beg; + + MD_ASSERT(text[off] == _T('&')); + off++; + + if(off+2 < max_end && text[off] == _T('#') && (text[off+1] == _T('x') || text[off+1] == _T('X'))) + is_contents = md_is_hex_entity_contents(ctx, text, off+2, max_end, &off); + else if(off+1 < max_end && text[off] == _T('#')) + is_contents = md_is_dec_entity_contents(ctx, text, off+1, max_end, &off); + else + is_contents = md_is_named_entity_contents(ctx, text, off, max_end, &off); + + if(is_contents && off < max_end && text[off] == _T(';')) { + *p_end = off+1; + return true; + } else { + return false; + } +} + +static inline int +md_is_entity(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end) +{ + return md_is_entity_str(ctx, ctx->text, beg, max_end, p_end); +} + + +/****************************** + *** Attribute Management *** + ******************************/ + +typedef struct MD_ATTRIBUTE_BUILD_tag MD_ATTRIBUTE_BUILD; +struct MD_ATTRIBUTE_BUILD_tag { + CHAR* text; + MD_TEXTTYPE* substr_types; + OFF* substr_offsets; + SZ substr_count; + SZ substr_alloc; + MD_TEXTTYPE trivial_types[1]; + OFF trivial_offsets[2]; +}; + + +#define MD_BUILD_ATTR_NO_ESCAPES 0x0001 + +static int +md_build_attr_append_substr(MD_CTX* ctx, MD_ATTRIBUTE_BUILD* build, + MD_TEXTTYPE type, OFF off) +{ + if(build->substr_count >= build->substr_alloc) { + MD_TEXTTYPE* new_substr_types; + OFF* new_substr_offsets; + SZ new_alloc = (build->substr_alloc > 0 + ? build->substr_alloc + build->substr_alloc / 2 + : 8); + + new_substr_types = (MD_TEXTTYPE*) realloc(build->substr_types, + new_alloc * sizeof(MD_TEXTTYPE)); + if(new_substr_types == NULL) { + MD_LOG("realloc() failed."); + return -1; + } + build->substr_types = new_substr_types; + + /* Note +1 to reserve space for final offset (== raw_size). */ + new_substr_offsets = (OFF*) realloc(build->substr_offsets, + (new_alloc+1) * sizeof(OFF)); + if(new_substr_offsets == NULL) { + MD_LOG("realloc() failed."); + return -1; + } + build->substr_offsets = new_substr_offsets; + build->substr_alloc = new_alloc; + } + + build->substr_types[build->substr_count] = type; + build->substr_offsets[build->substr_count] = off; + build->substr_count++; + return 0; +} + +static void +md_free_attribute(MD_CTX* ctx, MD_ATTRIBUTE_BUILD* build) +{ + MD_UNUSED(ctx); + + if(build->substr_alloc > 0) { + free(build->text); + free(build->substr_types); + free(build->substr_offsets); + } +} + +static int +md_build_attribute(MD_CTX* ctx, const CHAR* raw_text, SZ raw_size, + unsigned flags, MD_ATTRIBUTE* attr, MD_ATTRIBUTE_BUILD* build) +{ + OFF raw_off, off; + int is_trivial; + int ret = 0; + + memset(build, 0, sizeof(MD_ATTRIBUTE_BUILD)); + + /* If there is no backslash and no ampersand, build trivial attribute + * without any malloc(). */ + is_trivial = true; + for(raw_off = 0; raw_off < raw_size; raw_off++) { + if(ISANYOF3_(raw_text[raw_off], _T('\\'), _T('&'), _T('\0'))) { + is_trivial = false; + break; + } + } + + if(is_trivial) { + build->text = (CHAR*) (raw_size ? raw_text : NULL); + build->substr_types = build->trivial_types; + build->substr_offsets = build->trivial_offsets; + build->substr_count = 1; + build->substr_alloc = 0; + build->trivial_types[0] = MD_TEXT_NORMAL; + build->trivial_offsets[0] = 0; + build->trivial_offsets[1] = raw_size; + off = raw_size; + } else { + build->text = (CHAR*) malloc(raw_size * sizeof(CHAR)); + if(build->text == NULL) { + MD_LOG("malloc() failed."); + goto abort; + } + + raw_off = 0; + off = 0; + + while(raw_off < raw_size) { + if(raw_text[raw_off] == _T('\0')) { + MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_NULLCHAR, off)); + memcpy(build->text + off, raw_text + raw_off, sizeof(CHAR)); + off++; + raw_off++; + continue; + } + + if(raw_text[raw_off] == _T('&')) { + OFF ent_end; + + if(md_is_entity_str(ctx, raw_text, raw_off, raw_size, &ent_end)) { + MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_ENTITY, off)); + memcpy(build->text + off, raw_text + raw_off, (ent_end - raw_off) * sizeof(CHAR)); + off += ent_end - raw_off; + raw_off = ent_end; + continue; + } + } + + if(build->substr_count == 0 || build->substr_types[build->substr_count-1] != MD_TEXT_NORMAL) + MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_NORMAL, off)); + + if(!(flags & MD_BUILD_ATTR_NO_ESCAPES) && + raw_text[raw_off] == _T('\\') && raw_off+1 < raw_size && + (ISPUNCT_(raw_text[raw_off+1]) || ISNEWLINE_(raw_text[raw_off+1]))) + raw_off++; + + build->text[off++] = raw_text[raw_off++]; + } + build->substr_offsets[build->substr_count] = off; + } + + attr->text = build->text; + attr->size = off; + attr->substr_offsets = build->substr_offsets; + attr->substr_types = build->substr_types; + return 0; + +abort: + md_free_attribute(ctx, build); + return -1; +} + + +/************************************************** + *** Hashtable (with a text label as its key) *** + **************************************************/ + +#define MD_FNV1A_BASE 2166136261U +#define MD_FNV1A_PRIME 16777619U + +static inline unsigned +md_fnv1a(unsigned base, const void* data, size_t n) +{ + const unsigned char* buf = (const unsigned char*) data; + unsigned hash = base; + size_t i; + + for(i = 0; i < n; i++) { + hash ^= buf[i]; + hash *= MD_FNV1A_PRIME; + } + + return hash; +} + +/* Label equivalence is quite complicated with regards to whitespace and case + * folding. This complicates computing a hash of it as well as direct comparison + * of two labels. */ + +static unsigned +md_label_hash(const CHAR* label, SZ size) +{ + unsigned hash = MD_FNV1A_BASE; + OFF off; + unsigned codepoint; + int is_whitespace = false; + + off = md_skip_unicode_whitespace(label, 0, size); + while(off < size) { + SZ char_size; + + codepoint = md_decode_unicode(label, off, size, &char_size); + is_whitespace = ISUNICODEWHITESPACE_(codepoint) || ISNEWLINE_(label[off]); + + if(is_whitespace) { + codepoint = ' '; + hash = md_fnv1a(hash, &codepoint, sizeof(unsigned)); + off = md_skip_unicode_whitespace(label, off, size); + } else { + MD_UNICODE_FOLD_INFO fold_info; + + md_get_unicode_fold_info(codepoint, &fold_info); + hash = md_fnv1a(hash, fold_info.codepoints, fold_info.n_codepoints * sizeof(unsigned)); + off += char_size; + } + } + + return hash; +} + +static OFF +md_label_cmp_load_fold_info(const CHAR* label, OFF off, SZ size, + MD_UNICODE_FOLD_INFO* fold_info) +{ + unsigned codepoint; + SZ char_size; + + if(off >= size) { + /* Treat end of a link label as a whitespace. */ + goto whitespace; + } + + codepoint = md_decode_unicode(label, off, size, &char_size); + off += char_size; + if(ISUNICODEWHITESPACE_(codepoint)) { + /* Treat all whitespace as equivalent */ + goto whitespace; + } + + /* Get real folding info. */ + md_get_unicode_fold_info(codepoint, fold_info); + return off; + +whitespace: + fold_info->codepoints[0] = _T(' '); + fold_info->n_codepoints = 1; + return md_skip_unicode_whitespace(label, off, size); +} + +static int +md_label_cmp(const CHAR* a_label, SZ a_size, const CHAR* b_label, SZ b_size) +{ + OFF a_off; + OFF b_off; + MD_UNICODE_FOLD_INFO a_fi = { { 0 }, 0 }; + MD_UNICODE_FOLD_INFO b_fi = { { 0 }, 0 }; + OFF a_fi_off = 0; + OFF b_fi_off = 0; + int cmp; + + a_off = md_skip_unicode_whitespace(a_label, 0, a_size); + b_off = md_skip_unicode_whitespace(b_label, 0, b_size); + while(a_off < a_size || a_fi_off < a_fi.n_codepoints || + b_off < b_size || b_fi_off < b_fi.n_codepoints) + { + /* If needed, load fold info for next char. */ + if(a_fi_off >= a_fi.n_codepoints) { + a_fi_off = 0; + a_off = md_label_cmp_load_fold_info(a_label, a_off, a_size, &a_fi); + } + if(b_fi_off >= b_fi.n_codepoints) { + b_fi_off = 0; + b_off = md_label_cmp_load_fold_info(b_label, b_off, b_size, &b_fi); + } + + cmp = b_fi.codepoints[b_fi_off] - a_fi.codepoints[a_fi_off]; + if(cmp != 0) + return cmp; + + a_fi_off++; + b_fi_off++; + } + + return 0; +} + +typedef struct MD_LABEL_HASH_LIST_tag MD_LABEL_HASH_LIST; +struct MD_LABEL_HASH_LIST_tag { + unsigned n_entries; + unsigned alloc_entries; + MD_LABEL_HASH_ENTRY* entries[]; +}; + +static int +md_label_hash_entry_cmp(const void* a, const void* b) +{ + const MD_LABEL_HASH_ENTRY* a_entry = *(const MD_LABEL_HASH_ENTRY**)a; + const MD_LABEL_HASH_ENTRY* b_entry = *(const MD_LABEL_HASH_ENTRY**)b; + + if(a_entry->hash < b_entry->hash) + return -1; + else if(a_entry->hash > b_entry->hash) + return +1; + else + return md_label_cmp(a_entry->label, a_entry->label_size, + b_entry->label, b_entry->label_size); +} + +static int +md_label_hash_entry_cmp_for_sort(const void* a, const void* b) +{ + int cmp; + + cmp = md_label_hash_entry_cmp(a, b); + + /* Ensure stability of the sorting. */ + if(cmp == 0) { + const MD_LABEL_HASH_ENTRY* a_entry = *(const MD_LABEL_HASH_ENTRY**)a; + const MD_LABEL_HASH_ENTRY* b_entry = *(const MD_LABEL_HASH_ENTRY**)b; + + if(a_entry < b_entry) + cmp = -1; + else if(a_entry > b_entry) + cmp = +1; + } + + return cmp; +} + +static int +md_is_complex_label_bucket(MD_LABEL_HASH_TABLE* table, void* bucket) +{ + if(bucket == NULL) + return false; + + return (MD_LABEL_HASH_ENTRY*) bucket < (MD_LABEL_HASH_ENTRY*) table->defs || + (MD_LABEL_HASH_ENTRY*) bucket >= (MD_LABEL_HASH_ENTRY*)((char*)table->defs + table->n_defs * table->def_size); +} + +static int +md_build_label_hashtable(MD_CTX* ctx, MD_LABEL_HASH_TABLE* table) +{ + unsigned i, j; + + if(table->n_defs == 0) + return 0; + + table->n_buckets = (table->n_defs * 5) / 4; + table->buckets = malloc(table->n_buckets * sizeof(void*)); + if(table->buckets == NULL) { + MD_LOG("malloc() failed."); + goto abort; + } + memset(table->buckets, 0, table->n_buckets * sizeof(void*)); + + /* Each member of table->buckets[] can be: + * -- NULL, + * -- pointer to the MD_LABEL_HASH_ENTRY, or + * -- pointer to a MD_LABEL_HASH_LIST, which holds multiple pointers to + * such entries. + */ + for(i = 0; i < table->n_defs; i++) { + MD_LABEL_HASH_ENTRY* entry = (MD_LABEL_HASH_ENTRY*) ((char*) table->defs + i * table->def_size); + void** p_bucket = &table->buckets[entry->hash % table->n_buckets]; + MD_LABEL_HASH_LIST* list; + + if(*p_bucket == NULL) { + /* The bucket is empty. Make it just point to the entry. */ + *p_bucket = entry; + continue; + } + + if(!md_is_complex_label_bucket(table, *p_bucket)) + { + /* The bucket already contains one entry. Lets see whether it is the + * same label (duplicate) or different one (hash conflict). */ + MD_LABEL_HASH_ENTRY* old_entry = (MD_LABEL_HASH_ENTRY*) *p_bucket; + + if(md_label_cmp(entry->label, entry->label_size, + old_entry->label, old_entry->label_size) == 0) { + /* Duplicate label: We may ignore this definition. */ + continue; + } + + /* Make the bucket complex, i.e. able to hold more entries. */ + list = (MD_LABEL_HASH_LIST*) malloc(sizeof(MD_LABEL_HASH_LIST) + + 2 * sizeof(MD_LABEL_HASH_ENTRY*)); + if(list == NULL) { + MD_LOG("malloc() failed."); + goto abort; + } + list->entries[0] = old_entry; + list->entries[1] = entry; + list->n_entries = 2; + list->alloc_entries = 2; + *p_bucket = list; + continue; + } + + /* Append the entry to the complex bucket list. + * + * Note in this case we ignore potential duplicates to avoid expensive + * iterating over the complex bucket. Below, we revisit all the complex + * buckets and handle it more cheaply after the complex bucket contents + * is sorted. */ + list = (MD_LABEL_HASH_LIST*) *p_bucket; + if(list->n_entries >= list->alloc_entries) { + size_t alloc_entries = list->alloc_entries + list->alloc_entries / 2; + MD_LABEL_HASH_LIST* list_tmp = (MD_LABEL_HASH_LIST*) realloc(list, + sizeof(MD_LABEL_HASH_LIST) + alloc_entries * sizeof(MD_LABEL_HASH_ENTRY*)); + if(list_tmp == NULL) { + MD_LOG("realloc() failed."); + goto abort; + } + list = list_tmp; + list->alloc_entries = alloc_entries; + table->buckets[entry->hash % table->n_buckets] = list; + } + + list->entries[list->n_entries] = entry; + list->n_entries++; + } + + /* Sort the complex buckets so we can use bsearch() with them. */ + for(i = 0; i < table->n_buckets; i++) { + void* bucket = table->buckets[i]; + MD_LABEL_HASH_LIST* list; + + if(bucket == NULL) + continue; + + if(!md_is_complex_label_bucket(table, bucket)) + continue; + + list = (MD_LABEL_HASH_LIST*) bucket; + qsort(list->entries, list->n_entries, sizeof(MD_LABEL_HASH_ENTRY*), + md_label_hash_entry_cmp_for_sort); + + /* Disable all duplicates in the complex bucket by forcing all such + * records to point to the 1st such entry. I.e. no matter which + * record is found during the lookup, it will always point to the right + * definition. */ + for(j = 1; j < list->n_entries; j++) { + if(md_label_hash_entry_cmp(&list->entries[j-1], &list->entries[j]) == 0) + list->entries[j] = list->entries[j-1]; + } + } + + return 0; + +abort: + return -1; +} + +static void +md_free_label_hashtable(MD_CTX* ctx, MD_LABEL_HASH_TABLE* table) +{ + MD_UNUSED(ctx); + + if(table->buckets != NULL) { + unsigned i; + + for(i = 0; i < table->n_buckets; i++) { + void* bucket = table->buckets[i]; + if(md_is_complex_label_bucket(table, bucket)) + free(bucket); + } + + free(table->buckets); + } +} + +static const MD_LABEL_HASH_ENTRY* +md_lookup_label_hashtable(MD_CTX* ctx, MD_LABEL_HASH_TABLE* table, const CHAR* label, SZ label_size) +{ + unsigned hash; + void* bucket; + + MD_UNUSED(ctx); + + if(table->n_buckets == 0) + return NULL; + + hash = md_label_hash(label, label_size); + bucket = table->buckets[hash % table->n_buckets]; + + if(bucket == NULL) { + return NULL; + } else if(!md_is_complex_label_bucket(table, bucket)) { + MD_LABEL_HASH_ENTRY* entry = (MD_LABEL_HASH_ENTRY*) bucket; + + if(entry->hash == hash && + md_label_cmp(entry->label, entry->label_size, label, label_size) == 0) + return entry; + else + return NULL; + } else { + MD_LABEL_HASH_LIST* list = (MD_LABEL_HASH_LIST*) bucket; + MD_LABEL_HASH_ENTRY key_buf; + const MD_LABEL_HASH_ENTRY* key = &key_buf; + MD_LABEL_HASH_ENTRY** ret; + + key_buf.label = (CHAR*) label; + key_buf.label_size = label_size; + key_buf.hash = hash; + + ret = (MD_LABEL_HASH_ENTRY**) bsearch(&key, list->entries, + list->n_entries, sizeof(MD_LABEL_HASH_ENTRY*), md_label_hash_entry_cmp); + if(ret != NULL) + return *ret; + else + return NULL; + } +} + +static void* +md_add_label_def(MD_CTX* ctx, MD_LABEL_HASH_TABLE* table, const CHAR* label, SZ label_size) +{ + MD_LABEL_HASH_ENTRY* entry; + + if(table->n_defs >= table->alloc_defs) { + size_t new_alloc_defs; + void* new_defs; + + new_alloc_defs = (table->alloc_defs > 0 + ? table->alloc_defs + table->alloc_defs / 2 + : 8); + new_defs = realloc(table->defs, new_alloc_defs * table->def_size); + if(new_defs == NULL) { + MD_LOG("realloc() failed."); + return NULL; + } + + table->defs = new_defs; + table->alloc_defs = new_alloc_defs; + } + + entry = (MD_LABEL_HASH_ENTRY*)((char*)table->defs + table->n_defs * table->def_size); + memset(entry, 0, table->def_size); + entry->label = label; + entry->label_size = label_size; + entry->hash = md_label_hash(label, label_size); + + table->n_defs++; + + return entry; +} + + +/************************************ + *** Link Reference Definitions *** + ************************************/ + +struct MD_REF_DEF_tag { + MD_LABEL_HASH_ENTRY entry; + CHAR* title; + SZ title_size; + OFF dest_beg; + OFF dest_end; + unsigned char label_needs_free : 1; + unsigned char title_needs_free : 1; +}; + +static int +md_build_ref_def_hashtable(MD_CTX* ctx) +{ + return md_build_label_hashtable(ctx, &ctx->ref_def_hashtable); +} + +static const MD_REF_DEF* +md_lookup_ref_def(MD_CTX* ctx, const CHAR* label, SZ label_size) +{ + return (const MD_REF_DEF*) md_lookup_label_hashtable(ctx, + &ctx->ref_def_hashtable, label, label_size); +} + + +/******************************* + *** Footnote Definitions *** + *******************************/ + +struct MD_FOOTNOTE_DEF_tag { + MD_LABEL_HASH_ENTRY entry; + unsigned int index; /* 0 = unreferenced; 1-based order of first reference */ + unsigned int ref_count; /* Number of references to this footnote. */ + MD_LINE* content_lines; /* always heap-allocated; freed by md_free_footnote_defs */ + MD_SIZE n_content_lines; +}; + +/* Returns 0 if not a footnote definition. + * Returns N > 0 (number of lines consumed) if it is one and the definition + * was stored successfully. + * Returns -1 on memory allocation error. + */ +static int +md_is_footnote_definition(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines) +{ + OFF off; + OFF label_beg, label_end; + MD_LINE* content_lines = NULL; + MD_FOOTNOTE_DEF* def; + MD_SIZE n; + MD_SIZE n_content_lines; + int ret = 0; + + /* Caller guarantees: n_lines >= 1 and lines[0] starts with [^. */ + MD_ASSERT(n_lines >= 1); + off = lines[0].beg; + MD_ASSERT(CH(off) == _T('[') && CH(off+1) == _T('^')); + off += 2; + + /* Label: non-empty sequence of non-whitespace, non-bracket chars. */ + label_beg = off; + while(off < lines[0].end && CH(off) != _T(']') && !ISWHITESPACE(off) && CH(off) != _T('[')) + off++; + label_end = off; + if(label_end == label_beg) + return false; + + /* Closing bracket. */ + if(off >= lines[0].end || CH(off) != _T(']')) + return false; + off++; + + /* Colon. */ + if(off >= lines[0].end || CH(off) != _T(':')) + return false; + off++; + + /* Skip optional whitespace after colon on the first line. */ + while(off < lines[0].end && ISWHITESPACE(off)) + off++; + + /* Count continuation lines. GitHub-style footnotes allow the rest of the + * paragraph block to form the footnote body, including unindented lines. + * + * Blank lines cannot appear inside a paragraph block (they always trigger + * a block boundary), so we do not need to handle them here. Stop before a + * following line which itself starts a new footnote definition. */ + n = 1; + while(n < n_lines) { + OFF def_off = lines[n].beg; + + if(def_off + 3 < lines[n].end && CH(def_off) == _T('[') && CH(def_off+1) == _T('^')) { + OFF tmp = def_off + 2; + + while(tmp < lines[n].end && CH(tmp) != _T(']') && + !ISWHITESPACE(tmp) && CH(tmp) != _T('[')) + tmp++; + + if(tmp > def_off + 2 && tmp + 1 < lines[n].end && + CH(tmp) == _T(']') && CH(tmp+1) == _T(':')) + break; + } + + n++; + } + + /* Build content_lines array. + * Line 0 content starts after the "[^label]: " prefix. + * Lines 1..n-1 are stored verbatim (md4c strips indentation before + * handing us MD_LINE, so no further adjustment is needed). */ + n_content_lines = (off >= lines[0].end && n > 1) ? n - 1 : n; + content_lines = (MD_LINE*) malloc(n_content_lines * sizeof(MD_LINE)); + if(content_lines == NULL) { + MD_LOG("malloc() failed."); + ret = -1; + goto abort; + } + + if(n_content_lines < n) { + memcpy(content_lines, lines + 1, n_content_lines * sizeof(MD_LINE)); + } else { + content_lines[0].beg = off; + content_lines[0].end = lines[0].end; + if(n > 1) + memcpy(content_lines + 1, lines + 1, (n - 1) * sizeof(MD_LINE)); + } + + def = (MD_FOOTNOTE_DEF*) md_add_label_def(ctx, &ctx->footnote_hashtable, + (CHAR*) STR(label_beg), label_end - label_beg); + if(def == NULL) { + ret = -1; + goto abort; + } + def->content_lines = content_lines; + def->n_content_lines = n_content_lines; + + return (int) n; + +abort: + free(content_lines); + return ret; +} + +static MD_FOOTNOTE_DEF* +md_lookup_footnote_def(MD_CTX* ctx, const CHAR* label, SZ label_size) +{ + return (MD_FOOTNOTE_DEF*) md_lookup_label_hashtable(ctx, + &ctx->footnote_hashtable, label, label_size); +} + +static int +md_build_footnote_def_hashtable(MD_CTX* ctx) +{ + return md_build_label_hashtable(ctx, &ctx->footnote_hashtable); +} + +static void +md_free_footnote_defs(MD_CTX* ctx) +{ + unsigned i; + + md_free_label_hashtable(ctx, &ctx->footnote_hashtable); + + for(i = 0; i < ctx->footnote_hashtable.n_defs; i++) + free(ctx->footnote_hashtable.footnote_defs[i].content_lines); + free(ctx->footnote_hashtable.footnote_defs); +} + + +/*************************** + *** Recognizing Links *** + ***************************/ + +/* Note this code is partially shared between processing inlines and blocks + * as reference definitions and links share some helper parser functions. + */ + +typedef struct MD_LINK_ATTR_tag MD_LINK_ATTR; +struct MD_LINK_ATTR_tag { + OFF dest_beg; + OFF dest_end; + + CHAR* title; + SZ title_size; + int title_needs_free; +}; + + +static int +md_is_link_label(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, + OFF* p_end, MD_SIZE* p_beg_line_index, MD_SIZE* p_end_line_index, + OFF* p_contents_beg, OFF* p_contents_end) +{ + OFF off = beg; + OFF contents_beg = 0; + OFF contents_end = 0; + MD_SIZE line_index = 0; + int len = 0; + + *p_beg_line_index = 0; + + if(CH(off) != _T('[')) + return false; + off++; + + while(1) { + OFF line_end = lines[line_index].end; + + while(off < line_end) { + if(CH(off) == _T('\\') && off+1 < ctx->size && (ISPUNCT(off+1) || ISNEWLINE(off+1))) { + if(contents_end == 0) { + contents_beg = off; + *p_beg_line_index = line_index; + } + contents_end = off + 2; + off += 2; + } else if(CH(off) == _T('[')) { + return false; + } else if(CH(off) == _T(']')) { + if(contents_beg < contents_end) { + /* Success. */ + *p_contents_beg = contents_beg; + *p_contents_end = contents_end; + *p_end = off+1; + *p_end_line_index = line_index; + return true; + } else { + /* Link label must have some non-whitespace contents. */ + return false; + } + } else { + unsigned codepoint; + SZ char_size; + + codepoint = md_decode_unicode(ctx->text, off, ctx->size, &char_size); + if(!ISUNICODEWHITESPACE_(codepoint)) { + if(contents_end == 0) { + contents_beg = off; + *p_beg_line_index = line_index; + } + contents_end = off + char_size; + } + + off += char_size; + } + + len++; + if(len > 999) + return false; + } + + line_index++; + len++; + if(line_index < n_lines) + off = lines[line_index].beg; + else + break; + } + + return false; +} + +static int +md_is_link_destination_A(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end, + OFF* p_contents_beg, OFF* p_contents_end) +{ + OFF off = beg; + + if(off >= max_end || CH(off) != _T('<')) + return false; + off++; + + while(off < max_end) { + if(CH(off) == _T('\\') && off+1 < max_end && ISPUNCT(off+1)) { + off += 2; + continue; + } + + if(ISNEWLINE(off) || CH(off) == _T('<')) + return false; + + if(CH(off) == _T('>')) { + /* Success. */ + *p_contents_beg = beg+1; + *p_contents_end = off; + *p_end = off+1; + return true; + } + + off++; + } + + return false; +} + +static int +md_is_link_destination_B(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end, + OFF* p_contents_beg, OFF* p_contents_end) +{ + OFF off = beg; + int parenthesis_level = 0; + + while(off < max_end) { + if(CH(off) == _T('\\') && off+1 < max_end && ISPUNCT(off+1)) { + off += 2; + continue; + } + + if(ISWHITESPACE(off) || ISCNTRL(off)) + break; + + /* Link destination may include balanced pairs of unescaped '(' ')'. + * Note we limit the maximal nesting level by 32 to protect us from + * https://github.com/jgm/cmark/issues/214 */ + if(CH(off) == _T('(')) { + parenthesis_level++; + if(parenthesis_level > 32) + return false; + } else if(CH(off) == _T(')')) { + if(parenthesis_level == 0) + break; + parenthesis_level--; + } + + off++; + } + + if(parenthesis_level != 0 || off == beg) + return false; + + /* Success. */ + *p_contents_beg = beg; + *p_contents_end = off; + *p_end = off; + return true; +} + +static inline int +md_is_link_destination(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end, + OFF* p_contents_beg, OFF* p_contents_end) +{ + if(CH(beg) == _T('<')) + return md_is_link_destination_A(ctx, beg, max_end, p_end, p_contents_beg, p_contents_end); + else + return md_is_link_destination_B(ctx, beg, max_end, p_end, p_contents_beg, p_contents_end); +} + +static int +md_is_link_title(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, + OFF* p_end, MD_SIZE* p_beg_line_index, MD_SIZE* p_end_line_index, + OFF* p_contents_beg, OFF* p_contents_end) +{ + OFF off = beg; + CHAR closer_char; + MD_SIZE line_index = 0; + + /* White space with up to one line break. */ + while(off < lines[line_index].end && ISWHITESPACE(off)) + off++; + if(off >= lines[line_index].end) { + line_index++; + if(line_index >= n_lines) + return false; + off = lines[line_index].beg; + } + if(off == beg) + return false; + + *p_beg_line_index = line_index; + + /* First char determines how to detect end of it. */ + switch(CH(off)) { + case _T('"'): closer_char = _T('"'); break; + case _T('\''): closer_char = _T('\''); break; + case _T('('): closer_char = _T(')'); break; + default: return false; + } + off++; + + *p_contents_beg = off; + + while(line_index < n_lines) { + OFF line_end = lines[line_index].end; + + while(off < line_end) { + if(CH(off) == _T('\\') && off+1 < ctx->size && (ISPUNCT(off+1) || ISNEWLINE(off+1))) { + off++; + } else if(CH(off) == closer_char) { + /* Success. */ + *p_contents_end = off; + *p_end = off+1; + *p_end_line_index = line_index; + return true; + } else if(closer_char == _T(')') && CH(off) == _T('(')) { + /* ()-style title cannot contain (unescaped '(')) */ + return false; + } + + off++; + } + + line_index++; + } + + return false; +} + +/* Returns 0 if it is not a reference definition. + * + * Returns N > 0 if it is a reference definition. N then corresponds to the + * number of lines forming it). In this case the definition is stored for + * resolving any links referring to it. + * + * Returns -1 in case of an error (out of memory). + */ +static int +md_is_link_reference_definition(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines) +{ + OFF label_contents_beg; + OFF label_contents_end; + MD_SIZE label_contents_line_index; + int label_is_multiline = false; + OFF dest_contents_beg; + OFF dest_contents_end; + OFF title_contents_beg; + OFF title_contents_end; + MD_SIZE title_contents_line_index; + int title_is_multiline = false; + OFF off; + MD_SIZE line_index = 0; + MD_SIZE tmp_line_index; + MD_REF_DEF* def = NULL; + int ret = 0; + + /* Link label. */ + if(!md_is_link_label(ctx, lines, n_lines, lines[0].beg, + &off, &label_contents_line_index, &line_index, + &label_contents_beg, &label_contents_end)) + return false; + label_is_multiline = (label_contents_line_index != line_index); + + /* Colon. */ + if(off >= lines[line_index].end || CH(off) != _T(':')) + return false; + off++; + + /* Optional white space with up to one line break. */ + while(off < lines[line_index].end && ISWHITESPACE(off)) + off++; + if(off >= lines[line_index].end) { + line_index++; + if(line_index >= n_lines) + return false; + off = lines[line_index].beg; + } + + /* Link destination. */ + if(!md_is_link_destination(ctx, off, lines[line_index].end, + &off, &dest_contents_beg, &dest_contents_end)) + return false; + + /* (Optional) title. Note we interpret it as an title only if nothing + * more follows on its last line. */ + if(md_is_link_title(ctx, lines + line_index, n_lines - line_index, off, + &off, &title_contents_line_index, &tmp_line_index, + &title_contents_beg, &title_contents_end) + && off >= lines[line_index + tmp_line_index].end) + { + title_is_multiline = (tmp_line_index != title_contents_line_index); + title_contents_line_index += line_index; + line_index += tmp_line_index; + } else { + /* Not a title. */ + title_is_multiline = false; + title_contents_beg = off; + title_contents_end = off; + title_contents_line_index = 0; + } + + /* Nothing more can follow on the last line. */ + if(off < lines[line_index].end) + return false; + + if(label_is_multiline) { + CHAR* label; + SZ label_size; + + MD_CHECK(md_merge_lines_alloc(ctx, label_contents_beg, label_contents_end, + lines + label_contents_line_index, n_lines - label_contents_line_index, + _T(' '), &label, &label_size)); + def = (MD_REF_DEF*) md_add_label_def(ctx, &ctx->ref_def_hashtable, label, label_size); + if(def == NULL) { + free(label); + goto abort; + } + def->label_needs_free = true; + } else { + def = (MD_REF_DEF*) md_add_label_def(ctx, &ctx->ref_def_hashtable, + STR(label_contents_beg), label_contents_end - label_contents_beg); + if(def == NULL) + goto abort; + } + + if(title_is_multiline) { + MD_CHECK(md_merge_lines_alloc(ctx, title_contents_beg, title_contents_end, + lines + title_contents_line_index, n_lines - title_contents_line_index, + _T('\n'), &def->title, &def->title_size)); + def->title_needs_free = true; + } else { + def->title = (CHAR*) STR(title_contents_beg); + def->title_size = title_contents_end - title_contents_beg; + } + + def->dest_beg = dest_contents_beg; + def->dest_end = dest_contents_end; + + /* Success. */ + return line_index + 1; + +abort: + /* Failure. */ + if(def != NULL && def->label_needs_free) + free((CHAR*) def->entry.label); + if(def != NULL && def->title_needs_free) + free(def->title); + return ret; +} + +static int +md_is_link_reference(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + OFF beg, OFF end, MD_LINK_ATTR* attr) +{ + const MD_REF_DEF* def; + const MD_LINE* beg_line; + int is_multiline; + CHAR* label; + SZ label_size; + int ret = false; + + MD_ASSERT(CH(beg) == _T('[') || CH(beg) == _T('!')); + MD_ASSERT(CH(end-1) == _T(']')); + + if(ctx->max_ref_def_output == 0) + return false; + + beg += (CH(beg) == _T('!') ? 2 : 1); + end--; + + /* Find lines corresponding to the beg and end positions. */ + beg_line = md_lookup_line(beg, lines, n_lines, NULL); + is_multiline = (end > beg_line->end); + + if(is_multiline) { + MD_CHECK(md_merge_lines_alloc(ctx, beg, end, beg_line, + (int)(n_lines - (beg_line - lines)), _T(' '), &label, &label_size)); + } else { + label = (CHAR*) STR(beg); + label_size = end - beg; + } + + def = md_lookup_ref_def(ctx, label, label_size); + if(def != NULL) { + attr->dest_beg = def->dest_beg; + attr->dest_end = def->dest_end; + attr->title = def->title; + attr->title_size = def->title_size; + attr->title_needs_free = false; + } + + if(is_multiline) + free(label); + + if(def != NULL) { + /* See https://github.com/mity/md4c/issues/238 */ + MD_SIZE output_size_estimation = def->entry.label_size + def->title_size + def->dest_end - def->dest_beg; + if(output_size_estimation < ctx->max_ref_def_output) { + ctx->max_ref_def_output -= output_size_estimation; + ret = true; + } else { + MD_LOG("Too many link reference definition instantiations."); + ctx->max_ref_def_output = 0; + } + } + +abort: + return ret; +} + +static int +md_is_inline_link_spec(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + OFF beg, OFF* p_end, MD_LINK_ATTR* attr) +{ + MD_SIZE line_index = 0; + MD_SIZE tmp_line_index; + OFF title_contents_beg; + OFF title_contents_end; + MD_SIZE title_contents_line_index; + int title_is_multiline; + OFF off = beg; + int ret = false; + + md_lookup_line(off, lines, n_lines, &line_index); + + MD_ASSERT(CH(off) == _T('(')); + off++; + + /* Optional white space with up to one line break. */ + while(off < lines[line_index].end && ISWHITESPACE(off)) + off++; + if(off >= lines[line_index].end && (off >= ctx->size || ISNEWLINE(off))) { + line_index++; + if(line_index >= n_lines) + return false; + off = lines[line_index].beg; + } + + /* Link destination may be omitted, but only when not also having a title. */ + if(off < ctx->size && CH(off) == _T(')')) { + attr->dest_beg = off; + attr->dest_end = off; + attr->title = NULL; + attr->title_size = 0; + attr->title_needs_free = false; + off++; + *p_end = off; + return true; + } + + /* Link destination. */ + if(!md_is_link_destination(ctx, off, lines[line_index].end, + &off, &attr->dest_beg, &attr->dest_end)) + return false; + + /* (Optional) title. */ + if(md_is_link_title(ctx, lines + line_index, n_lines - line_index, off, + &off, &title_contents_line_index, &tmp_line_index, + &title_contents_beg, &title_contents_end)) + { + title_is_multiline = (tmp_line_index != title_contents_line_index); + title_contents_line_index += line_index; + line_index += tmp_line_index; + } else { + /* Not a title. */ + title_is_multiline = false; + title_contents_beg = off; + title_contents_end = off; + title_contents_line_index = 0; + } + + /* Optional whitespace followed with final ')'. */ + while(off < lines[line_index].end && ISWHITESPACE(off)) + off++; + if(off >= lines[line_index].end) { + line_index++; + if(line_index >= n_lines) + return false; + off = lines[line_index].beg; + } + if(CH(off) != _T(')')) + goto abort; + off++; + + if(title_contents_beg >= title_contents_end) { + attr->title = NULL; + attr->title_size = 0; + attr->title_needs_free = false; + } else if(!title_is_multiline) { + attr->title = (CHAR*) STR(title_contents_beg); + attr->title_size = title_contents_end - title_contents_beg; + attr->title_needs_free = false; + } else { + MD_CHECK(md_merge_lines_alloc(ctx, title_contents_beg, title_contents_end, + lines + title_contents_line_index, n_lines - title_contents_line_index, + _T('\n'), &attr->title, &attr->title_size)); + attr->title_needs_free = true; + } + + *p_end = off; + ret = true; + +abort: + return ret; +} + +static void +md_free_ref_defs(MD_CTX* ctx) +{ + unsigned i; + + md_free_label_hashtable(ctx, &ctx->ref_def_hashtable); + + for(i = 0; i < ctx->ref_def_hashtable.n_defs; i++) { + MD_REF_DEF* def = &ctx->ref_def_hashtable.ref_defs[i]; + + if(def->label_needs_free) + free((void*) def->entry.label); + if(def->title_needs_free) + free(def->title); + } + + free(ctx->ref_def_hashtable.ref_defs); +} + + +/****************************************** + *** Processing Inlines (a.k.a Spans) *** + ******************************************/ + +/* We process inlines in few phases: + * + * (1) We go through the block text and collect all significant characters + * which may start/end a span or some other significant position into + * ctx->marks[]. Core of this is what md_collect_marks() does. + * + * We also do some very brief preliminary context-less analysis, whether + * it might be opener or closer (e.g. of an emphasis span). + * + * This speeds the other steps as we do not need to re-iterate over all + * characters anymore. + * + * (2) We analyze each potential mark types, in order by their precedence. + * + * In each md_analyze_XXX() function, we re-iterate list of the marks, + * skipping already resolved regions (in preceding precedences) and try to + * resolve them. + * + * (2.1) For trivial marks, which are single (e.g. HTML entity), we just mark + * them as resolved. + * + * (2.2) For range-type marks, we analyze whether the mark could be closer + * and, if yes, whether there is some preceding opener it could satisfy. + * + * If not we check whether it could be really an opener and if yes, we + * remember it so subsequent closers may resolve it. + * + * (3) Finally, when all marks were analyzed, we render the block contents + * by calling MD_RENDERER::text() callback, interrupting by ::enter_span() + * or ::close_span() whenever we reach a resolved mark. + */ + + +/* The mark structure. + * + * '\\': Maybe escape sequence. + * '\0': NULL char. + * '*': Maybe (strong) emphasis start/end. + * '_': Maybe (strong) emphasis start/end. + * '~': Maybe strikethrough start/end (needs MD_FLAG_STRIKETHROUGH). + * '+': Maybe insert start/end (needs MD_FLAG_INSERT) + * '`': Maybe code span start/end. + * '&': Maybe start of entity. + * ';': Maybe end of entity. + * '<': Maybe start of raw HTML or autolink. + * '>': Maybe end of raw HTML or autolink. + * '=': Maybe highlight start/end (needs MD_FLAG_HIGHLIGHT). + * '[': Maybe start of link label or link text. + * '!': Equivalent of '[' for image. + * ']': Maybe end of link label or link text. + * '@': Maybe permissive e-mail auto-link (needs MD_FLAG_PERMISSIVEEMAILAUTOLINKS). + * ':': Maybe permissive URL auto-link (needs MD_FLAG_PERMISSIVEURLAUTOLINKS). + * '.': Maybe permissive WWW auto-link (needs MD_FLAG_PERMISSIVEWWWAUTOLINKS). + * 'D': Dummy mark, it reserves a space for splitting a previous mark + * (e.g. emphasis) or to make more space for storing some special data + * related to the preceding mark (e.g. link). + * + * Note that not all instances of these chars in the text imply creation of the + * structure. Only those which have (or may have, after we see more context) + * the special meaning. + * + * (Keep this struct as small as possible to fit as much of them into CPU + * cache line.) + */ +struct MD_MARK_tag { + union { + struct { + OFF beg; + OFF end; + }; + void* pointer; /* Dummy marks can sometimes store a pointer */ + }; + + /* For unresolved openers, 'next' may be used to form a stack of + * unresolved open openers. + * + * When resolved with MD_MARK_OPENER/CLOSER flag, next/prev is index of the + * respective closer/opener. + */ + int prev; + int next; + CHAR ch; + unsigned char flags; +}; + +/* Mark flags (these apply to ALL mark types). */ +#define MD_MARK_POTENTIAL_OPENER 0x01 /* Maybe opener. */ +#define MD_MARK_POTENTIAL_CLOSER 0x02 /* Maybe closer. */ +#define MD_MARK_OPENER 0x04 /* Definitely opener. */ +#define MD_MARK_CLOSER 0x08 /* Definitely closer. */ +#define MD_MARK_RESOLVED 0x10 /* Resolved in any definite way. */ + +/* Mark flags specific for just some mark type(s) (so the bits can be reused). */ +#define MD_MARK_EMPH_OC 0x20 /* Opener/closer mixed candidate. Helper for the "rule of 3". */ +#define MD_MARK_EMPH_MOD3_0 0x40 +#define MD_MARK_EMPH_MOD3_1 0x80 +#define MD_MARK_EMPH_MOD3_2 (0x40 | 0x80) +#define MD_MARK_EMPH_MOD3_MASK (0x40 | 0x80) +#define MD_MARK_AUTOLINK 0x20 /* Distinguisher for '<', '>'. */ +#define MD_MARK_AUTOLINK_MISSING_MAILTO 0x40 /* For '@' */ +#define MD_MARK_VALIDPERMISSIVEAUTOLINK 0x20 /* For '@', ':', '.'. */ +#define MD_MARK_BRACKET_CANBEIMAGE 0x20 /* For '[', if can be expanded to the left to eat '!'. */ +#define MD_MARK_BRACKET_HASNESTED 0x40 /* For '[' to rule out invalid link labels early. */ +#define MD_MARK_BRACKET_FOOTNOTEREF 0x80 /* For '[', To distinguish footnotes. */ + +static MD_MARKSTACK* +md_emph_stack(MD_CTX* ctx, MD_CHAR ch, unsigned flags) +{ + MD_MARKSTACK* stack; + + switch(ch) { + case '*': stack = &ASTERISK_OPENERS_oo_mod3_0; break; + case '_': stack = &UNDERSCORE_OPENERS_oo_mod3_0; break; + default: MD_UNREACHABLE(); + } + + if(flags & MD_MARK_EMPH_OC) + stack += 3; + + switch(flags & MD_MARK_EMPH_MOD3_MASK) { + case MD_MARK_EMPH_MOD3_0: stack += 0; break; + case MD_MARK_EMPH_MOD3_1: stack += 1; break; + case MD_MARK_EMPH_MOD3_2: stack += 2; break; + default: MD_UNREACHABLE(); + } + + return stack; +} + +static MD_MARKSTACK* +md_opener_stack(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + switch(mark->ch) { + case _T('*'): + case _T('_'): return md_emph_stack(ctx, mark->ch, mark->flags); + + case _T('~'): return (mark->end - mark->beg == 1) ? &TILDE_OPENERS_1 : &TILDE_OPENERS_2; + + case _T('!'): + case _T('['): return &BRACKET_OPENERS; + + default: MD_UNREACHABLE(); + } +} + +static MD_MARK* +md_add_mark(MD_CTX* ctx) +{ + if(ctx->n_marks >= ctx->alloc_marks) { + MD_MARK* new_marks; + + ctx->alloc_marks = (ctx->alloc_marks > 0 + ? ctx->alloc_marks + ctx->alloc_marks / 2 + : 64); + new_marks = realloc(ctx->marks, ctx->alloc_marks * sizeof(MD_MARK)); + if(new_marks == NULL) { + MD_LOG("realloc() failed."); + return NULL; + } + + ctx->marks = new_marks; + } + + return &ctx->marks[ctx->n_marks++]; +} + +#define ADD_MARK_() \ + do { \ + mark = md_add_mark(ctx); \ + if(mark == NULL) { \ + ret = -1; \ + goto abort; \ + } \ + } while(0) + +#define ADD_MARK(ch_, beg_, end_, flags_) \ + do { \ + ADD_MARK_(); \ + mark->beg = (beg_); \ + mark->end = (end_); \ + mark->prev = -1; \ + mark->next = -1; \ + mark->ch = (char)(ch_); \ + mark->flags = (flags_); \ + } while(0) + + +static inline void +md_mark_stack_push(MD_CTX* ctx, MD_MARKSTACK* stack, int mark_index) +{ + ctx->marks[mark_index].next = stack->top; + stack->top = mark_index; +} + +static inline int +md_mark_stack_pop(MD_CTX* ctx, MD_MARKSTACK* stack) +{ + int top = stack->top; + if(top >= 0) + stack->top = ctx->marks[top].next; + return top; +} + +/* Sometimes, we need to store a pointer into the mark. It can only happen + * for dummy marks. */ +static inline void +md_mark_store_ptr(MD_CTX* ctx, int mark_index, void* ptr) +{ + MD_ASSERT(ctx->marks[mark_index].ch == 'D'); + ctx->marks[mark_index].pointer = ptr; +} + +static inline void* +md_mark_get_ptr(MD_CTX* ctx, int mark_index) +{ + MD_ASSERT(ctx->marks[mark_index].ch == 'D'); + return ctx->marks[mark_index].pointer; +} + +static inline void +md_resolve_range(MD_CTX* ctx, int opener_index, int closer_index) +{ + MD_MARK* opener = &ctx->marks[opener_index]; + MD_MARK* closer = &ctx->marks[closer_index]; + + /* Interconnect opener and closer and mark both as resolved. */ + opener->next = closer_index; + closer->prev = opener_index; + + opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED; + closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED; +} + +/* Pop all opener records in the activated chains after the given mark. + * This makes sure, we have no crossing ranges. */ +static void +md_pop_openers(MD_CTX* ctx, int opener_index) +{ + int i; + + for(i = 0; i < (int) SIZEOF_ARRAY(ctx->opener_stacks); i++) { + MD_MARKSTACK* stack = &ctx->opener_stacks[i]; + while(stack->top >= opener_index) + md_mark_stack_pop(ctx, stack); + } +} + +static void +md_disable_marks(MD_CTX* ctx, int mark_index0, int mark_index1) +{ + int i; + + for(i = mark_index0; i < mark_index1; i++) { + MD_MARK* mark = &ctx->marks[i]; + + mark->ch = 'D'; + mark->flags = 0; + } +} + +static void +md_build_mark_char_map(MD_CTX* ctx) +{ + memset(ctx->mark_char_map, 0, sizeof(ctx->mark_char_map)); + + ctx->mark_char_map['\\'] = 1; + ctx->mark_char_map['*'] = 1; + ctx->mark_char_map['_'] = 1; + ctx->mark_char_map['`'] = 1; + ctx->mark_char_map['&'] = 1; + ctx->mark_char_map[';'] = 1; + ctx->mark_char_map['<'] = 1; + ctx->mark_char_map['>'] = 1; + ctx->mark_char_map['['] = 1; + ctx->mark_char_map['!'] = 1; + ctx->mark_char_map[']'] = 1; + ctx->mark_char_map['\0'] = 1; + + if(ctx->parser.flags & (MD_FLAG_STRIKETHROUGH | MD_FLAG_SUBSCRIPTS)) + ctx->mark_char_map['~'] = 1; + + if(ctx->parser.flags & MD_FLAG_SUPERSCRIPTS) + ctx->mark_char_map['^'] = 1; + + if(ctx->parser.flags & MD_FLAG_LATEXMATHSPANS) + ctx->mark_char_map['$'] = 1; + + if(ctx->parser.flags & MD_FLAG_HIGHLIGHT) + ctx->mark_char_map['='] = 1; + + if(ctx->parser.flags & MD_FLAG_INSERT) + ctx->mark_char_map['+'] = 1; + + if(ctx->parser.flags & MD_FLAG_PERMISSIVEEMAILAUTOLINKS) + ctx->mark_char_map['@'] = 1; + + if(ctx->parser.flags & MD_FLAG_PERMISSIVEURLAUTOLINKS) + ctx->mark_char_map[':'] = 1; + + if(ctx->parser.flags & MD_FLAG_PERMISSIVEWWWAUTOLINKS) + ctx->mark_char_map['.'] = 1; + + if((ctx->parser.flags & MD_FLAG_TABLES) || (ctx->parser.flags & MD_FLAG_WIKILINKS) || + (ctx->parser.flags & MD_FLAG_SPOILERS)) + ctx->mark_char_map['|'] = 1; + + if(ctx->parser.flags & MD_FLAG_COLLAPSEWHITESPACE) { + int i; + + for(i = 0; i < (int) sizeof(ctx->mark_char_map); i++) { + if(ISWHITESPACE_(i)) + ctx->mark_char_map[i] = 1; + } + } +} + +static int +md_is_code_span(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, + MD_MARK* opener, MD_MARK* closer, + OFF last_potential_closers[CODESPAN_MARK_MAXLEN], + int* p_reached_paragraph_end) +{ + OFF opener_beg = beg; + OFF opener_end; + OFF closer_beg; + OFF closer_end; + SZ mark_len; + OFF line_end; + int has_space_after_opener = false; + int has_eol_after_opener = false; + int has_space_before_closer = false; + int has_eol_before_closer = false; + int has_only_space = true; + MD_SIZE line_index = 0; + + line_end = lines[0].end; + opener_end = opener_beg; + while(opener_end < line_end && CH(opener_end) == _T('`')) + opener_end++; + has_space_after_opener = (opener_end < line_end && CH(opener_end) == _T(' ')); + has_eol_after_opener = (opener_end == line_end); + + /* The caller needs to know end of the opening mark even if we fail. */ + opener->end = opener_end; + + mark_len = opener_end - opener_beg; + if(mark_len > CODESPAN_MARK_MAXLEN) + return false; + + /* Check whether we already know there is no closer of this length. + * If so, re-scan does no sense. This fixes issue #59. */ + if(last_potential_closers[mark_len-1] >= lines[n_lines-1].end || + (*p_reached_paragraph_end && last_potential_closers[mark_len-1] < opener_end)) + return false; + + closer_beg = opener_end; + closer_end = opener_end; + + /* Find closer mark. */ + while(true) { + while(closer_beg < line_end && CH(closer_beg) != _T('`')) { + if(CH(closer_beg) != _T(' ')) + has_only_space = false; + closer_beg++; + } + closer_end = closer_beg; + while(closer_end < line_end && CH(closer_end) == _T('`')) + closer_end++; + + if(closer_end - closer_beg == mark_len) { + /* Success. */ + has_space_before_closer = (closer_beg > lines[line_index].beg && CH(closer_beg-1) == _T(' ')); + has_eol_before_closer = (closer_beg == lines[line_index].beg); + break; + } + + if(closer_end - closer_beg > 0) { + /* We have found a back-tick which is not part of the closer. */ + has_only_space = false; + + /* But if we eventually fail, remember it as a potential closer + * of its own length for future attempts. This mitigates needs for + * rescans. */ + if(closer_end - closer_beg < CODESPAN_MARK_MAXLEN) { + if(closer_beg > last_potential_closers[closer_end - closer_beg - 1]) + last_potential_closers[closer_end - closer_beg - 1] = closer_beg; + } + } + + if(closer_end >= line_end) { + line_index++; + if(line_index >= n_lines) { + /* Reached end of the paragraph and still nothing. */ + *p_reached_paragraph_end = true; + return false; + } + /* Try on the next line. */ + line_end = lines[line_index].end; + closer_beg = lines[line_index].beg; + } else { + closer_beg = closer_end; + } + } + + /* If there is a space or a new line both after and before the opener + * (and if the code span is not made of spaces only), consume one initial + * and one trailing space as part of the marks. */ + if(!has_only_space && + (has_space_after_opener || has_eol_after_opener) && + (has_space_before_closer || has_eol_before_closer)) + { + if(has_space_after_opener) + opener_end++; + else + opener_end = lines[1].beg; + + if(has_space_before_closer) + closer_beg--; + else { + /* Go back to the end of prev line */ + closer_beg = lines[line_index-1].end; + /* But restore any trailing whitespace */ + while(closer_beg < ctx->size && ISBLANK(closer_beg)) + closer_beg++; + } + } + + opener->ch = _T('`'); + opener->beg = opener_beg; + opener->end = opener_end; + opener->flags = MD_MARK_POTENTIAL_OPENER; + closer->ch = _T('`'); + closer->beg = closer_beg; + closer->end = closer_end; + closer->flags = MD_MARK_POTENTIAL_CLOSER; + return true; +} + +static int +md_is_autolink_uri(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg+1; + + MD_ASSERT(CH(beg) == _T('<')); + + /* Check for scheme. */ + if(off >= max_end || !ISALNUM(off)) + return false; + off++; + while(1) { + if(off >= max_end) + return false; + if(off - beg > 32) + return false; + if(CH(off) == _T(':') && off - beg >= 3) + break; + if(!ISALNUM(off) && CH(off) != _T('+') && CH(off) != _T('-') && CH(off) != _T('.')) + return false; + off++; + } + + /* Check the path after the scheme. */ + while(off < max_end && CH(off) != _T('>')) { + if(ISWHITESPACE(off) || ISCNTRL(off) || CH(off) == _T('<')) + return false; + off++; + } + + if(off >= max_end) + return false; + + MD_ASSERT(CH(off) == _T('>')); + *p_end = off+1; + return true; +} + +static int +md_is_autolink_email(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end) +{ + OFF off = beg + 1; + int label_len; + + MD_ASSERT(CH(beg) == _T('<')); + + /* The code should correspond to this regexp: + /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+ + @[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? + (?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ + */ + + /* Username (before '@'). */ + while(off < max_end && (ISALNUM(off) || ISANYOF(off, _T(".!#$%&'*+/=?^_`{|}~-")))) + off++; + if(off <= beg+1) + return false; + + /* '@' */ + if(off >= max_end || CH(off) != _T('@')) + return false; + off++; + + /* Labels delimited with '.'; each label is sequence of 1 - 63 alnum + * characters or '-', but '-' is not allowed as first or last char. */ + label_len = 0; + while(off < max_end) { + if(ISALNUM(off)) + label_len++; + else if(CH(off) == _T('-') && label_len > 0) + label_len++; + else if(CH(off) == _T('.') && label_len > 0 && CH(off-1) != _T('-')) + label_len = 0; + else + break; + + if(label_len > 63) + return false; + + off++; + } + + if(label_len <= 0 || off >= max_end || CH(off) != _T('>') || CH(off-1) == _T('-')) + return false; + + *p_end = off+1; + return true; +} + +static int +md_is_autolink(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end, int* p_missing_mailto) +{ + if(md_is_autolink_uri(ctx, beg, max_end, p_end)) { + *p_missing_mailto = false; + return true; + } + + if(md_is_autolink_email(ctx, beg, max_end, p_end)) { + *p_missing_mailto = true; + return true; + } + + return false; +} + +static int +md_collect_marks(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, int table_mode) +{ + MD_SIZE line_index; + int ret = 0; + MD_MARK* mark; + OFF codespan_last_potential_closers[CODESPAN_MARK_MAXLEN] = { 0 }; + int codespan_scanned_till_paragraph_end = false; + + for(line_index = 0; line_index < n_lines; line_index++) { + const MD_LINE* line = &lines[line_index]; + OFF off = line->beg; + + while(true) { + CHAR ch; + +#ifdef MD4C_USE_UTF16 + /* For UTF-16, mark_char_map[] covers only ASCII. */ + #define IS_MARK_CHAR(off) ((CH(off) < SIZEOF_ARRAY(ctx->mark_char_map)) && \ + (ctx->mark_char_map[(unsigned char) CH(off)])) +#else + /* For 8-bit encodings, mark_char_map[] covers all 256 elements. */ + #define IS_MARK_CHAR(off) (ctx->mark_char_map[(unsigned char) CH(off)]) +#endif + + /* Optimization: Use some loop unrolling. */ + while(off + 3 < line->end && !IS_MARK_CHAR(off+0) && !IS_MARK_CHAR(off+1) + && !IS_MARK_CHAR(off+2) && !IS_MARK_CHAR(off+3)) + off += 4; + while(off < line->end && !IS_MARK_CHAR(off+0)) + off++; + + if(off >= line->end) + break; + + ch = CH(off); + + /* A backslash escape. + * It can go beyond line->end as it may involve escaped new + * line to form a hard break. */ + if(ch == _T('\\') && off+1 < ctx->size && (ISPUNCT(off+1) || ISNEWLINE(off+1))) { + /* Hard-break cannot be on the last line of the block. */ + if(!ISNEWLINE(off+1) || line_index+1 < n_lines) + ADD_MARK(ch, off, off+2, MD_MARK_RESOLVED); + off += 2; + continue; + } + + /* A potential (string) emphasis start/end. */ + if(ch == _T('*') || ch == _T('_')) { + OFF tmp = off+1; + int left_level; /* What precedes: 0 = whitespace; 1 = punctuation; 2 = other char. */ + int right_level; /* What follows: 0 = whitespace; 1 = punctuation; 2 = other char. */ + + while(tmp < line->end && CH(tmp) == ch) + tmp++; + + if(off == line->beg || ISUNICODEWHITESPACEBEFORE(off)) + left_level = 0; + else if(ISUNICODEPUNCTBEFORE(off)) + left_level = 1; + else + left_level = 2; + + if(tmp == line->end || ISUNICODEWHITESPACE(tmp)) + right_level = 0; + else if(ISUNICODEPUNCT(tmp)) + right_level = 1; + else + right_level = 2; + + /* Intra-word underscore doesn't have special meaning. */ + if(ch == _T('_') && left_level == 2 && right_level == 2) { + left_level = 0; + right_level = 0; + } + + if(left_level != 0 || right_level != 0) { + unsigned flags = 0; + + if(left_level > 0 && left_level >= right_level) + flags |= MD_MARK_POTENTIAL_CLOSER; + if(right_level > 0 && right_level >= left_level) + flags |= MD_MARK_POTENTIAL_OPENER; + if(flags == (MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER)) + flags |= MD_MARK_EMPH_OC; + + /* For "the rule of three" we need to remember the original + * size of the mark (modulo three), before we potentially + * split the mark when being later resolved partially by some + * shorter closer. */ + switch((tmp - off) % 3) { + case 0: flags |= MD_MARK_EMPH_MOD3_0; break; + case 1: flags |= MD_MARK_EMPH_MOD3_1; break; + case 2: flags |= MD_MARK_EMPH_MOD3_2; break; + } + + ADD_MARK(ch, off, tmp, flags); + + /* During resolving, multiple asterisks may have to be + * split into independent span start/ends. Consider e.g. + * "**foo* bar*". Therefore we push also some empty dummy + * marks to have enough space for that. */ + off++; + while(off < tmp) { + ADD_MARK('D', off, off, 0); + off++; + } + continue; + } + + off = tmp; + continue; + } + + /* A potential code span start/end. */ + if(ch == _T('`')) { + MD_MARK opener; + MD_MARK closer; + int is_code_span; + + is_code_span = md_is_code_span(ctx, line, n_lines - line_index, off, + &opener, &closer, codespan_last_potential_closers, + &codespan_scanned_till_paragraph_end); + if(is_code_span) { + ADD_MARK(opener.ch, opener.beg, opener.end, opener.flags); + ADD_MARK(closer.ch, closer.beg, closer.end, closer.flags); + md_resolve_range(ctx, ctx->n_marks-2, ctx->n_marks-1); + off = closer.end; + + /* Advance the current line accordingly. */ + if(off > line->end) + line = md_lookup_line(off, lines, n_lines, &line_index); + continue; + } + + off = opener.end; + continue; + } + + /* A potential entity start. */ + if(ch == _T('&')) { + ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_OPENER); + off++; + continue; + } + + /* A potential entity end. */ + if(ch == _T(';')) { + /* We surely cannot be entity unless the previous mark is '&'. */ + if(ctx->n_marks > 0 && ctx->marks[ctx->n_marks-1].ch == _T('&')) + ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_CLOSER); + + off++; + continue; + } + + /* A potential autolink or raw HTML start/end. */ + if(ch == _T('<')) { + int is_autolink; + OFF autolink_end; + int missing_mailto; + + if(!(ctx->parser.flags & MD_FLAG_NOHTMLSPANS)) { + int is_html; + OFF html_end; + + /* Given the nature of the raw HTML, we have to recognize + * it here. Doing so later in md_analyze_lt_gt() could + * open can of worms of quadratic complexity. */ + is_html = md_is_html_any(ctx, line, n_lines - line_index, off, + lines[n_lines-1].end, &html_end); + if(is_html) { + ADD_MARK(_T('<'), off, off, MD_MARK_OPENER | MD_MARK_RESOLVED); + ADD_MARK(_T('>'), html_end, html_end, MD_MARK_CLOSER | MD_MARK_RESOLVED); + ctx->marks[ctx->n_marks-2].next = ctx->n_marks-1; + ctx->marks[ctx->n_marks-1].prev = ctx->n_marks-2; + off = html_end; + + /* Advance the current line accordingly. */ + if(off > line->end) + line = md_lookup_line(off, lines, n_lines, &line_index); + continue; + } + } + + is_autolink = md_is_autolink(ctx, off, lines[n_lines-1].end, + &autolink_end, &missing_mailto); + if(is_autolink) { + unsigned flags = MD_MARK_RESOLVED | MD_MARK_AUTOLINK; + if(missing_mailto) + flags |= MD_MARK_AUTOLINK_MISSING_MAILTO; + + ADD_MARK(_T('<'), off, off+1, MD_MARK_OPENER | flags); + ADD_MARK(_T('>'), autolink_end-1, autolink_end, MD_MARK_CLOSER | flags); + ctx->marks[ctx->n_marks-2].next = ctx->n_marks-1; + ctx->marks[ctx->n_marks-1].prev = ctx->n_marks-2; + off = autolink_end; + continue; + } + + off++; + continue; + } + + /* A potential link, footnote and similar or its part. */ + if(ch == _T('[') || (ch == _T('!') && off+1 < line->end && CH(off+1) == _T('['))) { + if(ch == _T('!')) { + ADD_MARK(ch, off+1, off+2, MD_MARK_POTENTIAL_OPENER | MD_MARK_BRACKET_CANBEIMAGE); + off += 2; + } else { + ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_OPENER); + off += 1; + } + + /* Two dummies to make enough place for data we need if it is + * a link. */ + ADD_MARK('D', off, off, 0); + ADD_MARK('D', off, off, 0); + continue; + } + if(ch == _T(']')) { + ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_CLOSER); + off++; + continue; + } + + /* A potential permissive e-mail autolink. */ + if(ch == _T('@')) { + if(line->beg + 1 <= off && ISALNUM(off-1) && + off + 3 < line->end && ISALNUM(off+1)) + { + ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_OPENER); + /* Push a dummy as a reserve for a closer. */ + ADD_MARK('D', line->beg, line->end, 0); + } + + off++; + continue; + } + + /* A potential permissive URL autolink. */ + if(ch == _T(':')) { + static const struct { + const CHAR* scheme; + SZ scheme_size; + const CHAR* suffix; + SZ suffix_size; + } scheme_map[] = { + /* In the order from the most frequently used, arguably. */ + { _T("http"), 4, _T("//"), 2 }, + { _T("https"), 5, _T("//"), 2 }, + { _T("ftp"), 3, _T("//"), 2 } + }; + int scheme_index; + + for(scheme_index = 0; scheme_index < (int) SIZEOF_ARRAY(scheme_map); scheme_index++) { + const CHAR* scheme = scheme_map[scheme_index].scheme; + const SZ scheme_size = scheme_map[scheme_index].scheme_size; + const CHAR* suffix = scheme_map[scheme_index].suffix; + const SZ suffix_size = scheme_map[scheme_index].suffix_size; + + if(line->beg + scheme_size <= off && md_ascii_eq(STR(off-scheme_size), scheme, scheme_size) && + off + 1 + suffix_size < line->end && md_ascii_eq(STR(off+1), suffix, suffix_size)) + { + ADD_MARK(ch, off-scheme_size, off+1+suffix_size, MD_MARK_POTENTIAL_OPENER); + /* Push a dummy as a reserve for a closer. */ + ADD_MARK('D', line->beg, line->end, 0); + off += 1 + suffix_size; + break; + } + } + + off++; + continue; + } + + /* A potential permissive WWW autolink. */ + if(ch == _T('.')) { + if(line->beg + 3 <= off && md_ascii_eq(STR(off-3), _T("www"), 3) && + (off-3 == line->beg || ISUNICODEWHITESPACEBEFORE(off-3) || ISUNICODEPUNCTBEFORE(off-3))) + { + ADD_MARK(ch, off-3, off+1, MD_MARK_POTENTIAL_OPENER); + /* Push a dummy as a reserve for a closer. */ + ADD_MARK('D', line->beg, line->end, 0); + off++; + continue; + } + + off++; + continue; + } + + /* A potential spoiler delimiter: || ... || + * Checked before the single-| handler so a double pipe is consumed + * as one mark and does not become two cell boundaries. */ + if(ch == _T('|') && (ctx->parser.flags & MD_FLAG_SPOILERS)) { + if(off + 1 < line->end && CH(off+1) == _T('|')) { + ADD_MARK(ch, off, off+2, MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER); + off += 2; + continue; + } + } + + /* A potential table cell boundary or wiki link label delimiter. */ + if((table_mode || (ctx->parser.flags & MD_FLAG_WIKILINKS)) && ch == _T('|')) { + ADD_MARK(ch, off, off+1, 0); + off++; + continue; + } + + /* A potential superscript start/end: ^text^ */ + if(ch == _T('^') && (ctx->parser.flags & MD_FLAG_SUPERSCRIPTS)) { + OFF tmp = off + 1; + + while(tmp < line->end && CH(tmp) == _T('^')) + tmp++; + + /* Only a single caret is a superscript delimiter; longer runs are literal. */ + if(tmp - off == 1) { + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + /* Cannot open before whitespace; cannot close after whitespace. */ + if(off + 1 >= line->end || ISUNICODEWHITESPACE(off + 1)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(off == line->beg || ISUNICODEWHITESPACEBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, off + 1, flags); + } + + off = tmp; + continue; + } + + /* A potential highlight start/end: ==text== */ + if(ch == _T('=') && (ctx->parser.flags & MD_FLAG_HIGHLIGHT)) { + OFF tmp = off + 1; + + while(tmp < line->end && CH(tmp) == _T('=')) + tmp++; + + /* Only exactly two equals signs form a highlight delimiter. */ + if(tmp - off == 2) { + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + /* Cannot open before whitespace; cannot close after whitespace. */ + if(tmp >= line->end || ISUNICODEWHITESPACE(tmp)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(off == line->beg || ISUNICODEWHITESPACEBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, tmp, flags); + } + + off = tmp; + continue; + } + + /* A potential insert start/end: ++text++ */ + if(ch == _T('+') && (ctx->parser.flags & MD_FLAG_INSERT)) { + OFF tmp = off + 1; + + while(tmp < line->end && CH(tmp) == _T('+')) + tmp++; + + /* Only exactly two plus signs form a insert delimiter. */ + if(tmp - off == 2) { + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + /* Cannot open before whitespace; cannot close after whitespace. */ + if(tmp >= line->end || ISUNICODEWHITESPACE(tmp)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(off == line->beg || ISUNICODEWHITESPACEBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, tmp, flags); + } + + off = tmp; + continue; + } + + /* A potential strikethrough/subscript start/end. */ + if(ch == _T('~')) { + OFF tmp = off + 1; + + while(tmp < line->end && CH(tmp) == _T('~')) + tmp++; + + if(tmp - off == 1 && (ctx->parser.flags & MD_FLAG_SUBSCRIPTS)) { + /* Subscript: can open after any non-whitespace, cannot open + * before whitespace; cannot close after whitespace. */ + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + if(off + 1 >= line->end || ISUNICODEWHITESPACE(off + 1)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(off == line->beg || ISUNICODEWHITESPACEBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, off + 1, flags); + } else if(tmp - off <= 2 && (ctx->parser.flags & MD_FLAG_STRIKETHROUGH)) { + /* Strikethrough: standard GFM left/right-flanking rules. */ + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + if(off > line->beg && !ISUNICODEWHITESPACEBEFORE(off) && !ISUNICODEPUNCTBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(tmp < line->end && !ISUNICODEWHITESPACE(tmp) && !ISUNICODEPUNCT(tmp)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, tmp, flags); + } + + off = tmp; + continue; + } + + /* A potential equation start/end. */ + if(ch == _T('$')) { + OFF tmp = off + 1; + + while(tmp < line->end && CH(tmp) == _T('$')) + tmp++; + + if(tmp - off <= 2) { + unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER; + + if(off > line->beg && !ISUNICODEWHITESPACEBEFORE(off) && !ISUNICODEPUNCTBEFORE(off)) + flags &= ~MD_MARK_POTENTIAL_OPENER; + if(tmp < line->end && !ISUNICODEWHITESPACE(tmp) && !ISUNICODEPUNCT(tmp)) + flags &= ~MD_MARK_POTENTIAL_CLOSER; + if(flags != 0) + ADD_MARK(ch, off, tmp, flags); + } + + off = tmp; + continue; + } + + /* Turn non-trivial whitespace into single space. */ + if(ISWHITESPACE_(ch)) { + OFF tmp = off+1; + + while(tmp < line->end && ISWHITESPACE(tmp)) + tmp++; + + if(tmp - off > 1 || ch != _T(' ')) + ADD_MARK(ch, off, tmp, MD_MARK_RESOLVED); + + off = tmp; + continue; + } + + /* NULL character. */ + if(ch == _T('\0')) { + ADD_MARK(ch, off, off+1, MD_MARK_RESOLVED); + off++; + continue; + } + + off++; + } + } + + /* Add a dummy mark at the end of the mark vector to simplify + * process_inlines(). */ + ADD_MARK(127, ctx->size, ctx->size, MD_MARK_RESOLVED); + +abort: + return ret; +} + +static void +md_analyze_bracket(MD_CTX* ctx, int mark_index) +{ + /* We cannot really resolve links here as for that we would need + * more context. E.g. a following pair of brackets (reference link), + * or enclosing pair of brackets (if the inner is the link, the outer + * one cannot be.) + * + * Therefore we here only construct a list of '[' ']' pairs ordered by + * position of the closer. This allows us to analyze what is or is not + * link in the right order, from inside to outside in case of nested + * brackets. + * + * The resolving itself is deferred to md_resolve_brackets(). + */ + + MD_MARK* mark = &ctx->marks[mark_index]; + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) { + if(BRACKET_OPENERS.top >= 0) + ctx->marks[BRACKET_OPENERS.top].flags |= MD_MARK_BRACKET_HASNESTED; + + md_mark_stack_push(ctx, &BRACKET_OPENERS, mark_index); + return; + } + + if(BRACKET_OPENERS.top >= 0) { + int opener_index = md_mark_stack_pop(ctx, &BRACKET_OPENERS); + MD_MARK* opener = &ctx->marks[opener_index]; + + /* Interconnect the opener and closer. */ + opener->next = mark_index; + mark->prev = opener_index; + + /* Add the pair into a list of potential brackets for md_resolve_brackets(). + * Note we misuse opener->prev for this as opener->next points to its + * closer. */ + if(ctx->unresolved_link_tail >= 0) + ctx->marks[ctx->unresolved_link_tail].prev = opener_index; + else + ctx->unresolved_link_head = opener_index; + ctx->unresolved_link_tail = opener_index; + opener->prev = -1; + } +} + +/* Forward declaration. */ +static void md_analyze_link_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + int mark_beg, int mark_end); + +/* Try to resolve a bracket pair as a wiki link '[[destination]]' or + * '[[destination|label]]'. + * Returns true if resolved, false if not a wiki link, -1 on error. */ +static int +md_resolve_bracket_wikilink(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + int opener_index, int closer_index, + MD_MARK* opener, MD_MARK* closer, + MD_MARK* next_opener, MD_MARK* next_closer, + OFF* last_link_beg, OFF* last_link_end, + int* p_opener_index) +{ + MD_MARK* delim = NULL; + int delim_index; + OFF dest_beg, dest_end; + OFF off; + + if(!(ctx->parser.flags & MD_FLAG_WIKILINKS)) + return false; + + if(opener->ch != _T('[') || opener->end - opener->beg != 1 || + next_opener == NULL || next_opener->ch != _T('[') || next_opener->end - next_opener->beg != 1 || + next_closer == NULL || next_closer->ch != _T(']') || next_closer->end - next_closer->beg != 1) + return false; + + /* Check that the next_opener and next_closer are nested properly. */ + if(next_opener->beg != opener->beg - 1 || next_closer->beg != closer->beg + 1) + return false; + + /* We don't allow destination to be longer than 100 characters. + * Lets scan to see whether there is '|'. (If not then the whole + * wiki-link has to be below the 100 characters.) */ + delim_index = opener_index + 1; + while(delim_index < closer_index) { + MD_MARK* m = &ctx->marks[delim_index]; + if(m->ch == _T('|')) { + delim = m; + break; + } + if(m->ch != _T('D')) { + if(m->beg - opener->end > 100) + break; + if(m->ch != _T('D') && (m->flags & MD_MARK_OPENER)) + delim_index = m->next; + } + delim_index++; + } + + dest_beg = opener->end; + dest_end = (delim != NULL) ? delim->beg : closer->beg; + if(dest_end - dest_beg == 0 || dest_end - dest_beg > 100) + return false; + + /* There may not be any new line in the destination. */ + for(off = dest_beg; off < dest_end; off++) { + if(ISNEWLINE(off)) + return false; + } + + md_pop_openers(ctx, opener_index); + + if(delim != NULL) { + if(delim->end < closer->beg) { + md_disable_marks(ctx, opener_index+1, delim_index); + delim->flags |= MD_MARK_RESOLVED; + opener->end = delim->beg; + } else { + /* The pipe is just before the closer: [[foo|]] */ + md_disable_marks(ctx, opener_index+1, closer_index); + closer->beg = delim->beg; + } + } + + opener->beg = next_opener->beg; + closer->end = next_closer->end; + md_resolve_range(ctx, opener_index, closer_index); + + *last_link_beg = opener->beg; + *last_link_end = closer->end; + + if(delim != NULL) + md_analyze_link_contents(ctx, lines, n_lines, delim_index+1, closer_index); + + *p_opener_index = next_opener->prev; + return true; +} + +/* Resolve footnote references [^label] in the current block. */ +static int +md_resolve_bracket_footnote(MD_CTX* ctx, MD_MARK* opener, MD_MARK* closer, + OFF* last_link_beg, OFF* last_link_end, + int* p_opener_index) +{ + MD_MARK* index_mark; + MD_FOOTNOTE_DEF* def; + OFF label_beg, label_end; + + if(!(ctx->parser.flags & MD_FLAG_FOOTNOTES)) + return false; + if(opener->ch != _T('[') || opener->end >= ctx->size || CH(opener->end) != _T('^')) + return false; + + /* Expand the opener to eat the '^' */ + opener->end++; + + closer = &ctx->marks[opener->next]; + + /* Label is the raw text between the opener end and the closer begin. + * opener->end points past [^, closer->beg points to ]. */ + label_beg = opener->end; + label_end = closer->beg; + + if(label_beg >= label_end) + return false; /* empty label */ + + def = md_lookup_footnote_def(ctx, STR(label_beg), label_end - label_beg); + if(def == NULL) + return false; + + /* Assign index on first reference. */ + if(def->index == 0) + def->index = ++ctx->next_footnote_index; + def->ref_count++; + + /* Store the public callback details in the dummy mark after the opener. */ + index_mark = opener + 1; + MD_ASSERT(index_mark->ch == _T('D')); + index_mark->beg = def->index; + index_mark->end = def->ref_count; + + /* Mark as resolved. */ + opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED | MD_MARK_BRACKET_FOOTNOTEREF; + closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED | MD_MARK_BRACKET_FOOTNOTEREF; + *last_link_beg = opener->beg; + *last_link_end = closer->end; + + *p_opener_index = opener->prev; + return true; +} + +/* Try to resolve a bracket pair as a CommonMark link or image. + * Returns -1 on error, 0 otherwise. */ +static int +md_resolve_bracket_link(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + int opener_index, int closer_index, + MD_MARK* opener, MD_MARK* closer, + MD_MARK* next_opener, MD_MARK* next_closer, + int* p_next_index, + OFF* last_link_beg, OFF* last_link_end, + OFF* last_img_beg, OFF* last_img_end) +{ + MD_LINK_ATTR attr; + int is_link = false; + + if(next_opener != NULL && next_opener->beg == closer->end) { + if(next_closer->beg > closer->end + 1) { + /* Might be full reference link. */ + if(!(next_opener->flags & MD_MARK_BRACKET_HASNESTED)) + is_link = md_is_link_reference(ctx, lines, n_lines, next_opener->beg, next_closer->end, &attr); + } else { + /* Might be shortcut reference link. */ + if(!(opener->flags & MD_MARK_BRACKET_HASNESTED)) + is_link = md_is_link_reference(ctx, lines, n_lines, opener->beg, closer->end, &attr); + } + + if(is_link < 0) + return -1; + + if(is_link) { + /* Eat the 2nd "[...]". */ + closer->end = next_closer->end; + + /* Do not analyze the label as a standalone link in the next + * iteration. */ + *p_next_index = ctx->marks[*p_next_index].prev; + } + } else { + if(closer->end < ctx->size && CH(closer->end) == _T('(')) { + /* Might be inline link. */ + OFF inline_link_end = UINT_MAX; + int following_mark_index = closer_index + 1; + + is_link = md_is_inline_link_spec(ctx, lines, n_lines, closer->end, &inline_link_end, &attr); + if(is_link < 0) + return -1; + + /* Check the closing ')' is not inside an already resolved range + * (i.e. a range with a higher priority), e.g. a code span. */ + if(is_link) { + while(following_mark_index < ctx->n_marks) { + MD_MARK* mark = &ctx->marks[following_mark_index]; + + if(mark->beg >= inline_link_end) + break; + if((mark->flags & (MD_MARK_OPENER | MD_MARK_RESOLVED)) == (MD_MARK_OPENER | MD_MARK_RESOLVED)) { + if(ctx->marks[mark->next].beg >= inline_link_end) { + /* Cancel the link status. */ + if(attr.title_needs_free) + free(attr.title); + is_link = false; + break; + } + + following_mark_index = mark->next + 1; + } else { + following_mark_index++; + } + } + } + + if(is_link) { + /* Eat the "(...)" */ + closer->end = inline_link_end; + md_disable_marks(ctx, closer_index+1, following_mark_index); + } + } + + if(!is_link) { + /* Might be collapsed reference link. */ + if(!(opener->flags & MD_MARK_BRACKET_HASNESTED)) + is_link = md_is_link_reference(ctx, lines, n_lines, opener->beg, closer->end, &attr); + if(is_link < 0) + return -1; + } + } + + if(is_link) { + /* Resolve the brackets as a link. */ + opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED; + closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED; + + /* If it is a link, we store the destination and title in the two + * dummy marks after the opener. */ + MD_ASSERT(ctx->marks[opener_index+1].ch == _T('D')); + ctx->marks[opener_index+1].beg = attr.dest_beg; + ctx->marks[opener_index+1].end = attr.dest_end; + + MD_ASSERT(ctx->marks[opener_index+2].ch == _T('D')); + md_mark_store_ptr(ctx, opener_index+2, attr.title); + /* The title might or might not have been allocated for us. */ + if(attr.title_needs_free) + md_mark_stack_push(ctx, &ctx->ptr_stack, opener_index+2); + ctx->marks[opener_index+2].prev = attr.title_size; + + if(opener->ch == _T('[')) { + *last_link_beg = opener->beg; + *last_link_end = closer->end; + } else { + *last_img_beg = opener->beg; + *last_img_end = closer->end; + } + + md_analyze_link_contents(ctx, lines, n_lines, opener_index+1, closer_index); + + /* If the link text is formed by nothing but permissive autolink, + * suppress the autolink. + * See https://github.com/mity/md4c/issues/152 for more info. */ + if(ctx->parser.flags & MD_FLAG_PERMISSIVEAUTOLINKS) { + MD_MARK* first_nested; + MD_MARK* last_nested; + + first_nested = opener + 1; + while(first_nested->ch == _T('D') && first_nested < closer) + first_nested++; + + last_nested = closer - 1; + while(first_nested->ch == _T('D') && last_nested > opener) + last_nested--; + + if((first_nested->flags & MD_MARK_RESOLVED) && + first_nested->beg == opener->end && + ISANYOF_(first_nested->ch, _T("@:.")) && + first_nested->next == (last_nested - ctx->marks) && + last_nested->end == closer->beg) + { + first_nested->ch = _T('D'); + first_nested->flags &= ~MD_MARK_RESOLVED; + last_nested->ch = _T('D'); + last_nested->flags &= ~MD_MARK_RESOLVED; + } + } + } + + return 0; +} + +/* Resolve bracket pairs as links, wiki links, or (in a 2nd pass) footnotes. */ +static int +md_resolve_brackets(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines) +{ + int opener_index = ctx->unresolved_link_head; + OFF last_link_beg = 0; + OFF last_link_end = 0; + OFF last_img_beg = 0; + OFF last_img_end = 0; + int ret; + + /* Note we here analyze from inner to outer as the marks are ordered + * by closer->beg. */ + while(opener_index >= 0) { + MD_MARK* opener = &ctx->marks[opener_index]; + int closer_index = opener->next; + MD_MARK* closer = &ctx->marks[closer_index]; + int next_index = opener->prev; + MD_MARK* next_opener; + MD_MARK* next_closer; + + if(opener->ch == _T('D')) { + /* We could have this disabled in previous iterations, and + * processing would be just burning CPU cycles. */ + opener_index = next_index; + continue; + } + + if(next_index >= 0) { + next_opener = &ctx->marks[next_index]; + next_closer = &ctx->marks[next_opener->next]; + } else { + next_opener = NULL; + next_closer = NULL; + } + + /* We can perhaps be an image? */ + if(opener->flags & MD_MARK_BRACKET_CANBEIMAGE) { + opener->ch = _T('!'); + opener->beg--; + } + + /* If nested ("[ [ ] ]"), we need to make sure that: + * - The outer does not end inside of (...) belonging to the inner. + * - The outer cannot be link if the inner is link (but this does not apply to images). */ + if((opener->beg < last_link_beg && closer->end < last_link_end) || + (opener->beg < last_img_beg && closer->end < last_img_end) || + (opener->beg < last_link_end && opener->ch != _T('!'))) + { + opener_index = next_index; + continue; + } + + ret = md_resolve_bracket_footnote(ctx, opener, closer, + &last_link_beg, &last_link_end, &opener_index); + if(ret < 0) + return -1; + if(ret > 0) + continue; + + ret = md_resolve_bracket_wikilink(ctx, lines, n_lines, opener_index, closer_index, + opener, closer, next_opener, next_closer, + &last_link_beg, &last_link_end, &opener_index); + if(ret < 0) + return -1; + if(ret > 0) + continue; + + ret = md_resolve_bracket_link(ctx, lines, n_lines, opener_index, closer_index, + opener, closer, next_opener, next_closer, &next_index, + &last_link_beg, &last_link_end, &last_img_beg, &last_img_end); + if(ret < 0) + return -1; + + opener_index = next_index; + } + + return 0; +} + +/* Analyze whether the mark '&' starts a HTML entity. + * If so, update its flags as well as flags of corresponding closer ';'. */ +static void +md_analyze_entity(MD_CTX* ctx, int mark_index) +{ + MD_MARK* opener = &ctx->marks[mark_index]; + MD_MARK* closer; + OFF off; + + /* Cannot be entity if there is no closer as the next mark. + * (Any other mark between would mean strange character which cannot be + * part of the entity. + * + * So we can do all the work on '&' and do not call this later for the + * closing mark ';'. + */ + if(mark_index + 1 >= ctx->n_marks) + return; + closer = &ctx->marks[mark_index+1]; + if(closer->ch != ';') + return; + + if(md_is_entity(ctx, opener->beg, closer->end, &off)) { + MD_ASSERT(off == closer->end); + + md_resolve_range(ctx, mark_index, mark_index+1); + opener->end = closer->end; + } +} + +static void +md_analyze_table_cell_boundary(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + mark->flags |= MD_MARK_RESOLVED; + mark->next = -1; + + if(ctx->table_cell_boundaries_head < 0) + ctx->table_cell_boundaries_head = mark_index; + else + ctx->marks[ctx->table_cell_boundaries_tail].next = mark_index; + ctx->table_cell_boundaries_tail = mark_index; + ctx->n_table_cell_boundaries++; +} + +/* Split a longer mark into two. The new mark takes the given count of + * characters. May only be called if an adequate number of dummy 'D' marks + * follows. + */ +static int +md_split_emph_mark(MD_CTX* ctx, int mark_index, SZ n) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + int new_mark_index = mark_index + (mark->end - mark->beg - n); + MD_MARK* dummy = &ctx->marks[new_mark_index]; + + MD_ASSERT(mark->end - mark->beg > n); + MD_ASSERT(dummy->ch == 'D'); + + memcpy(dummy, mark, sizeof(MD_MARK)); + mark->end -= n; + dummy->beg = mark->end; + + return new_mark_index; +} + +static void +md_analyze_emph(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + /* If we can be a closer, try to resolve with the preceding opener. */ + if(mark->flags & MD_MARK_POTENTIAL_CLOSER) { + MD_MARK* opener = NULL; + int opener_index = 0; + MD_MARKSTACK* opener_stacks[6]; + int i, n_opener_stacks; + unsigned flags = mark->flags; + + n_opener_stacks = 0; + + /* Apply the rule of 3 */ + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_0 | MD_MARK_EMPH_OC); + if((flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_2) + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_1 | MD_MARK_EMPH_OC); + if((flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_1) + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_2 | MD_MARK_EMPH_OC); + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_0); + if(!(flags & MD_MARK_EMPH_OC) || (flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_2) + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_1); + if(!(flags & MD_MARK_EMPH_OC) || (flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_1) + opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_2); + + /* Opener is the most recent mark from the allowed stacks. */ + for(i = 0; i < n_opener_stacks; i++) { + if(opener_stacks[i]->top >= 0) { + int m_index = opener_stacks[i]->top; + MD_MARK* m = &ctx->marks[m_index]; + + if(opener == NULL || m->end > opener->end) { + opener_index = m_index; + opener = m; + } + } + } + + /* Resolve, if we have found matching opener. */ + if(opener != NULL) { + SZ opener_size = opener->end - opener->beg; + SZ closer_size = mark->end - mark->beg; + MD_MARKSTACK* stack = md_opener_stack(ctx, opener_index); + + if(opener_size > closer_size) { + opener_index = md_split_emph_mark(ctx, opener_index, closer_size); + md_mark_stack_push(ctx, stack, opener_index); + } else if(opener_size < closer_size) { + md_split_emph_mark(ctx, mark_index, closer_size - opener_size); + } + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + } + + /* If we could not resolve as closer, we may be yet be an opener. */ + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, md_emph_stack(ctx, mark->ch, mark->flags), mark_index); +} + +static void +md_analyze_tilde(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + MD_MARKSTACK* stack = md_opener_stack(ctx, mark_index); + + /* We attempt to be Github Flavored Markdown compatible here. GFM accepts + * only tildes sequences of length 1 and 2, and the length of the opener + * and closer has to match. */ + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && stack->top >= 0) { + int opener_index = stack->top; + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, stack, mark_index); +} + +static void +md_analyze_caret(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && CARET_OPENERS.top >= 0) { + int opener_index = CARET_OPENERS.top; + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, &CARET_OPENERS, mark_index); +} + +static void +md_analyze_dollar(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && DOLLAR_OPENERS.top >= 0) { + /* If the potential closer has a non-matching number of $, discard */ + MD_MARK* opener = &ctx->marks[DOLLAR_OPENERS.top]; + int opener_index = DOLLAR_OPENERS.top; + MD_MARK* closer = mark; + int closer_index = mark_index; + + if(opener->end - opener->beg == closer->end - closer->beg) { + /* We are the matching closer */ + md_pop_openers(ctx, opener_index); + md_disable_marks(ctx, opener_index+1, closer_index); + md_resolve_range(ctx, opener_index, closer_index); + + /* Discard all pending openers: Latex math span do not allow + * nesting. */ + DOLLAR_OPENERS.top = -1; + return; + } + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, &DOLLAR_OPENERS, mark_index); +} + +static void +md_analyze_spoiler(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + /* Only "||" are recognized as spiler marks. */ + if(mark->end - mark->beg != 2) + return; + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && PIPE_OPENERS.top >= 0) { + int opener_index = PIPE_OPENERS.top; + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, &PIPE_OPENERS, mark_index); +} + +static void +md_analyze_highlight(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + /* Only "==" is recognized as a highlight mark. */ + if(mark->end - mark->beg != 2) + return; + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && EQUAL_OPENERS.top >= 0) { + int opener_index = EQUAL_OPENERS.top; + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, &EQUAL_OPENERS, mark_index); +} + +static void +md_analyze_insert(MD_CTX* ctx, int mark_index) +{ + MD_MARK* mark = &ctx->marks[mark_index]; + + /* Only "++" is recognized as a insert mark. */ + if(mark->end - mark->beg != 2) + return; + + if((mark->flags & MD_MARK_POTENTIAL_CLOSER) && PLUS_OPENERS.top >= 0) { + int opener_index = PLUS_OPENERS.top; + + md_pop_openers(ctx, opener_index); + md_resolve_range(ctx, opener_index, mark_index); + return; + } + + if(mark->flags & MD_MARK_POTENTIAL_OPENER) + md_mark_stack_push(ctx, &PLUS_OPENERS, mark_index); +} + +static MD_MARK* +md_scan_left_for_resolved_mark(MD_CTX* ctx, MD_MARK* mark_from, OFF off, MD_MARK** p_cursor) +{ + MD_MARK* mark; + + for(mark = mark_from; mark >= ctx->marks; mark--) { + if(mark->ch == 'D' || mark->beg > off) + continue; + if(mark->beg <= off && off < mark->end && (mark->flags & MD_MARK_RESOLVED)) { + if(p_cursor != NULL) + *p_cursor = mark; + return mark; + } + if(mark->end <= off) + break; + } + + if(p_cursor != NULL) + *p_cursor = mark; + return NULL; +} + +static MD_MARK* +md_scan_right_for_resolved_mark(MD_CTX* ctx, MD_MARK* mark_from, OFF off, MD_MARK** p_cursor) +{ + MD_MARK* mark; + + for(mark = mark_from; mark < ctx->marks + ctx->n_marks; mark++) { + if(mark->ch == 'D' || mark->end <= off) + continue; + if(mark->beg <= off && off < mark->end && (mark->flags & MD_MARK_RESOLVED)) { + if(p_cursor != NULL) + *p_cursor = mark; + return mark; + } + if(mark->beg > off) + break; + } + + if(p_cursor != NULL) + *p_cursor = mark; + return NULL; +} + +static int +md_analyze_permissive_autolink_segment(MD_CTX* ctx, OFF off, OFF end, OFF* p_end, + int scan_backwards, MD_CHAR component_delim, const MD_CHAR* word_extra, + const MD_CHAR* word_delims, MD_MARK** p_cursor) +{ + int n_components = 0; + int n_open_brackets = 0; + int seen_word_delim = true; + int seen_component_delim = true; + OFF component_beg = off; + + if(word_extra == NULL) + word_extra = _T(""); + if(word_delims == NULL) + word_delims = _T(""); + + while(off != end) { + if(scan_backwards) + off--; + + /* Only accept extra and delimiter characters if they're not part of a + * resolved mark. */ + if(!ISALNUM(off) && !ISWHITESPACE(off)) { + if((!scan_backwards && md_scan_right_for_resolved_mark(ctx, *p_cursor, off, p_cursor) != NULL) || + (scan_backwards && md_scan_left_for_resolved_mark(ctx, *p_cursor, off, p_cursor) != NULL)) { + if(scan_backwards) + off++; + break; + } + } + + /* The autolink can be _inside_ brackets so we disallow unbalanced bracket pairs in the URL. + * (Note the brackets are not allowed in e-mail username, so we happily skip this in that case.) */ + if(!scan_backwards) { + if(CH(off) == _T('(')) { + n_open_brackets++; + } else if(CH(off) == _T(')')) { + if(n_open_brackets <= 0) + break; + n_open_brackets--; + } + } + + if(ISALNUM(off) || ISANYOF(off, word_extra)) { + seen_word_delim = false; + seen_component_delim = false; + } else { + if(seen_word_delim) + break; + + if(ISANYOF(off, word_delims)) { + seen_word_delim = true; + } else if(component_delim != _T('\0') && CH(off) == component_delim) { + if(seen_component_delim) + break; + seen_component_delim = true; + component_beg = off; + n_components++; + } else { + if(scan_backwards) + off++; + break; + } + } + + if(!scan_backwards) + off++; + } + + /* Rollback falsely consumed delimiter. */ + if(off != component_beg && (seen_word_delim || seen_component_delim)) + off = (scan_backwards ? off+1 : off-1); + + if(off != component_beg) + n_components++; + + if(n_open_brackets != 0) + return -1; + + *p_end = off; + return n_components; +} + +static void +md_analyze_permissive_autolink(MD_CTX* ctx, int mark_index) +{ + MD_MARK* opener = &ctx->marks[mark_index]; + MD_MARK* closer = &ctx->marks[mark_index + 1]; /* The dummy. */ + OFF line_beg = closer->beg; /* md_collect_mark() sets this for us */ + OFF line_end = closer->end; /* ditto */ + OFF beg = opener->beg; + OFF end = opener->end; + MD_MARK* left_cursor = opener; + MD_MARK* right_cursor = opener; + + MD_ASSERT(closer->ch == 'D'); + + /* E-mail requires the user name (before '@', i.e. scanning backwards). */ + if(opener->ch == '@') { + MD_ASSERT(CH(opener->beg) == _T('@')); + if(md_analyze_permissive_autolink_segment(ctx, beg, line_beg, &beg, true, + _T('\0'), NULL, _T(".-_+"), &left_cursor) < 1) + return; + } + + /* Verify there's line boundary, whitespace, allowed punctuation or + * resolved opener mark just before the suspected autolink. */ + if(beg > line_beg && !ISUNICODEWHITESPACEBEFORE(beg) && !ISANYOF(beg-1, _T("({["))) { + MD_MARK* mark; + + mark = md_scan_left_for_resolved_mark(ctx, left_cursor, beg-1, &left_cursor); + if(mark == NULL || !(mark->flags & MD_MARK_OPENER)) + return; + } + + /* Scan for hostname segment. Hostname is mandatory. With an explicit scheme + * a single component is enough (e.g. "http://localhost"); WWW and e-mail + * autolinks require at least two components delimited with a dot. */ + if(md_analyze_permissive_autolink_segment(ctx, end, line_end, &end, false, + _T('.'), NULL, _T("-_"), &right_cursor) < (opener->ch == ':' ? 1 : 2)) + return; + + if(opener->ch != '@') { + /* Scan for optional port number. */ + if(end+1 < line_end && CH(end) == _T(':') && ISDIGIT(end+1)) { + end += 2; + while(end < line_end && ISDIGIT(end)) + end++; + } + + /* A colon that continues the URL ("user:pass@host") is user info, + * which this scanner does not parse. Refuse the URL instead of + * linking only the user name. */ + if(end+1 < line_end && CH(end) == _T(':') && !ISUNICODEWHITESPACE(end+1)) + return; + } + + /* Abort the scan early if possible + * (https://github.com/mity/md4c/issues/464) */ + if(end < ctx->permissive_autolink_tail_horizon) + return; + + if(opener->ch != '@' && end < line_end && ISANYOF(end, _T("/?#"))) { + OFF tail_beg = end; + OFF off = end; + OFF n_open_brackets = 0; + OFF n_close_brackets = 0; + + /* Scan a continuous URL tail, stopping at whitespace or '<'. + * Keep the mark check so URLs cannot cross resolved Markdown syntax. */ + while(off < line_end) { + SZ char_size; + int codepoint = md_decode_unicode(ctx->text, off, ctx->size, &char_size); + + if(ISUNICODEWHITESPACE_(codepoint) || codepoint == '<' || + codepoint < 0x20 || codepoint == 0x7f) + break; + if(codepoint >= 128) { + off += char_size; + continue; + } + + if(!ISALNUM(off) && + md_scan_right_for_resolved_mark(ctx, right_cursor, off, &right_cursor) != NULL) + break; + + if(CH(off) == _T('(')) { + n_open_brackets++; + } else if(CH(off) == _T(')')) { + n_close_brackets++; + } + off++; + } + + /* Trim only excess trailing closing parentheses. Unmatched opening + * parentheses within a URL are valid. */ + while(off > tail_beg) { + if(CH(off-1) == _T(')') && n_close_brackets > n_open_brackets) { + n_close_brackets--; + off--; + } else if(ISANYOF(off-1, _T("?!.,:;*_~'\""))) { + off--; + } else { + break; + } + } + end = off; + } + + /* Sentence punctuation is not part of a permissive autolink. Trim only + * the final suffix, so dots inside paths and queries remain intact. + * Explicit Markdown destinations and angle-bracket autolinks do not use + * this analyzer and retain their authored punctuation. */ + while(end > beg && ISANYOF(end-1, _T(".,;:!?"))) + end--; + + /* Verify there's line boundary, whitespace, allowed punctuation or + * resolved closer mark just after the suspected autolink. */ + if(end < line_end && !ISUNICODEWHITESPACE(end) && + !ISANYOF(end, _T(")}].!?,;:")) && + !(opener->ch != '@' && ISANYOF(end, _T(":*_~'\"<")))) { + MD_MARK* mark; + + mark = md_scan_right_for_resolved_mark(ctx, right_cursor, end, &right_cursor); + if(mark == NULL || !(mark->flags & MD_MARK_CLOSER)) { + ctx->permissive_autolink_tail_horizon = end; + return; + } + } + + /* Success, we are an autolink. */ + opener->beg = beg; + opener->end = beg; + closer->beg = end; + closer->end = end; + closer->ch = opener->ch; + md_resolve_range(ctx, mark_index, mark_index + 1); +} + +#define MD_ANALYZE_NOSKIP_EMPH 0x01 + +static inline void +md_analyze_marks(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + int mark_beg, int mark_end, const CHAR* mark_chars, const CHAR* noskip_mark_chars) +{ + int i = mark_beg; + OFF last_end = lines[0].beg; + + MD_UNUSED(lines); + MD_UNUSED(n_lines); + + while(i < mark_end) { + MD_MARK* mark = &ctx->marks[i]; + + /* Skip resolved spans. */ + if(mark->flags & MD_MARK_RESOLVED) { + if((mark->flags & MD_MARK_OPENER) && + (noskip_mark_chars == NULL || !(ISANYOF_(mark->ch, noskip_mark_chars)))) + { + MD_ASSERT(i < mark->next); + i = mark->next + 1; + } else { + i++; + } + continue; + } + + /* Skip marks we do not want to deal with. */ + if(!ISANYOF_(mark->ch, mark_chars)) { + i++; + continue; + } + + /* The resolving in previous step could have expanded a mark. */ + if(mark->beg < last_end) { + i++; + continue; + } + + /* Analyze the mark. */ + switch(mark->ch) { + case '[': MD_FALLTHROUGH(); + case '!': MD_FALLTHROUGH(); + case ']': md_analyze_bracket(ctx, i); break; + case '&': md_analyze_entity(ctx, i); break; + case '_': MD_FALLTHROUGH(); + case '*': md_analyze_emph(ctx, i); break; + case '~': md_analyze_tilde(ctx, i); break; + case '^': md_analyze_caret(ctx, i); break; + case '$': md_analyze_dollar(ctx, i); break; + case '.': MD_FALLTHROUGH(); + case ':': MD_FALLTHROUGH(); + case '@': md_analyze_permissive_autolink(ctx, i); break; + case '|': md_analyze_spoiler(ctx, i); break; + case '=': md_analyze_highlight(ctx, i); break; + case '+': md_analyze_insert(ctx, i); break; + } + + if(mark->flags & MD_MARK_RESOLVED) { + if(mark->flags & MD_MARK_OPENER) + last_end = ctx->marks[mark->next].end; + else + last_end = mark->end; + } + + i++; + } +} + +/* Analyze marks (build ctx->marks). */ +static int +md_analyze_inlines(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, int table_mode) +{ + int i; + int ret; + + /* Reset the previously collected stack of marks. */ + ctx->n_marks = 0; + + /* Collect all marks. */ + MD_CHECK(md_collect_marks(ctx, lines, n_lines, table_mode)); + + /* (1) Bracket spans: links, wiki links, footnotes. */ + md_analyze_marks(ctx, lines, n_lines, 0, ctx->n_marks, _T("[]!"), NULL); + MD_CHECK(md_resolve_brackets(ctx, lines, n_lines)); + BRACKET_OPENERS.top = -1; + ctx->unresolved_link_head = -1; + ctx->unresolved_link_tail = -1; + + if(table_mode) { + /* (2) Analyze table cell boundaries. */ + MD_ASSERT(n_lines == 1); + ctx->n_table_cell_boundaries = 0; + for(i = 0; i < ctx->n_marks; i++) { + MD_MARK* mark = &ctx->marks[i]; + if(!(mark->flags & MD_MARK_RESOLVED) && + mark->ch == '|' && mark->end - mark->beg == 1) + md_analyze_table_cell_boundary(ctx, i); + } + return ret; + } + + /* (3) Emphasis and strong emphasis; permissive autolinks. */ + md_analyze_link_contents(ctx, lines, n_lines, 0, ctx->n_marks); + +abort: + return ret; +} + +static void +md_analyze_link_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, + int mark_beg, int mark_end) +{ + int i; + CHAR emph_mark_types[16]; + SZ n_emph_mark_types = 0; + + emph_mark_types[n_emph_mark_types++] = _T('&'); + emph_mark_types[n_emph_mark_types++] = _T('*'); + emph_mark_types[n_emph_mark_types++] = _T('_'); + if(ctx->parser.flags & MD_FLAG_LATEXMATHSPANS) + emph_mark_types[n_emph_mark_types++] = _T('$'); + if(ctx->parser.flags & MD_FLAG_HIGHLIGHT) + emph_mark_types[n_emph_mark_types++] = _T('='); + if(ctx->parser.flags & MD_FLAG_INSERT) + emph_mark_types[n_emph_mark_types++] = _T('+'); + if(ctx->parser.flags & MD_FLAG_SPOILERS) + emph_mark_types[n_emph_mark_types++] = _T('|'); + if(ctx->parser.flags & MD_FLAG_SUPERSCRIPTS) + emph_mark_types[n_emph_mark_types++] = _T('^'); + if((ctx->parser.flags & MD_FLAG_STRIKETHROUGH) || (ctx->parser.flags & MD_FLAG_SUBSCRIPTS)) + emph_mark_types[n_emph_mark_types++] = _T('~'); + emph_mark_types[n_emph_mark_types] = _T('\0'); + md_analyze_marks(ctx, lines, n_lines, mark_beg, mark_end, emph_mark_types, NULL); + + if(ctx->parser.flags & MD_FLAG_PERMISSIVEAUTOLINKS) { + /* These have to be processed last, as they may be greedy and expand + * from their original mark. Also their implementation must be careful + * not to cross any (previously) resolved marks when doing so. */ + CHAR autolink_mark_types[16]; + SZ n_autolink_mark_types = 0; + + if(ctx->parser.flags & MD_FLAG_PERMISSIVEEMAILAUTOLINKS) + autolink_mark_types[n_autolink_mark_types++] = _T('@'); + if(ctx->parser.flags & MD_FLAG_PERMISSIVEURLAUTOLINKS) + autolink_mark_types[n_autolink_mark_types++] = _T(':'); + if(ctx->parser.flags & MD_FLAG_PERMISSIVEWWWAUTOLINKS) + autolink_mark_types[n_autolink_mark_types++] = _T('.'); + autolink_mark_types[n_autolink_mark_types] = _T('\0'); + md_analyze_marks(ctx, lines, n_lines, mark_beg, mark_end, autolink_mark_types, emph_mark_types); + } + + for(i = 0; i < (int) SIZEOF_ARRAY(ctx->opener_stacks); i++) + ctx->opener_stacks[i].top = -1; +} + +static int +md_enter_leave_span_a(MD_CTX* ctx, int enter, MD_SPANTYPE type, + const CHAR* dest, SZ dest_size, int is_autolink, + const CHAR* title, SZ title_size) +{ + MD_ATTRIBUTE_BUILD href_build = { 0 }; + MD_ATTRIBUTE_BUILD title_build = { 0 }; + MD_SPAN_A_DETAIL det; + int ret = 0; + + /* Note we here rely on fact that MD_SPAN_A_DETAIL and + * MD_SPAN_IMG_DETAIL are binary-compatible. */ + memset(&det, 0, sizeof(MD_SPAN_A_DETAIL)); + MD_CHECK(md_build_attribute(ctx, dest, dest_size, + (is_autolink ? MD_BUILD_ATTR_NO_ESCAPES : 0), + &det.href, &href_build)); + MD_CHECK(md_build_attribute(ctx, title, title_size, 0, &det.title, &title_build)); + det.is_autolink = is_autolink; + if(enter) + MD_ENTER_SPAN(type, &det); + else + MD_LEAVE_SPAN(type, &det); + +abort: + md_free_attribute(ctx, &href_build); + md_free_attribute(ctx, &title_build); + return ret; +} + +static int +md_enter_leave_span_wikilink(MD_CTX* ctx, int enter, const CHAR* target, SZ target_size) +{ + MD_ATTRIBUTE_BUILD target_build = { 0 }; + MD_SPAN_WIKILINK_DETAIL det; + int ret = 0; + + memset(&det, 0, sizeof(MD_SPAN_WIKILINK_DETAIL)); + MD_CHECK(md_build_attribute(ctx, target, target_size, 0, &det.target, &target_build)); + + if (enter) + MD_ENTER_SPAN(MD_SPAN_WIKILINK, &det); + else + MD_LEAVE_SPAN(MD_SPAN_WIKILINK, &det); + +abort: + md_free_attribute(ctx, &target_build); + return ret; +} + +static int +md_enter_leave_span_footnote_ref(MD_CTX* ctx, unsigned int id, + unsigned int ref_id, const CHAR* label, SZ label_size) +{ + MD_ATTRIBUTE_BUILD label_build = { 0 }; + MD_SPAN_FOOTNOTE_REF_DETAIL det; + int ret = 0; + + memset(&det, 0, sizeof(MD_SPAN_FOOTNOTE_REF_DETAIL)); + det.id = id; + det.ref_id = ref_id; + MD_CHECK(md_build_attribute(ctx, label, label_size, 0, + &det.label, &label_build)); + + MD_ENTER_SPAN(MD_SPAN_FOOTNOTE_REF, &det); + MD_LEAVE_SPAN(MD_SPAN_FOOTNOTE_REF, &det); + +abort: + md_free_attribute(ctx, &label_build); + return ret; +} + + +/* Render the output, accordingly to the analyzed ctx->marks. */ +static int +md_process_inlines(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines) +{ + MD_TEXTTYPE text_type; + const MD_LINE* line = lines; + MD_MARK* prev_mark = NULL; + MD_MARK* mark; + OFF off = lines[0].beg; + OFF end = lines[n_lines-1].end; + OFF tmp; + int enforce_hardbreak = 0; + int ret = 0; + + /* Find first resolved mark. Note there is always at least one resolved + * mark, the dummy last one after the end of the latest line we actually + * never really reach. This saves us of a lot of special checks and cases + * in this function. */ + mark = ctx->marks; + while(!(mark->flags & MD_MARK_RESOLVED)) + mark++; + + text_type = MD_TEXT_NORMAL; + + while(1) { + /* Process the text up to the next mark or end-of-line. */ + tmp = (line->end < mark->beg ? line->end : mark->beg); + if(tmp > off) { + MD_TEXT(text_type, STR(off), tmp - off); + off = tmp; + } + + /* If reached the mark, process it and move to next one. */ + if(off >= mark->beg) { + switch(mark->ch) { + case '\\': /* Backslash escape. */ + if(ISNEWLINE(mark->beg+1)) + enforce_hardbreak = 1; + else + MD_TEXT(text_type, STR(mark->beg+1), 1); + break; + + case ' ': /* Non-trivial space. */ + MD_TEXT(text_type, _T(" "), 1); + break; + + case '`': /* Code span. */ + if(mark->flags & MD_MARK_OPENER) { + MD_ENTER_SPAN(MD_SPAN_CODE, NULL); + text_type = MD_TEXT_CODE; + } else { + MD_LEAVE_SPAN(MD_SPAN_CODE, NULL); + text_type = MD_TEXT_NORMAL; + } + break; + + case '_': /* Underline (or emphasis if we fall through). */ + if(ctx->parser.flags & MD_FLAG_UNDERLINE) { + if(mark->flags & MD_MARK_OPENER) { + while(off < mark->end) { + MD_ENTER_SPAN(MD_SPAN_U, NULL); + off++; + } + } else { + while(off < mark->end) { + MD_LEAVE_SPAN(MD_SPAN_U, NULL); + off++; + } + } + break; + } + MD_FALLTHROUGH(); + + case '*': /* Emphasis, strong emphasis. */ + if(mark->flags & MD_MARK_OPENER) { + if((mark->end - off) % 2) { + MD_ENTER_SPAN(MD_SPAN_EM, NULL); + off++; + } + while(off + 1 < mark->end) { + MD_ENTER_SPAN(MD_SPAN_STRONG, NULL); + off += 2; + } + } else { + while(off + 1 < mark->end) { + MD_LEAVE_SPAN(MD_SPAN_STRONG, NULL); + off += 2; + } + if((mark->end - off) % 2) { + MD_LEAVE_SPAN(MD_SPAN_EM, NULL); + off++; + } + } + break; + + case '~': + if(mark->end - mark->beg == 1 && (ctx->parser.flags & MD_FLAG_SUBSCRIPTS)) { + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_SUBSCRIPT, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_SUBSCRIPT, NULL); + } else { + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_DEL, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_DEL, NULL); + } + break; + + case '^': + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_SUPERSCRIPT, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_SUPERSCRIPT, NULL); + break; + + case '|': + if(mark->end - mark->beg == 2) { + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_SPOILER, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_SPOILER, NULL); + } + break; + + case '=': + if(mark->end - mark->beg == 2) { + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_MARK, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_MARK, NULL); + } + break; + + case '+': + if(mark->end - mark->beg == 2) { + if(mark->flags & MD_MARK_OPENER) + MD_ENTER_SPAN(MD_SPAN_INS, NULL); + else + MD_LEAVE_SPAN(MD_SPAN_INS, NULL); + } + break; + + case '$': + if(mark->flags & MD_MARK_OPENER) { + MD_ENTER_SPAN((mark->end - off) % 2 ? MD_SPAN_LATEXMATH : MD_SPAN_LATEXMATH_DISPLAY, NULL); + text_type = MD_TEXT_LATEXMATH; + } else { + MD_LEAVE_SPAN((mark->end - off) % 2 ? MD_SPAN_LATEXMATH : MD_SPAN_LATEXMATH_DISPLAY, NULL); + text_type = MD_TEXT_NORMAL; + } + break; + + case '[': /* Footnote reference, link, wiki link, or image. */ + case '!': + case ']': + { + const MD_MARK* opener = (mark->ch != ']' ? mark : &ctx->marks[mark->prev]); + const MD_MARK* closer = &ctx->marks[opener->next]; + const MD_MARK* dest_mark; + const MD_MARK* title_mark; + + /* Footnote reference: self-contained span, no text emitted. + * Only the opener is ever processed here; the closer mark + * is guaranteed to be skipped by the off-advance below. */ + if(opener->flags & MD_MARK_BRACKET_FOOTNOTEREF) { + MD_MARK* index_mark = (MD_MARK*) opener + 1; + MD_ASSERT(mark->ch != ']'); + MD_ASSERT(index_mark->ch == 'D'); + MD_CHECK(md_enter_leave_span_footnote_ref(ctx, + (unsigned int) index_mark->beg, + (unsigned int) index_mark->end, + STR(opener->end), closer->beg - opener->end)); + /* Redirect the opener's end past the whole [^label] + * so that the post-switch "off = mark->end" skips + * the label text and the closing ]. */ + ((MD_MARK*) mark)->end = closer->end; + break; + } + + if ((opener->ch == '[' && closer->ch == ']') && + opener->end - opener->beg >= 2 && + closer->end - closer->beg >= 2) + { + int has_label = (opener->end - opener->beg > 2); + SZ target_sz; + + if(has_label) + target_sz = opener->end - (opener->beg+2); + else + target_sz = closer->beg - opener->end; + + MD_CHECK(md_enter_leave_span_wikilink(ctx, (mark->ch != ']'), + has_label ? STR(opener->beg+2) : STR(opener->end), + target_sz)); + + break; + } + + dest_mark = opener+1; + MD_ASSERT(dest_mark->ch == 'D'); + title_mark = opener+2; + MD_ASSERT(title_mark->ch == 'D'); + + MD_CHECK(md_enter_leave_span_a(ctx, (mark->ch != ']'), + (opener->ch == '!' ? MD_SPAN_IMG : MD_SPAN_A), + STR(dest_mark->beg), dest_mark->end - dest_mark->beg, false, + md_mark_get_ptr(ctx, (int)(title_mark - ctx->marks)), + title_mark->prev)); + + /* link/image closer may span multiple lines. */ + if(mark->ch == ']') { + while(mark->end > line->end) + line++; + } + + break; + } + + case '<': + case '>': /* Autolink or raw HTML. */ + if(!(mark->flags & MD_MARK_AUTOLINK)) { + /* Raw HTML. */ + if(mark->flags & MD_MARK_OPENER) + text_type = MD_TEXT_HTML; + else + text_type = MD_TEXT_NORMAL; + break; + } + /* Pass through, if auto-link. */ + MD_FALLTHROUGH(); + + case '@': /* Permissive e-mail autolink. */ + case ':': /* Permissive URL autolink. */ + case '.': /* Permissive WWW autolink. */ + { + MD_MARK* opener = ((mark->flags & MD_MARK_OPENER) ? mark : &ctx->marks[mark->prev]); + MD_MARK* closer = &ctx->marks[opener->next]; + const CHAR* dest = STR(opener->end); + SZ dest_size = closer->beg - opener->end; + + /* For permissive auto-links we do not know closer mark + * position at the time of md_collect_marks(), therefore + * it can be out-of-order in ctx->marks[]. + * + * With this flag, we make sure that we output the closer + * only if we processed the opener. */ + if(mark->flags & MD_MARK_OPENER) + closer->flags |= MD_MARK_VALIDPERMISSIVEAUTOLINK; + + if(opener->ch == '@' || opener->ch == '.' || + (opener->ch == '<' && (opener->flags & MD_MARK_AUTOLINK_MISSING_MAILTO))) + { + dest_size += 7; + MD_TEMP_BUFFER(dest_size * sizeof(CHAR)); + memcpy(ctx->buffer, + (opener->ch == '.' ? _T("http://") : _T("mailto:")), + 7 * sizeof(CHAR)); + memcpy(ctx->buffer + 7, dest, (dest_size-7) * sizeof(CHAR)); + dest = ctx->buffer; + } + + if(closer->flags & MD_MARK_VALIDPERMISSIVEAUTOLINK) + MD_CHECK(md_enter_leave_span_a(ctx, (mark->flags & MD_MARK_OPENER), + MD_SPAN_A, dest, dest_size, true, NULL, 0)); + break; + } + + case '&': /* Entity. */ + MD_TEXT(MD_TEXT_ENTITY, STR(mark->beg), mark->end - mark->beg); + break; + + case '\0': + MD_TEXT(MD_TEXT_NULLCHAR, _T(""), 1); + break; + + case 127: + goto abort; + } + + off = mark->end; + + /* Move to next resolved mark. */ + prev_mark = mark; + mark++; + while(!(mark->flags & MD_MARK_RESOLVED) || mark->beg < off) + mark++; + } + + /* If reached end of line, move to next one. */ + if(off >= line->end) { + /* If it is the last line, we are done. */ + if(off >= end) + break; + + if(text_type == MD_TEXT_CODE || text_type == MD_TEXT_LATEXMATH) { + MD_ASSERT(prev_mark != NULL); + MD_ASSERT(ISANYOF2_(prev_mark->ch, '`', '$') && (prev_mark->flags & MD_MARK_OPENER)); + MD_ASSERT(ISANYOF2_(mark->ch, '`', '$') && (mark->flags & MD_MARK_CLOSER)); + + /* Inside a code span, trailing line whitespace has to be + * outputted. */ + tmp = off; + while(off < ctx->size && ISBLANK(off)) + off++; + if(off > tmp) + MD_TEXT(text_type, STR(tmp), off-tmp); + + /* and new lines are transformed into single spaces. Emit the + * space when off rests on an interior newline still preceding + * the closer. Testing off == line->end here instead drops the + * space when the line ends in whitespace, because the loop + * above advances off past line->end over the trailing blanks + * (CommonMark code-span examples 335, 337, 640). */ + if(off < mark->beg && ISNEWLINE(off)) + MD_TEXT(text_type, _T(" "), 1); + } else if(text_type == MD_TEXT_HTML) { + /* Inside raw HTML, we output the new line verbatim, including + * any trailing spaces. */ + tmp = off; + while(tmp < end && ISBLANK(tmp)) + tmp++; + if(tmp > off) + MD_TEXT(MD_TEXT_HTML, STR(off), tmp - off); + MD_TEXT(MD_TEXT_HTML, _T("\n"), 1); + } else { + /* Output soft or hard line break. */ + MD_TEXTTYPE break_type = MD_TEXT_SOFTBR; + + if(text_type == MD_TEXT_NORMAL) { + if(enforce_hardbreak || (ctx->parser.flags & MD_FLAG_HARD_SOFT_BREAKS)) { + break_type = MD_TEXT_BR; + } else { + while(off < ctx->size && ISBLANK(off)) + off++; + if(off >= line->end + 2 && CH(off-2) == _T(' ') && CH(off-1) == _T(' ') && ISNEWLINE(off)) + break_type = MD_TEXT_BR; + } + } + + MD_TEXT(break_type, _T("\n"), 1); + } + + /* Move to the next line. */ + line++; + off = MAX(off, line->beg); + + enforce_hardbreak = 0; + } + } + +abort: + return ret; +} + + +/*************************** + *** Processing Tables *** + ***************************/ + +static void +md_analyze_table_alignment(MD_CTX* ctx, OFF beg, OFF end, MD_ALIGN* align, int n_align) +{ + static const MD_ALIGN align_map[] = { MD_ALIGN_DEFAULT, MD_ALIGN_LEFT, MD_ALIGN_RIGHT, MD_ALIGN_CENTER }; + OFF off = beg; + + while(n_align > 0) { + int index = 0; /* index into align_map[] */ + + while(off < end && CH(off) != _T('-')) + off++; + if(off > beg && CH(off-1) == _T(':')) + index |= 1; + while(off < end && CH(off) == _T('-')) + off++; + if(off < end && CH(off) == _T(':')) + index |= 2; + + *align = align_map[index]; + align++; + n_align--; + } + +} + +/* Forward declaration. */ +static int md_process_normal_block_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines); + +static int +md_process_table_cell(MD_CTX* ctx, MD_BLOCKTYPE cell_type, MD_ALIGN align, OFF beg, OFF end) +{ + MD_LINE line; + MD_BLOCK_TD_DETAIL det; + int ret = 0; + + while(beg < end && ISWHITESPACE(beg)) + beg++; + while(end > beg && ISWHITESPACE(end-1)) + end--; + + det.align = align; + line.beg = beg; + line.end = end; + + MD_ENTER_BLOCK(cell_type, &det); + MD_CHECK(md_process_normal_block_contents(ctx, &line, 1)); + MD_LEAVE_BLOCK(cell_type, &det); + +abort: + return ret; +} + +static int +md_process_table_row(MD_CTX* ctx, MD_BLOCKTYPE cell_type, OFF beg, OFF end, + const MD_ALIGN* align, int col_count) +{ + MD_LINE line; + OFF* pipe_offs = NULL; + int i, j, k, n; + int ret = 0; + + line.beg = beg; + line.end = end; + + /* Break the line into table cells by identifying pipe characters who + * form the cell boundary. */ + MD_CHECK(md_analyze_inlines(ctx, &line, 1, true)); + + /* We have to remember the cell boundaries in local buffer because + * ctx->marks[] shall be reused during cell contents processing. */ + n = ctx->n_table_cell_boundaries + 2; + pipe_offs = (OFF*) malloc(n * sizeof(OFF)); + if(pipe_offs == NULL) { + MD_LOG("malloc() failed."); + ret = -1; + goto abort; + } + j = 0; + pipe_offs[j++] = beg; + for(i = ctx->table_cell_boundaries_head; i >= 0; i = ctx->marks[i].next) { + MD_MARK* mark = &ctx->marks[i]; + pipe_offs[j++] = mark->end; + } + pipe_offs[j++] = end+1; + + /* Process cells. */ + MD_ENTER_BLOCK(MD_BLOCK_TR, NULL); + k = 0; + for(i = 0; i < j-1 && k < col_count; i++) { + if(pipe_offs[i] < pipe_offs[i+1]-1) + MD_CHECK(md_process_table_cell(ctx, cell_type, align[k++], pipe_offs[i], pipe_offs[i+1]-1)); + } + /* Make sure we call enough table cells even if the current table contains + * too few of them. */ + while(k < col_count) + MD_CHECK(md_process_table_cell(ctx, cell_type, align[k++], 0, 0)); + MD_LEAVE_BLOCK(MD_BLOCK_TR, NULL); + +abort: + free(pipe_offs); + + ctx->table_cell_boundaries_head = -1; + ctx->table_cell_boundaries_tail = -1; + + return ret; +} + +static int +md_process_table_block_contents(MD_CTX* ctx, int col_count, const MD_LINE* lines, MD_SIZE n_lines) +{ + MD_ALIGN* align; + MD_SIZE line_index; + int ret = 0; + + /* At least two lines have to be present: The column headers and the line + * with the underlines. */ + MD_ASSERT(n_lines >= 2); + + align = malloc(col_count * sizeof(MD_ALIGN)); + if(align == NULL) { + MD_LOG("malloc() failed."); + ret = -1; + goto abort; + } + + md_analyze_table_alignment(ctx, lines[1].beg, lines[1].end, align, col_count); + + MD_ENTER_BLOCK(MD_BLOCK_THEAD, NULL); + MD_CHECK(md_process_table_row(ctx, MD_BLOCK_TH, + lines[0].beg, lines[0].end, align, col_count)); + MD_LEAVE_BLOCK(MD_BLOCK_THEAD, NULL); + + if(n_lines > 2) { + MD_ENTER_BLOCK(MD_BLOCK_TBODY, NULL); + for(line_index = 2; line_index < n_lines; line_index++) { + MD_CHECK(md_process_table_row(ctx, MD_BLOCK_TD, + lines[line_index].beg, lines[line_index].end, align, col_count)); + } + MD_LEAVE_BLOCK(MD_BLOCK_TBODY, NULL); + } + +abort: + free(align); + return ret; +} + + +/************************** + *** Processing Block *** + **************************/ + +#define MD_BLOCK_CONTAINER_OPENER 0x01 +#define MD_BLOCK_CONTAINER_CLOSER 0x02 +#define MD_BLOCK_CONTAINER (MD_BLOCK_CONTAINER_OPENER | MD_BLOCK_CONTAINER_CLOSER) +#define MD_BLOCK_LOOSE_LIST 0x04 +#define MD_BLOCK_SETEXT_HEADER 0x08 + +struct MD_BLOCK_tag { + MD_BLOCKTYPE type : 8; + unsigned flags : 8; + + /* MD_BLOCK_H: Header level (1 - 6) + * MD_BLOCK_CODE: Non-zero if fenced, zero if indented. + * MD_BLOCK_LI: Task mark character (0 if not task list item, 'x', 'X' or ' '). + * MD_BLOCK_TABLE: Column count (as determined by the table underline). + * MD_BLOCK_ADMONITION: Admonition type. + */ + unsigned data : 16; + + /* Leaf blocks: Count of lines (MD_LINE or MD_VERBATIMLINE) on the block. + * MD_BLOCK_LI: Task mark offset in the input doc. + * MD_BLOCK_OL: Start item number. + */ + MD_SIZE n_lines; +}; + +struct MD_CONTAINER_tag { + CHAR ch; + unsigned is_loose : 1; + unsigned is_task : 1; + unsigned is_admonition : 1; + unsigned admonition_type : 3; + unsigned start; + unsigned mark_indent; + unsigned contents_indent; + OFF block_byte_off; + OFF task_mark_off; +}; + + +static int +md_process_normal_block_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines) +{ + int i; + int ret; + + MD_CHECK(md_analyze_inlines(ctx, lines, n_lines, false)); + MD_CHECK(md_process_inlines(ctx, lines, n_lines)); + +abort: + /* Free any temporary memory blocks stored within some dummy marks. */ + for(i = ctx->ptr_stack.top; i >= 0; i = ctx->marks[i].next) + free(md_mark_get_ptr(ctx, i)); + ctx->ptr_stack.top = -1; + + return ret; +} + +static int +md_process_verbatim_block_contents(MD_CTX* ctx, MD_TEXTTYPE text_type, const MD_VERBATIMLINE* lines, MD_SIZE n_lines) +{ + static const CHAR indent_chunk_str[] = _T(" "); + static const SZ indent_chunk_size = SIZEOF_ARRAY(indent_chunk_str) - 1; + + MD_SIZE line_index; + int ret = 0; + + for(line_index = 0; line_index < n_lines; line_index++) { + const MD_VERBATIMLINE* line = &lines[line_index]; + int indent = line->indent; + + MD_ASSERT(indent >= 0); + + /* Output code indentation. */ + while(indent > (int) indent_chunk_size) { + MD_TEXT(text_type, indent_chunk_str, indent_chunk_size); + indent -= indent_chunk_size; + } + if(indent > 0) + MD_TEXT(text_type, indent_chunk_str, indent); + + /* Output the code line itself. */ + MD_TEXT_INSECURE(text_type, STR(line->beg), line->end - line->beg); + + /* Enforce end-of-line. */ + MD_TEXT(text_type, _T("\n"), 1); + } + +abort: + return ret; +} + +static int +md_process_code_block_contents(MD_CTX* ctx, int is_fenced, const MD_VERBATIMLINE* lines, MD_SIZE n_lines) +{ + if(is_fenced) { + /* Skip the first line in case of fenced code: It is the fence. + * (Only the starting fence is present due to logic in md_analyze_line().) */ + lines++; + n_lines--; + } else { + /* Ignore blank lines at start/end of indented code block. */ + while(n_lines > 0 && lines[0].beg == lines[0].end) { + lines++; + n_lines--; + } + while(n_lines > 0 && lines[n_lines-1].beg == lines[n_lines-1].end) { + n_lines--; + } + } + + if(n_lines == 0) + return 0; + + return md_process_verbatim_block_contents(ctx, MD_TEXT_CODE, lines, n_lines); +} + +static int +md_setup_fenced_code_detail(MD_CTX* ctx, const MD_BLOCK* block, MD_BLOCK_CODE_DETAIL* det, + MD_ATTRIBUTE_BUILD* info_build, MD_ATTRIBUTE_BUILD* lang_build) +{ + const MD_VERBATIMLINE* fence_line = (const MD_VERBATIMLINE*)(block + 1); + OFF beg = fence_line->beg; + OFF end = fence_line->end; + OFF lang_end; + CHAR fence_ch = CH(fence_line->beg); + int ret = 0; + + /* Skip the fence itself. */ + while(beg < ctx->size && CH(beg) == fence_ch) + beg++; + /* Trim initial spaces. */ + while(beg < ctx->size && CH(beg) == _T(' ')) + beg++; + + /* Trim trailing spaces. */ + while(end > beg && CH(end-1) == _T(' ')) + end--; + + /* Build info string attribute. */ + MD_CHECK(md_build_attribute(ctx, STR(beg), end - beg, 0, &det->info, info_build)); + + /* Build info string attribute. */ + lang_end = beg; + while(lang_end < end && !ISWHITESPACE(lang_end)) + lang_end++; + MD_CHECK(md_build_attribute(ctx, STR(beg), lang_end - beg, 0, &det->lang, lang_build)); + + det->fence_char = fence_ch; + +abort: + return ret; +} + +static int +md_process_leaf_block(MD_CTX* ctx, MD_BLOCK* block) +{ + union { + MD_BLOCK_H_DETAIL header; + MD_BLOCK_CODE_DETAIL code; + MD_BLOCK_TABLE_DETAIL table; + MD_BLOCK_BLANK_DETAIL blank; + } det; + MD_ATTRIBUTE_BUILD info_build = { 0 }; + MD_ATTRIBUTE_BUILD lang_build = { 0 }; + int is_in_tight_list; + int clean_fence_code_detail = false; + int ret = 0; + + /* For large tables check the table density: If it's too low, lets suppress + * its interpretation as a table, as a safety measure against quadratic + * output size explosion. See https://github.com/mity/md4c/issues/345 */ + if(block->type == MD_BLOCK_TABLE) { + unsigned n_cols = block->data; + unsigned n_rows = block->n_lines; + + if(n_cols > 32 && n_rows > 4096 / n_cols) { + const MD_LINE* lines = (const MD_LINE*)(block + 1); + SZ table_input_size = n_rows; + unsigned i; + + for(i = 0; i < n_rows; i++) + table_input_size += lines[i].end - lines[i].beg; + + if(table_input_size / n_cols < n_rows / 4) { + /* Number of characters encoding the table in the input is + * lower then 25% of all cells to be generated? */ + MD_LOG("Suppressing too sparse table " + "(see https://github.com/mity/md4c/issues/345)"); + block->type = MD_BLOCK_P; + } + } + } + + memset(&det, 0, sizeof(det)); + + if(ctx->n_containers == 0) + is_in_tight_list = false; + else + is_in_tight_list = !ctx->containers[ctx->n_containers-1].is_loose; + + switch(block->type) { + case MD_BLOCK_H: + det.header.level = block->data; + break; + + case MD_BLOCK_CODE: + /* For fenced code block, we may need to set the info string. */ + if(block->data != 0) { + memset(&det.code, 0, sizeof(MD_BLOCK_CODE_DETAIL)); + clean_fence_code_detail = true; + MD_CHECK(md_setup_fenced_code_detail(ctx, block, &det.code, &info_build, &lang_build)); + } + break; + + case MD_BLOCK_TABLE: + det.table.col_count = block->data; + det.table.head_row_count = 1; + det.table.body_row_count = block->n_lines - 2; + break; + + case MD_BLOCK_BLANK: + det.blank.line_count = block->data; + break; + + default: + /* Noop. */ + break; + } + + if(!is_in_tight_list || block->type != MD_BLOCK_P) + MD_ENTER_BLOCK(block->type, (void*) &det); + + /* Process the block contents accordingly to is type. */ + switch(block->type) { + case MD_BLOCK_HR: + case MD_BLOCK_BLANK: + /* noop (no contents) */ + break; + + case MD_BLOCK_CODE: + MD_CHECK(md_process_code_block_contents(ctx, (block->data != 0), + (const MD_VERBATIMLINE*)(block + 1), block->n_lines)); + break; + + case MD_BLOCK_HTML: + MD_CHECK(md_process_verbatim_block_contents(ctx, MD_TEXT_HTML, + (const MD_VERBATIMLINE*)(block + 1), block->n_lines)); + break; + + case MD_BLOCK_TABLE: + MD_CHECK(md_process_table_block_contents(ctx, block->data, + (const MD_LINE*)(block + 1), block->n_lines)); + break; + + default: + MD_CHECK(md_process_normal_block_contents(ctx, + (const MD_LINE*)(block + 1), block->n_lines)); + break; + } + + if(!is_in_tight_list || block->type != MD_BLOCK_P) + MD_LEAVE_BLOCK(block->type, (void*) &det); + +abort: + if(clean_fence_code_detail) { + md_free_attribute(ctx, &info_build); + md_free_attribute(ctx, &lang_build); + } + return ret; +} + +static const MD_CHAR* MD_ADMONITION_TAGS[] = { _T("note"), _T("tip"), _T("important"), _T("warning"), _T("caution") }; + +static int +md_process_all_blocks(MD_CTX* ctx) +{ + MD_TEXTTYPE adm_substr_types[1] = { MD_TEXT_NORMAL }; + MD_OFFSET adm_substr_offsets[2]; + int byte_off = 0; + int ret = 0; + + /* ctx->containers now is not needed for detection of lists and list items + * so we reuse it for tracking what lists are loose or tight. We rely + * on the fact the vector is large enough to hold the deepest nesting + * level of lists. */ + ctx->n_containers = 0; + + while(byte_off < ctx->n_block_bytes) { + MD_BLOCK* block = (MD_BLOCK*)((char*)ctx->block_bytes + byte_off); + union { + MD_BLOCK_UL_DETAIL ul; + MD_BLOCK_OL_DETAIL ol; + MD_BLOCK_LI_DETAIL li; + MD_BLOCK_ADMONITION_DETAIL adm; + } det; + + switch(block->type) { + case MD_BLOCK_UL: + det.ul.is_tight = (block->flags & MD_BLOCK_LOOSE_LIST) ? false : true; + det.ul.mark = (CHAR) block->data; + break; + + case MD_BLOCK_OL: + det.ol.start = block->n_lines; + det.ol.is_tight = (block->flags & MD_BLOCK_LOOSE_LIST) ? false : true; + det.ol.mark_delimiter = (CHAR) block->data; + break; + + case MD_BLOCK_LI: + det.li.is_task = (block->data != 0); + det.li.task_mark = (CHAR) block->data; + det.li.task_mark_offset = (OFF) block->n_lines; + break; + + case MD_BLOCK_ADMONITION: + adm_substr_offsets[0] = 0; + adm_substr_offsets[1] = md_strlen(MD_ADMONITION_TAGS[block->data]); + + det.adm.type.text = MD_ADMONITION_TAGS[block->data]; + det.adm.type.size = adm_substr_offsets[1]; + det.adm.type.substr_types = adm_substr_types; + det.adm.type.substr_offsets = adm_substr_offsets; + break; + + default: + /* noop */ + break; + } + + if(block->flags & MD_BLOCK_CONTAINER) { + if(block->flags & MD_BLOCK_CONTAINER_CLOSER) { + MD_LEAVE_BLOCK(block->type, &det); + + if(block->type == MD_BLOCK_UL || block->type == MD_BLOCK_OL || + block->type == MD_BLOCK_QUOTE || block->type == MD_BLOCK_ADMONITION) + ctx->n_containers--; + } + + if(block->flags & MD_BLOCK_CONTAINER_OPENER) { + MD_ENTER_BLOCK(block->type, &det); + + if(block->type == MD_BLOCK_UL || block->type == MD_BLOCK_OL) { + ctx->containers[ctx->n_containers].is_loose = (block->flags & MD_BLOCK_LOOSE_LIST) ? true : false; + ctx->n_containers++; + } else if(block->type == MD_BLOCK_QUOTE || block->type == MD_BLOCK_ADMONITION) { + /* This causes that any text in a block quote, even if + * nested inside a tight list item, is wrapped with + *

...

. */ + ctx->containers[ctx->n_containers].is_loose = true; + ctx->n_containers++; + } + } + } else { + MD_CHECK(md_process_leaf_block(ctx, block)); + + if(block->type == MD_BLOCK_CODE || block->type == MD_BLOCK_HTML) + byte_off += block->n_lines * sizeof(MD_VERBATIMLINE); + else + byte_off += block->n_lines * sizeof(MD_LINE); + } + + byte_off += sizeof(MD_BLOCK); + } + + ctx->n_block_bytes = 0; + +abort: + return ret; +} + + +/************************************ + *** Grouping Lines into Blocks *** + ************************************/ + +static void* +md_push_block_bytes(MD_CTX* ctx, int n_bytes) +{ + void* ptr; + + if(ctx->n_block_bytes + n_bytes > ctx->alloc_block_bytes) { + void* new_block_bytes; + + ctx->alloc_block_bytes = (ctx->alloc_block_bytes > 0 + ? ctx->alloc_block_bytes + ctx->alloc_block_bytes / 2 + : 512); + new_block_bytes = realloc(ctx->block_bytes, ctx->alloc_block_bytes); + if(new_block_bytes == NULL) { + MD_LOG("realloc() failed."); + return NULL; + } + + /* Fix the ->current_block after the reallocation. */ + if(ctx->current_block != NULL) { + OFF off_current_block = (OFF) ((char*) ctx->current_block - (char*) ctx->block_bytes); + ctx->current_block = (MD_BLOCK*) ((char*) new_block_bytes + off_current_block); + } + + ctx->block_bytes = new_block_bytes; + } + + ptr = (char*)ctx->block_bytes + ctx->n_block_bytes; + ctx->n_block_bytes += n_bytes; + return ptr; +} + +static int +md_start_new_block(MD_CTX* ctx, const MD_LINE_ANALYSIS* line) +{ + MD_BLOCK* block; + + MD_ASSERT(ctx->current_block == NULL); + + block = (MD_BLOCK*) md_push_block_bytes(ctx, sizeof(MD_BLOCK)); + if(block == NULL) + return -1; + + switch(line->type) { + case MD_LINE_HR: + block->type = MD_BLOCK_HR; + break; + + case MD_LINE_ATXHEADER: + case MD_LINE_SETEXTHEADER: + block->type = MD_BLOCK_H; + break; + + case MD_LINE_FENCEDCODE: + case MD_LINE_INDENTEDCODE: + block->type = MD_BLOCK_CODE; + break; + + case MD_LINE_TEXT: + block->type = MD_BLOCK_P; + break; + + case MD_LINE_HTML: + block->type = MD_BLOCK_HTML; + break; + + case MD_LINE_BLANK: + case MD_LINE_SETEXTUNDERLINE: + case MD_LINE_TABLEUNDERLINE: + default: + MD_UNREACHABLE(); + break; + } + + block->flags = 0; + block->data = line->data; + block->n_lines = 0; + + ctx->current_block = block; + return 0; +} + +/* Eat from start of current (textual) block any reference definitions and/or + * footnote definitions, and remember them. + * + * (Such definitions can only be at start of it as they cannot break a + * paragraph.) + */ +static int +md_consume_link_reference_definitions(MD_CTX* ctx) +{ + MD_LINE* lines = (MD_LINE*) (ctx->current_block + 1); + MD_SIZE n_lines = ctx->current_block->n_lines; + MD_SIZE n = 0; + + while(n < n_lines) { + int n_consumed = 0; + + /* When footnotes are enabled, try footnote definition first for lines + * starting with [^, so they are not accidentally consumed as link ref + * definitions (which would also match [^label]: url). */ + if((ctx->parser.flags & MD_FLAG_FOOTNOTES) && + lines[n].beg + 1 < ctx->size && + CH(lines[n].beg) == _T('[') && CH(lines[n].beg + 1) == _T('^')) + { + n_consumed = md_is_footnote_definition(ctx, lines + n, n_lines - n); + if(n_consumed < 0) + return -1; + } + + if(n_consumed == 0) { + n_consumed = md_is_link_reference_definition(ctx, lines + n, n_lines - n); + if(n_consumed < 0) + return -1; + } + + if(n_consumed == 0) + break; + + n += n_consumed; + } + + /* If there was at least one definition, we need to remove its lines from + * the block, or perhaps even the whole block. */ + if(n > 0) { + if(n == n_lines) { + /* Remove complete block. */ + ctx->n_block_bytes -= n * sizeof(MD_LINE); + ctx->n_block_bytes -= sizeof(MD_BLOCK); + ctx->current_block = NULL; + } else { + /* Remove just some initial lines from the block. */ + memmove(lines, lines + n, (n_lines - n) * sizeof(MD_LINE)); + ctx->current_block->n_lines -= n; + ctx->n_block_bytes -= n * sizeof(MD_LINE); + } + } + + return 0; +} + +static int +md_end_current_block(MD_CTX* ctx) +{ + int ret = 0; + + if(ctx->current_block == NULL) + return ret; + + /* Check whether there is a reference definition. (We do this here instead + * of in md_analyze_line() because reference definition can take multiple + * lines.) */ + if(ctx->current_block->type == MD_BLOCK_P || + (ctx->current_block->type == MD_BLOCK_H && (ctx->current_block->flags & MD_BLOCK_SETEXT_HEADER))) + { + MD_LINE* lines = (MD_LINE*) (ctx->current_block + 1); + if(lines[0].beg < ctx->size && CH(lines[0].beg) == _T('[')) { + MD_CHECK(md_consume_link_reference_definitions(ctx)); + if(ctx->current_block == NULL) + return ret; + } + } + + if(ctx->current_block->type == MD_BLOCK_H && (ctx->current_block->flags & MD_BLOCK_SETEXT_HEADER)) { + MD_SIZE n_lines = ctx->current_block->n_lines; + + if(n_lines > 1) { + /* Get rid of the underline. */ + ctx->current_block->n_lines--; + ctx->n_block_bytes -= sizeof(MD_LINE); + } else { + /* Only the underline has left after eating the ref. defs. + * Keep the line as beginning of a new ordinary paragraph. */ + ctx->current_block->type = MD_BLOCK_P; + return 0; + } + } + + /* Mark we are not building any block anymore. */ + ctx->current_block = NULL; + +abort: + return ret; +} + +static int +md_add_line_into_current_block(MD_CTX* ctx, const MD_LINE_ANALYSIS* analysis) +{ + MD_ASSERT(ctx->current_block != NULL); + + if(ctx->current_block->type == MD_BLOCK_CODE || ctx->current_block->type == MD_BLOCK_HTML) { + MD_VERBATIMLINE* line; + + line = (MD_VERBATIMLINE*) md_push_block_bytes(ctx, sizeof(MD_VERBATIMLINE)); + if(line == NULL) + return -1; + + line->indent = analysis->indent; + line->beg = analysis->beg; + line->end = analysis->end; + } else { + MD_LINE* line; + + line = (MD_LINE*) md_push_block_bytes(ctx, sizeof(MD_LINE)); + if(line == NULL) + return -1; + + line->beg = analysis->beg; + line->end = analysis->end; + } + ctx->current_block->n_lines++; + + return 0; +} + +/* Part of the MD_FLAG_PRESERVEBLANKLINES implementation. */ +static int +md_flush_blank_lines(MD_CTX* ctx) +{ + MD_BLOCK* block; + + if(ctx->n_blank_lines == 0) + return 0; + + block = (MD_BLOCK*) md_push_block_bytes(ctx, sizeof(MD_BLOCK)); + if(block == NULL) + return -1; + + block->type = MD_BLOCK_BLANK; + block->flags = 0; + block->data = ctx->n_blank_lines; + block->n_lines = 0; + + ctx->n_blank_lines = 0; + return 0; +} + +static int +md_push_container_bytes(MD_CTX* ctx, MD_BLOCKTYPE type, unsigned start, + unsigned data, unsigned flags) +{ + MD_BLOCK* block; + int ret = 0; + + MD_CHECK(md_flush_blank_lines(ctx)); + MD_CHECK(md_end_current_block(ctx)); + + block = (MD_BLOCK*) md_push_block_bytes(ctx, sizeof(MD_BLOCK)); + if(block == NULL) + return -1; + + block->type = type; + block->flags = flags; + block->data = data; + block->n_lines = start; + +abort: + return ret; +} + + + +/*********************** + *** Line Analysis *** + ***********************/ + +static int +md_is_hr_line(MD_CTX* ctx, OFF beg, OFF* p_end, OFF* p_killer) +{ + OFF off = beg + 1; + int n = 1; + + while(off < ctx->size && (CH(off) == CH(beg) || CH(off) == _T(' ') || CH(off) == _T('\t'))) { + if(CH(off) == CH(beg)) + n++; + off++; + } + + if(n < 3) { + *p_killer = off; + return false; + } + + /* Nothing else can be present on the line. */ + if(off < ctx->size && !ISNEWLINE(off)) { + *p_killer = off; + return false; + } + + *p_end = off; + return true; +} + +static int +md_is_atxheader_line(MD_CTX* ctx, OFF beg, OFF* p_beg, OFF* p_end, unsigned* p_level) +{ + int n; + OFF off = beg + 1; + + while(off < ctx->size && CH(off) == _T('#') && off - beg < 7) + off++; + n = off - beg; + + if(n > 6) + return false; + *p_level = n; + + if(!(ctx->parser.flags & MD_FLAG_PERMISSIVEATXHEADERS) && off < ctx->size && + !ISBLANK(off) && !ISNEWLINE(off)) + return false; + + while(off < ctx->size && ISBLANK(off)) + off++; + *p_beg = off; + *p_end = off; + return true; +} + +static int +md_is_setext_underline(MD_CTX* ctx, OFF beg, OFF* p_end, unsigned* p_level) +{ + OFF off = beg + 1; + + while(off < ctx->size && CH(off) == CH(beg)) + off++; + + /* Optionally, space(s) or tabs can follow. */ + while(off < ctx->size && ISBLANK(off)) + off++; + + /* But nothing more is allowed on the line. */ + if(off < ctx->size && !ISNEWLINE(off)) + return false; + + *p_level = (CH(beg) == _T('=') ? 1 : 2); + *p_end = off; + return true; +} + +static int +md_is_table_underline(MD_CTX* ctx, OFF beg, OFF* p_end, unsigned* p_col_count) +{ + OFF off = beg; + int found_pipe = false; + unsigned col_count = 0; + + if(off < ctx->size && CH(off) == _T('|')) { + found_pipe = true; + off++; + while(off < ctx->size && ISWHITESPACE(off)) + off++; + } + + while(1) { + int delimited = false; + + /* Cell underline ("-----", ":----", "----:" or ":----:") */ + if(off < ctx->size && CH(off) == _T(':')) + off++; + if(off >= ctx->size || CH(off) != _T('-')) + return false; + while(off < ctx->size && CH(off) == _T('-')) + off++; + if(off < ctx->size && CH(off) == _T(':')) + off++; + + col_count++; + + /* Pipe delimiter (optional at the end of line). */ + while(off < ctx->size && ISWHITESPACE(off)) + off++; + if(off < ctx->size && CH(off) == _T('|')) { + delimited = true; + found_pipe = true; + off++; + while(off < ctx->size && ISWHITESPACE(off)) + off++; + } + + /* Success, if we reach end of line. */ + if(off >= ctx->size || ISNEWLINE(off)) + break; + + if(!delimited) + return false; + } + + if(!found_pipe) + return false; + + *p_end = off; + *p_col_count = col_count; + return true; +} + +static int +md_is_opening_code_fence(MD_CTX* ctx, OFF beg, OFF* p_end) +{ + OFF off = beg; + + while(off < ctx->size && CH(off) == CH(beg)) + off++; + + /* Fence must have at least three characters. */ + if(off - beg < 3) + return false; + + ctx->code_fence_length = off - beg; + + /* Optionally, space(s) can follow. */ + while(off < ctx->size && CH(off) == _T(' ')) + off++; + + /* Optionally, an info string can follow. */ + while(off < ctx->size && !ISNEWLINE(off)) { + /* Backtick-based fence must not contain '`' in the info string. */ + if(CH(beg) == _T('`') && CH(off) == _T('`')) + return false; + off++; + } + + *p_end = off; + return true; +} + +static int +md_is_closing_code_fence(MD_CTX* ctx, CHAR ch, OFF beg, OFF* p_end) +{ + OFF off = beg; + int ret = false; + + /* Closing fence must have at least the same length and use same char as + * opening one. */ + while(off < ctx->size && CH(off) == ch) + off++; + if(off - beg < ctx->code_fence_length) + goto out; + + /* Optionally, space(s) can follow */ + while(off < ctx->size && ISANYOF2(off, _T(' '), _T('\t'))) + off++; + + /* But nothing more is allowed on the line. */ + if(off < ctx->size && !ISNEWLINE(off)) + goto out; + + ret = true; + +out: + /* Note we set *p_end even on failure: If we are not closing fence, caller + * would eat the line anyway without any parsing. */ + *p_end = off; + return ret; +} + + +/* Helper data for md_is_html_block_start_condition() and + * md_is_html_block_end_condition() */ +typedef struct TAG_tag TAG; +struct TAG_tag { + const CHAR* name; + unsigned len : 8; +}; + +#ifdef X + #undef X +#endif +#define X(name) { _T(name), (sizeof(_T(name))-1) / sizeof(CHAR) } +#define Xend { NULL, 0 } + +static const TAG t1[] = { X("pre"), X("script"), X("style"), X("textarea"), Xend }; + +static const TAG a6[] = { X("address"), X("article"), X("aside"), Xend }; +static const TAG b6[] = { X("base"), X("basefont"), X("blockquote"), X("body"), Xend }; +static const TAG c6[] = { X("caption"), X("center"), X("col"), X("colgroup"), Xend }; +static const TAG d6[] = { X("dd"), X("details"), X("dialog"), X("dir"), + X("div"), X("dl"), X("dt"), Xend }; +static const TAG f6[] = { X("fieldset"), X("figcaption"), X("figure"), X("footer"), + X("form"), X("frame"), X("frameset"), Xend }; +static const TAG h6[] = { X("h1"), X("h2"), X("h3"), X("h4"), X("h5"), X("h6"), + X("head"), X("header"), X("hr"), X("html"), Xend }; +static const TAG i6[] = { X("iframe"), Xend }; +static const TAG l6[] = { X("legend"), X("li"), X("link"), Xend }; +static const TAG m6[] = { X("main"), X("menu"), X("menuitem"), Xend }; +static const TAG n6[] = { X("nav"), X("noframes"), Xend }; +static const TAG o6[] = { X("ol"), X("optgroup"), X("option"), Xend }; +static const TAG p6[] = { X("p"), X("param"), Xend }; +static const TAG s6[] = { X("search"), X("section"), X("summary"), Xend }; +static const TAG t6[] = { X("table"), X("tbody"), X("td"), X("tfoot"), X("th"), + X("thead"), X("title"), X("tr"), X("track"), Xend }; +static const TAG u6[] = { X("ul"), Xend }; +static const TAG v6[] = { X("video"), Xend }; +static const TAG xx[] = { Xend }; + +#undef X +#undef Xend + +/* Returns type of the raw HTML block, or false if it is not HTML block. + * (Refer to CommonMark specification for details about the types.) + */ +static int +md_is_html_block_start_condition(MD_CTX* ctx, OFF beg) +{ + /* Type 6 is started by a long list of allowed tags. We use two-level + * tree to speed-up the search. */ + static const TAG* map6[26] = { + a6, b6, c6, d6, xx, f6, xx, h6, i6, xx, xx, l6, m6, + n6, o6, p6, xx, xx, s6, t6, u6, v6, xx, xx, xx, xx + }; + OFF off = beg + 1; + int i; + + /* Check for type 1: size) { + if(md_ascii_case_eq(STR(off), t1[i].name, t1[i].len)) + return 1; + } + } + + /* Check for type 2: "), 3, p_end) ? 2 : false); + + case 3: + return (md_line_contains(ctx, beg, _T("?>"), 2, p_end) ? 3 : false); + + case 4: + return (md_line_contains(ctx, beg, _T(">"), 1, p_end) ? 4 : false); + + case 5: + return (md_line_contains(ctx, beg, _T("]]>"), 3, p_end) ? 5 : false); + + case 6: MD_FALLTHROUGH(); + case 7: + if(beg >= ctx->size || ISNEWLINE(beg)) { + /* Blank line ends types 6 and 7. */ + *p_end = beg; + return ctx->html_block_type; + } + return false; + + default: + MD_UNREACHABLE(); + } + return false; +} + + +static int +md_is_container_compatible(const MD_CONTAINER* pivot, const MD_CONTAINER* container) +{ + /* Block quote has no "items" like lists. */ + if(container->ch == _T('>')) + return false; + + if(container->ch != pivot->ch) + return false; + if(container->mark_indent > pivot->contents_indent) + return false; + + return true; +} + +static int +md_push_container(MD_CTX* ctx, const MD_CONTAINER* container) +{ + if(ctx->n_containers >= ctx->alloc_containers) { + MD_CONTAINER* new_containers; + + ctx->alloc_containers = (ctx->alloc_containers > 0 + ? ctx->alloc_containers + ctx->alloc_containers / 2 + : 16); + new_containers = realloc(ctx->containers, ctx->alloc_containers * sizeof(MD_CONTAINER)); + if(new_containers == NULL) { + MD_LOG("realloc() failed."); + return -1; + } + + ctx->containers = new_containers; + } + + memcpy(&ctx->containers[ctx->n_containers++], container, sizeof(MD_CONTAINER)); + return 0; +} + +static int +md_enter_child_containers(MD_CTX* ctx, int n_children) +{ + int i; + int ret = 0; + + for(i = ctx->n_containers - n_children; i < ctx->n_containers; i++) { + MD_CONTAINER* c = &ctx->containers[i]; + int is_ordered_list = false; + + switch(c->ch) { + case _T(')'): + case _T('.'): + is_ordered_list = true; + MD_FALLTHROUGH(); + + case _T('-'): + case _T('+'): + case _T('*'): + /* Remember offset in ctx->block_bytes so we can revisit the + * block if we detect it is a loose list. */ + md_end_current_block(ctx); + c->block_byte_off = ctx->n_block_bytes; + + MD_CHECK(md_push_container_bytes(ctx, + (is_ordered_list ? MD_BLOCK_OL : MD_BLOCK_UL), + c->start, c->ch, MD_BLOCK_CONTAINER_OPENER)); + MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI, + c->task_mark_off, + (c->is_task ? CH(c->task_mark_off) : 0), + MD_BLOCK_CONTAINER_OPENER)); + break; + + case _T('>'): + MD_CHECK(md_push_container_bytes(ctx, + (c->is_admonition ? MD_BLOCK_ADMONITION : MD_BLOCK_QUOTE), + 0, c->admonition_type, MD_BLOCK_CONTAINER_OPENER)); + break; + + default: + MD_UNREACHABLE(); + break; + } + } + +abort: + return ret; +} + +static int +md_leave_child_containers(MD_CTX* ctx, int n_keep) +{ + int ret = 0; + + while(ctx->n_containers > n_keep) { + MD_CONTAINER* c = &ctx->containers[ctx->n_containers-1]; + int is_ordered_list = false; + + switch(c->ch) { + case _T(')'): + case _T('.'): + is_ordered_list = true; + MD_FALLTHROUGH(); + + case _T('-'): + case _T('+'): + case _T('*'): + MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI, + c->task_mark_off, (c->is_task ? CH(c->task_mark_off) : 0), + MD_BLOCK_CONTAINER_CLOSER)); + MD_CHECK(md_push_container_bytes(ctx, + (is_ordered_list ? MD_BLOCK_OL : MD_BLOCK_UL), 0, + c->ch, MD_BLOCK_CONTAINER_CLOSER)); + break; + + case _T('>'): + MD_CHECK(md_push_container_bytes(ctx, + (c->is_admonition ? MD_BLOCK_ADMONITION : MD_BLOCK_QUOTE), + 0, c->admonition_type, MD_BLOCK_CONTAINER_CLOSER)); + break; + + default: + MD_UNREACHABLE(); + break; + } + + ctx->n_containers--; + } + +abort: + return ret; +} + +static int +md_is_container_mark(MD_CTX* ctx, unsigned indent, OFF beg, OFF* p_end, MD_CONTAINER* p_container) +{ + OFF off = beg; + OFF max_end; + + if(off >= ctx->size || indent >= ctx->code_indent_offset) + return false; + + /* Check for block quote mark. */ + if(CH(off) == _T('>')) { + off++; + p_container->ch = _T('>'); + p_container->is_loose = false; + p_container->is_task = false; + p_container->mark_indent = indent; + p_container->contents_indent = indent + 1; + *p_end = off; + return true; + } + + /* Check for list item bullet mark. */ + if(ISANYOF(off, _T("-+*")) && (off+1 >= ctx->size || ISBLANK(off+1) || ISNEWLINE(off+1))) { + p_container->ch = CH(off); + p_container->is_loose = false; + p_container->is_task = false; + p_container->mark_indent = indent; + p_container->contents_indent = indent + 1; + *p_end = off+1; + return true; + } + + /* Check for ordered list item marks. */ + max_end = off + 9; + if(max_end > ctx->size) + max_end = ctx->size; + p_container->start = 0; + while(off < max_end && ISDIGIT(off)) { + p_container->start = p_container->start * 10 + CH(off) - _T('0'); + off++; + } + if(off > beg && + off < ctx->size && + (CH(off) == _T('.') || CH(off) == _T(')')) && + (off+1 >= ctx->size || ISBLANK(off+1) || ISNEWLINE(off+1))) + { + p_container->ch = CH(off); + p_container->is_loose = false; + p_container->is_task = false; + p_container->mark_indent = indent; + p_container->contents_indent = indent + off - beg + 1; + *p_end = off+1; + return true; + } + + return false; +} + +static unsigned +md_line_indentation(MD_CTX* ctx, unsigned total_indent, OFF beg, OFF* p_end) +{ + OFF off = beg; + unsigned indent = total_indent; + + while(off < ctx->size && ISBLANK(off)) { + if(CH(off) == _T('\t')) + indent = (indent + 4) & ~3; + else + indent++; + off++; + } + + *p_end = off; + return indent - total_indent; +} + +static const MD_LINE_ANALYSIS md_dummy_blank_line = { MD_LINE_BLANK, 0, 0, 0, 0, 0 }; + +/* Analyze type of the line and find some its properties. This serves as a + * main input for determining type and boundaries of a block. */ +static int +md_analyze_line(MD_CTX* ctx, OFF beg, OFF* p_end, + const MD_LINE_ANALYSIS* pivot_line, MD_LINE_ANALYSIS* line) +{ + unsigned total_indent = 0; + int n_parents = 0; + int n_brothers = 0; + int n_children = 0; + MD_CONTAINER container = { 0 }; + int prev_line_has_list_loosening_effect = ctx->last_line_has_list_loosening_effect; + OFF off = beg; + OFF hr_killer = 0; + int ret = 0; + + line->indent = md_line_indentation(ctx, total_indent, off, &off); + total_indent += line->indent; + line->beg = off; + line->enforce_new_block = false; + + /* Given the indentation and block quote marks '>', determine how many of + * the current containers are our parents. */ + while(n_parents < ctx->n_containers) { + MD_CONTAINER* c = &ctx->containers[n_parents]; + + if(c->ch == _T('>') && line->indent < ctx->code_indent_offset && + off < ctx->size && CH(off) == _T('>')) + { + /* Block quote mark. */ + off++; + total_indent++; + line->indent = md_line_indentation(ctx, total_indent, off, &off); + total_indent += line->indent; + + /* The optional 1st space after '>' is part of the block quote mark. */ + if(line->indent > 0) + line->indent--; + + line->beg = off; + + } else if(c->ch != _T('>') && line->indent >= c->contents_indent) { + /* List. */ + line->indent -= c->contents_indent; + } else { + break; + } + + n_parents++; + } + + if(off >= ctx->size || ISNEWLINE(off)) { + /* Blank line does not need any real indentation to be nested inside + * a list. */ + if(n_brothers + n_children == 0) { + while(n_parents < ctx->n_containers && ctx->containers[n_parents].ch != _T('>')) + n_parents++; + } + } + + while(true) { + /* Check whether we are fenced code continuation. */ + if(pivot_line->type == MD_LINE_FENCEDCODE) { + line->beg = off; + + /* We are another MD_LINE_FENCEDCODE unless we are closing fence + * which we transform into MD_LINE_BLANK. */ + if(line->indent < ctx->code_indent_offset) { + if(md_is_closing_code_fence(ctx, CH(pivot_line->beg), off, &off)) { + line->type = MD_LINE_BLANK; + ctx->last_line_has_list_loosening_effect = false; + break; + } + } + + /* Change indentation accordingly to the initial code fence. */ + if(n_parents == ctx->n_containers) { + if(line->indent > pivot_line->indent) + line->indent -= pivot_line->indent; + else + line->indent = 0; + + line->type = MD_LINE_FENCEDCODE; + break; + } + } + + /* Check whether we are HTML block continuation. */ + if(pivot_line->type == MD_LINE_HTML && ctx->html_block_type > 0) { + if(n_parents < ctx->n_containers) { + /* HTML block is implicitly ended if the enclosing container + * block ends. */ + ctx->html_block_type = 0; + } else { + int html_block_type; + + html_block_type = md_is_html_block_end_condition(ctx, off, &off); + if(html_block_type > 0) { + MD_ASSERT(html_block_type == ctx->html_block_type); + + /* Make sure this is the last line of the block. */ + ctx->html_block_type = 0; + + /* Some end conditions serve as blank lines at the same time. */ + if(html_block_type == 6 || html_block_type == 7) { + line->type = MD_LINE_BLANK; + line->indent = 0; + break; + } + } + + line->type = MD_LINE_HTML; + n_parents = ctx->n_containers; + break; + } + } + + /* Check for blank line. */ + if(off >= ctx->size || ISNEWLINE(off)) { + if(pivot_line->type == MD_LINE_INDENTEDCODE && n_parents == ctx->n_containers) { + line->type = MD_LINE_INDENTEDCODE; + if(line->indent > ctx->code_indent_offset) + line->indent -= ctx->code_indent_offset; + else + line->indent = 0; + ctx->last_line_has_list_loosening_effect = false; + } else { + line->type = MD_LINE_BLANK; + ctx->last_line_has_list_loosening_effect = (n_parents > 0 && + n_brothers + n_children == 0 && + ctx->containers[n_parents-1].ch != _T('>')); + + #if 1 + /* See https://github.com/mity/md4c/issues/6 + * + * This ugly checking tests we are in (yet empty) list item but + * not its very first line (i.e. not the line with the list + * item mark). + * + * If we are such a blank line, then any following non-blank + * line which would be part of the list item actually has to + * end the list because according to the specification, "a list + * item can begin with at most one blank line." + */ + if(n_parents > 0 && ctx->containers[n_parents-1].ch != _T('>') && + n_brothers + n_children == 0 && ctx->current_block == NULL && + ctx->n_block_bytes > (int) sizeof(MD_BLOCK)) + { + MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK)); + if(top_block->type == MD_BLOCK_LI) + ctx->last_list_item_starts_with_two_blank_lines = true; + } + #endif + } + break; + } else { + #if 1 + /* This is the 2nd half of the hack. If the flag is set (i.e. there + * was a 2nd blank line at the beginning of the list item) and if + * we would otherwise still belong to the list item, we enforce + * the end of the list. */ + if(ctx->last_list_item_starts_with_two_blank_lines) { + if(n_parents > 0 && n_parents == ctx->n_containers && + ctx->containers[n_parents-1].ch != _T('>') && + n_brothers + n_children == 0 && ctx->current_block == NULL && + ctx->n_block_bytes > (int) sizeof(MD_BLOCK)) + { + MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK)); + if(top_block->type == MD_BLOCK_LI) { + n_parents--; + + line->indent = total_indent; + if(n_parents > 0) + line->indent -= MIN(line->indent, ctx->containers[n_parents-1].contents_indent); + } + } + + ctx->last_list_item_starts_with_two_blank_lines = false; + } + #endif + ctx->last_line_has_list_loosening_effect = false; + } + + /* Check whether we are Setext underline. */ + if(line->indent < ctx->code_indent_offset && pivot_line->type == MD_LINE_TEXT + && off < ctx->size && ISANYOF2(off, _T('='), _T('-')) + && (n_parents == ctx->n_containers)) + { + unsigned level; + + if(md_is_setext_underline(ctx, off, &off, &level)) { + line->type = MD_LINE_SETEXTUNDERLINE; + line->data = level; + break; + } + } + + /* Check for thematic break line. */ + if(line->indent < ctx->code_indent_offset + && off < ctx->size && off >= hr_killer + && ISANYOF(off, _T("-_*"))) + { + if(md_is_hr_line(ctx, off, &off, &hr_killer)) { + line->type = MD_LINE_HR; + break; + } + } + + /* Check for "brother" container. I.e. whether we are another list item + * in already started list. */ + if(n_parents < ctx->n_containers && n_brothers + n_children == 0) { + OFF tmp; + + if(md_is_container_mark(ctx, line->indent, off, &tmp, &container) && + md_is_container_compatible(&ctx->containers[n_parents], &container)) + { + pivot_line = &md_dummy_blank_line; + + off = tmp; + + total_indent += container.contents_indent - container.mark_indent; + line->indent = md_line_indentation(ctx, total_indent, off, &off); + total_indent += line->indent; + line->beg = off; + + /* Some of the following whitespace actually still belongs to the mark. */ + if(off >= ctx->size || ISNEWLINE(off)) { + container.contents_indent++; + } else if(line->indent <= ctx->code_indent_offset) { + container.contents_indent += line->indent; + line->indent = 0; + } else { + container.contents_indent += 1; + line->indent--; + } + + ctx->containers[n_parents].mark_indent = container.mark_indent; + ctx->containers[n_parents].contents_indent = container.contents_indent; + + n_brothers++; + continue; + } + } + + /* Check for indented code. + * Note indented code block cannot interrupt a paragraph. */ + if(line->indent >= ctx->code_indent_offset && (pivot_line->type != MD_LINE_TEXT)) { + line->type = MD_LINE_INDENTEDCODE; + line->indent -= ctx->code_indent_offset; + line->data = 0; + break; + } + + /* Check for start of a new container block. */ + if(line->indent < ctx->code_indent_offset && + md_is_container_mark(ctx, line->indent, off, &off, &container)) + { + if(pivot_line->type == MD_LINE_TEXT && n_parents == ctx->n_containers && + (off >= ctx->size || ISNEWLINE(off)) && container.ch != _T('>')) + { + /* Noop. List mark followed by a blank line cannot interrupt a paragraph. */ + } else if(pivot_line->type == MD_LINE_TEXT && n_parents == ctx->n_containers && + ISANYOF2_(container.ch, _T('.'), _T(')')) && container.start != 1) + { + /* Noop. Ordered list cannot interrupt a paragraph unless the start index is 1. */ + } else { + total_indent += container.contents_indent - container.mark_indent; + line->indent = md_line_indentation(ctx, total_indent, off, &off); + total_indent += line->indent; + + line->beg = off; + line->data = container.ch; + + /* Some of the following whitespace actually still belongs to the mark. */ + if(off >= ctx->size || ISNEWLINE(off)) { + container.contents_indent++; + } else if(line->indent <= ctx->code_indent_offset) { + container.contents_indent += line->indent; + line->indent = 0; + } else { + container.contents_indent += 1; + line->indent--; + } + + if(n_brothers + n_children == 0) + pivot_line = &md_dummy_blank_line; + + if(n_children == 0) + MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers)); + + n_children++; + MD_CHECK(md_push_container(ctx, &container)); + continue; + } + } + + /* Check whether we are table continuation. */ + if(pivot_line->type == MD_LINE_TABLE && n_parents == ctx->n_containers) { + line->type = MD_LINE_TABLE; + break; + } + + /* Check for ATX header. */ + if(line->indent < ctx->code_indent_offset && + off < ctx->size && CH(off) == _T('#')) + { + unsigned level; + + if(md_is_atxheader_line(ctx, off, &line->beg, &off, &level)) { + line->type = MD_LINE_ATXHEADER; + line->data = level; + break; + } + } + + /* Check whether we are starting code fence. */ + if(line->indent < ctx->code_indent_offset && + off < ctx->size && ISANYOF2(off, _T('`'), _T('~'))) + { + if(md_is_opening_code_fence(ctx, off, &off)) { + line->type = MD_LINE_FENCEDCODE; + line->data = 1; + line->enforce_new_block = true; + break; + } + } + + /* Check for start of raw HTML block. */ + if(off < ctx->size && CH(off) == _T('<') + && !(ctx->parser.flags & MD_FLAG_NOHTMLBLOCKS)) + { + ctx->html_block_type = md_is_html_block_start_condition(ctx, off); + + /* HTML block type 7 cannot interrupt paragraph. */ + if(ctx->html_block_type == 7 && pivot_line->type == MD_LINE_TEXT) + ctx->html_block_type = 0; + + if(ctx->html_block_type > 0) { + /* The line itself also may immediately close the block. */ + if(md_is_html_block_end_condition(ctx, off, &off) == ctx->html_block_type) { + /* Make sure this is the last line of the block. */ + ctx->html_block_type = 0; + } + + line->enforce_new_block = true; + line->type = MD_LINE_HTML; + break; + } + } + + /* Check for table underline. */ + if((ctx->parser.flags & MD_FLAG_TABLES) && pivot_line->type == MD_LINE_TEXT + && off < ctx->size && ISANYOF3(off, _T('|'), _T('-'), _T(':')) + && n_parents == ctx->n_containers) + { + unsigned col_count; + + if(ctx->current_block != NULL && ctx->current_block->n_lines == 1 && + md_is_table_underline(ctx, off, &off, &col_count)) + { + line->data = col_count; + line->type = MD_LINE_TABLEUNDERLINE; + break; + } + } + + /* By default, we are normal text line. */ + line->type = MD_LINE_TEXT; + if(pivot_line->type == MD_LINE_TEXT && n_brothers + n_children == 0) { + /* Lazy continuation. */ + n_parents = ctx->n_containers; + } + + /* Check for task mark. */ + if((ctx->parser.flags & MD_FLAG_TASKLISTS) && n_brothers + n_children > 0 && + ISANYOF_(ctx->containers[ctx->n_containers-1].ch, _T("-+*.)"))) + { + OFF tmp = off; + + while(tmp < ctx->size && tmp < off + 3 && ISBLANK(tmp)) + tmp++; + if(tmp + 2 < ctx->size && CH(tmp) == _T('[') && + ISANYOF(tmp+1, _T("xX ")) && CH(tmp+2) == _T(']') && + (tmp + 3 == ctx->size || ISBLANK(tmp+3) || ISNEWLINE(tmp+3))) + { + MD_CONTAINER* task_container = (n_children > 0 ? &ctx->containers[ctx->n_containers-1] : &container); + task_container->is_task = true; + task_container->task_mark_off = tmp + 1; + off = tmp + 3; + while(off < ctx->size && ISWHITESPACE(off)) + off++; + line->beg = off; + } + } + + break; + } + + /* Scan for end of the line. */ + /* Optimization: Use some loop unrolling. */ + while(off + 3 < ctx->size && !ISNEWLINE(off+0) && !ISNEWLINE(off+1) + && !ISNEWLINE(off+2) && !ISNEWLINE(off+3)) + off += 4; + while(off < ctx->size && !ISNEWLINE(off)) + off++; + + /* Set end of the line. */ + line->end = off; + + /* But for ATX header, we should exclude the optional trailing mark. */ + if(line->type == MD_LINE_ATXHEADER) { + OFF tmp = line->end; + while(tmp > line->beg && ISBLANK(tmp-1)) + tmp--; + while(tmp > line->beg && CH(tmp-1) == _T('#')) + tmp--; + if(tmp == line->beg || ISBLANK(tmp-1) || (ctx->parser.flags & MD_FLAG_PERMISSIVEATXHEADERS)) + line->end = tmp; + } + + /* Trim trailing spaces. */ + if(line->type != MD_LINE_INDENTEDCODE && line->type != MD_LINE_FENCEDCODE && line->type != MD_LINE_HTML) { + while(line->end > line->beg && ISBLANK(line->end-1)) + line->end--; + } + + /* Eat also the new line. */ + if(off < ctx->size && CH(off) == _T('\r')) + off++; + if(off < ctx->size && CH(off) == _T('\n')) + off++; + + *p_end = off; + + /* If we belong to a list after seeing a blank line, the list is loose. */ + if(prev_line_has_list_loosening_effect && line->type != MD_LINE_BLANK && n_parents + n_brothers > 0) { + MD_CONTAINER* c = &ctx->containers[n_parents + n_brothers - 1]; + if(c->ch != _T('>')) { + MD_BLOCK* block = (MD_BLOCK*) (((char*)ctx->block_bytes) + c->block_byte_off); + block->flags |= MD_BLOCK_LOOSE_LIST; + } + } + + /* Leave any containers we are not part of anymore. */ + if(n_children == 0 && n_parents + n_brothers < ctx->n_containers) + MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers)); + + /* Enter any container we found a mark for. */ + if(n_brothers > 0) { + MD_ASSERT(n_brothers == 1); + MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI, + ctx->containers[n_parents].task_mark_off, + (ctx->containers[n_parents].is_task ? CH(ctx->containers[n_parents].task_mark_off) : 0), + MD_BLOCK_CONTAINER_CLOSER)); + MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI, + container.task_mark_off, + (container.is_task ? CH(container.task_mark_off) : 0), + MD_BLOCK_CONTAINER_OPENER)); + ctx->containers[n_parents].is_task = container.is_task; + ctx->containers[n_parents].task_mark_off = container.task_mark_off; + } + + if(n_children > 0) { + /* Check for admonition tag. */ + if((ctx->parser.flags & MD_FLAG_ADMONITIONS) && n_children > 0 && + ctx->containers[ctx->n_containers-1].ch == _T('>') && line->type == MD_LINE_TEXT && + 3 < line->end - line->beg && line->end - line->beg < 16 && + CH(line->beg) == _T('[') && CH(line->beg+1) == _T('!') && CH(line->end-1) == _T(']')) + { + unsigned i; + + for(i = 0; i < SIZEOF_ARRAY(MD_ADMONITION_TAGS); i++) { + if(line->end - line->beg == md_strlen(MD_ADMONITION_TAGS[i]) + 3 && + md_ascii_case_eq(STR(line->beg+2), MD_ADMONITION_TAGS[i], line->end - line->beg - 3)) + { + ctx->containers[ctx->n_containers-1].is_admonition = true; + ctx->containers[ctx->n_containers-1].admonition_type = i; + line->type = MD_LINE_BLANK; + break; + } + } + } + + /* Enter all the child container blocks. */ + MD_CHECK(md_enter_child_containers(ctx, n_children)); + } + +abort: + return ret; +} + +static int +md_process_line(MD_CTX* ctx, const MD_LINE_ANALYSIS** p_pivot_line, MD_LINE_ANALYSIS* line) +{ + const MD_LINE_ANALYSIS* pivot_line = *p_pivot_line; + int ret = 0; + + /* Blank line ends current leaf block. */ + if(line->type == MD_LINE_BLANK) { + MD_CHECK(md_end_current_block(ctx)); + /* Count only genuinely empty lines: some non-blank lines (e.g. a closing + * code fence) are internally retyped as MD_LINE_BLANK but still hold + * their text (beg < end), and must not be counted. */ + if((ctx->parser.flags & MD_FLAG_PRESERVEBLANKLINES) && line->beg >= line->end) + ctx->n_blank_lines++; + *p_pivot_line = &md_dummy_blank_line; + return 0; + } + + /* The blank lines preceding this block (if any) form a block separation + * which we report before the block itself. */ + MD_CHECK(md_flush_blank_lines(ctx)); + + if(line->enforce_new_block) + MD_CHECK(md_end_current_block(ctx)); + + /* Some line types form block on their own. */ + if(line->type == MD_LINE_HR || line->type == MD_LINE_ATXHEADER) { + MD_CHECK(md_end_current_block(ctx)); + + /* Add our single-line block. */ + MD_CHECK(md_start_new_block(ctx, line)); + MD_CHECK(md_add_line_into_current_block(ctx, line)); + MD_CHECK(md_end_current_block(ctx)); + *p_pivot_line = &md_dummy_blank_line; + return 0; + } + + /* MD_LINE_SETEXTUNDERLINE changes meaning of the current block and ends it. */ + if(line->type == MD_LINE_SETEXTUNDERLINE) { + MD_ASSERT(ctx->current_block != NULL); + ctx->current_block->type = MD_BLOCK_H; + ctx->current_block->data = line->data; + ctx->current_block->flags |= MD_BLOCK_SETEXT_HEADER; + MD_CHECK(md_add_line_into_current_block(ctx, line)); + MD_CHECK(md_end_current_block(ctx)); + if(ctx->current_block == NULL) { + *p_pivot_line = &md_dummy_blank_line; + } else { + /* This happens if we have consumed all the body as link ref. defs. + * and downgraded the underline into start of a new paragraph block. */ + line->type = MD_LINE_TEXT; + *p_pivot_line = line; + } + return 0; + } + + /* MD_LINE_TABLEUNDERLINE changes meaning of the current block. */ + if(line->type == MD_LINE_TABLEUNDERLINE) { + MD_ASSERT(ctx->current_block != NULL); + MD_ASSERT(ctx->current_block->n_lines == 1); + ctx->current_block->type = MD_BLOCK_TABLE; + ctx->current_block->data = line->data; + MD_ASSERT(pivot_line != &md_dummy_blank_line); + ((MD_LINE_ANALYSIS*)pivot_line)->type = MD_LINE_TABLE; + MD_CHECK(md_add_line_into_current_block(ctx, line)); + return 0; + } + + /* The current block also ends if the line has different type. */ + if(line->type != pivot_line->type) + MD_CHECK(md_end_current_block(ctx)); + + /* The current line may start a new block. */ + if(ctx->current_block == NULL) { + MD_CHECK(md_start_new_block(ctx, line)); + *p_pivot_line = line; + } + + /* In all other cases the line is just a continuation of the current block. */ + MD_CHECK(md_add_line_into_current_block(ctx, line)); + +abort: + return ret; +} + +static int +md_footnote_def_cmp_index(const void* a, const void* b) +{ + const MD_FOOTNOTE_DEF* da = (const MD_FOOTNOTE_DEF*) a; + const MD_FOOTNOTE_DEF* db = (const MD_FOOTNOTE_DEF*) b; + + /* Unreferenced defs (index == 0) always sort after referenced ones. */ + if(da->index == 0 && db->index == 0) return 0; + if(da->index == 0) return +1; + if(db->index == 0) return -1; + if(da->index < db->index) return -1; + if(da->index > db->index) return +1; + return 0; +} + +static int +md_process_footnote_def(MD_CTX* ctx, MD_FOOTNOTE_DEF* def) +{ + MD_BLOCK_FOOTNOTE_DEF_DETAIL det; + MD_ATTRIBUTE_BUILD label_build = { 0 }; + int ret = 0; + + memset(&det, 0, sizeof(MD_BLOCK_FOOTNOTE_DEF_DETAIL)); + det.id = def->index; + det.ref_count = def->ref_count; + MD_CHECK(md_build_attribute(ctx, def->entry.label, def->entry.label_size, 0, + &det.label, &label_build)); + + MD_ENTER_BLOCK(MD_BLOCK_FOOTNOTE_DEF, &det); + MD_CHECK(md_process_normal_block_contents(ctx, def->content_lines, + def->n_content_lines)); + MD_LEAVE_BLOCK(MD_BLOCK_FOOTNOTE_DEF, &det); + +abort: + md_free_attribute(ctx, &label_build); + return ret; +} + +/* Render footnote definitions that were actually referenced, in reference order. + * Called from md_process_doc() after md_process_all_blocks(). */ +static int +md_process_footnote_defs(MD_CTX* ctx) +{ + unsigned i; + int ret = 0; + + if(ctx->footnote_hashtable.n_defs == 0 || ctx->next_footnote_index == 0) + return 0; + + /* Sort defs by index so we emit in reference order. */ + qsort(ctx->footnote_hashtable.defs, ctx->footnote_hashtable.n_defs, + sizeof(MD_FOOTNOTE_DEF), md_footnote_def_cmp_index); + + MD_ENTER_BLOCK(MD_BLOCK_FOOTNOTE_DEF_SECTION, NULL); + + for(i = 0; i < ctx->footnote_hashtable.n_defs; i++) { + MD_FOOTNOTE_DEF* def = &ctx->footnote_hashtable.footnote_defs[i]; + if(def->index == 0) + break; + MD_CHECK(md_process_footnote_def(ctx, def)); + } + + MD_LEAVE_BLOCK(MD_BLOCK_FOOTNOTE_DEF_SECTION, NULL); + +abort: + return ret; +} + +static int +md_process_doc(MD_CTX *ctx) +{ + const MD_LINE_ANALYSIS* pivot_line = &md_dummy_blank_line; + MD_LINE_ANALYSIS line_buf[2]; + MD_LINE_ANALYSIS* line = &line_buf[0]; + OFF off = 0; + int ret = 0; + + MD_ENTER_BLOCK(MD_BLOCK_DOC, NULL); + + while(off < ctx->size) { + if(line == pivot_line) + line = (line == &line_buf[0] ? &line_buf[1] : &line_buf[0]); + + MD_CHECK(md_analyze_line(ctx, off, &off, pivot_line, line)); + MD_CHECK(md_process_line(ctx, &pivot_line, line)); + } + + md_end_current_block(ctx); + + MD_CHECK(md_build_ref_def_hashtable(ctx)); + if(ctx->parser.flags & MD_FLAG_FOOTNOTES) + MD_CHECK(md_build_footnote_def_hashtable(ctx)); + + /* Process all blocks. */ + MD_CHECK(md_leave_child_containers(ctx, 0)); + /* Report any blank lines trailing the document. */ + MD_CHECK(md_flush_blank_lines(ctx)); + MD_CHECK(md_process_all_blocks(ctx)); + + /* Emit footnote definitions that were referenced, in reference order. */ + if(ctx->parser.flags & MD_FLAG_FOOTNOTES) + MD_CHECK(md_process_footnote_defs(ctx)); + + MD_LEAVE_BLOCK(MD_BLOCK_DOC, NULL); + +abort: + +#if 0 + /* Output some memory consumption statistics. */ + { + char buffer[256]; + sprintf(buffer, "Alloced %u bytes for block buffer.", + (unsigned)(ctx->alloc_block_bytes)); + MD_LOG(buffer); + + sprintf(buffer, "Alloced %u bytes for containers buffer.", + (unsigned)(ctx->alloc_containers * sizeof(MD_CONTAINER))); + MD_LOG(buffer); + + sprintf(buffer, "Alloced %u bytes for marks buffer.", + (unsigned)(ctx->alloc_marks * sizeof(MD_MARK))); + MD_LOG(buffer); + + sprintf(buffer, "Alloced %u bytes for aux. buffer.", + (unsigned)(ctx->alloc_buffer * sizeof(MD_CHAR))); + MD_LOG(buffer); + } +#endif + + return ret; +} + + +/******************** + *** Public API *** + ********************/ + +int +md_parse(const MD_CHAR* text, MD_SIZE size, const MD_PARSER* parser, void* userdata) +{ + MD_CTX ctx; + int i; + int ret; + + if(parser->abi_version != 0) { + if(parser->debug_log != NULL) + parser->debug_log("Unsupported abi_version.", userdata); + return -1; + } + + /* Setup context structure. */ + memset(&ctx, 0, sizeof(MD_CTX)); + ctx.text = text; + ctx.size = size; + memcpy(&ctx.parser, parser, sizeof(MD_PARSER)); + ctx.userdata = userdata; + ctx.code_indent_offset = (ctx.parser.flags & MD_FLAG_NOINDENTEDCODEBLOCKS) ? (OFF)(-1) : 4; + md_build_mark_char_map(&ctx); + ctx.doc_ends_with_newline = (size > 0 && ISNEWLINE_(text[size-1])); + ctx.ref_def_hashtable.def_size = sizeof(MD_REF_DEF); + ctx.max_ref_def_output = 16 * MIN(size, (MD_SIZE)(1024 * 1024 / 16)); + ctx.footnote_hashtable.def_size = sizeof(MD_FOOTNOTE_DEF); + + /* Reset all mark stacks and lists. */ + for(i = 0; i < (int) SIZEOF_ARRAY(ctx.opener_stacks); i++) + ctx.opener_stacks[i].top = -1; + ctx.ptr_stack.top = -1; + ctx.unresolved_link_head = -1; + ctx.unresolved_link_tail = -1; + ctx.table_cell_boundaries_head = -1; + ctx.table_cell_boundaries_tail = -1; + + /* All the work. */ + ret = md_process_doc(&ctx); + + /* Clean-up. */ + md_free_ref_defs(&ctx); + md_free_footnote_defs(&ctx); + free(ctx.buffer); + free(ctx.marks); + free(ctx.block_bytes); + free(ctx.containers); + + return ret; +} diff --git a/packages/react-native-enriched-markdown/cpp/md4c/md4c.h b/packages/react-native-enriched-markdown/cpp/md4c/md4c.h new file mode 100644 index 000000000000..cf965d8cc17c --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/md4c/md4c.h @@ -0,0 +1,492 @@ +/* + * MD4C: Markdown parser for C + * (https://github.com/mity/md4c) + * + * Copyright (c) 2016-2026 Martin Mitáš + * + * 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. + */ + +#ifndef MD4C_H +#define MD4C_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined MD4C_USE_UTF16 +/* Magic to support UTF-16. Note that in order to use it, you have to define + * the macro MD4C_USE_UTF16 both when building MD4C as well as when + * including this header in your code. */ +#ifdef _WIN32 +#include +typedef WCHAR MD_CHAR; +#else +#error MD4C_USE_UTF16 is only supported on Windows. +#endif +#else +typedef char MD_CHAR; +#endif + +typedef unsigned MD_SIZE; +typedef unsigned MD_OFFSET; + +/* Block represents a part of document hierarchy structure like a paragraph + * or list item. + */ +typedef enum MD_BLOCKTYPE { + /* ... */ + MD_BLOCK_DOC = 0, + + /*
...
*/ + MD_BLOCK_QUOTE, + + /*
    ...
+ * Detail: Structure MD_BLOCK_UL_DETAIL. */ + MD_BLOCK_UL, + + /*
    ...
+ * Detail: Structure MD_BLOCK_OL_DETAIL. */ + MD_BLOCK_OL, + + /*
  • ...
  • + * Detail: Structure MD_BLOCK_LI_DETAIL. */ + MD_BLOCK_LI, + + /*
    */ + MD_BLOCK_HR, + + /*

    ...

    (for levels up to 6) + * Detail: Structure MD_BLOCK_H_DETAIL. */ + MD_BLOCK_H, + + /*
    ...
    + * Note the text lines within code blocks are terminated with '\n' + * instead of explicit MD_TEXT_BR. */ + MD_BLOCK_CODE, + + /* Raw HTML block. This itself does not correspond to any particular HTML + * tag. The contents of it _is_ raw HTML source intended to be put + * in verbatim form to the HTML output. */ + MD_BLOCK_HTML, + + /*

    ...

    */ + MD_BLOCK_P, + + /* ...
    and its contents. + * Detail: Structure MD_BLOCK_TABLE_DETAIL (for MD_BLOCK_TABLE), + * structure MD_BLOCK_TD_DETAIL (for MD_BLOCK_TH and MD_BLOCK_TD) + * Note all of these are used only if extension MD_FLAG_TABLES is enabled. */ + MD_BLOCK_TABLE, + MD_BLOCK_THEAD, + MD_BLOCK_TBODY, + MD_BLOCK_TR, + MD_BLOCK_TH, + MD_BLOCK_TD, + + /* Container for all referenced footnote definitions, rendered at the end + * of the document. + * Detail: NULL. + * Note: Used only if extension MD_FLAG_FOOTNOTES is enabled, and only when + * at least one footnote definition is referenced. */ + MD_BLOCK_FOOTNOTE_DEF_SECTION, + + /* A single footnote definition, rendered at the end of the document. + * Detail: Structure MD_BLOCK_FOOTNOTE_DEF_DETAIL. + * Note: Used only if extension MD_FLAG_FOOTNOTES is enabled. + * Only definitions that are actually referenced in the document are + * emitted, in order of first reference. */ + MD_BLOCK_FOOTNOTE_DEF, + + /* Adminition extension. + * Detail MD_BLOCK_ADMONITION_DETAIL. + * Note: Recognized only when MD_FLAG_ADMONITIONS is enabled. */ + MD_BLOCK_ADMONITION, + + /* A run of blank lines separating two blocks. Has no contents. + * Detail: Structure MD_BLOCK_BLANK_DETAIL. + * Note: Emitted only when MD_FLAG_PRESERVEBLANKLINES is enabled. */ + MD_BLOCK_BLANK +} MD_BLOCKTYPE; + +/* Span represents an in-line piece of a document which should be rendered with + * the same font, color and other attributes. A sequence of spans forms a block + * like paragraph or list item. */ +typedef enum MD_SPANTYPE { + /* ... */ + MD_SPAN_EM, + + /* ... */ + MD_SPAN_STRONG, + + /* ... + * Detail: Structure MD_SPAN_A_DETAIL. */ + MD_SPAN_A, + + /* ... + * Detail: Structure MD_SPAN_IMG_DETAIL. + * Note: Image text can contain nested spans and even nested images. + * If rendered into ALT attribute of HTML tag, it's responsibility + * of the parser to deal with it. + */ + MD_SPAN_IMG, + + /* ... */ + MD_SPAN_CODE, + + /* ... + * Syntax: ++insert++ + * Note: Recognized only when MD_FLAG_INSERT is enabled. */ + MD_SPAN_INS, + + /* ... + * Note: Recognized only when MD_FLAG_STRIKETHROUGH is enabled. + */ + MD_SPAN_DEL, + + /* For recognizing inline ($) and display ($$) equations + * Note: Recognized only when MD_FLAG_LATEXMATHSPANS is enabled. + */ + MD_SPAN_LATEXMATH, + MD_SPAN_LATEXMATH_DISPLAY, + + /* Wiki links + * Note: Recognized only when MD_FLAG_WIKILINKS is enabled. + */ + MD_SPAN_WIKILINK, + + /* ... + * Note: Recognized only when MD_FLAG_UNDERLINE is enabled. */ + MD_SPAN_U, + + /* Spoiler (hidden content revealed on interaction). + * Syntax: ||hidden text|| + * Note: Recognized only when MD_FLAG_SPOILERS is enabled. */ + MD_SPAN_SPOILER, + + /* ... + * Syntax: ^superscript^ + * Note: Recognized only when MD_FLAG_SUPERSCRIPTS is enabled. */ + MD_SPAN_SUPERSCRIPT, + + /* ... + * Syntax: ~subscript~ + * Note: Recognized only when MD_FLAG_SUBSCRIPTS is enabled. */ + MD_SPAN_SUBSCRIPT, + + /* Footnote reference, e.g. [^1] or [^note]. + * Syntax: [^label] + * Note: Recognized only when MD_FLAG_FOOTNOTES is enabled. + * The span is self-contained: no MD_TEXT callbacks fire between enter and + * leave. All needed information is in MD_SPAN_FOOTNOTE_REF_DETAIL. */ + MD_SPAN_FOOTNOTE_REF, + + /* ... + * Syntax: ==highlight== + * Note: Recognized only when MD_FLAG_HIGHLIGHT is enabled. */ + MD_SPAN_MARK +} MD_SPANTYPE; + +/* Text is the actual textual contents of span. */ +typedef enum MD_TEXTTYPE { + /* Normal text. */ + MD_TEXT_NORMAL = 0, + + /* NULL character. CommonMark requires replacing NULL character with + * the replacement char U+FFFD, so this allows caller to do that easily. */ + MD_TEXT_NULLCHAR, + + /* Line breaks. + * Note these are not sent from blocks with verbatim output (MD_BLOCK_CODE + * or MD_BLOCK_HTML). In such cases, '\n' is part of the text itself. */ + MD_TEXT_BR, /*
    (hard break) */ + MD_TEXT_SOFTBR, /* '\n' in source text where it is not semantically meaningful (soft break) */ + + /* Entity. + * (a) Named entity, e.g.   + * (Note MD4C does not have a list of known entities. + * Anything matching the regexp /&[A-Za-z][A-Za-z0-9]{1,47};/ is + * treated as a named entity.) + * (b) Numerical entity, e.g. Ӓ + * (c) Hexadecimal entity, e.g. ካ + * + * As MD4C is mostly encoding agnostic, application gets the verbatim + * entity text into the MD_PARSER::text_callback(). */ + MD_TEXT_ENTITY, + + /* Text in a code block (inside MD_BLOCK_CODE) or inlined code (`code`). + * If it is inside MD_BLOCK_CODE, it includes spaces for indentation and + * '\n' for new lines. MD_TEXT_BR and MD_TEXT_SOFTBR are not sent for this + * kind of text. */ + MD_TEXT_CODE, + + /* Text is a raw HTML. If it is contents of a raw HTML block (i.e. not + * an inline raw HTML), then MD_TEXT_BR and MD_TEXT_SOFTBR are not used. + * The text contains verbatim '\n' for the new lines. */ + MD_TEXT_HTML, + + /* Text is inside an equation. This is processed the same way as inlined code + * spans (`code`). */ + MD_TEXT_LATEXMATH +} MD_TEXTTYPE; + +/* Alignment enumeration. */ +typedef enum MD_ALIGN { + MD_ALIGN_DEFAULT = 0, /* When unspecified. */ + MD_ALIGN_LEFT, + MD_ALIGN_CENTER, + MD_ALIGN_RIGHT +} MD_ALIGN; + +/* String attribute. + * + * This wraps strings which are outside of a normal text flow and which are + * propagated within various detailed structures, but which still may contain + * string portions of different types like e.g. entities. + * + * So, for example, lets consider this image: + * + * ![image alt text](http://example.org/image.png 'foo " bar') + * + * The image alt text is propagated as a normal text via the MD_PARSER::text() + * callback. However, the image title ('foo " bar') is propagated as + * MD_ATTRIBUTE in MD_SPAN_IMG_DETAIL::title. + * + * Then the attribute MD_SPAN_IMG_DETAIL::title shall provide the following: + * -- [0]: "foo " (substr_types[0] == MD_TEXT_NORMAL; substr_offsets[0] == 0) + * -- [1]: """ (substr_types[1] == MD_TEXT_ENTITY; substr_offsets[1] == 4) + * -- [2]: " bar" (substr_types[2] == MD_TEXT_NORMAL; substr_offsets[2] == 10) + * -- [3]: (n/a) (n/a ; substr_offsets[3] == 14) + * + * Note that these invariants are always guaranteed: + * -- substr_offsets[0] == 0 + * -- substr_offsets[LAST+1] == size + * -- Currently, only MD_TEXT_NORMAL, MD_TEXT_ENTITY, MD_TEXT_NULLCHAR + * substrings can appear. This could change only of the specification + * changes. + */ +typedef struct MD_ATTRIBUTE { + const MD_CHAR *text; + MD_SIZE size; + const MD_TEXTTYPE *substr_types; + const MD_OFFSET *substr_offsets; +} MD_ATTRIBUTE; + +/* Detailed info for MD_BLOCK_UL. */ +typedef struct MD_BLOCK_UL_DETAIL { + int is_tight; /* Non-zero if tight list, zero if loose. */ + MD_CHAR mark; /* Item bullet character in MarkDown source of the list, e.g. '-', '+', '*'. */ +} MD_BLOCK_UL_DETAIL; + +/* Detailed info for MD_BLOCK_OL. */ +typedef struct MD_BLOCK_OL_DETAIL { + unsigned start; /* Start index of the ordered list. */ + int is_tight; /* Non-zero if tight list, zero if loose. */ + MD_CHAR mark_delimiter; /* Character delimiting the item marks in MarkDown source, e.g. '.' or ')' */ +} MD_BLOCK_OL_DETAIL; + +/* Detailed info for MD_BLOCK_LI. */ +typedef struct MD_BLOCK_LI_DETAIL { + int is_task; /* Can be non-zero only with MD_FLAG_TASKLISTS */ + MD_CHAR task_mark; /* If is_task, then one of 'x', 'X' or ' '. Undefined otherwise. */ + MD_OFFSET task_mark_offset; /* If is_task, then offset in the input of the char between '[' and ']'. */ +} MD_BLOCK_LI_DETAIL; + +/* Detailed info for MD_BLOCK_H. */ +typedef struct MD_BLOCK_H_DETAIL { + unsigned level; /* Header level (1 - 6) */ +} MD_BLOCK_H_DETAIL; + +/* Detailed info for MD_BLOCK_CODE. */ +typedef struct MD_BLOCK_CODE_DETAIL { + MD_ATTRIBUTE info; + MD_ATTRIBUTE lang; + MD_CHAR fence_char; /* The character used for fenced code block; or zero for indented code block. */ +} MD_BLOCK_CODE_DETAIL; + +/* Detailed info for MD_BLOCK_TABLE. */ +typedef struct MD_BLOCK_TABLE_DETAIL { + unsigned col_count; /* Count of columns in the table. */ + unsigned head_row_count; /* Count of rows in the table header (currently always 1) */ + unsigned body_row_count; /* Count of rows in the table body */ +} MD_BLOCK_TABLE_DETAIL; + +/* Detailed info for MD_BLOCK_TH and MD_BLOCK_TD. */ +typedef struct MD_BLOCK_TD_DETAIL { + MD_ALIGN align; +} MD_BLOCK_TD_DETAIL; + +/* Detailed info for MD_BLOCK_ADMONITION. */ +typedef struct MD_BLOCK_ADMONITION_DETAIL { + MD_ATTRIBUTE type; /* One of "note", "tip", "important", "warning", "caution" */ +} MD_BLOCK_ADMONITION_DETAIL; + +/* Detailed info for MD_SPAN_A. */ +typedef struct MD_SPAN_A_DETAIL { + MD_ATTRIBUTE href; + MD_ATTRIBUTE title; + int is_autolink; /* nonzero if this is an autolink */ +} MD_SPAN_A_DETAIL; + +/* Detailed info for MD_SPAN_IMG. */ +typedef struct MD_SPAN_IMG_DETAIL { + MD_ATTRIBUTE src; + MD_ATTRIBUTE title; +} MD_SPAN_IMG_DETAIL; + +/* Detailed info for MD_SPAN_WIKILINK. */ +typedef struct MD_SPAN_WIKILINK { + MD_ATTRIBUTE target; +} MD_SPAN_WIKILINK_DETAIL; + +/* Detailed info for MD_SPAN_FOOTNOTE_REF. */ +typedef struct MD_SPAN_FOOTNOTE_REF_DETAIL { + unsigned int id; /* 1-based identifier of the referenced footnote */ + unsigned int ref_id; /* 1-based identifier of this reference among references to the same footnote */ + MD_ATTRIBUTE label; /* Raw label text, e.g. "1" or "note" */ +} MD_SPAN_FOOTNOTE_REF_DETAIL; + +/* Detailed info for MD_BLOCK_FOOTNOTE_DEF. */ +typedef struct MD_BLOCK_FOOTNOTE_DEF_DETAIL { + unsigned int id; /* 1-based identifier of this footnote */ + unsigned int ref_count; /* Number of references to this footnote */ + MD_ATTRIBUTE label; /* Raw label text */ +} MD_BLOCK_FOOTNOTE_DEF_DETAIL; + +/* Detailed info for MD_BLOCK_BLANK. */ +typedef struct MD_BLOCK_BLANK_DETAIL { + unsigned line_count; /* Count of blank lines forming the block separation */ +} MD_BLOCK_BLANK_DETAIL; + +/* Flags specifying extensions/deviations from CommonMark specification. + * + * By default (when MD_PARSER::flags == 0), we follow CommonMark specification. + * The following flags may allow some extensions or deviations from it. + */ +#define MD_FLAG_COLLAPSEWHITESPACE 0x1 /* In MD_TEXT_NORMAL, collapse non-trivial whitespace into single ' ' */ +#define MD_FLAG_PERMISSIVEATXHEADERS 0x2 /* Do not require space in ATX headers ( ###header ) */ +#define MD_FLAG_PERMISSIVEURLAUTOLINKS 0x4 /* Recognize URLs as autolinks even without '<', '>' */ +#define MD_FLAG_PERMISSIVEEMAILAUTOLINKS 0x8 /* Recognize e-mails as autolinks even without '<', '>' and 'mailto:' */ +#define MD_FLAG_NOINDENTEDCODEBLOCKS 0x10 /* Disable indented code blocks. (Only fenced code works.) */ +#define MD_FLAG_NOHTMLBLOCKS 0x20 /* Disable raw HTML blocks. */ +#define MD_FLAG_NOHTMLSPANS 0x40 /* Disable raw HTML (inline). */ +#define MD_FLAG_TABLES 0x100 /* Enable tables extension. */ +#define MD_FLAG_STRIKETHROUGH 0x200 /* Enable strikethrough extension. */ +#define MD_FLAG_PERMISSIVEWWWAUTOLINKS \ + 0x400 /* Enable WWW autolinks (even without any scheme prefix, if they begin with 'www.') */ +#define MD_FLAG_TASKLISTS 0x800 /* Enable task list extension. */ +#define MD_FLAG_LATEXMATHSPANS 0x1000 /* Enable $ and $$ containing LaTeX equations. */ +#define MD_FLAG_WIKILINKS 0x2000 /* Enable wiki links extension. */ +#define MD_FLAG_UNDERLINE 0x4000 /* Enable underline extension (and disables '_' for normal emphasis). */ +#define MD_FLAG_HARD_SOFT_BREAKS 0x8000 /* Force all soft breaks to act as hard breaks. */ +#define MD_FLAG_SPOILERS 0x10000 /* Enable ||hidden text|| spoiler spans. */ +#define MD_FLAG_SUPERSCRIPTS 0x20000 /* Enable ^superscript^ spans. */ +#define MD_FLAG_SUBSCRIPTS 0x40000 /* Enable ~subscript~ spans. */ +#define MD_FLAG_ADMONITIONS 0x80000 /* Enable admonitions extension. */ +#define MD_FLAG_FOOTNOTES 0x100000 /* Enable [^label] footnote references. */ +#define MD_FLAG_HIGHLIGHT 0x200000 /* Enable ==highlight== spans. */ +#define MD_FLAG_PRESERVEBLANKLINES 0x400000 /* Report blank line runs as MD_BLOCK_BLANK. */ +#define MD_FLAG_INSERT 0x800000 /* Enable insert extension. */ + +#define MD_FLAG_PERMISSIVEAUTOLINKS \ + (MD_FLAG_PERMISSIVEEMAILAUTOLINKS | MD_FLAG_PERMISSIVEURLAUTOLINKS | MD_FLAG_PERMISSIVEWWWAUTOLINKS) +#define MD_FLAG_NOHTML (MD_FLAG_NOHTMLBLOCKS | MD_FLAG_NOHTMLSPANS) + +/* Convenient sets of flags corresponding to well-known Markdown dialects. + * + * Note we may only support subset of features of the referred dialect. + * The constant just enables those extensions which bring us as close as + * possible given what features we implement. + * + * ABI compatibility note: Meaning of these can change in time as new + * extensions, bringing the dialect closer to the original, are implemented. + */ +#define MD_DIALECT_COMMONMARK 0 +#define MD_DIALECT_GITHUB \ + (MD_FLAG_PERMISSIVEAUTOLINKS | MD_FLAG_TABLES | MD_FLAG_STRIKETHROUGH | MD_FLAG_TASKLISTS | MD_FLAG_ADMONITIONS | \ + MD_FLAG_FOOTNOTES) + +/* Parser structure. + */ +typedef struct MD_PARSER { + /* Reserved. Set to zero. + */ + unsigned abi_version; + + /* Dialect options. Bitmask of MD_FLAG_xxxx values. + */ + unsigned flags; + + /* Caller-provided rendering callbacks. + * + * For some block/span types, more detailed information is provided in a + * type-specific structure pointed by the argument 'detail'. + * + * The last argument of all callbacks, 'userdata', is just propagated from + * md_parse() and is available for any use by the application. + * + * Note any strings provided to the callbacks as their arguments or as + * members of any detail structure are generally not zero-terminated. + * Application has to take the respective size information into account. + * + * Any rendering callback may abort further parsing of the document by + * returning non-zero. + */ + int (*enter_block)(MD_BLOCKTYPE /*type*/, void * /*detail*/, void * /*userdata*/); + int (*leave_block)(MD_BLOCKTYPE /*type*/, void * /*detail*/, void * /*userdata*/); + + int (*enter_span)(MD_SPANTYPE /*type*/, void * /*detail*/, void * /*userdata*/); + int (*leave_span)(MD_SPANTYPE /*type*/, void * /*detail*/, void * /*userdata*/); + + int (*text)(MD_TEXTTYPE /*type*/, const MD_CHAR * /*text*/, MD_SIZE /*size*/, void * /*userdata*/); + + /* Debug callback. Optional (may be NULL). + * + * If provided and something goes wrong, this function gets called. + * This is intended for debugging and problem diagnosis for developers; + * it is not intended to provide any errors suitable for displaying to an + * end user. + */ + void (*debug_log)(const char * /*msg*/, void * /*userdata*/); + + /* Reserved. Set to NULL. + */ + void (*syntax)(void); +} MD_PARSER; + +/* For backward compatibility. Do not use in new code. + */ +typedef MD_PARSER MD_RENDERER; + +/* Parse the Markdown document stored in the string 'text' of size 'size'. + * The parser provides callbacks to be called during the parsing so the + * caller can render the document on the screen or convert the Markdown + * to another format. + * + * Zero is returned on success. If a runtime error occurs (e.g. a memory + * fails), -1 is returned. If the processing is aborted due any callback + * returning non-zero, the return value of the callback is returned. + */ +int md_parse(const MD_CHAR *text, MD_SIZE size, const MD_PARSER *parser, void *userdata); + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* MD4C_H */ diff --git a/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.cpp b/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.cpp new file mode 100644 index 000000000000..c93aaf745c91 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.cpp @@ -0,0 +1,895 @@ +#include "MD4CParser.hpp" +#include "../md4c/md4c.h" +#include +#include +#include + +namespace Markdown { + +namespace { +struct HtmlTag { + std::string name; + std::unordered_map attributes; +}; +HtmlTag parseHtmlOpenTag(const std::string &html); +std::shared_ptr tryPromoteHtmlBlock(const std::string &html); +} // namespace + +class MD4CParser::Impl { +public: + std::shared_ptr root; + std::vector> nodeStack; + std::string currentText; + const char *inputText = nullptr; + bool inHtmlBlock = false; + std::string htmlBlockContent; + + static const std::string ATTR_LEVEL; + static const std::string ATTR_URL; + static const std::string ATTR_TITLE; + static const std::string ATTR_FENCE_CHAR; + static const std::string ATTR_LANGUAGE; + static const std::string ATTR_IS_TASK; + static const std::string ATTR_TASK_CHECKED; + static const std::string ATTR_START; + static const std::string ATTR_BLANK_LINE_COUNT; + static const std::string ATTR_ADMONITION_TYPE; + + void reset(size_t estimatedDepth) { + root = std::make_shared(NodeType::Document); + nodeStack.clear(); + // Reserve based on estimated depth, with reasonable bounds + // Typical markdown has 5-15 levels, but can go deeper with nested structures + // Cap at 128 to avoid excessive memory for extreme cases + nodeStack.reserve(std::min(estimatedDepth, static_cast(128))); + nodeStack.push_back(root); + currentText.clear(); + currentText.reserve(256); + inHtmlBlock = false; + htmlBlockContent.clear(); + } + + void flushText() { + if (!currentText.empty() && !nodeStack.empty()) { + auto textNode = std::make_shared(NodeType::Text); + textNode->content = std::move(currentText); + nodeStack.back()->addChild(std::move(textNode)); + currentText.clear(); + } + } + + void pushNode(std::shared_ptr node) { + flushText(); + if (node && !nodeStack.empty()) { + nodeStack.back()->addChild(node); + nodeStack.push_back(std::move(node)); + } + } + + void popNode() { + flushText(); + if (nodeStack.size() > 1) { + nodeStack.pop_back(); + } + } + + void addInlineNode(std::shared_ptr node) { + flushText(); + if (node && !nodeStack.empty()) { + nodeStack.back()->addChild(node); + } + } + + std::string getAttributeText(const MD_ATTRIBUTE *attr) { + if (!attr || attr->size == 0 || !attr->text) + return {}; + + // Use string constructor directly - let SSO handle small strings efficiently + // Empty return {} avoids allocating empty string object + return std::string(attr->text, attr->size); + } + + static int enterBlock(MD_BLOCKTYPE type, void *detail, void *userdata) { + if (!userdata) + return 1; + auto *impl = static_cast(userdata); + + switch (type) { + case MD_BLOCK_DOC: + // Document node already created in reset() + break; + + case MD_BLOCK_P: { + impl->pushNode(std::make_shared(NodeType::Paragraph)); + break; + } + + case MD_BLOCK_H: { + auto node = std::make_shared(NodeType::Heading); + if (detail) { + auto *h = static_cast(detail); + int level = static_cast(h->level); + // Clamp level to valid range (1-6) + level = (level < 1) ? 1 : (level > 6) ? 6 : level; + // Use char conversion for small integers (1-6) + // Avoids std::to_string() allocation overhead + char levelStr[2] = {static_cast('0' + level), '\0'}; + node->setAttribute(ATTR_LEVEL, levelStr); + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_QUOTE: { + impl->pushNode(std::make_shared(NodeType::Blockquote)); + break; + } + + case MD_BLOCK_ADMONITION: { + auto node = std::make_shared(NodeType::Admonition); + if (detail) { + auto *adm = static_cast(detail); + std::string admonitionType = impl->getAttributeText(&adm->type); + if (!admonitionType.empty()) { + node->setAttribute(ATTR_ADMONITION_TYPE, admonitionType); + } + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_UL: { + impl->pushNode(std::make_shared(NodeType::UnorderedList)); + break; + } + + case MD_BLOCK_OL: { + auto node = std::make_shared(NodeType::OrderedList); + if (detail) { + auto *ol = static_cast(detail); + if (ol->start != 1) { + node->setAttribute(ATTR_START, std::to_string(ol->start)); + } + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_LI: { + auto node = std::make_shared(NodeType::ListItem); + if (detail) { + auto *li = static_cast(detail); + if (li->is_task) { + node->setAttribute(ATTR_IS_TASK, "true"); + node->setAttribute(ATTR_TASK_CHECKED, (li->task_mark == 'x' || li->task_mark == 'X') ? "true" : "false"); + } + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_CODE: { + auto node = std::make_shared(NodeType::CodeBlock); + if (detail) { + auto *codeDetail = static_cast(detail); + // Extract fence character (if fenced code block) + if (codeDetail->fence_char != 0) { + char fenceStr[2] = {static_cast(codeDetail->fence_char), '\0'}; + node->setAttribute(ATTR_FENCE_CHAR, fenceStr); + } + // Extract language from lang attribute + std::string lang = impl->getAttributeText(&codeDetail->lang); + if (!lang.empty()) { + node->setAttribute(ATTR_LANGUAGE, lang); + } + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_HR: { + impl->pushNode(std::make_shared(NodeType::ThematicBreak)); + break; + } + + case MD_BLOCK_BLANK: { + auto node = std::make_shared(NodeType::BlankLine); + if (detail) { + auto *blankDetail = static_cast(detail); + node->setAttribute(ATTR_BLANK_LINE_COUNT, std::to_string(blankDetail->line_count)); + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_TABLE: { + auto node = std::make_shared(NodeType::Table); + if (detail) { + auto *tableDetail = static_cast(detail); + node->setAttribute("colCount", std::to_string(tableDetail->col_count)); + node->setAttribute("headRowCount", std::to_string(tableDetail->head_row_count)); + node->setAttribute("bodyRowCount", std::to_string(tableDetail->body_row_count)); + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_THEAD: { + impl->pushNode(std::make_shared(NodeType::TableHead)); + break; + } + + case MD_BLOCK_TBODY: { + impl->pushNode(std::make_shared(NodeType::TableBody)); + break; + } + + case MD_BLOCK_TR: { + impl->pushNode(std::make_shared(NodeType::TableRow)); + break; + } + + case MD_BLOCK_TH: + case MD_BLOCK_TD: { + auto node = + std::make_shared(type == MD_BLOCK_TH ? NodeType::TableHeaderCell : NodeType::TableCell); + if (detail) { + auto *tdDetail = static_cast(detail); + const char *alignStr; + switch (tdDetail->align) { + case MD_ALIGN_LEFT: + alignStr = "left"; + break; + case MD_ALIGN_CENTER: + alignStr = "center"; + break; + case MD_ALIGN_RIGHT: + alignStr = "right"; + break; + default: + alignStr = "default"; + break; + } + node->setAttribute("align", alignStr); + } + impl->pushNode(node); + break; + } + + case MD_BLOCK_HTML: { + impl->inHtmlBlock = true; + impl->htmlBlockContent.clear(); + break; + } + + default: + // Other block types not yet implemented + break; + } + + return 0; + } + + static int leaveBlock(MD_BLOCKTYPE type, void *detail, void *userdata) { + (void)detail; + if (!userdata) + return 1; + auto *impl = static_cast(userdata); + + if (type == MD_BLOCK_HTML) { + impl->inHtmlBlock = false; + auto node = tryPromoteHtmlBlock(impl->htmlBlockContent); + impl->htmlBlockContent.clear(); + if (node && !impl->nodeStack.empty()) { + impl->nodeStack.back()->addChild(std::move(node)); + } + return 0; + } + + if (type != MD_BLOCK_DOC && !impl->nodeStack.empty()) { + impl->popNode(); + } + + return 0; + } + + static int enterSpan(MD_SPANTYPE type, void *detail, void *userdata) { + if (!userdata) + return 1; + auto *impl = static_cast(userdata); + + switch (type) { + case MD_SPAN_A: { + auto node = std::make_shared(NodeType::Link); + if (detail) { + auto *linkDetail = static_cast(detail); + std::string url = impl->getAttributeText(&linkDetail->href); + if (!url.empty()) { + node->setAttribute(ATTR_URL, url); + } + const auto title = impl->getAttributeText(&linkDetail->title); + if (!title.empty()) { + node->setAttribute(ATTR_TITLE, title); + } + } + impl->pushNode(node); + break; + } + + case MD_SPAN_STRONG: { + impl->pushNode(std::make_shared(NodeType::Strong)); + break; + } + + case MD_SPAN_EM: { + impl->pushNode(std::make_shared(NodeType::Emphasis)); + break; + } + + case MD_SPAN_U: { + impl->pushNode(std::make_shared(NodeType::Underline)); + break; + } + + case MD_SPAN_CODE: { + impl->pushNode(std::make_shared(NodeType::Code)); + break; + } + + case MD_SPAN_DEL: { + impl->pushNode(std::make_shared(NodeType::Strikethrough)); + break; + } + + case MD_SPAN_IMG: { + auto node = std::make_shared(NodeType::Image); + if (detail) { + auto *imgDetail = static_cast(detail); + std::string url = impl->getAttributeText(&imgDetail->src); + if (!url.empty()) { + node->setAttribute(ATTR_URL, url); + } + std::string title = impl->getAttributeText(&imgDetail->title); + if (!title.empty()) { + node->setAttribute(ATTR_TITLE, title); + } + } + impl->pushNode(node); + break; + } + + case MD_SPAN_LATEXMATH: { + impl->pushNode(std::make_shared(NodeType::LatexMathInline)); + break; + } + + case MD_SPAN_LATEXMATH_DISPLAY: { + impl->pushNode(std::make_shared(NodeType::LatexMathDisplay)); + break; + } + + case MD_SPAN_SPOILER: { + impl->pushNode(std::make_shared(NodeType::Spoiler)); + break; + } + + case MD_SPAN_SUPERSCRIPT: { + impl->pushNode(std::make_shared(NodeType::Superscript)); + break; + } + + case MD_SPAN_SUBSCRIPT: { + impl->pushNode(std::make_shared(NodeType::Subscript)); + break; + } + + case MD_SPAN_MARK: { + impl->pushNode(std::make_shared(NodeType::Highlight)); + break; + } + + default: + break; + } + + return 0; + } + + static int leaveSpan(MD_SPANTYPE type, void *detail, void *userdata) { + (void)detail; + if (!userdata) + return 1; + auto *impl = static_cast(userdata); + + if (!impl->nodeStack.empty()) { + impl->popNode(); + } + + return 0; + } + + static int text(MD_TEXTTYPE type, const MD_CHAR *text, MD_SIZE size, void *userdata) { + if (!userdata || !text || size == 0) + return 0; + auto *impl = static_cast(userdata); + + if (type == MD_TEXT_SOFTBR) { + impl->addInlineNode(std::make_shared(NodeType::SoftBreak)); + return 0; + } + + if (type == MD_TEXT_BR) { + impl->addInlineNode(std::make_shared(NodeType::LineBreak)); + return 0; + } + + if (type == MD_TEXT_HTML) { + if (impl->inHtmlBlock) { + impl->htmlBlockContent.append(text, size); + } + return 0; + } + + // Handle text content (normal text, code text, LaTeX math, etc.) + if (type == MD_TEXT_NORMAL || type == MD_TEXT_CODE || type == MD_TEXT_LATEXMATH) { + impl->currentText.append(text, size); + } + + return 0; + } +}; + +namespace { + +HtmlTag parseHtmlOpenTag(const std::string &html) { + HtmlTag tag; + size_t pos = 0; + + while (pos < html.size() && std::isspace(static_cast(html[pos]))) + ++pos; + if (pos >= html.size() || html[pos] != '<') + return tag; + ++pos; + + if (pos < html.size() && html[pos] == '/') + return tag; + + while (pos < html.size() && std::isspace(static_cast(html[pos]))) + ++pos; + + size_t nameStart = pos; + while (pos < html.size() && !std::isspace(static_cast(html[pos])) && html[pos] != '>' && + html[pos] != '/') { + ++pos; + } + if (pos == nameStart) + return tag; + tag.name.reserve(pos - nameStart); + for (size_t i = nameStart; i < pos; ++i) + tag.name += static_cast(std::tolower(static_cast(html[i]))); + + while (pos < html.size()) { + while (pos < html.size() && std::isspace(static_cast(html[pos]))) + ++pos; + if (pos >= html.size() || html[pos] == '>' || html[pos] == '/') + break; + + size_t attrStart = pos; + while (pos < html.size() && html[pos] != '=' && !std::isspace(static_cast(html[pos])) && + html[pos] != '>' && html[pos] != '/') { + ++pos; + } + + if (pos == attrStart) { + ++pos; + continue; + } + + std::string attrName; + attrName.reserve(pos - attrStart); + for (size_t i = attrStart; i < pos; ++i) + attrName += static_cast(std::tolower(static_cast(html[i]))); + + while (pos < html.size() && std::isspace(static_cast(html[pos]))) + ++pos; + + if (pos < html.size() && html[pos] == '=') { + ++pos; + while (pos < html.size() && std::isspace(static_cast(html[pos]))) + ++pos; + + std::string attrValue; + if (pos < html.size() && (html[pos] == '"' || html[pos] == '\'')) { + char quote = html[pos++]; + size_t valueStart = pos; + while (pos < html.size() && html[pos] != quote) + ++pos; + attrValue = html.substr(valueStart, pos - valueStart); + if (pos < html.size()) + ++pos; + } else { + size_t valueStart = pos; + while (pos < html.size() && !std::isspace(static_cast(html[pos])) && html[pos] != '>' && + html[pos] != '/') { + ++pos; + } + attrValue = html.substr(valueStart, pos - valueStart); + } + tag.attributes[attrName] = attrValue; + } else { + tag.attributes[attrName] = ""; + } + } + + return tag; +} + +std::shared_ptr tryPromoteHtmlBlock(const std::string &html) { + auto tag = parseHtmlOpenTag(html); + if (tag.name.empty()) + return nullptr; + + if (tag.name == "video") { + auto srcIt = tag.attributes.find("src"); + if (srcIt == tag.attributes.end() || srcIt->second.empty()) { + return nullptr; + } + auto node = std::make_shared(NodeType::Video); + node->setAttribute("url", srcIt->second); + return node; + } + + return nullptr; +} + +using NodeList = std::vector>; + +bool isDisplayMathNode(const MarkdownASTNode &node) { + return node.type == NodeType::LatexMathDisplay; +} + +bool isSeparatorNode(const MarkdownASTNode &node) { + return node.type == NodeType::LineBreak || node.type == NodeType::SoftBreak || + (node.type == NodeType::Text && node.content.find_first_not_of(" \t\n\r") == std::string::npos); +} + +// A display-math node is "isolated" — i.e. block-level — when at least one of its +// neighbours is a boundary: the paragraph edge, or a separator (LineBreak / blank +// text). Display math flanked by real text on BOTH sides (e.g. `a $$x$$ b`) is +// genuinely inline and is left in place. +bool isIsolatedDisplayMath(const std::vector> &children, size_t i) { + if (!isDisplayMathNode(*children[i])) + return false; + bool leftBoundary = (i == 0) || isSeparatorNode(*children[i - 1]); + bool rightBoundary = (i + 1 >= children.size()) || isSeparatorNode(*children[i + 1]); + return leftBoundary || rightBoundary; +} + +// md4c parses $$...$$ as an inline span, so display math always lands nested inside a +// Paragraph — even when it sits on its own line, and even in the middle of a paragraph +// (text on lines before and after it, with no blank separator). +// +// This rebuilds such a paragraph into a sequence of top-level siblings so the rendering +// layer sees isolated display math as a block: each run of inline content becomes its own +// Paragraph, and each isolated display-math node becomes a bare LatexMathDisplay sibling. +// Separators bordering a promoted node are dropped. Returns an empty vector when the +// paragraph has no promotable display math, signalling the caller to leave it untouched. +// +// This subsumes the earlier trailing-only behaviour: pure (`$$x$$`), trailing +// (`text\n$$x$$`) and leading (`$$x$$\ntext`) are all just special cases of the general +// interior split. +std::vector> +splitParagraphAroundDisplayMath(const std::vector> &children) { + bool anyPromotion = false; + for (size_t i = 0; i < children.size(); ++i) { + if (isIsolatedDisplayMath(children, i)) { + anyPromotion = true; + break; + } + } + if (!anyPromotion) + return {}; + + std::vector> result; + std::vector> inlineRun; + + auto flushInlineRun = [&]() { + // Trim separators left dangling against the promoted math on either side. + size_t start = 0; + size_t end = inlineRun.size(); + while (start < end && isSeparatorNode(*inlineRun[start])) + ++start; + while (end > start && isSeparatorNode(*inlineRun[end - 1])) + --end; + if (start < end) { + auto paragraph = std::make_shared(NodeType::Paragraph); + paragraph->children.assign(inlineRun.begin() + static_cast(start), + inlineRun.begin() + static_cast(end)); + result.push_back(std::move(paragraph)); + } + inlineRun.clear(); + }; + + for (size_t i = 0; i < children.size(); ++i) { + if (isIsolatedDisplayMath(children, i)) { + flushInlineRun(); + result.push_back(children[i]); + } else { + inlineRun.push_back(children[i]); + } + } + flushInlineRun(); + + return result; +} + +// Walk the document's top-level children and promote isolated display math out of its +// parent Paragraph so the rendering layer sees it as a top-level block element. +void promoteDisplayMathFromParagraphs(MarkdownASTNode &root) { + auto &children = root.children; + + for (size_t i = 0; i < children.size();) { + auto ¶graph = children[i]; + if (paragraph->type != NodeType::Paragraph || paragraph->children.empty()) { + ++i; + continue; + } + + auto replacement = splitParagraphAroundDisplayMath(paragraph->children); + if (replacement.empty()) { + ++i; + continue; + } + + auto position = children.erase(children.begin() + static_cast(i)); + children.insert(position, replacement.begin(), replacement.end()); + i += replacement.size(); + } +} + +bool isBlockNode(const MarkdownASTNode &node) { + switch (node.type) { + case NodeType::Document: + case NodeType::Paragraph: + case NodeType::Heading: + case NodeType::Blockquote: + case NodeType::Admonition: + case NodeType::UnorderedList: + case NodeType::OrderedList: + case NodeType::ListItem: + case NodeType::CodeBlock: + case NodeType::ThematicBreak: + case NodeType::BlankLine: + case NodeType::LatexMathDisplay: + case NodeType::Table: + case NodeType::TableHead: + case NodeType::TableBody: + case NodeType::TableRow: + case NodeType::TableHeaderCell: + case NodeType::TableCell: + case NodeType::Video: + return true; + default: + return false; + } +} + +// md4c omits Paragraph wrappers around the inline content of tight list items. +// Wrap each run of consecutive inline children of a ListItem in a synthetic +// Paragraph (marked "tight") so renderers only ever see block children. +void wrapListItemInlineRuns(MarkdownASTNode &node) { + for (auto &child : node.children) { + wrapListItemInlineRuns(*child); + } + + if (node.type != NodeType::ListItem) + return; + + bool hasInlineChild = false; + for (auto &child : node.children) { + if (!isBlockNode(*child)) { + hasInlineChild = true; + break; + } + } + if (!hasInlineChild) + return; + + std::vector> newChildren; + newChildren.reserve(node.children.size()); + std::vector> run; + + auto flushRun = [&]() { + if (run.empty()) + return; + bool hasContent = false; + for (auto &n : run) { + if (!isSeparatorNode(*n)) { + hasContent = true; + break; + } + } + if (hasContent) { + auto paragraph = std::make_shared(NodeType::Paragraph); + paragraph->setAttribute("tight", "true"); + paragraph->children = std::move(run); + newChildren.push_back(std::move(paragraph)); + } else { + // Whitespace-only run between blocks — keep as-is, a paragraph would add spacing. + for (auto &n : run) { + newChildren.push_back(std::move(n)); + } + } + run.clear(); + }; + + for (auto &child : node.children) { + if (isBlockNode(*child)) { + flushRun(); + newChildren.push_back(std::move(child)); + } else { + run.push_back(std::move(child)); + } + } + flushRun(); + node.children = std::move(newChildren); +} + +bool isVideoOnlyListItem(const MarkdownASTNode &item) { + return item.type == NodeType::ListItem && item.children.size() == 1 && item.children[0]->type == NodeType::Video; +} + +void promoteVideosFromListItems(MarkdownASTNode &node) { + for (auto &child : node.children) { + if (child->type == NodeType::Blockquote || child->type == NodeType::Admonition) { + promoteVideosFromListItems(*child); + } + } + + auto &children = node.children; + for (size_t i = 0; i < children.size();) { + auto &list = children[i]; + if (list->type != NodeType::UnorderedList && list->type != NodeType::OrderedList) { + ++i; + continue; + } + + bool hasVideoItem = false; + for (auto &item : list->children) { + if (isVideoOnlyListItem(*item)) { + hasVideoItem = true; + break; + } + } + if (!hasVideoItem) { + ++i; + continue; + } + + std::vector> replacement; + std::vector> currentItems; + NodeType listType = list->type; + + for (auto &item : list->children) { + if (isVideoOnlyListItem(*item)) { + if (!currentItems.empty()) { + auto sublist = std::make_shared(listType); + sublist->children = std::move(currentItems); + currentItems.clear(); + replacement.push_back(std::move(sublist)); + } + replacement.push_back(item->children[0]); + } else { + currentItems.push_back(std::move(item)); + } + } + + if (!currentItems.empty()) { + auto sublist = std::make_shared(listType); + sublist->children = std::move(currentItems); + replacement.push_back(std::move(sublist)); + } + + auto position = children.erase(children.begin() + static_cast(i)); + children.insert(position, replacement.begin(), replacement.end()); + i += replacement.size(); + } +} + +} // anonymous namespace + +MD4CParser::MD4CParser() : impl_(std::make_unique()) {} + +MD4CParser::~MD4CParser() = default; + +std::shared_ptr MD4CParser::parse(const std::string &markdown, const Md4cFlags &md4cFlags, + bool isGFM) { + if (markdown.empty()) { + return std::make_shared(NodeType::Document); + } + + // Estimate stack depth based on markdown size + // Heuristic: ~1 nesting level per 500-1000 characters for typical markdown + // This is a rough estimate - actual depth depends on structure, not just size + // Base depth of 12 covers typical nested structures (blockquotes, future lists) + size_t estimatedDepth = 12; // Base depth for small documents + if (markdown.size() > 1000) { + // Scale up for larger documents, but cap the growth + estimatedDepth = std::min(static_cast(12 + (markdown.size() / 1000)), static_cast(64)); + } + + impl_->reset(estimatedDepth); + impl_->inputText = markdown.c_str(); + + unsigned flags = MD_FLAG_NOHTMLSPANS | MD_FLAG_SPOILERS; + if (isGFM) { + flags |= MD_FLAG_TABLES | MD_FLAG_STRIKETHROUGH | MD_FLAG_TASKLISTS; + } + if (md4cFlags.permissiveAutolinks) { + flags |= MD_FLAG_PERMISSIVEAUTOLINKS; + } + if (md4cFlags.latexMath) { + flags |= MD_FLAG_LATEXMATHSPANS; + } + if (md4cFlags.underline) { + flags |= MD_FLAG_UNDERLINE; + } + if (md4cFlags.superscript) { + flags |= MD_FLAG_SUPERSCRIPTS; + } + if (md4cFlags.subscript) { + flags |= MD_FLAG_SUBSCRIPTS; + } + if (md4cFlags.highlight) { + flags |= MD_FLAG_HIGHLIGHT; + } + if (md4cFlags.hardSoftBreaks) { + flags |= MD_FLAG_HARD_SOFT_BREAKS; + } + if (md4cFlags.preserveBlankLines) { + flags |= MD_FLAG_PRESERVEBLANKLINES; + } + if (md4cFlags.admonitions) { + flags |= MD_FLAG_ADMONITIONS; + } + + // Configure MD4C parser with callbacks + MD_PARSER parser = { + 0, // abi_version + flags, &Impl::enterBlock, &Impl::leaveBlock, &Impl::enterSpan, &Impl::leaveSpan, &Impl::text, + nullptr, // debug_log + nullptr // syntax + }; + + // Parse the markdown + int result = md_parse(markdown.c_str(), static_cast(markdown.size()), &parser, impl_.get()); + + if (result != 0) { + // Parsing failed, return empty document + return std::make_shared(NodeType::Document); + } + + impl_->flushText(); + + if (impl_->root) { + promoteDisplayMathFromParagraphs(*impl_->root); + wrapListItemInlineRuns(*impl_->root); + promoteVideosFromListItems(*impl_->root); + } + + return impl_->root ? impl_->root : std::make_shared(NodeType::Document); +} + +// Static member definitions +const std::string MD4CParser::Impl::ATTR_LEVEL = "level"; +const std::string MD4CParser::Impl::ATTR_URL = "url"; +const std::string MD4CParser::Impl::ATTR_TITLE = "title"; +const std::string MD4CParser::Impl::ATTR_FENCE_CHAR = "fenceChar"; +const std::string MD4CParser::Impl::ATTR_LANGUAGE = "language"; +const std::string MD4CParser::Impl::ATTR_IS_TASK = "isTask"; +const std::string MD4CParser::Impl::ATTR_TASK_CHECKED = "taskChecked"; +const std::string MD4CParser::Impl::ATTR_START = "start"; +const std::string MD4CParser::Impl::ATTR_BLANK_LINE_COUNT = "count"; +const std::string MD4CParser::Impl::ATTR_ADMONITION_TYPE = "admonitionType"; + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.hpp b/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.hpp new file mode 100644 index 000000000000..10f1afbf0be6 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/parser/MD4CParser.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "MarkdownASTNode.hpp" +#include +#include + +namespace Markdown { + +struct Md4cFlags { + bool underline = false; + bool latexMath = true; + bool superscript = false; + bool subscript = false; + bool highlight = false; + bool permissiveAutolinks = true; + bool hardSoftBreaks = false; + bool preserveBlankLines = false; + bool admonitions = true; +}; + +class MD4CParser { +public: + MD4CParser(); + ~MD4CParser(); + + // Parse markdown string and return AST root node + std::shared_ptr parse( + const std::string& markdown, + const Md4cFlags& flags = Md4cFlags{}, + bool isGFM = true); + +private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/parser/MarkdownASTNode.hpp b/packages/react-native-enriched-markdown/cpp/parser/MarkdownASTNode.hpp new file mode 100644 index 000000000000..bf8edfbc7176 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/parser/MarkdownASTNode.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include + +namespace Markdown { + +enum class NodeType { + Document, + Paragraph, + Text, + Link, + Heading, + LineBreak, + Strong, + Emphasis, + Strikethrough, + Underline, + Code, + Image, + Blockquote, + UnorderedList, + OrderedList, + ListItem, + CodeBlock, + ThematicBreak, + Table, + TableHead, + TableBody, + TableRow, + TableHeaderCell, + TableCell, + LatexMathInline, + LatexMathDisplay, + Spoiler, + Superscript, + Subscript, + Highlight, + SoftBreak, + BlankLine, + Admonition, + Video +}; + +struct MarkdownASTNode { + NodeType type; + std::string content; + std::unordered_map attributes; + std::vector> children; + + explicit MarkdownASTNode(NodeType t) : type(t) {} + + void addChild(std::shared_ptr child) { + if (child) { + children.push_back(std::move(child)); + } + } + + void setAttribute(const std::string& key, const std::string& value) { + attributes[key] = value; + } +}; + +} // namespace Markdown + diff --git a/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.cpp b/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.cpp new file mode 100644 index 000000000000..6f3d92391d7d --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.cpp @@ -0,0 +1,175 @@ +#include "TextLinkRecognizer.hpp" + +#include +#include +#include +#include + +namespace Markdown { + +namespace { + +using NodePtr = std::shared_ptr; +using NodeList = std::vector; + +bool isOpaque(NodeType type) { + switch (type) { + case NodeType::Link: + case NodeType::CodeBlock: + case NodeType::Image: + case NodeType::Video: + case NodeType::LatexMathInline: + case NodeType::LatexMathDisplay: + return true; + default: + return false; + } +} + +NodePtr makeLink(NodePtr child, const std::string& url) { + auto link = std::make_shared(NodeType::Link); + link->setAttribute("url", url); + link->setAttribute("recognizedLink", "true"); + link->addChild(std::move(child)); + return link; +} + +NodePtr textSlice(const MarkdownASTNode& source, std::string content) { + auto text = std::make_shared(NodeType::Text); + text->content = std::move(content); + text->attributes = source.attributes; + return text; +} + +// Byte offset of each UTF-16 code unit boundary in a UTF-8 string, plus the end. +std::vector utf16BoundariesToBytes(const std::string& text) { + std::vector bytes; + bytes.reserve(text.size() + 1); + size_t i = 0; + while (i < text.size()) { + unsigned char lead = static_cast(text[i]); + size_t length = lead < 0x80 ? 1 : lead < 0xE0 ? 2 : lead < 0xF0 ? 3 : 4; + if (i + length > text.size()) length = text.size() - i; + bytes.push_back(i); + if (length == 4) bytes.push_back(i); // surrogate pair: two units, one start + i += length; + } + bytes.push_back(text.size()); + return bytes; +} + +struct Candidate { + MarkdownASTNode* parent; + size_t index; +}; + +void collect(MarkdownASTNode& node, bool wantText, bool wantCode, std::vector& texts, + std::vector& codes) { + for (size_t i = 0; i < node.children.size(); i++) { + MarkdownASTNode& child = *node.children[i]; + if (isOpaque(child.type)) continue; + if (child.type == NodeType::Text) { + if (wantText && !child.content.empty()) texts.push_back({&node, i}); + } else if (child.type == NodeType::Code) { + if (wantCode) codes.push_back({&node, i}); + } else { + collect(child, wantText, wantCode, texts, codes); + } + } +} + +std::string codeContent(const MarkdownASTNode& code) { + std::string content; + for (const auto& child : code.children) content += child->content; + return content; +} + +using Replacements = std::unordered_map; + +void splitText(const NodePtr& textNode, const std::vector& ranges, Replacements& out) { + const std::string& content = textNode->content; + std::vector bytes = utf16BoundariesToBytes(content); + NodeList pieces; + size_t offset = 0; + for (const TextRange& range : ranges) { + if (range.end <= range.start || range.end >= bytes.size()) continue; + size_t start = bytes[range.start]; + size_t end = bytes[range.end]; + if (start < offset || end <= start) continue; + if (start > offset) pieces.push_back(textSlice(*textNode, content.substr(offset, start - offset))); + std::string matched = content.substr(start, end - start); + pieces.push_back(makeLink(textSlice(*textNode, matched), matched)); + offset = end; + } + if (offset == 0) return; + if (offset < content.size()) pieces.push_back(textSlice(*textNode, content.substr(offset))); + out[textNode.get()] = std::move(pieces); +} + +void applyReplacements(MarkdownASTNode& node, const Replacements& replacements) { + bool changed = false; + for (const auto& child : node.children) { + if (replacements.count(child.get())) { + changed = true; + break; + } + } + if (changed) { + NodeList children; + children.reserve(node.children.size()); + for (const auto& child : node.children) { + auto it = replacements.find(child.get()); + if (it == replacements.end()) { + children.push_back(child); + } else { + children.insert(children.end(), it->second.begin(), it->second.end()); + } + } + node.children = std::move(children); + } + for (const auto& child : node.children) { + if (!isOpaque(child->type)) applyReplacements(*child, replacements); + } +} + +} // namespace + +void recognizeTextLinks(MarkdownASTNode& root, const TextLinkMatchers& matchers) { + const bool wantText = static_cast(matchers.text); + const bool wantCode = static_cast(matchers.inlineCode); + if (!wantText && !wantCode) return; + + std::vector texts; + std::vector codes; + collect(root, wantText, wantCode, texts, codes); + if (texts.empty() && codes.empty()) return; + + Replacements replacements; + + if (!texts.empty()) { + std::vector runs; + runs.reserve(texts.size()); + for (const Candidate& c : texts) runs.emplace_back(c.parent->children[c.index]->content); + std::vector> matches = matchers.text(runs); + for (size_t i = 0; i < texts.size() && i < matches.size(); i++) { + if (!matches[i].empty()) splitText(texts[i].parent->children[texts[i].index], matches[i], replacements); + } + } + + if (!codes.empty()) { + std::vector contents; + contents.reserve(codes.size()); + for (const Candidate& c : codes) contents.push_back(codeContent(*c.parent->children[c.index])); + std::vector spans(contents.begin(), contents.end()); + std::vector matched = matchers.inlineCode(spans); + for (size_t i = 0; i < codes.size() && i < matched.size(); i++) { + if (!matched[i] || contents[i].empty()) continue; + const NodePtr& code = codes[i].parent->children[codes[i].index]; + replacements[code.get()] = NodeList{makeLink(code, contents[i])}; + } + } + + if (!replacements.empty()) applyReplacements(root, replacements); +} + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.hpp b/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.hpp new file mode 100644 index 000000000000..e426affd6d5e --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/parser/TextLinkRecognizer.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include "MarkdownASTNode.hpp" +#include +#include +#include +#include +#include + +namespace Markdown { + +// Offsets are UTF-16 code units, as every host regex engine reports them. +struct TextRange { + size_t start; + size_t end; +}; + +// Host-provided matching, one call per kind per parse. A null function is off. +struct TextLinkMatchers { + // Non-overlapping matches per run, in order. + std::function>(const std::vector& runs)> text; + std::function(const std::vector& spans)> inlineCode; +}; + +// In place. Existing links, code blocks, media and math are not entered. +void recognizeTextLinks(MarkdownASTNode& root, const TextLinkMatchers& matchers); + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.cpp b/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.cpp new file mode 100644 index 000000000000..9cd5d76471f4 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.cpp @@ -0,0 +1,166 @@ +#include "ASTSerializer.hpp" +#include +#include + +namespace Markdown { + +static const char *nodeTypeToString(NodeType type) { + switch (type) { + case NodeType::Document: + return "Document"; + case NodeType::Paragraph: + return "Paragraph"; + case NodeType::Text: + return "Text"; + case NodeType::Link: + return "Link"; + case NodeType::Heading: + return "Heading"; + case NodeType::LineBreak: + return "LineBreak"; + case NodeType::SoftBreak: + return "SoftBreak"; + case NodeType::Strong: + return "Strong"; + case NodeType::Emphasis: + return "Emphasis"; + case NodeType::Strikethrough: + return "Strikethrough"; + case NodeType::Underline: + return "Underline"; + case NodeType::Code: + return "Code"; + case NodeType::Image: + return "Image"; + case NodeType::Blockquote: + return "Blockquote"; + case NodeType::UnorderedList: + return "UnorderedList"; + case NodeType::OrderedList: + return "OrderedList"; + case NodeType::ListItem: + return "ListItem"; + case NodeType::CodeBlock: + return "CodeBlock"; + case NodeType::ThematicBreak: + return "ThematicBreak"; + case NodeType::Table: + return "Table"; + case NodeType::TableHead: + return "TableHead"; + case NodeType::TableBody: + return "TableBody"; + case NodeType::TableRow: + return "TableRow"; + case NodeType::TableHeaderCell: + return "TableHeaderCell"; + case NodeType::TableCell: + return "TableCell"; + case NodeType::LatexMathInline: + return "LatexMathInline"; + case NodeType::LatexMathDisplay: + return "LatexMathDisplay"; + case NodeType::Spoiler: + return "Spoiler"; + case NodeType::Superscript: + return "Superscript"; + case NodeType::Subscript: + return "Subscript"; + case NodeType::Highlight: + return "Highlight"; + case NodeType::BlankLine: + return "BlankLine"; + case NodeType::Admonition: + return "Admonition"; + case NodeType::Video: + return "Video"; + default: + assert(false && "unhandled NodeType in nodeTypeToString"); + return ""; + } +} + +void ASTSerializer::appendEscaped(const std::string &str, std::string &out) { + out += '"'; + for (unsigned char c : str) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + default: + if (c < 0x20) { + char buf[7]; + std::snprintf(buf, sizeof(buf), "\\u%04x", c); + out += buf; + } else { + out += static_cast(c); + } + break; + } + } + out += '"'; +} + +void ASTSerializer::serializeNode(const MarkdownASTNode &node, std::string &out) { + out += "{\"type\":\""; + out += nodeTypeToString(node.type); + out += '"'; + + if (!node.content.empty()) { + out += ",\"content\":"; + appendEscaped(node.content, out); + } + + if (!node.attributes.empty()) { + out += ",\"attributes\":{"; + bool first = true; + for (const auto &kv : node.attributes) { + if (!first) + out += ','; + first = false; + appendEscaped(kv.first, out); + out += ':'; + appendEscaped(kv.second, out); + } + out += '}'; + } + + if (!node.children.empty()) { + out += ",\"children\":["; + for (size_t i = 0; i < node.children.size(); ++i) { + if (i > 0) + out += ','; + serializeNode(*node.children[i], out); + } + out += ']'; + } + + out += '}'; +} + +std::string ASTSerializer::serialize(const MarkdownASTNode &node) { + std::string out; + out.reserve(1024); + serializeNode(node, out); + return out; +} + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.hpp b/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.hpp new file mode 100644 index 000000000000..99c4dbae7c0e --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/wasm/ASTSerializer.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "../parser/MarkdownASTNode.hpp" +#include + +namespace Markdown { + +class ASTSerializer { +public: + static std::string serialize(const MarkdownASTNode &node); + +private: + static void serializeNode(const MarkdownASTNode &node, std::string &out); + static void appendEscaped(const std::string &str, std::string &out); +}; + +} // namespace Markdown diff --git a/packages/react-native-enriched-markdown/cpp/wasm/build.sh b/packages/react-native-enriched-markdown/cpp/wasm/build.sh new file mode 100755 index 000000000000..45e38440dce3 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/wasm/build.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Compile md4c + the WASM wrapper to a single self-contained JS file. +# +# Prerequisites: +# brew install emscripten # macOS +# # or follow https://emscripten.org/docs/getting_started/downloads.html +# +# Usage: +# bash packages/core/cpp/wasm/build.sh +# +# Output: +# packages/react-native-enriched-markdown/src/web/wasm/md4c.js +# +# NOTE: the committed md4c.js is an artifact, and the docs describe what the +# *committed* one can do - not what this source can. It was last rebuilt before +# the Video node type was added, so the shipped parser emits no `Video` node and +# three doc pages correctly say video does not render on web: +# docs/docs/introduction/supported-features.md (Videos | Web | No) +# docs/docs/react-native/guides/web-support.md ("Not supported on web") +# docs/docs/react-native/api-reference/element-structure.md (the video caution) +# A VideoRenderer, `videoStyle` and the 'Video' type already exist under +# src/web/, so the day this script is run those three pages flip to wrong at +# once. Update them in the same commit as the rebuilt artifact. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CPP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)" +OUT_DIR="${OUT_DIR:-$REPO_ROOT/packages/react-native-enriched-markdown/src/web/wasm}" + +mkdir -p "$OUT_DIR" + +echo "Building md4c WASM…" + +# Compile the C file separately (no -std=c++17) +emcc \ + -I "$CPP_ROOT" \ + -O2 \ + -c "$CPP_ROOT/md4c/md4c.c" \ + -o "$OUT_DIR/md4c.o" + +# Compile C++ sources and link everything together +emcc \ + "$SCRIPT_DIR/md4c_wasm.cpp" \ + "$SCRIPT_DIR/ASTSerializer.cpp" \ + "$CPP_ROOT/parser/MD4CParser.cpp" \ + "$OUT_DIR/md4c.o" \ + -I "$CPP_ROOT" \ + -I "$SCRIPT_DIR" \ + -O2 \ + -std=c++17 \ + -Wswitch \ + -s WASM=1 \ + -s SINGLE_FILE=1 \ + -s EXPORTED_FUNCTIONS='["_parseMarkdown"]' \ + -s EXPORTED_RUNTIME_METHODS='["ccall","cwrap","UTF8ToString"]' \ + -s ENVIRONMENT='web' \ + -s MODULARIZE=1 \ + -s EXPORT_NAME='createMd4cModule' \ + -s STACK_SIZE=8MB \ + -s INITIAL_MEMORY=16MB \ + -s MAXIMUM_MEMORY=512MB \ + -s ALLOW_MEMORY_GROWTH=1 \ + -s GROWABLE_ARRAYBUFFERS=0 \ + -o "$OUT_DIR/md4c.js" + +rm "$OUT_DIR/md4c.o" + +echo "Done → $OUT_DIR/md4c.js" diff --git a/packages/react-native-enriched-markdown/cpp/wasm/md4c_wasm.cpp b/packages/react-native-enriched-markdown/cpp/wasm/md4c_wasm.cpp new file mode 100644 index 000000000000..f8ca3c3420f3 --- /dev/null +++ b/packages/react-native-enriched-markdown/cpp/wasm/md4c_wasm.cpp @@ -0,0 +1,49 @@ +#include "../parser/MD4CParser.hpp" +#include "ASTSerializer.hpp" +#include + +// Static buffer for the JSON result. +// Safe for single-threaded WASM execution — the caller must consume (copy) +// the returned string before calling parseMarkdown again. +static std::string g_resultBuffer; + +extern "C" { + +/** + * Parse a markdown string and return its AST as a JSON string. + * + * @param markdown Null-terminated UTF-8 markdown input. + * @param underline 1 → enable __ underline extension; 0 → __ means emphasis. + * @param latexMath 1 → enable $…$ / $$…$$ LaTeX math spans; 0 → disable. + * @param superscript 1 → enable ^superscript^ spans; 0 → disable. + * @param subscript 1 → enable ~subscript~ spans; 0 → disable. + * @param highlight 1 → enable ==highlight== spans; 0 → disable. + * @param hardSoftBreaks 1 → treat soft breaks as hard breaks; 0 → collapse to space. + * @param preserveBlankLines 1 → report runs of blank lines as BlankLine nodes; 0 → collapse them. + * @param admonitions 1 → enable GitHub-style admonitions/alerts; 0 → disable. + * @return Null-terminated UTF-8 JSON string, valid until the next call. + */ +const char *parseMarkdown(const char *markdown, int underline, int latexMath, int superscript, int subscript, + int highlight, int hardSoftBreaks, int preserveBlankLines, int admonitions) { + if (!markdown) { + g_resultBuffer = "{\"type\":\"Document\"}"; + return g_resultBuffer.c_str(); + } + + Markdown::Md4cFlags flags; + flags.underline = (underline != 0); + flags.latexMath = (latexMath != 0); + flags.superscript = (superscript != 0); + flags.subscript = (subscript != 0); + flags.highlight = (highlight != 0); + flags.hardSoftBreaks = (hardSoftBreaks != 0); + flags.preserveBlankLines = (preserveBlankLines != 0); + flags.admonitions = (admonitions != 0); + + Markdown::MD4CParser parser; + auto root = parser.parse(std::string(markdown), flags); + g_resultBuffer = Markdown::ASTSerializer::serialize(*root); + return g_resultBuffer.c_str(); +} + +} // extern "C" diff --git a/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.h b/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.h new file mode 100644 index 000000000000..99ea444f3f86 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.h @@ -0,0 +1,27 @@ +#import "ENRMUIKit.h" +#import "StyleConfig.h" +#import + +#ifndef EnrichedMarkdownNativeComponent_h +#define EnrichedMarkdownNativeComponent_h + +NS_ASSUME_NONNULL_BEGIN + +@interface EnrichedMarkdown : RCTViewComponentView +@property (nonatomic, strong) StyleConfig *config; +- (CGSize)measureSize:(CGFloat)maxWidth; +- (void)renderMarkdownSynchronously:(NSString *)markdownString; +- (BOOL)hasRenderedMarkdown:(NSString *)markdown; +- (BOOL)hasRenderedWithStyleFingerprint:(size_t)fingerprint; + +/// Size last committed by Fabric via `updateLayoutMetrics:`, readable from +/// any thread without blocking (issue #550: the shadow-node measure path must +/// never wait on the main thread, and reading `bounds` off-main is unsafe). +/// Backed by a single lock-free atomic, so the pair can't tear. Returns +/// CGSizeZero until the first layout is committed. +- (CGSize)lastCommittedLayoutSize; +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.mm b/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.mm new file mode 100644 index 000000000000..be7b30aa55c4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/EnrichedMarkdown.mm @@ -0,0 +1,1691 @@ +#import "EnrichedMarkdown.h" +#import "ContextMenuUtils.h" +#import "ENRMAccessibilityLabels.h" +#import "ENRMAsyncRenderCoordinator.h" +#import "ENRMAtomicSize.h" +#import "ENRMImageAttachment.h" +#import "ENRMLatexErrorCoordinator.h" +#import "ENRMLinkContextMenus.h" +#import "ENRMLinkRegexProps.h" +#import "ENRMMarkdownParser.h" +#import "ENRMTailFadeInAnimator.h" +#import "ENRMTextInteractionUtils.h" +#import "ENRMTextRenderer.h" +#import "ENRMTextViewSetup.h" +#import "ENRMUIKit.h" +#import "EditMenuUtils.h" +#import "ImageRequestHeaderUtils.h" +#import "LinkContextMenuUtils.h" +#import "LinkPillContentUtils.h" + +#import "ENRMFeatureFlags.h" + +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathContainerView.h" +#endif +#if ENRICHED_MARKDOWN_VIDEO +#import "ENRMVideoContainerView.h" +#endif +#import "ENRMBlockquoteContainerView.h" +#import "ENRMCodeBlockContainerView.h" +#import "ENRMDynamicBlockProps.h" +#import "ENRMSpoilerCapable.h" +#import "ENRMSpoilerOverlayView.h" +#import "ENRMSpoilerTapUtils.h" +#import "EnrichedMarkdownInternalText.h" +#import "FontScaleObserver.h" +#import "FontUtils.h" +#import "HeightUpdateUtils.h" +#import "LastElementUtils.h" +#import "LinkTapUtils.h" +#import "MarkdownASTNode.h" +#import "MarkdownAccessibilityElementBuilder.h" +#import "MarkdownExtractor.h" +#import "MeasurementCache.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RenderedMarkdownSegment.h" +#import "RuntimeKeys.h" +#import "SegmentReconciler.h" +#import "SegmentRenderer.h" +#import "SegmentViewRegistry.h" +#import "SelectionColorUtils.h" +#import "StreamingMarkdownFilter.h" +#import "StyleConfig.h" +#import "StylePropsUtils.h" +#import "TableContainerView.h" +#import "TaskListTapUtils.h" +#import "TextViewLayoutManager.h" +#import +#import + +#import +#import +#import +#import + +#import "RCTFabricComponentsPlugins.h" +#import +#import +#import + +using namespace facebook::react; + +typedef NS_OPTIONS(NSUInteger, ENRMDirtyFlags) { + ENRMDirtyNone = 0, + ENRMDirtyRecreateSegments = 1 << 0, + ENRMDirtyForceHeight = 1 << 1, + ENRMDirtyRender = 1 << 2, +}; + +static char kENRMSegmentFadeAnimatorKey; + +@interface EnrichedMarkdown () ++ (ENRMMd4cFlags *)flagsFromProps:(const EnrichedMarkdownMd4cFlagsStruct &)props; +- (void)emitLinkPress:(NSString *)url sourceType:(NSString *)sourceType; +- (void)emitLinkLongPress:(NSString *)url; +- (void)emitLinkContextMenuItemPress:(NSString *)itemText pattern:(NSString *)pattern url:(NSString *)url; +- (void)emitImagePress:(NSString *)url altText:(NSString *)altText; +- (void)emitTaskListItemPress:(NSInteger)index checked:(BOOL)checked text:(NSString *)text; +- (void)emitCopyPress:(NSString *)code language:(NSString *)language; +- (void)emitCodeBlockPress:(NSString *)code language:(NSString *)language; +- (void)emitContextMenuItemPress:(NSString *)itemText + selectedText:(NSString *)selectedText + selectionStart:(NSUInteger)selectionStart + selectionEnd:(NSUInteger)selectionEnd; +@end + +#if !TARGET_OS_OSX +@interface EnrichedMarkdown () +@end +#endif + +@implementation EnrichedMarkdown { + ENRMMarkdownParser *_parser; + StyleConfig *_config; + ENRMMd4cFlags *_md4cFlags; + BOOL _isGFM; + ENRMLinkRegexConfig *_linkRegex; + ENRMLinkRegexConfig *_inlineCodeLinkRegex; + NSString *_cachedMarkdown; + NSString *_renderedMarkdown; + ENRMLatexErrorCoordinator *_latexErrorCoordinator; + NSMutableArray *_segmentViews; + NSMutableArray *_segmentSignatures; + ENRMSegmentViewRegistry *_segmentViewRegistry; + ENRMDirtyFlags _dirtyFlags; + + ENRMAsyncRenderCoordinator *_renderCoordinator; + + EnrichedMarkdownShadowNode::ConcreteState::Shared _state; + int _heightUpdateCounter; + + FontScaleObserver *_fontScaleObserver; + CGFloat _maxFontSizeMultiplier; + + BOOL _allowTrailingMargin; + BOOL _selectable; + BOOL _enableLinkPreview; + BOOL _enableTaskListItemToggle; + BOOL _enableImagePress; + BOOL _streamingAnimation; + ENRMTableStreamingMode _tableStreamingMode; + ENRMCodeBlockStreamingMode _codeBlockStreamingMode; + // Trailing code block whose closing fence hasn't streamed in yet, if any. + ENRMCodeBlockSegment *_pendingCodeBlockSegment; + + size_t _renderedStyleFingerprint; + size_t _pendingStyleFingerprint; + + ENRMLinkContextMenus *_linkContextMenus; + NSArray *_contextMenuItemTexts; + NSArray *_contextMenuItemIcons; + ENRMSelectionMenuConfig _selectionMenuConfig; + ENRMAccessibilityLabels *_accessibilityLabels; + ENRMSelectionMenuLabels _selectionMenuLabels; + + ENRMDynamicBlockProps *_dynamicBlockProps; + + ENRMSpoilerOverlay _spoilerOverlay; + + NSLineBreakStrategy _lineBreakStrategy; + + ENRMWritingDirectionMode _writingDirectionMode; + NSWritingDirection _resolvedLayoutDirection; + + ENRMAtomicSize _lastCommittedSize; +} + ++ (ComponentDescriptorProvider)componentDescriptorProvider +{ + return concreteComponentDescriptorProvider(); +} + ++ (ENRMMd4cFlags *)flagsFromProps:(const EnrichedMarkdownMd4cFlagsStruct &)props +{ + ENRMMd4cFlags *flags = [ENRMMd4cFlags defaultFlags]; + flags.underline = props.underline; + flags.superscript = props.superscript; + flags.subscript = props.subscript; + flags.latexMath = props.latexMath; + flags.highlight = props.highlight; + flags.hardSoftBreaks = props.hardSoftBreaks; + flags.preserveBlankLines = props.preserveBlankLines; + flags.admonitions = props.admonitions; + return flags; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + static const auto defaultProps = std::make_shared(); + _props = defaultProps; + + self.backgroundColor = [RCTUIColor clearColor]; + _parser = [[ENRMMarkdownParser alloc] init]; + _md4cFlags = [EnrichedMarkdown flagsFromProps:defaultProps->md4cFlags]; + _isGFM = defaultProps->isGFM; + _linkRegex = ENRMLinkRegexConfigFromProps(defaultProps->linkRecognition.text); + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(defaultProps->linkRecognition.inlineCode); + _segmentViews = [NSMutableArray array]; + _segmentSignatures = [NSMutableArray array]; + __weak __typeof(self) weakLatexSelf = self; + _latexErrorCoordinator = + [[ENRMLatexErrorCoordinator alloc] initWithEmit:^BOOL(NSString *source, NSString *message, BOOL displayMode) { + __typeof(self) strongSelf = weakLatexSelf; + if (!strongSelf) + return NO; + auto emitter = std::static_pointer_cast(strongSelf->_eventEmitter); + if (!emitter) + return NO; + emitter->onLatexError({ + .source = std::string(source.UTF8String ?: ""), + .message = std::string(message.UTF8String ?: ""), + .displayMode = displayMode ? true : false, + }); + return YES; + }]; + _dirtyFlags = ENRMDirtyNone; + [self configureSegmentViewRegistry]; + + _renderCoordinator = + [[ENRMAsyncRenderCoordinator alloc] initWithQueueLabel:"com.swmansion.enriched.markdown.container.render"]; + + _maxFontSizeMultiplier = 0; + _allowTrailingMargin = NO; + _selectable = YES; + _enableLinkPreview = YES; + _enableTaskListItemToggle = YES; + _enableImagePress = NO; + _dynamicBlockProps = [[ENRMDynamicBlockProps alloc] init]; + _linkContextMenus = [[ENRMLinkContextMenus alloc] init]; + __weak EnrichedMarkdown *weakMenuSelf = self; + _linkContextMenus.onPress = ^(NSString *url, NSString *pattern, NSString *itemText) { + [weakMenuSelf emitLinkContextMenuItemPress:itemText pattern:pattern url:url]; + }; + _dynamicBlockProps.linkContextMenus = _linkContextMenus; + _streamingAnimation = NO; + _tableStreamingMode = ENRMTableStreamingModeProgressive; + _codeBlockStreamingMode = ENRMCodeBlockStreamingModeProgressive; + _selectionMenuConfig = (ENRMSelectionMenuConfig){.copyAsMarkdown = YES, .copyImageURL = YES}; + _lineBreakStrategy = NSLineBreakStrategyNone; + _writingDirectionMode = ENRMWritingDirectionModeFirstStrong; + _resolvedLayoutDirection = + [[RCTI18nUtil sharedInstance] isRTL] ? NSWritingDirectionRightToLeft : NSWritingDirectionLeftToRight; + + _fontScaleObserver = [[FontScaleObserver alloc] init]; + __weak EnrichedMarkdown *weakSelf = self; + _fontScaleObserver.onChange = ^{ + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) + return; + if (strongSelf->_config != nil) { + [strongSelf->_config setFontScaleMultiplier:strongSelf->_fontScaleObserver.effectiveFontScale]; + } + if (strongSelf->_cachedMarkdown != nil && strongSelf->_cachedMarkdown.length > 0) { + strongSelf->_dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight; + [strongSelf renderMarkdownContent:strongSelf->_cachedMarkdown]; + } + }; + } + return self; +} + +- (void)configureSegmentViewRegistry +{ + __weak EnrichedMarkdown *weakSelf = self; + NSMutableArray *handlers = [NSMutableArray array]; + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindText + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[EnrichedMarkdownInternalText class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + EnrichedMarkdownInternalText *view = + [strongSelf createTextViewForRenderedSegment:segment.textResult]; + [strongSelf animateTextView:view fromTailStart:0]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) { + [strongSelf updateTextView:(EnrichedMarkdownInternalText *)view + withRenderedSegment:segment.textResult]; + } + }]]; + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindTable + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[TableContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + TableContainerView *view = [strongSelf createTableViewForSegment:segment.tableSegment]; + [strongSelf animateBlockViewIfNeeded:view]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) { + [strongSelf updateTableView:(TableContainerView *)view withSegment:segment.tableSegment]; + } + }]]; + +#if ENRICHED_MARKDOWN_MATH + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindMath + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMMathContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + ENRMMathContainerView *view = + [strongSelf createMathViewForSegment:(ENRMMathSegment *)segment.mathSegment]; + [strongSelf animateBlockViewIfNeeded:view]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMMathContainerView *)view applyLatex:((ENRMMathSegment *)segment.mathSegment).latex]; + }]]; +#endif + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindCodeBlock + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMCodeBlockContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + ENRMCodeBlockContainerView *view = + [strongSelf createCodeBlockViewForSegment:segment.codeBlockSegment]; + [strongSelf animateBlockViewIfNeeded:view]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + ENRMCodeBlockContainerView *codeBlockView = (ENRMCodeBlockContainerView *)view; + codeBlockView.pending = + strongSelf && segment.codeBlockSegment == strongSelf->_pendingCodeBlockSegment; + [codeBlockView applyCodeBlockNode:segment.codeBlockSegment.codeBlockNode]; + }]]; + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindBlockquote + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMBlockquoteContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + ENRMBlockquoteContainerView *view = + [strongSelf createBlockquoteViewForSegment:segment.blockquoteSegment]; + [strongSelf animateBlockViewIfNeeded:view]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMBlockquoteContainerView *)view + applyBlockquoteNode:segment.blockquoteSegment.blockquoteNode]; + }]]; + +#if ENRICHED_MARKDOWN_VIDEO + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindVideo + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMVideoContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return [[RCTUIView alloc] init]; + } + + ENRMVideoContainerView *view = + [[ENRMVideoContainerView alloc] initWithConfig:strongSelf->_config]; + view.dynamicProps = strongSelf->_dynamicBlockProps; + [view applyVideoNode:segment.videoSegment.videoNode]; + [strongSelf animateBlockViewIfNeeded:view]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + ENRMVideoContainerView *videoView = (ENRMVideoContainerView *)view; + [videoView applyVideoNode:segment.videoSegment.videoNode]; + [videoView reapplyStyle]; + }]]; +#endif + + _segmentViewRegistry = [[ENRMSegmentViewRegistry alloc] initWithHandlers:handlers]; +} + +- (ENRMBlockquoteContainerView *)createBlockquoteViewForSegment:(ENRMBlockquoteSegment *)blockquoteSegment +{ + ENRMBlockquoteContainerView *view = [[ENRMBlockquoteContainerView alloc] initWithConfig:_config]; + view.allowFontScaling = _fontScaleObserver.allowFontScaling; + view.lineBreakStrategy = _lineBreakStrategy; + view.dynamicProps = _dynamicBlockProps; + view.accessibilityLabels = _accessibilityLabels; + + __weak EnrichedMarkdown *weakSelf = self; + view.onCopyPress = ^(NSString *code, NSString *language) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitCopyPress:code language:language]; + }; + view.onCodeBlockPress = ^(NSString *code, NSString *language) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitCodeBlockPress:code language:language]; + }; + view.onLinkPress = ^(NSString *url, NSString *sourceType) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && url) + [strongSelf emitLinkPress:url sourceType:sourceType]; + }; + view.onLinkLongPress = ^(NSString *url) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && url) + [strongSelf emitLinkLongPress:url]; + }; + + view.onImagePress = ^(NSString *url, NSString *altText) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && strongSelf->_enableImagePress && url) + [strongSelf emitImagePress:url altText:altText]; + }; + + [view applyBlockquoteNode:blockquoteSegment.blockquoteNode]; + return view; +} + +/// The box the segments actually live in: the component frame inset by the +/// `containerStyle` border and padding (`LayoutMetrics::getContentFrame`). +/// +/// Yoga hands `measureContent` an available size that already excludes those +/// insets and then adds them back to the frame it commits, so laying the +/// segments out against `self.bounds` would stack them over the padding and +/// across the border while the space Yoga reserved for the content stays blank +/// at the bottom. Unlike `EnrichedMarkdownText`, the segments are attached to +/// the component view itself rather than to `contentView`, so nothing applies +/// the insets for us. +/// +/// Taken from `_layoutMetrics` rather than recomputed off `self.bounds`: +/// `prepareForRecycle` resets the metrics but leaves the bounds behind, so the +/// two do not always agree. The box is empty both before the first layout +/// metrics arrive and when the insets consume the whole component width; neither +/// may fall back to `self.bounds`, which is the padded border box the segments +/// must not be drawn across, so an over-constrained box clamps to zero and +/// callers skip laying out at all. +- (CGRect)contentBounds +{ + CGRect box = RCTCGRectFromRect(_layoutMetrics.getContentFrame()); + box.size.width = MAX(box.size.width, 0); + box.size.height = MAX(box.size.height, 0); + return box; +} + +- (CGSize)computeSegmentLayoutForWidth:(CGFloat)width applyFrames:(BOOL)applyFrames +{ + if (_segmentViews.count == 0) + return CGSizeZero; + + if (applyFrames) { + CGFloat overhang = MAX(_config.tableHorizontalOverflow, 0); + BOOL needsOverhang = NO; + if (overhang > 0) { + for (RCTUIView *seg in _segmentViews) { + if ([seg isKindOfClass:[TableContainerView class]]) { + needsOverhang = YES; + break; + } + } + } +#if TARGET_OS_OSX + BOOL isClipping = self.layer.masksToBounds; + if (isClipping && needsOverhang) + self.layer.masksToBounds = NO; + else if (!isClipping && !needsOverhang) + self.layer.masksToBounds = YES; +#else + if (self.clipsToBounds != !needsOverhang) + self.clipsToBounds = !needsOverhang; +#endif + } + + __block CGFloat yOffset = 0.0; + __block CGFloat maxContentWidth = 0.0; + const NSUInteger lastIndex = _segmentViews.count - 1; + // Frames are stacked in the component's own coordinate space, so the content + // origin (containerStyle border + padding) shifts every segment. yOffset stays + // content-relative because it doubles as the measured content height. + const CGPoint contentOrigin = applyFrames ? [self contentBounds].origin : CGPointZero; + + [_segmentViews enumerateObjectsUsingBlock:^(RCTUIView *segment, NSUInteger i, BOOL *stop) { + const BOOL isLast = (i == lastIndex); + const BOOL shouldAddBottomMargin = (!isLast || _allowTrailingMargin); + + CGFloat segmentHeight = 0; + const BOOL isTable = [segment isKindOfClass:[TableContainerView class]]; + + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textView = (EnrichedMarkdownInternalText *)segment; + textView.allowTrailingMargin = shouldAddBottomMargin; + CGSize textSize = [textView measureSize:width]; + segmentHeight = textSize.height; + maxContentWidth = MAX(maxContentWidth, textSize.width); + + } else if (isTable) { + yOffset += _config.tableMarginTop; + segmentHeight = [(TableContainerView *)segment measureHeight:width]; + maxContentWidth = width; + } +#if ENRICHED_MARKDOWN_MATH + else if ([segment isKindOfClass:[ENRMMathContainerView class]]) { + yOffset += _config.mathMarginTop; + segmentHeight = [(ENRMMathContainerView *)segment measureHeight:width]; + maxContentWidth = width; + } +#endif + else if ([segment isKindOfClass:[ENRMCodeBlockContainerView class]]) { + yOffset += _config.codeBlockMarginTop; + segmentHeight = [(ENRMCodeBlockContainerView *)segment measureHeight:width]; + maxContentWidth = width; + } else if ([segment isKindOfClass:[ENRMBlockquoteContainerView class]]) { + yOffset += _config.blockquoteMarginTop; + segmentHeight = [(ENRMBlockquoteContainerView *)segment measureHeight:width]; + maxContentWidth = width; + } +#if ENRICHED_MARKDOWN_VIDEO + else if ([segment isKindOfClass:[ENRMVideoContainerView class]]) { + yOffset += _config.videoMarginTop; + segmentHeight = [(ENRMVideoContainerView *)segment measureHeight:width]; + maxContentWidth = width; + } +#endif + + if (applyFrames) { + CGFloat segmentX = contentOrigin.x; + CGFloat segmentWidth = width; + if (isTable) { + CGFloat overhang = MAX(_config.tableHorizontalOverflow, 0); + if (overhang > 0) { + segmentX = contentOrigin.x - overhang; + segmentWidth = width + overhang * 2; + } + } + CGRect segmentFrame = CGRectMake(segmentX, contentOrigin.y + yOffset, segmentWidth, segmentHeight); + segment.frame = segmentFrame; +#if TARGET_OS_OSX + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textSeg = (EnrichedMarkdownInternalText *)segment; + textSeg.textView.frame = segment.bounds; + textSeg.textView.textContainer.size = CGSizeMake(width, CGFLOAT_MAX); + [textSeg.textView.layoutManager ensureLayoutForTextContainer:textSeg.textView.textContainer]; + ENRMSetNeedsDisplay(textSeg.textView); + } +#endif + } + + yOffset += segmentHeight; + + if ([segment isKindOfClass:[TableContainerView class]] && shouldAddBottomMargin) { + yOffset += _config.tableMarginBottom; + } +#if ENRICHED_MARKDOWN_MATH + else if ([segment isKindOfClass:[ENRMMathContainerView class]] && shouldAddBottomMargin) { + yOffset += _config.mathMarginBottom; + } +#endif + else if ([segment isKindOfClass:[ENRMCodeBlockContainerView class]] && shouldAddBottomMargin) { + yOffset += _config.codeBlockMarginBottom; + } else if ([segment isKindOfClass:[ENRMBlockquoteContainerView class]] && shouldAddBottomMargin) { + yOffset += _config.blockquoteMarginBottom; + } +#if ENRICHED_MARKDOWN_VIDEO + else if ([segment isKindOfClass:[ENRMVideoContainerView class]] && shouldAddBottomMargin) { + yOffset += _config.videoMarginBottom; + } +#endif + }]; + + return CGSizeMake(maxContentWidth, yOffset); +} + +- (CGSize)measureSize:(CGFloat)maxWidth +{ + CGFloat defaultHeight = UIFontLineHeight([UIFont systemFontOfSize:16.0]); + CGSize contentSize = [self computeSegmentLayoutForWidth:maxWidth applyFrames:NO]; + if (contentSize.height == 0) + return CGSizeMake(maxWidth, defaultHeight); + + CGFloat scale = RCTScreenScale(); + CGFloat measuredWidth = MIN(ceil(contentSize.width * scale) / scale, maxWidth); + CGFloat measuredHeight = ceil(contentSize.height * scale) / scale; + return CGSizeMake(measuredWidth, measuredHeight); +} + +- (CGSize)lastCommittedLayoutSize +{ + return _lastCommittedSize.load(); +} + +- (BOOL)hasRenderedMarkdown:(NSString *)markdown +{ + return _renderedMarkdown != nil && [_renderedMarkdown isEqualToString:markdown]; +} + +- (BOOL)hasRenderedWithStyleFingerprint:(size_t)fingerprint +{ + return _renderedStyleFingerprint == fingerprint; +} + +- (BOOL)renderedSegmentsChangeTopology:(NSArray *)renderedSegments +{ + if (renderedSegments.count != _segmentViews.count) { + return YES; + } + + for (NSUInteger index = 0; index < renderedSegments.count; index++) { + if (![_segmentViewRegistry view:_segmentViews[index] matchesSegment:renderedSegments[index]]) { + return YES; + } + } + + return NO; +} + +- (void)updateState:(const facebook::react::State::Shared &)state + oldState:(const facebook::react::State::Shared &)oldState +{ + _state = std::static_pointer_cast(state); + + if (oldState == nullptr) { + [self requestHeightUpdate]; + } +} + +/// Publishes the committed size to the streaming fast path's mailbox, and picks +/// up the Yoga-resolved direction inherited from any ancestor `direction` style. +/// In FirstStrong mode the direction feeds the neutral-paragraph fallback, so a +/// change requires segment recreation. +/// +/// The mailbox holds a content size, not the border box: `measureContent` +/// returns it straight to Yoga, which adds the `containerStyle` insets back on +/// top of whatever it gets, so storing `frame.size` would double-count them. +- (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics + oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics +{ + [super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics]; + + const auto contentSize = layoutMetrics.getContentFrame().size; + _lastCommittedSize.store(CGSizeMake(contentSize.width, contentSize.height)); + + NSWritingDirection resolved = _resolvedLayoutDirection; + if (layoutMetrics.layoutDirection == LayoutDirection::RightToLeft) { + resolved = NSWritingDirectionRightToLeft; + } else if (layoutMetrics.layoutDirection == LayoutDirection::LeftToRight) { + resolved = NSWritingDirectionLeftToRight; + } + + if (resolved != _resolvedLayoutDirection) { + _resolvedLayoutDirection = resolved; + [self pushWritingDirectionToTableSegments]; + if (_writingDirectionMode == ENRMWritingDirectionModeFirstStrong && _cachedMarkdown.length > 0) { + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight; + [self renderMarkdownContent:_cachedMarkdown]; + } + } +} + +- (void)pushWritingDirectionToTableSegments +{ + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[TableContainerView class]]) { + TableContainerView *tableView = (TableContainerView *)segment; + tableView.writingDirectionMode = _writingDirectionMode; + tableView.resolvedLayoutDirection = _resolvedLayoutDirection; + } + } +} + +- (void)pushAccessibilityLabelsToSegments +{ + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + ((EnrichedMarkdownInternalText *)segment).accessibilityLabels = _accessibilityLabels; + } else if ([segment isKindOfClass:[TableContainerView class]]) { + ((TableContainerView *)segment).accessibilityLabels = _accessibilityLabels; + } else if ([segment isKindOfClass:[ENRMBlockquoteContainerView class]]) { + ((ENRMBlockquoteContainerView *)segment).accessibilityLabels = _accessibilityLabels; + } +#if ENRICHED_MARKDOWN_MATH + else if ([segment isKindOfClass:[ENRMMathContainerView class]]) { + ((ENRMMathContainerView *)segment).accessibilityLabels = _accessibilityLabels; + } +#endif + } +} + +- (void)requestHeightUpdate +{ + ENRMRequestHeightUpdate(_state, _heightUpdateCounter, self); +} + +// A block image in one of the text segments resolved its box height after +// loading (maxHeight/aspectRatio sizing). The shadow node measured — and +// cached — this markdown with the pre-load fallback height, so drop those +// entries, re-stack segments, and re-measure. +- (void)imageAttachmentDidResolveLayout +{ + if (_renderedMarkdown.length > 0) { + MeasurementCache::shared().removeMatchingMarkdown(std::string(_renderedMarkdown.UTF8String)); + } + + CGRect contentBounds = [self contentBounds]; + if (contentBounds.size.width > 0) { + [self setNeedsLayout]; + CGSize measured = [self measureSize:contentBounds.size.width]; + if (needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } +} + +- (void)renderMarkdownContent:(NSString *)markdownString +{ + if (_renderCoordinator.blockAsyncRender) + return; + + _cachedMarkdown = [markdownString copy]; + + StyleConfig *config = [_config copy]; + ENRMMarkdownParser *parser = _parser; + ENRMMd4cFlags *md4cFlags = [_md4cFlags copy]; + BOOL isGFM = _isGFM; + ENRMLinkRegexConfig *linkRegex = _linkRegex; + ENRMLinkRegexConfig *inlineCodeLinkRegex = _inlineCodeLinkRegex; + + BOOL allowFontScaling = _fontScaleObserver.allowFontScaling; + CGFloat maxFontSizeMultiplier = _maxFontSizeMultiplier; + BOOL allowTrailingMargin = _allowTrailingMargin; + BOOL streamingAnimation = _streamingAnimation; + ENRMTableStreamingMode tableStreamingMode = _tableStreamingMode; + ENRMCodeBlockStreamingMode codeBlockStreamingMode = _codeBlockStreamingMode; + NSLineBreakStrategy lineBreakStrategy = _lineBreakStrategy; + ENRMWritingDirectionMode writingDirectionMode = _writingDirectionMode; + NSWritingDirection resolvedLayoutDirection = _resolvedLayoutDirection; + + __block NSArray *renderedSegments = nil; + __block NSString *renderableMarkdown = nil; + __block BOOL endsInsideOpenCodeFence = NO; + + [_renderCoordinator + scheduleRender:^BOOL { + renderableMarkdown = streamingAnimation + ? ENRMRenderableMarkdownForStreaming(markdownString, tableStreamingMode, + codeBlockStreamingMode, &endsInsideOpenCodeFence) + : markdownString; + + if (renderableMarkdown.length == 0) { + renderedSegments = @[]; + return YES; + } + + MarkdownASTNode *ast = [parser parseMarkdown:renderableMarkdown + flags:md4cFlags + isGFM:isGFM + linkRegex:linkRegex + inlineCodeLinkRegex:inlineCodeLinkRegex]; + if (!ast) + return NO; + + renderedSegments = ENRMRenderSegmentsFromAST(ast, config, allowTrailingMargin, allowFontScaling, + maxFontSizeMultiplier, lineBreakStrategy, + /*blockquoteContent*/ NO); + for (ENRMRenderedSegment *segment in renderedSegments) { + if (segment.kind == ENRMSegmentKindText && segment.textResult) { + ENRMApplyWritingDirectionMode(segment.textResult.attributedText, writingDirectionMode, + resolvedLayoutDirection); + } + } + return YES; + } + apply:^{ + self->_renderedStyleFingerprint = self->_pendingStyleFingerprint; + [self applyRenderedSegments:renderedSegments + renderedMarkdown:renderableMarkdown + endsInsideOpenCodeFence:endsInsideOpenCodeFence]; + }]; +} + +- (NSArray *)parseAndRenderSegments:(NSString *)markdownString +{ + MarkdownASTNode *ast = [_parser parseMarkdown:markdownString + flags:_md4cFlags + isGFM:_isGFM + linkRegex:_linkRegex + inlineCodeLinkRegex:_inlineCodeLinkRegex]; + if (!ast) { + return nil; + } + + NSArray *segments = + ENRMRenderSegmentsFromAST(ast, _config, _allowTrailingMargin, _fontScaleObserver.allowFontScaling, + _maxFontSizeMultiplier, _lineBreakStrategy, /*blockquoteContent*/ NO); + for (ENRMRenderedSegment *segment in segments) { + if (segment.kind == ENRMSegmentKindText && segment.textResult) { + ENRMApplyWritingDirectionMode(segment.textResult.attributedText, _writingDirectionMode, _resolvedLayoutDirection); + } + } + return segments; +} + +/// Synchronous rendering for mock view measurement (no UI updates needed). +- (void)renderMarkdownSynchronously:(NSString *)markdownString +{ + if (!markdownString || markdownString.length == 0) { + return; + } + + for (RCTUIView *view in _segmentViews) { + [view removeFromSuperview]; + } + [_segmentViews removeAllObjects]; + [_segmentSignatures removeAllObjects]; + + _renderCoordinator.blockAsyncRender = YES; + _cachedMarkdown = [markdownString copy]; + BOOL endsInsideOpenCodeFence = NO; + NSString *renderableMarkdown = + _streamingAnimation ? ENRMRenderableMarkdownForStreaming(markdownString, _tableStreamingMode, + _codeBlockStreamingMode, &endsInsideOpenCodeFence) + : markdownString; + _renderedMarkdown = [renderableMarkdown copy]; + _renderedStyleFingerprint = _pendingStyleFingerprint; + + if (renderableMarkdown.length == 0) { + return; + } + + NSArray *renderedSegments = [self parseAndRenderSegments:renderableMarkdown]; + if (!renderedSegments) { + return; + } + + [self updatePendingCodeBlockSegment:endsInsideOpenCodeFence segments:renderedSegments]; + + for (ENRMRenderedSegment *segment in renderedSegments) { + RCTUIView *view = [_segmentViewRegistry createViewForSegment:segment]; + [_segmentViews addObject:view]; + [_segmentSignatures addObject:@(segment.signature)]; + [self addSubview:view]; + } +} + +- (void)updatePendingCodeBlockSegment:(BOOL)endsInsideOpenCodeFence segments:(NSArray *)segments +{ + _pendingCodeBlockSegment = nil; + if (!_streamingAnimation || !endsInsideOpenCodeFence) { + return; + } + ENRMRenderedSegment *last = segments.lastObject; + if (last.kind == ENRMSegmentKindCodeBlock) { + _pendingCodeBlockSegment = last.codeBlockSegment; + } +} + +- (void)applyRenderedSegments:(NSArray *)renderedSegments + renderedMarkdown:(NSString *)renderedMarkdown + endsInsideOpenCodeFence:(BOOL)endsInsideOpenCodeFence +{ + _renderedMarkdown = [renderedMarkdown copy]; + [self updatePendingCodeBlockSegment:endsInsideOpenCodeFence segments:renderedSegments]; + BOOL segmentTopologyChanged = _streamingAnimation && [self renderedSegmentsChangeTopology:renderedSegments]; + + ENRMSegmentReconciliationResult *result = [ENRMSegmentReconciler reconcileCurrentViews:_segmentViews + currentSignatures:_segmentSignatures + renderedSegments:renderedSegments + reset:(_dirtyFlags & ENRMDirtyRecreateSegments) != 0 + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + return [self->_segmentViewRegistry createViewForSegment:segment]; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [self->_segmentViewRegistry updateView:view withSegment:segment]; + } + attachView:^(RCTUIView *view) { [self addSubview:view]; } + removeView:^(RCTUIView *view) { [view removeFromSuperview]; } + matchesKind:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [self->_segmentViewRegistry view:view matchesSegment:segment]; + }]; + BOOL forceHeightUpdate = (_dirtyFlags & ENRMDirtyForceHeight) != 0; + _dirtyFlags = ENRMDirtyNone; + + _segmentViews = result.views; + _segmentSignatures = result.signatures; + + // A just-closed block has unchanged content, so the reconciler reuses it + // without an update; sync pending here to trigger its deferred highlight. + [_segmentViews enumerateObjectsUsingBlock:^(RCTUIView *segment, NSUInteger i, BOOL *stop) { + if ([segment isKindOfClass:[ENRMCodeBlockContainerView class]]) { + ((ENRMCodeBlockContainerView *)segment).pending = + self->_pendingCodeBlockSegment != nil && i == self->_segmentViews.count - 1; + } + }]; + + CGRect contentBounds = [self contentBounds]; + if (contentBounds.size.width > 0) { + [self setNeedsLayout]; + + if (forceHeightUpdate || segmentTopologyChanged) { + [self computeSegmentLayoutForWidth:contentBounds.size.width applyFrames:YES]; + [self layoutIfNeeded]; + [self requestHeightUpdate]; + } else { + CGSize measured = [self measureSize:contentBounds.size.width]; + if (needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } + } +} + +- (void)configureTextView:(EnrichedMarkdownInternalText *)view withRenderedSegment:(ENRMRenderResult *)segment +{ + view.spoilerOverlay = _spoilerOverlay; + view.allowTrailingMargin = _allowTrailingMargin; + view.lastElementMarginBottom = segment.lastElementMarginBottom; + view.accessibilityInfo = segment.accessibilityInfo; + view.accessibilityLabels = _accessibilityLabels; + view.textView.selectable = _selectable; + [_latexErrorCoordinator wireReporters:segment.context.mathReporters]; + [view applyAttributedText:segment.attributedText context:segment.context]; + + const auto &selectionProps = *std::static_pointer_cast(self->_props); + ENRMApplySelectionColor(view.textView, selectionProps.selectionColor); +} + +- (EnrichedMarkdownInternalText *)createTextViewForRenderedSegment:(ENRMRenderResult *)segment +{ + EnrichedMarkdownInternalText *view = [[EnrichedMarkdownInternalText alloc] initWithConfig:_config]; + [self configureTextView:view withRenderedSegment:segment]; + + ENRMTapRecognizer *tapRecognizer = [[ENRMTapRecognizer alloc] initWithTarget:self action:@selector(textTapped:)]; + [view.textView addGestureRecognizer:tapRecognizer]; + +#if !TARGET_OS_OSX + view.textView.delegate = self; +#else + __weak EnrichedMarkdown *weakSelf = self; + [view setContextMenuProvider:^NSMenu *_Nullable(NSMenu *baseMenu, NSTextView *textView) { + EnrichedMarkdown *strongSelf = weakSelf; + if (!strongSelf) { + return baseMenu; + } + NSString *segmentMarkdown = extractMarkdownFromAttributedString(textView.textStorage, textView.selectedRange); + NSArray *customItems = ENRMBuildContextMenuItems( + strongSelf->_contextMenuItemTexts, strongSelf->_contextMenuItemIcons, textView, + ^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) { + [strongSelf emitContextMenuItemPress:itemText + selectedText:selectedText + selectionStart:selectionStart + selectionEnd:selectionEnd]; + }); + return buildEditMenuForSelection(textView.textStorage, textView.selectedRange, segmentMarkdown, strongSelf->_config, + @[ baseMenu ], customItems, strongSelf -> _selectionMenuConfig); + }]; +#endif + + return view; +} + +- (TableContainerView *)createTableViewForSegment:(ENRMTableSegment *)tableSegment +{ + TableContainerView *tableView = [[TableContainerView alloc] initWithConfig:_config]; + + tableView.allowFontScaling = _fontScaleObserver.allowFontScaling; + tableView.maxFontSizeMultiplier = _maxFontSizeMultiplier; + tableView.enableLinkPreview = _enableLinkPreview; + tableView.dynamicProps = _dynamicBlockProps; + tableView.writingDirectionMode = _writingDirectionMode; + tableView.resolvedLayoutDirection = _resolvedLayoutDirection; + tableView.accessibilityLabels = _accessibilityLabels; + + __weak EnrichedMarkdown *weakSelf = self; + + tableView.onLinkPress = ^(NSString *url, NSString *sourceType) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && url) + [strongSelf emitLinkPress:url sourceType:sourceType]; + }; + + tableView.onLinkLongPress = ^(NSString *url) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && url) + [strongSelf emitLinkLongPress:url]; + }; + + tableView.onImagePress = ^(NSString *url, NSString *altText) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf && strongSelf->_enableImagePress && url) + [strongSelf emitImagePress:url altText:altText]; + }; + + [tableView applyTableNode:tableSegment.tableNode]; + + return tableView; +} + +- (void)updateTableView:(TableContainerView *)view withSegment:(ENRMTableSegment *)tableSegment +{ + view.writingDirectionMode = _writingDirectionMode; + view.resolvedLayoutDirection = _resolvedLayoutDirection; + NSUInteger previousRowCount = view.rowCount; + [view applyTableNode:tableSegment.tableNode]; + + if (_streamingAnimation && !ENRMShouldReduceMotion()) { + [view animateNewRowsFromPreviousCount:previousRowCount duration:0.20]; + } +} + +#if ENRICHED_MARKDOWN_MATH +- (ENRMMathContainerView *)createMathViewForSegment:(ENRMMathSegment *)mathSegment +{ + ENRMMathContainerView *mathView = [[ENRMMathContainerView alloc] initWithConfig:_config]; + mathView.dynamicProps = _dynamicBlockProps; + mathView.accessibilityLabels = _accessibilityLabels; + ENRMLatexErrorCoordinator *coordinator = _latexErrorCoordinator; + mathView.onLatexError = ^(NSString *source, NSString *message, BOOL displayMode) { + [coordinator reportSource:source message:message displayMode:displayMode]; + }; + [mathView applyLatex:mathSegment.latex]; + return mathView; +} +#endif + +- (ENRMCodeBlockContainerView *)createCodeBlockViewForSegment:(ENRMCodeBlockSegment *)codeBlockSegment +{ + ENRMCodeBlockContainerView *codeBlockView = [[ENRMCodeBlockContainerView alloc] initWithConfig:_config]; + codeBlockView.dynamicProps = _dynamicBlockProps; + + __weak EnrichedMarkdown *weakSelf = self; + codeBlockView.onCopyPress = ^(NSString *code, NSString *language) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitCopyPress:code language:language]; + }; + codeBlockView.onCodeBlockPress = ^(NSString *code, NSString *language) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitCodeBlockPress:code language:language]; + }; + + codeBlockView.pending = codeBlockSegment == _pendingCodeBlockSegment; + [codeBlockView applyCodeBlockNode:codeBlockSegment.codeBlockNode]; + return codeBlockView; +} + +- (void)animateBlockViewIfNeeded:(RCTUIView *)view +{ + if (!_streamingAnimation) + return; + +#if !TARGET_OS_OSX + if (ENRMShouldReduceMotion()) { + return; + } + view.alpha = 0.0; + [UIView animateWithDuration:0.20 animations:^{ view.alpha = 1.0; }]; +#endif +} + +- (void)animateTextView:(EnrichedMarkdownInternalText *)view fromTailStart:(NSUInteger)tailStart +{ + if (!_streamingAnimation) + return; + + ENRMTailFadeInAnimator *animator = objc_getAssociatedObject(view.textView, &kENRMSegmentFadeAnimatorKey); + if (!animator) { + animator = [[ENRMTailFadeInAnimator alloc] initWithTextView:view.textView]; + objc_setAssociatedObject(view.textView, &kENRMSegmentFadeAnimatorKey, animator, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + [animator animateFrom:tailStart to:ENRMGetAttributedText(view.textView).length]; +} + +- (void)updateTextView:(EnrichedMarkdownInternalText *)view withRenderedSegment:(ENRMRenderResult *)segment +{ + NSUInteger tailStart = ENRMGetAttributedText(view.textView).length; + [self configureTextView:view withRenderedSegment:segment]; + [self animateTextView:view fromTailStart:tailStart]; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + CGFloat contentWidth = [self contentBounds].size.width; + if (contentWidth > 0) { + [self computeSegmentLayoutForWidth:contentWidth applyFrames:YES]; + } +} + +- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps +{ + const auto &oldViewProps = *std::static_pointer_cast(_props); + const auto &newViewProps = *std::static_pointer_cast(props); + + BOOL markdownChanged = oldViewProps.markdown != newViewProps.markdown; + if (markdownChanged) { + _dirtyFlags |= ENRMDirtyRender; + } + + if (_config == nil) { + _config = [[StyleConfig alloc] init]; + [_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale]; + } + + if (applyMarkdownStyleToConfig(_config, newViewProps.markdownStyle, oldViewProps.markdownStyle)) { + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + if (!markdownChanged) { + _dirtyFlags |= ENRMDirtyRecreateSegments; + } + } + + if (ENRMImageRequestHeadersChanged(oldViewProps.imageRequestHeaders, newViewProps.imageRequestHeaders)) { + [_config setImageRequestHeaders:ENRMImageRequestHeadersFromProps(newViewProps.imageRequestHeaders)]; + _dirtyFlags |= ENRMDirtyRender; + if (!markdownChanged) { + _dirtyFlags |= ENRMDirtyRecreateSegments; + } + } + + // Pill labels change layout, so treat new content like a style change. + if (ENRMLinkPillContentChanged(oldViewProps.linkPillContent, newViewProps.linkPillContent)) { + [_config setLinkPillContent:ENRMLinkPillContentFromProps(newViewProps.linkPillContent)]; + _dirtyFlags |= ENRMDirtyRender; + if (!markdownChanged) { + _dirtyFlags |= ENRMDirtyRecreateSegments; + } + } + + _selectable = newViewProps.selectable; + + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment; + if (textSegment.textView.selectable != newViewProps.selectable) { + textSegment.textView.selectable = newViewProps.selectable; + } + } + } + + if (newViewProps.allowFontScaling != oldViewProps.allowFontScaling) { + _fontScaleObserver.allowFontScaling = newViewProps.allowFontScaling; + if (_config != nil) { + [_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale]; + } + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (newViewProps.maxFontSizeMultiplier != oldViewProps.maxFontSizeMultiplier) { + _maxFontSizeMultiplier = newViewProps.maxFontSizeMultiplier; + if (_config != nil) { + [_config setMaxFontSizeMultiplier:_maxFontSizeMultiplier]; + } + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (newViewProps.allowTrailingMargin != oldViewProps.allowTrailingMargin) { + _allowTrailingMargin = newViewProps.allowTrailingMargin; + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (!ENRMLinkRegexPropsEqual(oldViewProps.linkRecognition.text, newViewProps.linkRecognition.text)) { + _linkRegex = ENRMLinkRegexConfigFromProps(newViewProps.linkRecognition.text); + _dirtyFlags |= ENRMDirtyRender; + _dirtyFlags |= ENRMDirtyForceHeight; + } + if (!ENRMLinkRegexPropsEqual(oldViewProps.linkRecognition.inlineCode, newViewProps.linkRecognition.inlineCode)) { + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(newViewProps.linkRecognition.inlineCode); + _dirtyFlags |= ENRMDirtyRender; + _dirtyFlags |= ENRMDirtyForceHeight; + } + + if (newViewProps.md4cFlags.underline != oldViewProps.md4cFlags.underline || + newViewProps.md4cFlags.superscript != oldViewProps.md4cFlags.superscript || + newViewProps.md4cFlags.subscript != oldViewProps.md4cFlags.subscript || + newViewProps.md4cFlags.latexMath != oldViewProps.md4cFlags.latexMath || + newViewProps.md4cFlags.highlight != oldViewProps.md4cFlags.highlight || + newViewProps.md4cFlags.hardSoftBreaks != oldViewProps.md4cFlags.hardSoftBreaks || + newViewProps.md4cFlags.preserveBlankLines != oldViewProps.md4cFlags.preserveBlankLines || + newViewProps.md4cFlags.admonitions != oldViewProps.md4cFlags.admonitions) { + _md4cFlags = [EnrichedMarkdown flagsFromProps:newViewProps.md4cFlags]; + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (newViewProps.isGFM != oldViewProps.isGFM) { + _isGFM = newViewProps.isGFM; + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight | ENRMDirtyRender; + } + + _enableLinkPreview = newViewProps.enableLinkPreview; + _enableTaskListItemToggle = newViewProps.enableTaskListItemToggle; + _enableImagePress = newViewProps.enableImagePress; + + // Block gates: mutate the shared box in place. Every existing and future block + // view reads it live at use-time, so no push into segments is needed. + _dynamicBlockProps.enableLinkPreview = newViewProps.enableLinkPreview; + _dynamicBlockProps.enableBlockContextMenu = newViewProps.enableBlockContextMenu; + _dynamicBlockProps.enableCodeBlockPress = newViewProps.enableCodeBlockPress; + + if (newViewProps.streamingAnimation != oldViewProps.streamingAnimation) { + _streamingAnimation = newViewProps.streamingAnimation; + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + if (!_streamingAnimation) { + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + ENRMTailFadeInAnimator *animator = objc_getAssociatedObject( + ((EnrichedMarkdownInternalText *)segment).textView, &kENRMSegmentFadeAnimatorKey); + [animator cancel]; + objc_setAssociatedObject(((EnrichedMarkdownInternalText *)segment).textView, &kENRMSegmentFadeAnimatorKey, + nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + } + } + } + + if (newViewProps.streamingConfig.tableMode != oldViewProps.streamingConfig.tableMode) { + NSString *tableModeStr = [[NSString alloc] initWithUTF8String:newViewProps.streamingConfig.tableMode.c_str()]; + _tableStreamingMode = + [tableModeStr isEqualToString:@"hidden"] ? ENRMTableStreamingModeHidden : ENRMTableStreamingModeProgressive; + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (newViewProps.streamingConfig.codeBlockMode != oldViewProps.streamingConfig.codeBlockMode) { + NSString *codeBlockModeStr = + [[NSString alloc] initWithUTF8String:newViewProps.streamingConfig.codeBlockMode.c_str()]; + _codeBlockStreamingMode = [codeBlockModeStr isEqualToString:@"hidden"] ? ENRMCodeBlockStreamingModeHidden + : ENRMCodeBlockStreamingModeProgressive; + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (ENRMLinkContextMenuItemsChanged(oldViewProps.linkContextMenuItems, newViewProps.linkContextMenuItems)) { + _linkContextMenus.entries = ENRMLinkContextMenuEntriesFromProps(newViewProps.linkContextMenuItems); + } + + if (ENRMContextMenuItemsChanged(oldViewProps.contextMenuItems, newViewProps.contextMenuItems)) { + _contextMenuItemTexts = ENRMContextMenuTextsFromItems(newViewProps.contextMenuItems); + _contextMenuItemIcons = ENRMContextMenuIconsFromItems(newViewProps.contextMenuItems); + } + + _selectionMenuLabels = ENRMParseSelectionMenuLabels(newViewProps.selectionMenuConfig); + _selectionMenuConfig = + ENRMBuildSelectionMenuConfig(_selectionMenuLabels, newViewProps.selectionMenuConfig.copyAsMarkdown, + newViewProps.selectionMenuConfig.copyImageUrl); + // Block menu labels live in the shared box; block views read them live at + // menu-open. (_selectionMenuLabels also feeds the text selection menu above.) + _dynamicBlockProps.copyLabel = _selectionMenuLabels.copyLabel; + _dynamicBlockProps.copyAsMarkdownLabel = _selectionMenuLabels.copyAsMarkdownLabel; + + if (ENRMAccessibilityLabelsChanged(oldViewProps.accessibilityLabels, newViewProps.accessibilityLabels)) { + _accessibilityLabels = [[ENRMAccessibilityLabels alloc] init]; + _accessibilityLabels.bulletPoint = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.bulletPoint.c_str()]; + _accessibilityLabels.nestedBulletPoint = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.nestedBulletPoint.c_str()]; + _accessibilityLabels.orderedItem = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.orderedItem.c_str()]; + _accessibilityLabels.nestedOrderedItem = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.nestedOrderedItem.c_str()]; + _accessibilityLabels.blockquote = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.blockquote.quote.c_str()]; + _accessibilityLabels.nestedBlockquote = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.blockquote.nestedQuote.c_str()]; + _accessibilityLabels.tableRow = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.table.row.c_str()]; + _accessibilityLabels.mathEquation = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.math.equation.c_str()]; + _accessibilityLabels.rotorHeadings = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.headings.c_str()]; + _accessibilityLabels.rotorLinks = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.links.c_str()]; + _accessibilityLabels.rotorImages = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.images.c_str()]; + [self pushAccessibilityLabelsToSegments]; + } + + if (newViewProps.spoilerOverlay != oldViewProps.spoilerOverlay) { + NSString *modeStr = [[NSString alloc] initWithUTF8String:newViewProps.spoilerOverlay.c_str()]; + _spoilerOverlay = ENRMSpoilerOverlayFromString(modeStr); + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + ((EnrichedMarkdownInternalText *)segment).spoilerOverlay = _spoilerOverlay; + } + } + } + + if (newViewProps.selectionColor != oldViewProps.selectionColor) { + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + ENRMPlatformTextView *tv = ((EnrichedMarkdownInternalText *)segment).textView; + ENRMApplySelectionColor(tv, newViewProps.selectionColor); + } + } + } + + if (newViewProps.lineBreakStrategyIOS != oldViewProps.lineBreakStrategyIOS) { + NSString *strategy = [[NSString alloc] initWithUTF8String:newViewProps.lineBreakStrategyIOS.c_str()]; + _lineBreakStrategy = ENRMResolveLineBreakStrategy(strategy); + _dirtyFlags |= ENRMDirtyForceHeight | ENRMDirtyRender; + } + + if (newViewProps.writingDirection != oldViewProps.writingDirection) { + NSString *value = [[NSString alloc] initWithUTF8String:newViewProps.writingDirection.c_str()]; + _writingDirectionMode = ENRMResolveWritingDirectionMode(value); + _dirtyFlags |= ENRMDirtyRecreateSegments | ENRMDirtyForceHeight | ENRMDirtyRender; + [self pushWritingDirectionToTableSegments]; + } + + if (_dirtyFlags & ENRMDirtyRender) { + _pendingStyleFingerprint = + computeStyleFingerprint(newViewProps.markdownStyle) ^ std::hash{}(newViewProps.allowTrailingMargin); + NSString *markdownString = [[NSString alloc] initWithUTF8String:newViewProps.markdown.c_str()]; + [self renderMarkdownContent:markdownString]; + _dirtyFlags &= ~ENRMDirtyRender; + } + + [super updateProps:props oldProps:oldProps]; +} + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + + if (self.window && _renderedMarkdown != nil) { + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment; + ENRMRefreshTextViewAfterWindowAttach(textSegment.textView, textSegment.bounds); + } + } + + CGRect contentBounds = [self contentBounds]; + if (contentBounds.size.width > 0) { + CGSize measured = [self measureSize:contentBounds.size.width]; + if (needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } + } +} + +- (void)prepareForRecycle +{ + const auto resetProps = std::make_shared(); + _props = resetProps; + [_renderCoordinator invalidate]; + + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment; + ENRMTailFadeInAnimator *animator = objc_getAssociatedObject(textSegment.textView, &kENRMSegmentFadeAnimatorKey); + [animator cancel]; + objc_setAssociatedObject(textSegment.textView, &kENRMSegmentFadeAnimatorKey, nil, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + [segment removeFromSuperview]; + } + [_segmentViews removeAllObjects]; + [_segmentSignatures removeAllObjects]; + + _cachedMarkdown = nil; + _renderedMarkdown = nil; + _config = nil; + _md4cFlags = [EnrichedMarkdown flagsFromProps:resetProps->md4cFlags]; + _isGFM = resetProps->isGFM; + _linkRegex = ENRMLinkRegexConfigFromProps(resetProps->linkRecognition.text); + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(resetProps->linkRecognition.inlineCode); + _maxFontSizeMultiplier = 0; + _allowTrailingMargin = NO; + _streamingAnimation = NO; + _tableStreamingMode = ENRMTableStreamingModeProgressive; + _codeBlockStreamingMode = ENRMCodeBlockStreamingModeProgressive; + _pendingCodeBlockSegment = nil; + _lineBreakStrategy = NSLineBreakStrategyNone; + _writingDirectionMode = ENRMWritingDirectionModeFirstStrong; + _renderedStyleFingerprint = 0; + _pendingStyleFingerprint = 0; + _linkContextMenus.entries = @[]; + _contextMenuItemTexts = nil; + _contextMenuItemIcons = nil; + _fontScaleObserver.allowFontScaling = resetProps->allowFontScaling; + _accessibilityLabels = nil; + _spoilerOverlay = + ENRMSpoilerOverlayFromString([[NSString alloc] initWithUTF8String:resetProps->spoilerOverlay.c_str()]); + _dirtyFlags = ENRMDirtyNone; + + [super prepareForRecycle]; +} + +Class EnrichedMarkdownCls(void) +{ + return EnrichedMarkdown.class; +} + +#if !TARGET_OS_OSX +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event +{ + if ([super pointInside:point withEvent:event]) { + return YES; + } + + for (RCTUIView *segment in _segmentViews) { + if (CGRectContainsPoint(segment.frame, point)) { + return YES; + } + } + + return NO; +} +#endif + +- (facebook::react::SharedTouchEventEmitter)touchEventEmitterAtPoint:(CGPoint)point +{ + for (RCTUIView *segment in _segmentViews) { + if ([segment isKindOfClass:[TableContainerView class]]) { + CGPoint segmentPoint = [self convertPoint:point toView:segment]; +#if !TARGET_OS_OSX + if ([segment pointInside:segmentPoint withEvent:nil]) { + return nil; + } +#else + if (CGRectContainsPoint(segment.bounds, segmentPoint)) { + return nil; + } +#endif + } + + if (![segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + continue; + } + EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment; + CGPoint segmentPoint = [self convertPoint:point toView:textSegment.textView]; +#if !TARGET_OS_OSX + BOOL isInsideView = [textSegment.textView pointInside:segmentPoint withEvent:nil]; +#else + BOOL isInsideView = CGRectContainsPoint(textSegment.textView.bounds, segmentPoint); +#endif + if (isInsideView) { + if (isPointOnInteractiveElement(textSegment.textView, segmentPoint, _enableImagePress, NO)) { + return nil; + } + break; + } + } + + return [super touchEventEmitterAtPoint:point]; +} + +#if TARGET_OS_OSX +- (void)mouseDown:(NSEvent *)event +{ + for (RCTUIView *segment in _segmentViews) { + if (![segment isKindOfClass:[EnrichedMarkdownInternalText class]]) { + continue; + } + ENRMPlatformTextView *tv = ((EnrichedMarkdownInternalText *)segment).textView; + if (tv.selectedRange.length > 0) { + tv.selectedRange = NSMakeRange(0, 0); + } + } + [super mouseDown:event]; +} +#endif + +- (void)emitLinkPress:(NSString *)url sourceType:(NSString *)sourceType +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onLinkPress({.url = std::string(url.UTF8String), .sourceType = std::string(sourceType.UTF8String)}); +} + +- (void)emitImagePress:(NSString *)url altText:(NSString *)altText +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onImagePress({.url = std::string(url.UTF8String ?: ""), .altText = std::string(altText.UTF8String ?: "")}); +} + +- (void)emitLinkLongPress:(NSString *)url +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onLinkLongPress({.url = std::string(url.UTF8String)}); +} + +- (void)emitLinkContextMenuItemPress:(NSString *)itemText pattern:(NSString *)pattern url:(NSString *)url +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) { + emitter->onLinkContextMenuItemPress({.url = std::string(url.UTF8String), + .pattern = std::string(pattern.UTF8String), + .itemText = std::string(itemText.UTF8String)}); + } +} + +- (void)emitTaskListItemPress:(NSInteger)index checked:(BOOL)checked text:(NSString *)text +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onTaskListItemPress({.index = (int)index, .checked = checked, .text = std::string(text.UTF8String ?: "")}); +} + +- (void)emitCopyPress:(NSString *)code language:(NSString *)language +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onCopyPress( + {.code = std::string(code.UTF8String ?: ""), .language = std::string(language.UTF8String ?: "")}); +} + +- (void)emitCodeBlockPress:(NSString *)code language:(NSString *)language +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onCodeBlockPress( + {.code = std::string(code.UTF8String ?: ""), .language = std::string(language.UTF8String ?: "")}); +} + +- (void)emitContextMenuItemPress:(NSString *)itemText + selectedText:(NSString *)selectedText + selectionStart:(NSUInteger)selectionStart + selectionEnd:(NSUInteger)selectionEnd +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onContextMenuItemPress({ + .itemText = std::string(itemText.UTF8String), + .selectedText = std::string(selectedText.UTF8String), + .selectionStart = (int)selectionStart, + .selectionEnd = (int)selectionEnd, + }); +} + +- (void)updateEventEmitter:(const facebook::react::EventEmitter::Shared &)eventEmitter +{ + [super updateEventEmitter:eventEmitter]; + [_latexErrorCoordinator flushPending]; +} + +- (void)textTapped:(ENRMTapRecognizer *)recognizer +{ + ENRMPlatformTextView *textView = (ENRMPlatformTextView *)recognizer.view; + + if (_enableTaskListItemToggle && + handleTaskListTapWithSharedLogic( + textView, recognizer, &self->_cachedMarkdown, self->_config, + ^(NSInteger index, BOOL checked, NSString *itemText) { + [self emitTaskListItemPress:index checked:checked text:itemText]; + }, + ^(NSString *updatedMarkdown) { [self renderMarkdownContent:updatedMarkdown]; })) { + return; + } + + for (RCTUIView *segment in _segmentViews) { + if ([segment conformsToProtocol:@protocol(ENRMSpoilerCapable)]) { + id spoilerSegment = (id)segment; + if (spoilerSegment.textView == textView) { + if (handleSpoilerTap(textView, recognizer, spoilerSegment.spoilerManager)) + return; + break; + } + } + } + + if (ENRMHandleTapOnTextView(textView, recognizer, ^(NSString *url, NSString *sourceType) { + [self emitLinkPress:url sourceType:sourceType]; + })) { + return; + } + + if (_enableImagePress) { + NSDictionary *image = imageAtTapLocation(textView, recognizer); + if (image) { + [self emitImagePress:image[@"url"] altText:image[@"altText"]]; + } + } +} + +// TODO: Remove API_AVAILABLE(ios(16.0)) guard when the minimum iOS deployment target in RN is bumped to 16. +#if !TARGET_OS_OSX +- (UIMenu *)textView:(UITextView *)textView + editMenuForTextInRange:(NSRange)range + suggestedActions:(NSArray *)suggestedActions API_AVAILABLE(ios(16.0)) +{ + __weak EnrichedMarkdown *weakSelf = self; + ENRMContextMenuPressHandler handler = + ^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) { + EnrichedMarkdown *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitContextMenuItemPress:itemText + selectedText:selectedText + selectionStart:selectionStart + selectionEnd:selectionEnd]; + }; + NSMutableArray *customActions = + ENRMBuildContextMenuActions(_contextMenuItemTexts, _contextMenuItemIcons, textView, range, handler); + + NSString *segmentMarkdown = extractMarkdownFromAttributedString(textView.attributedText, range); + return buildEditMenuForSelection(textView.attributedText, range, segmentMarkdown, _config, suggestedActions, + customActions, _selectionMenuConfig); +} + +- (UITextItemMenuConfiguration *)textView:(UITextView *)textView + menuConfigurationForTextItem:(UITextItem *)textItem + defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0)) +{ + __weak EnrichedMarkdown *weakSelf = self; + return ENRMLinkMenuConfigurationForTextItem(textView, textItem, defaultMenu, _linkContextMenus, _enableLinkPreview, + ^(NSString *url) { [weakSelf emitLinkLongPress:url]; }); +} + +- (ENRMLinkContextMenus *)linkContextMenusForTextView:(UITextView *)textView +{ + return _linkContextMenus; +} + +- (BOOL)textView:(UITextView *)textView + shouldInteractWithURL:(NSURL *)URL + inRange:(NSRange)characterRange + interaction:(UITextItemInteraction)interaction +{ + if (interaction != UITextItemInteractionPresentActions) { + return YES; + } + + NSString *urlString = linkURLAtRange(textView, characterRange); + + // A link with a menu is presented by the iOS 17 callback above and must not be vetoed here. + if ([_linkContextMenus hasMenuForURL:urlString]) + return YES; + + if (!urlString || _enableLinkPreview) { + return YES; + } + + [self emitLinkLongPress:urlString]; + return NO; +} +#endif + +- (BOOL)isAccessibilityElement +{ + return NO; +} + +- (NSArray *)accessibilityElements +{ + return _segmentViews; +} + +- (NSInteger)accessibilityElementCount +{ + return [self accessibilityElements].count; +} + +- (id)accessibilityElementAtIndex:(NSInteger)index +{ + NSArray *elements = [self accessibilityElements]; + if (index < 0 || index >= (NSInteger)elements.count) { + return nil; + } + return elements[index]; +} + +- (NSInteger)indexOfAccessibilityElement:(id)element +{ + return [[self accessibilityElements] indexOfObject:element]; +} + +#if !TARGET_OS_OSX +- (NSArray *)accessibilityCustomRotors +{ + return [MarkdownAccessibilityElementBuilder buildRotorsFromElements:[self accessibilityElements] + labels:_accessibilityLabels]; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.h b/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.h new file mode 100644 index 000000000000..7287ac2b9fd4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.h @@ -0,0 +1,27 @@ +#import "ENRMUIKit.h" +#import "StyleConfig.h" +#import + +#ifndef EnrichedMarkdownTextNativeComponent_h +#define EnrichedMarkdownTextNativeComponent_h + +NS_ASSUME_NONNULL_BEGIN + +@interface EnrichedMarkdownText : RCTViewComponentView +@property (nonatomic, strong) StyleConfig *config; +- (CGSize)measureSize:(CGFloat)maxWidth; +- (void)renderMarkdownSynchronously:(NSString *)markdownString; +- (BOOL)hasRenderedMarkdown:(NSString *)markdown; +- (BOOL)hasRenderedWithStyleFingerprint:(size_t)fingerprint; + +/// Size last committed by Fabric via `updateLayoutMetrics:`, readable from +/// any thread without blocking (issue #550: the shadow-node measure path must +/// never wait on the main thread, and reading `bounds` off-main is unsafe). +/// Backed by a single lock-free atomic, so the pair can't tear. Returns +/// CGSizeZero until the first layout is committed. +- (CGSize)lastCommittedLayoutSize; +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.mm b/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.mm new file mode 100644 index 000000000000..2fa091f43ceb --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/EnrichedMarkdownText.mm @@ -0,0 +1,1146 @@ +#import "EnrichedMarkdownText.h" +#import "CodeBlockBackground.h" +#import "ContextMenuUtils.h" +#import "ENRMAccessibilityLabels.h" +#import "ENRMAsyncRenderCoordinator.h" +#import "ENRMAtomicSize.h" +#import "ENRMContextMenuTextView+macOS.h" +#import "ENRMImageAttachment.h" +#import "ENRMLatexErrorCoordinator.h" +#import "ENRMLinkContextMenus.h" +#import "ENRMLinkRegexProps.h" +#import "ENRMMarkdownParser.h" +#import "ENRMMarkdownTextView.h" +#import "ENRMSpoilerOverlayManager.h" +#import "ENRMSpoilerTapUtils.h" +#import "ENRMTailFadeInAnimator.h" +#import "ENRMTextInteractionUtils.h" +#import "ENRMTextRenderer.h" +#import "ENRMTextViewSetup.h" +#import "ENRMUIKit.h" +#import "EditMenuUtils.h" +#import "FontScaleObserver.h" +#import "FontUtils.h" +#import "HeightUpdateUtils.h" +#import "ImageRequestHeaderUtils.h" +#import "LinkContextMenuUtils.h" +#import "LinkPillContentUtils.h" +#import "LinkTapUtils.h" +#import "MarkdownASTNode.h" +#import "MarkdownAccessibilityElementBuilder.h" +#import "MarkdownExtractor.h" +#import "MeasurementCache.h" +#import "ParagraphStyleUtils.h" +#import "PasteboardUtils.h" +#import "RenderContext.h" +#import "RuntimeKeys.h" +#import "SelectionColorUtils.h" +#import "StylePropsUtils.h" +#import "TaskListTapUtils.h" + +#import +#import +#import +#import + +#import "RCTFabricComponentsPlugins.h" +#import +#import +#import + +using namespace facebook::react; + +typedef NS_OPTIONS(NSUInteger, ENRMDirtyFlags) { + ENRMDirtyNone = 0, + ENRMDirtyRender = 1 << 0, +}; + +@interface EnrichedMarkdownText () ++ (ENRMMd4cFlags *)flagsFromProps:(const EnrichedMarkdownTextMd4cFlagsStruct &)props; +- (void)setupTextView; +- (void)renderMarkdownContent:(NSString *)markdownString; +- (void)applyRenderedText:(NSMutableAttributedString *)attributedText; +- (void)textTapped:(ENRMTapRecognizer *)recognizer; +- (void)setupLayoutManager; +- (void)emitLinkPress:(NSString *)url sourceType:(NSString *)sourceType; +- (void)emitLinkLongPress:(NSString *)url; +- (void)emitLinkContextMenuItemPress:(NSString *)itemText pattern:(NSString *)pattern url:(NSString *)url; +- (void)emitImagePress:(NSString *)url altText:(NSString *)altText; +- (void)emitCodeBlockPress:(NSString *)code language:(NSString *)language; +- (void)emitTaskListItemPress:(NSInteger)index checked:(BOOL)checked text:(NSString *)text; +- (void)emitContextMenuItemPress:(NSString *)itemText + selectedText:(NSString *)selectedText + selectionStart:(NSUInteger)selectionStart + selectionEnd:(NSUInteger)selectionEnd; +@end + +#if !TARGET_OS_OSX +@interface EnrichedMarkdownText () +@end +#endif + +@implementation EnrichedMarkdownText { + ENRMPlatformTextView *_textView; + ENRMMarkdownParser *_parser; + NSString *_cachedMarkdown; + NSString *_renderedMarkdown; + StyleConfig *_config; + ENRMMd4cFlags *_md4cFlags; + BOOL _isGFM; + ENRMLinkRegexConfig *_linkRegex; + ENRMLinkRegexConfig *_inlineCodeLinkRegex; + + ENRMAsyncRenderCoordinator *_renderCoordinator; + + EnrichedMarkdownTextShadowNode::ConcreteState::Shared _state; + int _heightUpdateCounter; + + FontScaleObserver *_fontScaleObserver; + CGFloat _maxFontSizeMultiplier; + + CGFloat _lastElementMarginBottom; + BOOL _allowTrailingMargin; + BOOL _enableLinkPreview; + BOOL _enableTaskListItemToggle; + BOOL _enableImagePress; + BOOL _enableCodeBlockPress; + BOOL _streamingAnimation; + BOOL _forceHeightUpdateOnNextRender; + + size_t _renderedStyleFingerprint; + size_t _pendingStyleFingerprint; + + NSUInteger _previousTextLength; + ENRMTailFadeInAnimator *_fadeAnimator; + + AccessibilityInfo *_accessibilityInfo; + ENRMAccessibilityLabels *_accessibilityLabels; +#if !TARGET_OS_OSX + NSMutableArray *_accessibilityElements; +#else + NSMutableArray *_accessibilityElements; +#endif + BOOL _accessibilityNeedsRebuild; + + ENRMLinkContextMenus *_linkContextMenus; + NSArray *_contextMenuItemTexts; + NSArray *_contextMenuItemIcons; + ENRMSelectionMenuConfig _selectionMenuConfig; + ENRMSelectionMenuLabels _selectionMenuLabels; + + ENRMSpoilerOverlayManager *_spoilerManager; + + NSLineBreakStrategy _lineBreakStrategy; + + NSInteger _numberOfLines; + NSLineBreakMode _ellipsizeLineBreakMode; + + ENRMWritingDirectionMode _writingDirectionMode; + NSWritingDirection _resolvedLayoutDirection; + + ENRMDirtyFlags _dirtyFlags; + + ENRMAtomicSize _lastCommittedSize; + + ENRMLatexErrorCoordinator *_latexErrorCoordinator; +} + ++ (ComponentDescriptorProvider)componentDescriptorProvider +{ + return concreteComponentDescriptorProvider(); +} + ++ (ENRMMd4cFlags *)flagsFromProps:(const EnrichedMarkdownTextMd4cFlagsStruct &)props +{ + ENRMMd4cFlags *flags = [ENRMMd4cFlags defaultFlags]; + flags.underline = props.underline; + flags.superscript = props.superscript; + flags.subscript = props.subscript; + flags.latexMath = props.latexMath; + flags.highlight = props.highlight; + flags.hardSoftBreaks = props.hardSoftBreaks; + flags.preserveBlankLines = props.preserveBlankLines; + flags.admonitions = props.admonitions; + return flags; +} + +#pragma mark - Measuring and State + +/// The box the text actually lives in: `self.bounds` inset by the +/// `containerStyle` border and padding. +/// +/// Yoga hands `measureContent` an available size that already excludes those +/// insets, and `RCTViewComponentView` sizes `contentView` (our text view) to +/// `layoutMetrics.getContentFrame()`, so the shadow node's height and the text +/// view's frame are both content-box quantities. Measuring at `self.bounds` +/// instead overshoots by the horizontal insets, and because +/// `ENRMMeasureTextLayout` measures by resizing the live display container and +/// leaves it there (UIKit never re-syncs it - `widthTracksTextView` does not +/// apply with `scrollEnabled = NO`), the overshoot becomes the layout the user +/// sees: glyphs spill past the text view and get clipped, while the taller +/// content-width height Yoga committed shows up as blank space at the bottom. +/// +/// The text view's frame is authoritative, so this is zero-sized both before the +/// first layout metrics arrive and when the insets consume the whole component +/// width. Neither may fall back to `self.bounds`: that is the padded border box, +/// and in the second case it is a real layout the text would then be drawn +/// across. Callers skip measuring and laying out at a zero width instead. +/// +/// The frame, not the bounds: a `UITextView` is a scroll view, so its +/// `bounds.origin` is the content offset rather than the inset the segments of +/// `EnrichedMarkdown` get from the matching method. +- (CGRect)contentBounds +{ + return _textView.frame; +} + +- (CGSize)measureSize:(CGFloat)maxWidth +{ + CGSize size = ENRMMeasureMarkdownText(_textView, maxWidth, _config, _allowTrailingMargin, _lastElementMarginBottom); + if (CGSizeEqualToSize(size, CGSizeZero)) { + CGFloat defaultHeight = UIFontLineHeight([UIFont systemFontOfSize:16.0]); + return CGSizeMake(maxWidth, defaultHeight); + } + return size; +} + +- (CGSize)lastCommittedLayoutSize +{ + return _lastCommittedSize.load(); +} + +- (BOOL)hasRenderedMarkdown:(NSString *)markdown +{ + return _renderedMarkdown != nil && [_renderedMarkdown isEqualToString:markdown]; +} + +- (BOOL)hasRenderedWithStyleFingerprint:(size_t)fingerprint +{ + return _renderedStyleFingerprint == fingerprint; +} + +- (void)updateState:(const facebook::react::State::Shared &)state + oldState:(const facebook::react::State::Shared &)oldState +{ + _state = std::static_pointer_cast(state); + + if (oldState == nullptr) { + [self requestHeightUpdate]; + } +} + +/// Publishes the committed size to the streaming fast path's mailbox, and picks +/// up the Yoga-resolved direction inherited from any ancestor `direction` style. +/// In FirstStrong mode the direction feeds the neutral-paragraph fallback, so a +/// change requires a re-render of the cached markdown. +/// +/// The mailbox holds a content size, not the border box: `measureContent` +/// returns it straight to Yoga, which adds the `containerStyle` insets back on +/// top of whatever it gets, so storing `frame.size` would double-count them. +- (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics + oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics +{ + [super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics]; + + const auto contentSize = layoutMetrics.getContentFrame().size; + _lastCommittedSize.store(CGSizeMake(contentSize.width, contentSize.height)); + + NSWritingDirection resolved = _resolvedLayoutDirection; + if (layoutMetrics.layoutDirection == LayoutDirection::RightToLeft) { + resolved = NSWritingDirectionRightToLeft; + } else if (layoutMetrics.layoutDirection == LayoutDirection::LeftToRight) { + resolved = NSWritingDirectionLeftToRight; + } + + if (resolved != _resolvedLayoutDirection) { + _resolvedLayoutDirection = resolved; + if (_writingDirectionMode == ENRMWritingDirectionModeFirstStrong && _cachedMarkdown.length > 0) { + [self renderMarkdownContent:_cachedMarkdown]; + } + } +} + +- (void)requestHeightUpdate +{ + ENRMRequestHeightUpdate(_state, _heightUpdateCounter, self); +} + +// A block image resolved its box height after loading (maxHeight/aspectRatio +// sizing). The shadow node measured — and cached — this markdown with the +// pre-load fallback height, so drop those entries and re-measure. +- (void)imageAttachmentDidResolveLayout +{ + // The text around the attachment moved, and the spoiler overlays with it. + [_spoilerManager setNeedsUpdate]; + [_spoilerManager updateIfNeeded]; + + if (_renderedMarkdown.length > 0) { + facebook::react::MeasurementCache::shared().removeMatchingMarkdown(std::string(_renderedMarkdown.UTF8String)); + } + + CGRect contentBounds = [self contentBounds]; + if (contentBounds.size.width > 0) { + CGSize measured = [self measureSize:contentBounds.size.width]; + if (needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + static const auto defaultProps = std::make_shared(); + _props = defaultProps; + + self.backgroundColor = [RCTUIColor clearColor]; + _parser = [[ENRMMarkdownParser alloc] init]; + _linkContextMenus = [[ENRMLinkContextMenus alloc] init]; + __weak EnrichedMarkdownText *weakMenuSelf = self; + _linkContextMenus.onPress = ^(NSString *url, NSString *pattern, NSString *itemText) { + [weakMenuSelf emitLinkContextMenuItemPress:itemText pattern:pattern url:url]; + }; + _md4cFlags = [EnrichedMarkdownText flagsFromProps:defaultProps->md4cFlags]; + _isGFM = defaultProps->isGFM; + _linkRegex = ENRMLinkRegexConfigFromProps(defaultProps->linkRecognition.text); + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(defaultProps->linkRecognition.inlineCode); + + _renderCoordinator = + [[ENRMAsyncRenderCoordinator alloc] initWithQueueLabel:"com.swmansion.enriched.markdown.render"]; + + __weak __typeof(self) weakLatexSelf = self; + _latexErrorCoordinator = + [[ENRMLatexErrorCoordinator alloc] initWithEmit:^BOOL(NSString *source, NSString *message, BOOL displayMode) { + __typeof(self) strongSelf = weakLatexSelf; + if (!strongSelf) + return NO; + auto emitter = std::static_pointer_cast(strongSelf->_eventEmitter); + if (!emitter) + return NO; + emitter->onLatexError({ + .source = std::string(source.UTF8String ?: ""), + .message = std::string(message.UTF8String ?: ""), + .displayMode = displayMode ? true : false, + }); + return YES; + }]; + _maxFontSizeMultiplier = 0; + _allowTrailingMargin = NO; + _enableLinkPreview = YES; + _enableTaskListItemToggle = YES; + _enableImagePress = NO; + _enableCodeBlockPress = NO; + _forceHeightUpdateOnNextRender = NO; + _selectionMenuConfig = (ENRMSelectionMenuConfig){.copyAsMarkdown = YES, .copyImageURL = YES}; + _lineBreakStrategy = NSLineBreakStrategyNone; + _numberOfLines = 0; + _ellipsizeLineBreakMode = NSLineBreakByTruncatingTail; + _writingDirectionMode = ENRMWritingDirectionModeFirstStrong; + _resolvedLayoutDirection = + [[RCTI18nUtil sharedInstance] isRTL] ? NSWritingDirectionRightToLeft : NSWritingDirectionLeftToRight; + _dirtyFlags = ENRMDirtyNone; + + _fontScaleObserver = [[FontScaleObserver alloc] init]; + __weak EnrichedMarkdownText *weakSelf = self; + _fontScaleObserver.onChange = ^{ + EnrichedMarkdownText *strongSelf = weakSelf; + if (!strongSelf) + return; + if (strongSelf->_config != nil) { + [strongSelf->_config setFontScaleMultiplier:strongSelf->_fontScaleObserver.effectiveFontScale]; + } + if (strongSelf->_cachedMarkdown != nil && strongSelf->_cachedMarkdown.length > 0) { + strongSelf->_forceHeightUpdateOnNextRender = YES; + [strongSelf renderMarkdownContent:strongSelf->_cachedMarkdown]; + } + }; + + [self setupTextView]; + } + + return self; +} + +- (void)setupTextView +{ +#if !TARGET_OS_OSX + ENRMMarkdownTextView *markdownTextView = [[ENRMMarkdownTextView alloc] init]; + __weak EnrichedMarkdownText *weakCopyOwner = self; + markdownTextView.copySelectionHandler = ^(NSRange range) { + EnrichedMarkdownText *owner = weakCopyOwner; + if (!owner) + return; + NSAttributedString *text = owner->_textView.textStorage; + copyAttributedStringToPasteboard([text attributedSubstringFromRange:range], + markdownForRange(text, range, owner->_cachedMarkdown), owner -> _config); + }; + _textView = markdownTextView; + _textView.text = @""; +#else + _textView = [[ENRMContextMenuTextView alloc] init]; + _textView.string = @""; +#endif + ENRMConfigureMarkdownTextView(_textView); + _textView.delegate = self; + _textView.hidden = YES; + +#if TARGET_OS_OSX + __weak EnrichedMarkdownText *weakSelf = self; + ((ENRMContextMenuTextView *)_textView).contextMenuProvider = + ^NSMenu *_Nullable(NSMenu *baseMenu, NSTextView *textView) + { + EnrichedMarkdownText *strongSelf = weakSelf; + if (!strongSelf) { + return baseMenu; + } + NSArray *customItems = ENRMBuildContextMenuItems( + strongSelf->_contextMenuItemTexts, strongSelf->_contextMenuItemIcons, textView, + ^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) { + [strongSelf emitContextMenuItemPress:itemText + selectedText:selectedText + selectionStart:selectionStart + selectionEnd:selectionEnd]; + }); + return buildEditMenuForSelection(textView.textStorage, textView.selectedRange, strongSelf->_cachedMarkdown, + strongSelf->_config, @[ baseMenu ], customItems, + strongSelf -> _selectionMenuConfig); + }; +#endif + + ENRMTapRecognizer *tapRecognizer = [[ENRMTapRecognizer alloc] initWithTarget:self action:@selector(textTapped:)]; + [_textView addGestureRecognizer:tapRecognizer]; + + self.contentView = _textView; +} + +- (void)didAddSubview:(RCTUIView *)subview +{ + [super didAddSubview:subview]; + + if (subview == _textView) { + [self setupLayoutManager]; + } +} + +- (void)willRemoveSubview:(RCTUIView *)subview +{ + if (subview == _textView) { + ENRMDetachLayoutManager(_textView); + } + [super willRemoveSubview:subview]; +} + +- (void)setupLayoutManager +{ + ENRMAttachLayoutManager(_textView, _config); +} + +- (void)renderMarkdownContent:(NSString *)markdownString +{ + if (_renderCoordinator.blockAsyncRender) + return; + + _cachedMarkdown = [markdownString copy]; + + StyleConfig *config = [_config copy]; + ENRMMarkdownParser *parser = _parser; + ENRMMd4cFlags *md4cFlags = [_md4cFlags copy]; + BOOL isGFM = _isGFM; + ENRMLinkRegexConfig *linkRegex = _linkRegex; + ENRMLinkRegexConfig *inlineCodeLinkRegex = _inlineCodeLinkRegex; + + BOOL allowFontScaling = _fontScaleObserver.allowFontScaling; + CGFloat maxFontSizeMultiplier = _maxFontSizeMultiplier; + BOOL allowTrailingMargin = _allowTrailingMargin; + NSLineBreakStrategy lineBreakStrategy = _lineBreakStrategy; + ENRMWritingDirectionMode writingDirectionMode = _writingDirectionMode; + NSWritingDirection resolvedLayoutDirection = _resolvedLayoutDirection; + + __block ENRMRenderResult *result = nil; + + [_renderCoordinator + scheduleRender:^BOOL { + MarkdownASTNode *ast = [parser parseMarkdown:markdownString + flags:md4cFlags + isGFM:isGFM + linkRegex:linkRegex + inlineCodeLinkRegex:inlineCodeLinkRegex]; + if (!ast) + return NO; + + result = ENRMRenderASTNodes(ast.children, config, allowTrailingMargin, allowFontScaling, maxFontSizeMultiplier, + lineBreakStrategy); + ENRMApplyWritingDirectionMode(result.attributedText, writingDirectionMode, resolvedLayoutDirection); + return YES; + } + apply:^{ + self->_lastElementMarginBottom = result.lastElementMarginBottom; + self->_accessibilityInfo = result.accessibilityInfo; + self->_renderedStyleFingerprint = self->_pendingStyleFingerprint; + [self->_latexErrorCoordinator wireReporters:result.context.mathReporters]; + [self applyRenderedText:result.attributedText]; + }]; +} + +- (NSMutableAttributedString *)parseAndRenderMarkdown:(NSString *)markdownString +{ + MarkdownASTNode *ast = [_parser parseMarkdown:markdownString + flags:_md4cFlags + isGFM:_isGFM + linkRegex:_linkRegex + inlineCodeLinkRegex:_inlineCodeLinkRegex]; + if (!ast) { + return nil; + } + + ENRMRenderResult *result = + ENRMRenderASTNodes(ast.children, _config, _allowTrailingMargin, _fontScaleObserver.allowFontScaling, + _maxFontSizeMultiplier, _lineBreakStrategy); + ENRMApplyWritingDirectionMode(result.attributedText, _writingDirectionMode, _resolvedLayoutDirection); + + _lastElementMarginBottom = result.lastElementMarginBottom; + _accessibilityInfo = result.accessibilityInfo; + + return result.attributedText; +} + +/// Synchronous rendering for mock view measurement (no UI updates needed). +- (void)renderMarkdownSynchronously:(NSString *)markdownString +{ + if (!markdownString || markdownString.length == 0) { + return; + } + + _renderCoordinator.blockAsyncRender = YES; + _cachedMarkdown = [markdownString copy]; + + NSMutableAttributedString *attributedText = [self parseAndRenderMarkdown:markdownString]; + if (!attributedText) { + return; + } + + _textView.attributedText = attributedText; + _renderedMarkdown = [_cachedMarkdown copy]; + _renderedStyleFingerprint = _pendingStyleFingerprint; +} + +// Kept in sync with the view-free measurement so the rendered line count matches +// the measured height: both clamp a layout performed at the content width (see +// contentBounds), so the truncation falls on the same word. +// numberOfLines == 0 restores the unlimited default. +- (void)applyLineClampToTextContainer +{ + if (_numberOfLines > 0) { + _textView.textContainer.maximumNumberOfLines = _numberOfLines; + _textView.textContainer.lineBreakMode = _ellipsizeLineBreakMode; + } else { + _textView.textContainer.maximumNumberOfLines = 0; + _textView.textContainer.lineBreakMode = NSLineBreakByWordWrapping; + } +} + +- (void)applyRenderedText:(NSMutableAttributedString *)attributedText +{ + NSUInteger tailStart = _previousTextLength; + + NSLayoutManager *layoutManager = _textView.layoutManager; + if ([layoutManager isKindOfClass:[TextViewLayoutManager class]]) { + [layoutManager setValue:_config forKey:@"config"]; + } + + objc_setAssociatedObject(_textView.textContainer, kTextViewKey, _textView, OBJC_ASSOCIATION_ASSIGN); + + // Ensure the text container has unlimited height before setting content. + // updateLayoutMetrics may have shrunk the frame (and thus the text container) + // from a previous layout pass, which would clip the new attributed text. + CGRect contentBounds = [self contentBounds]; + CGFloat containerWidth = contentBounds.size.width; + if (containerWidth <= 0) { + containerWidth = _textView.textContainer.size.width; + } + _textView.textContainer.size = CGSizeMake(containerWidth, CGFLOAT_MAX); + [self applyLineClampToTextContainer]; + + _accessibilityElements = nil; + _accessibilityNeedsRebuild = YES; + + _textView.attributedText = attributedText; + _renderedMarkdown = [_cachedMarkdown copy]; + + [_textView.layoutManager invalidateLayoutForCharacterRange:NSMakeRange(0, attributedText.length) + actualCharacterRange:NULL]; + + // When bounds width is zero (recycled view not yet laid out), skip layout + // and measurement — layoutSubviews will handle it once the view has real + // bounds. Measuring with width=0 produces a bogus single-line measurement + // that corrupts the height sent to Yoga. + [_spoilerManager setNeedsUpdate]; + + if (contentBounds.size.width > 0) { + // Font/style changes can produce the same measured size before UIKit has + // fully refreshed layout, so force one Yoga update after those renders. + BOOL forceHeightUpdate = _forceHeightUpdateOnNextRender; + _forceHeightUpdateOnNextRender = NO; + + [_textView.layoutManager ensureLayoutForTextContainer:_textView.textContainer]; + ENRMSetNeedsDisplay(_textView); +#if !TARGET_OS_OSX + [self setNeedsLayout]; +#endif + + [_spoilerManager updateIfNeeded]; + + CGSize measured = [self measureSize:contentBounds.size.width]; + if (forceHeightUpdate || needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } + + if (_textView.hidden) { + dispatch_async(dispatch_get_main_queue(), ^{ self->_textView.hidden = NO; }); + } + + if (_streamingAnimation) { + if (!_fadeAnimator) { + _fadeAnimator = [[ENRMTailFadeInAnimator alloc] initWithTextView:_textView]; + } + [_fadeAnimator animateFrom:tailStart to:attributedText.length]; + _previousTextLength = attributedText.length; + } +} + +#if !TARGET_OS_OSX +- (void)layoutSubviews +{ + [super layoutSubviews]; + [_spoilerManager updateIfNeeded]; +} +#endif + +- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps +{ + const auto &oldViewProps = *std::static_pointer_cast(_props); + const auto &newViewProps = *std::static_pointer_cast(props); + + if (oldViewProps.markdown != newViewProps.markdown) { + _dirtyFlags |= ENRMDirtyRender; + } + + if (_config == nil) { + _config = [[StyleConfig alloc] init]; + [_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale]; + _spoilerManager = [[ENRMSpoilerOverlayManager alloc] initWithTextView:_textView config:_config]; + } + + if (applyMarkdownStyleToConfig(_config, newViewProps.markdownStyle, oldViewProps.markdownStyle)) { + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (ENRMImageRequestHeadersChanged(oldViewProps.imageRequestHeaders, newViewProps.imageRequestHeaders)) { + [_config setImageRequestHeaders:ENRMImageRequestHeadersFromProps(newViewProps.imageRequestHeaders)]; + _dirtyFlags |= ENRMDirtyRender; + } + + // Pill labels change layout, so treat new content like a style change. + if (ENRMLinkPillContentChanged(oldViewProps.linkPillContent, newViewProps.linkPillContent)) { + [_config setLinkPillContent:ENRMLinkPillContentFromProps(newViewProps.linkPillContent)]; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + NSLayoutManager *layoutManager = _textView.layoutManager; + if ([layoutManager isKindOfClass:[TextViewLayoutManager class]]) { + StyleConfig *currentConfig = [layoutManager valueForKey:@"config"]; + if (currentConfig != _config) { + [layoutManager setValue:_config forKey:@"config"]; + } + } + + if (_textView.selectable != newViewProps.selectable) { + _textView.selectable = newViewProps.selectable; + } + + if (newViewProps.selectionColor != oldViewProps.selectionColor) { + ENRMApplySelectionColor(_textView, newViewProps.selectionColor); + } + + if (newViewProps.allowFontScaling != oldViewProps.allowFontScaling) { + _fontScaleObserver.allowFontScaling = newViewProps.allowFontScaling; + + if (_config != nil) { + [_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale]; + } + + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.maxFontSizeMultiplier != oldViewProps.maxFontSizeMultiplier) { + _maxFontSizeMultiplier = newViewProps.maxFontSizeMultiplier; + + if (_config != nil) { + [_config setMaxFontSizeMultiplier:_maxFontSizeMultiplier]; + } + + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.allowTrailingMargin != oldViewProps.allowTrailingMargin) { + _allowTrailingMargin = newViewProps.allowTrailingMargin; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (!ENRMLinkRegexPropsEqual(oldViewProps.linkRecognition.text, newViewProps.linkRecognition.text)) { + _linkRegex = ENRMLinkRegexConfigFromProps(newViewProps.linkRecognition.text); + _dirtyFlags |= ENRMDirtyRender; + _forceHeightUpdateOnNextRender = YES; + } + if (!ENRMLinkRegexPropsEqual(oldViewProps.linkRecognition.inlineCode, newViewProps.linkRecognition.inlineCode)) { + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(newViewProps.linkRecognition.inlineCode); + _dirtyFlags |= ENRMDirtyRender; + _forceHeightUpdateOnNextRender = YES; + } + + if (newViewProps.md4cFlags.underline != oldViewProps.md4cFlags.underline || + newViewProps.md4cFlags.superscript != oldViewProps.md4cFlags.superscript || + newViewProps.md4cFlags.subscript != oldViewProps.md4cFlags.subscript || + newViewProps.md4cFlags.latexMath != oldViewProps.md4cFlags.latexMath || + newViewProps.md4cFlags.highlight != oldViewProps.md4cFlags.highlight || + newViewProps.md4cFlags.hardSoftBreaks != oldViewProps.md4cFlags.hardSoftBreaks || + newViewProps.md4cFlags.preserveBlankLines != oldViewProps.md4cFlags.preserveBlankLines || + newViewProps.md4cFlags.admonitions != oldViewProps.md4cFlags.admonitions) { + _md4cFlags = [EnrichedMarkdownText flagsFromProps:newViewProps.md4cFlags]; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.isGFM != oldViewProps.isGFM) { + _isGFM = newViewProps.isGFM; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + _enableLinkPreview = newViewProps.enableLinkPreview; + _enableTaskListItemToggle = newViewProps.enableTaskListItemToggle; + _enableImagePress = newViewProps.enableImagePress; + _enableCodeBlockPress = newViewProps.enableCodeBlockPress; + + if (ENRMLinkContextMenuItemsChanged(oldViewProps.linkContextMenuItems, newViewProps.linkContextMenuItems)) { + _linkContextMenus.entries = ENRMLinkContextMenuEntriesFromProps(newViewProps.linkContextMenuItems); + } + + if (ENRMContextMenuItemsChanged(oldViewProps.contextMenuItems, newViewProps.contextMenuItems)) { + _contextMenuItemTexts = ENRMContextMenuTextsFromItems(newViewProps.contextMenuItems); + _contextMenuItemIcons = ENRMContextMenuIconsFromItems(newViewProps.contextMenuItems); + } + + _selectionMenuLabels = ENRMParseSelectionMenuLabels(newViewProps.selectionMenuConfig); + _selectionMenuConfig = + ENRMBuildSelectionMenuConfig(_selectionMenuLabels, newViewProps.selectionMenuConfig.copyAsMarkdown, + newViewProps.selectionMenuConfig.copyImageUrl); + + if (ENRMAccessibilityLabelsChanged(oldViewProps.accessibilityLabels, newViewProps.accessibilityLabels)) { + _accessibilityLabels = [[ENRMAccessibilityLabels alloc] init]; + _accessibilityLabels.bulletPoint = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.bulletPoint.c_str()]; + _accessibilityLabels.nestedBulletPoint = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.nestedBulletPoint.c_str()]; + _accessibilityLabels.orderedItem = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.orderedItem.c_str()]; + _accessibilityLabels.nestedOrderedItem = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.list.nestedOrderedItem.c_str()]; + _accessibilityLabels.blockquote = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.blockquote.quote.c_str()]; + _accessibilityLabels.nestedBlockquote = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.blockquote.nestedQuote.c_str()]; + _accessibilityLabels.tableRow = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.table.row.c_str()]; + _accessibilityLabels.mathEquation = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.math.equation.c_str()]; + _accessibilityLabels.rotorHeadings = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.headings.c_str()]; + _accessibilityLabels.rotorLinks = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.links.c_str()]; + _accessibilityLabels.rotorImages = + [[NSString alloc] initWithUTF8String:newViewProps.accessibilityLabels.rotor.images.c_str()]; + _accessibilityNeedsRebuild = YES; + } + + if (newViewProps.streamingAnimation != oldViewProps.streamingAnimation) { + _streamingAnimation = newViewProps.streamingAnimation; + if (_streamingAnimation) { + _previousTextLength = ENRMGetAttributedText(_textView).length; + } else { + [_fadeAnimator cancel]; + _fadeAnimator = nil; + _previousTextLength = 0; + } + } + + if (newViewProps.spoilerOverlay != oldViewProps.spoilerOverlay) { + NSString *modeStr = [[NSString alloc] initWithUTF8String:newViewProps.spoilerOverlay.c_str()]; + _spoilerManager.spoilerOverlay = ENRMSpoilerOverlayFromString(modeStr); + } + + if (newViewProps.lineBreakStrategyIOS != oldViewProps.lineBreakStrategyIOS) { + NSString *strategy = [[NSString alloc] initWithUTF8String:newViewProps.lineBreakStrategyIOS.c_str()]; + _lineBreakStrategy = ENRMResolveLineBreakStrategy(strategy); + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.writingDirection != oldViewProps.writingDirection) { + NSString *value = [[NSString alloc] initWithUTF8String:newViewProps.writingDirection.c_str()]; + _writingDirectionMode = ENRMResolveWritingDirectionMode(value); + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.numberOfLines != oldViewProps.numberOfLines) { + _numberOfLines = (NSInteger)newViewProps.numberOfLines; + [self applyLineClampToTextContainer]; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (newViewProps.ellipsizeMode != oldViewProps.ellipsizeMode) { + _ellipsizeLineBreakMode = + ENRMResolveEllipsizeLineBreakMode([[NSString alloc] initWithUTF8String:newViewProps.ellipsizeMode.c_str()]); + [self applyLineClampToTextContainer]; + _forceHeightUpdateOnNextRender = YES; + _dirtyFlags |= ENRMDirtyRender; + } + + if (_dirtyFlags & ENRMDirtyRender) { + _pendingStyleFingerprint = + computeStyleFingerprint(newViewProps.markdownStyle) ^ std::hash{}(newViewProps.allowTrailingMargin); + NSString *markdownString = [[NSString alloc] initWithUTF8String:newViewProps.markdown.c_str()]; + [self renderMarkdownContent:markdownString]; + _dirtyFlags &= ~ENRMDirtyRender; + } + + [super updateProps:props oldProps:oldProps]; +} + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + + if (self.window && _renderedMarkdown != nil) { + _textView.hidden = NO; + // Refresh in place: RCTViewComponentView owns the text view's frame and has + // already set it to the content frame, so re-assigning self.bounds here would + // drop the containerStyle insets (see contentBounds). + ENRMRefreshTextViewLayout(_textView); + + [_spoilerManager setNeedsUpdate]; + [_spoilerManager updateIfNeeded]; + + CGRect contentBounds = [self contentBounds]; + if (contentBounds.size.width > 0) { + CGSize measured = [self measureSize:contentBounds.size.width]; + if (needsHeightUpdate(measured, contentBounds)) { + [self requestHeightUpdate]; + } + } + } +} + +- (void)prepareForRecycle +{ + const auto resetProps = std::make_shared(); + _props = resetProps; + [_renderCoordinator invalidate]; + + [_fadeAnimator cancel]; + _fadeAnimator = nil; + _previousTextLength = 0; + _streamingAnimation = NO; + _forceHeightUpdateOnNextRender = NO; + _cachedMarkdown = nil; + _renderedMarkdown = nil; + _config = nil; + _md4cFlags = [EnrichedMarkdownText flagsFromProps:resetProps->md4cFlags]; + _isGFM = resetProps->isGFM; + _linkRegex = ENRMLinkRegexConfigFromProps(resetProps->linkRecognition.text); + _inlineCodeLinkRegex = ENRMLinkRegexConfigFromProps(resetProps->linkRecognition.inlineCode); + _maxFontSizeMultiplier = 0; + _lastElementMarginBottom = 0; + _allowTrailingMargin = NO; + _lineBreakStrategy = NSLineBreakStrategyNone; + _writingDirectionMode = ENRMWritingDirectionModeFirstStrong; + _renderedStyleFingerprint = 0; + _pendingStyleFingerprint = 0; + _linkContextMenus.entries = @[]; + _contextMenuItemTexts = nil; + _contextMenuItemIcons = nil; + _fontScaleObserver.allowFontScaling = resetProps->allowFontScaling; + _accessibilityLabels = nil; + _accessibilityElements = nil; + _accessibilityInfo = nil; + _accessibilityNeedsRebuild = NO; + [_spoilerManager removeAllOverlays]; + _spoilerManager = nil; + if (_textView != nil) { + ENRMSetAttributedText(_textView, [[NSAttributedString alloc] initWithString:@""]); + _textView.hidden = YES; + } + + [super prepareForRecycle]; +} + +Class EnrichedMarkdownTextCls(void) +{ + return EnrichedMarkdownText.class; +} + +- (facebook::react::SharedTouchEventEmitter)touchEventEmitterAtPoint:(CGPoint)point +{ + if (_textView) { + CGPoint textViewPoint = [self convertPoint:point toView:_textView]; + if (isPointOnInteractiveElement(_textView, textViewPoint, _enableImagePress, _enableCodeBlockPress)) { + return nil; + } + } + + return [super touchEventEmitterAtPoint:point]; +} + +- (void)emitLinkPress:(NSString *)url sourceType:(NSString *)sourceType +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onLinkPress({.url = std::string(url.UTF8String), .sourceType = std::string(sourceType.UTF8String)}); +} + +- (void)emitLinkLongPress:(NSString *)url +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onLinkLongPress({.url = std::string(url.UTF8String)}); +} + +- (void)emitLinkContextMenuItemPress:(NSString *)itemText pattern:(NSString *)pattern url:(NSString *)url +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) { + emitter->onLinkContextMenuItemPress({.url = std::string(url.UTF8String), + .pattern = std::string(pattern.UTF8String), + .itemText = std::string(itemText.UTF8String)}); + } +} + +- (void)emitImagePress:(NSString *)url altText:(NSString *)altText +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onImagePress({.url = std::string(url.UTF8String ?: ""), .altText = std::string(altText.UTF8String ?: "")}); +} + +- (void)emitCodeBlockPress:(NSString *)code language:(NSString *)language +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onCodeBlockPress( + {.code = std::string(code.UTF8String ?: ""), .language = std::string(language.UTF8String ?: "")}); +} + +- (void)emitTaskListItemPress:(NSInteger)index checked:(BOOL)checked text:(NSString *)text +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onTaskListItemPress({.index = (int)index, .checked = checked, .text = std::string(text.UTF8String ?: "")}); +} + +- (void)emitContextMenuItemPress:(NSString *)itemText + selectedText:(NSString *)selectedText + selectionStart:(NSUInteger)selectionStart + selectionEnd:(NSUInteger)selectionEnd +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (emitter) + emitter->onContextMenuItemPress({ + .itemText = std::string(itemText.UTF8String), + .selectedText = std::string(selectedText.UTF8String), + .selectionStart = (int)selectionStart, + .selectionEnd = (int)selectionEnd, + }); +} + +- (void)updateEventEmitter:(const facebook::react::EventEmitter::Shared &)eventEmitter +{ + [super updateEventEmitter:eventEmitter]; + [_latexErrorCoordinator flushPending]; +} + +- (void)textTapped:(ENRMTapRecognizer *)recognizer +{ + ENRMPlatformTextView *textView = (ENRMPlatformTextView *)recognizer.view; + + if (_enableTaskListItemToggle && + handleTaskListTapWithSharedLogic( + textView, recognizer, &self->_cachedMarkdown, self->_config, + ^(NSInteger index, BOOL checked, NSString *itemText) { + [self emitTaskListItemPress:index checked:checked text:itemText]; + }, + ^(NSString *updatedMarkdown) { [self renderMarkdownContent:updatedMarkdown]; })) { + return; + } + + if (handleSpoilerTap(textView, recognizer, _spoilerManager)) { + return; + } + + if (ENRMHandleTapOnTextView(textView, recognizer, ^(NSString *url, NSString *sourceType) { + [self emitLinkPress:url sourceType:sourceType]; + })) { + return; + } + + if (_enableImagePress) { + NSDictionary *image = imageAtTapLocation(textView, recognizer); + if (image) { + [self emitImagePress:image[@"url"] altText:image[@"altText"]]; + return; + } + } + + // Skip while text is selected so the tap clears the selection instead of + // firing the press (matches the web guard). + if (_enableCodeBlockPress && textView.selectedRange.length == 0) { + NSDictionary *codeBlock = codeBlockAtTapLocation(textView, recognizer); + if (codeBlock) { + [self emitCodeBlockPress:codeBlock[@"code"] language:codeBlock[@"language"]]; + return; + } + } +} + +#pragma mark - UITextViewDelegate (Link Interaction) + +#if !TARGET_OS_OSX +- (UITextItemMenuConfiguration *)textView:(UITextView *)textView + menuConfigurationForTextItem:(UITextItem *)textItem + defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0)) +{ + __weak EnrichedMarkdownText *weakSelf = self; + return ENRMLinkMenuConfigurationForTextItem(textView, textItem, defaultMenu, _linkContextMenus, _enableLinkPreview, + ^(NSString *url) { [weakSelf emitLinkLongPress:url]; }); +} + +- (ENRMLinkContextMenus *)linkContextMenusForTextView:(UITextView *)textView +{ + return _linkContextMenus; +} + +- (BOOL)textView:(ENRMPlatformTextView *)textView + shouldInteractWithURL:(NSURL *)URL + inRange:(NSRange)characterRange + interaction:(UITextItemInteraction)interaction +{ + if (interaction != UITextItemInteractionPresentActions) { + return YES; + } + + NSString *urlString = linkURLAtRange(textView, characterRange); + + // A link with a menu is presented by the iOS 17 callback above and must not be vetoed here. + if ([_linkContextMenus hasMenuForURL:urlString]) + return YES; + + if (!urlString || _enableLinkPreview) { + return YES; + } + + [self emitLinkLongPress:urlString]; + return NO; +} + +#pragma mark - UITextViewDelegate (Edit Menu) + +// TODO: Remove API_AVAILABLE(ios(16.0)) guard when the minimum iOS deployment target in RN is bumped to 16. +- (UIMenu *)textView:(ENRMPlatformTextView *)textView + editMenuForTextInRange:(NSRange)range + suggestedActions:(NSArray *)suggestedActions API_AVAILABLE(ios(16.0)) +{ + __weak EnrichedMarkdownText *weakSelf = self; + ENRMContextMenuPressHandler handler = + ^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) { + EnrichedMarkdownText *strongSelf = weakSelf; + if (strongSelf) + [strongSelf emitContextMenuItemPress:itemText + selectedText:selectedText + selectionStart:selectionStart + selectionEnd:selectionEnd]; + }; + NSMutableArray *customActions = + ENRMBuildContextMenuActions(_contextMenuItemTexts, _contextMenuItemIcons, textView, range, handler); + + return buildEditMenuForSelection(textView.attributedText, range, _cachedMarkdown, _config, suggestedActions, + customActions, _selectionMenuConfig); +} +#endif + +#pragma mark - Accessibility (VoiceOver Navigation) + +- (void)rebuildAccessibilityElementsIfNeeded +{ + if (!_accessibilityNeedsRebuild) { + return; + } + _accessibilityNeedsRebuild = NO; +#if !TARGET_OS_OSX + _accessibilityElements = [MarkdownAccessibilityElementBuilder buildElementsForTextView:_textView + info:_accessibilityInfo + labels:_accessibilityLabels + container:self]; +#else + _accessibilityElements = [NSMutableArray array]; +#endif +} + +- (BOOL)isAccessibilityElement +{ + return NO; +} + +- (NSInteger)accessibilityElementCount +{ + [self rebuildAccessibilityElementsIfNeeded]; + return _accessibilityElements.count; +} + +- (id)accessibilityElementAtIndex:(NSInteger)index +{ + [self rebuildAccessibilityElementsIfNeeded]; + if (index < 0 || index >= (NSInteger)_accessibilityElements.count) { + return nil; + } + return _accessibilityElements[index]; +} + +- (NSInteger)indexOfAccessibilityElement:(id)element +{ + [self rebuildAccessibilityElementsIfNeeded]; + return [_accessibilityElements indexOfObject:element]; +} + +- (NSArray *)accessibilityElements +{ + [self rebuildAccessibilityElementsIfNeeded]; + return _accessibilityElements; +} + +#if !TARGET_OS_OSX +- (NSArray *)accessibilityCustomRotors +{ + [self rebuildAccessibilityElementsIfNeeded]; + return [MarkdownAccessibilityElementBuilder buildRotorsFromElements:_accessibilityElements + labels:_accessibilityLabels]; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.h new file mode 100644 index 000000000000..b0247d7cb0c5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.h @@ -0,0 +1,51 @@ +#pragma once +#import "ENRMUIKit.h" + +@class StyleConfig; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Adopted by component views that host markdown text. Notified when a block + * image resolves its box height after loading (maxHeight/aspectRatio sizing), + * so the view can drop stale cached measurements and request a height update. + */ +@protocol ENRMImageLayoutObserver +- (void)imageAttachmentDidResolveLayout; +@end + +@interface RCTUIView (ENRMImageLayoutObserver) +/** + * Nearest ancestor (self included) adopting ENRMImageLayoutObserver, walking up + * the superview chain. Returns nil when none is found. + */ +- (nullable id)enrm_imageLayoutObserver; +@end + +/** + * Custom NSTextAttachment for rendering markdown images. + * Images are loaded asynchronously and scaled dynamically based on text container width. + * Supports inline and block images with custom height and border radius from config. + */ +@interface ENRMImageAttachment : NSTextAttachment + +@property (nonatomic, readonly) NSString *imageURL; +@property (nonatomic, readonly) BOOL isInline; + +/** + * Invoked on the main thread whenever the image finishes loading/processing. + * Used by self-drawing hosts (e.g. a table grid) that rasterize the attributed + * string via -drawWithRect: and therefore never get a live text view for the + * attachment's normal -refreshDisplay invalidation to reach. Such hosts set this + * to trigger their own redraw (e.g. -setNeedsDisplay). + */ +@property (nonatomic, copy, nullable) void (^onImageLoaded)(void); + ++ (instancetype)attachmentForURL:(NSString *)imageURL config:(StyleConfig *)config isInline:(BOOL)isInline; + ++ (NSCache *)originalImageCache; ++ (NSCache *)processedImageCache; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.m new file mode 100644 index 000000000000..bf2ae56364c7 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMImageAttachment.m @@ -0,0 +1,398 @@ +#import "ENRMImageAttachment.h" +#import "ENRMImageDownloader.h" +#import "ENRMUIKit.h" +#import "RuntimeKeys.h" +#import "StyleConfig.h" +#import + +#define CACHE_KEY_PROCESSED(url, w, h, r, m) [NSString stringWithFormat:@"%@_w%.1f_h%.1f_r%.1f_m%@", url, w, h, r, m] + +static NSCache *_originalImageCache; +static NSCache *_processedImageCache; + +@implementation RCTUIView (ENRMImageLayoutObserver) + +- (id)enrm_imageLayoutObserver +{ + RCTUIView *view = self; + while (view && ![view conformsToProtocol:@protocol(ENRMImageLayoutObserver)]) { + view = view.superview; + } + return (id)view; +} + +@end + +@interface ENRMImageAttachment () + +@property (nonatomic, copy) NSString *imageURL; +@property (nonatomic, copy, nullable) NSDictionary *requestHeaders; +@property (nonatomic, copy) NSString *cacheKey; +@property (nonatomic, assign) BOOL isInline; +@property (nonatomic, assign) CGFloat cachedHeight; +@property (nonatomic, assign) CGFloat cachedMaxHeight; +@property (nonatomic, assign) CGFloat cachedAspectRatio; +@property (nonatomic, copy) NSString *cachedResizeMode; +@property (nonatomic, assign) CGFloat cachedBorderRadius; +@property (nonatomic, weak) NSTextContainer *textContainer; +@property (nonatomic, weak) ENRMPlatformTextView *textView; +@property (nonatomic, strong) RCTUIImage *originalImage; +@property (nonatomic, strong) RCTUIImage *loadedImage; +@property (nonatomic, strong) RCTUIImage *placeholderImage; +@property (nonatomic, copy) NSString *lastProcessedKey; + +@end + +@implementation ENRMImageAttachment + ++ (NSCache *)originalImageCache +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _originalImageCache = [[NSCache alloc] init]; + _originalImageCache.countLimit = 50; + _originalImageCache.totalCostLimit = 1024 * 1024 * 20; // 20 MB + }); + return _originalImageCache; +} + ++ (NSCache *)processedImageCache +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _processedImageCache = [[NSCache alloc] init]; + _processedImageCache.countLimit = 100; + _processedImageCache.totalCostLimit = 1024 * 1024 * 30; // 30 MB + }); + return _processedImageCache; +} + ++ (instancetype)attachmentForURL:(NSString *)imageURL config:(StyleConfig *)config isInline:(BOOL)isInline +{ + // Always a fresh instance, never shared across positions: the table renderer can draw + // the same image URL at a different width than a copy outside the table, and a shared + // NSTextAttachment would thrash its single last-processed width into a redraw loop. The + // image caches keep fresh instances cheap (no re-fetch or re-scale). + return [[self alloc] initWithImageURL:imageURL config:config isInline:isInline]; +} + +- (instancetype)initWithImageURL:(NSString *)imageURL config:(StyleConfig *)config isInline:(BOOL)isInline +{ + self = [super init]; + if (self) { + _imageURL = imageURL; + _requestHeaders = [[config imageRequestHeaders] copy]; + _cacheKey = ENRMImageCacheKey(imageURL, _requestHeaders); + _isInline = isInline; + + _cachedHeight = isInline ? [config inlineImageSize] : [config imageHeight]; + _cachedMaxHeight = [config imageMaxHeight]; + _cachedAspectRatio = [config imageAspectRatio]; + _cachedResizeMode = [config imageResizeMode]; + _cachedBorderRadius = [config imageBorderRadius]; + + [self setupPlaceholder]; + [self startDownloadingImage]; + } + return self; +} + +- (CGFloat)resolvedBoxHeightForWidth:(CGFloat)width +{ + if (self.cachedAspectRatio > 0 && width > 0) { + return width / self.cachedAspectRatio; + } + + if (self.cachedMaxHeight > 0) { + RCTUIImage *source = self.originalImage; + if (source && width > 0 && source.size.width > 0 && source.size.height > 0) { + CGFloat fitted = width * source.size.height / source.size.width; + return MIN(self.cachedMaxHeight, fitted); + } + // Intrinsic size not known yet — fall back to the full max height; the box + // shrinks once the image loads and layout is invalidated. + return self.cachedMaxHeight; + } + + return self.cachedHeight; +} + +// True when resizeMode is unset ('') - legacy always implies a fixed height box. + +- (BOOL)isLegacyBlockSizing +{ + return !self.isInline && self.cachedResizeMode.length == 0; +} + +- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer + proposedLineFragment:(CGRect)lineFragment + glyphPosition:(CGPoint)position + characterIndex:(NSUInteger)characterIndex +{ + CGFloat height = self.cachedHeight; + CGFloat width = self.isInline ? height : (lineFragment.size.width > 0 ? lineFragment.size.width : height); + + if (!self.isInline) { + height = [self resolvedBoxHeightForWidth:width]; + return CGRectMake(0, 0, width, height); + } + + UIFont *appliedFont = nil; + NSLayoutManager *layoutManager = textContainer.layoutManager; + NSTextStorage *textStorage = layoutManager.textStorage; + + if (textStorage && characterIndex < textStorage.length) { + appliedFont = [textStorage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL]; + } + + CGFloat verticalOffset; + if (appliedFont) { + verticalOffset = (appliedFont.capHeight - height) / 2.0; + } else { + verticalOffset = (lineFragment.size.height - height) / 2.0; + } + + return CGRectMake(0, verticalOffset, width, height); +} + +- (RCTUIImage *)imageForBounds:(CGRect)imageBounds + textContainer:(NSTextContainer *)textContainer + characterIndex:(NSUInteger)characterIndex +{ + self.textContainer = textContainer; + + if (self.originalImage && imageBounds.size.width > 0) { + self.bounds = imageBounds; + [self processAndApplyImage:self.originalImage withTargetWidth:imageBounds.size.width]; + } + + return self.loadedImage ?: self.placeholderImage; +} + +- (void)handleLoadedImage:(RCTUIImage *)image +{ + if (!image) + return; + + // The downloader completes synchronously on cache hits, which can happen on the render queue + if (!NSThread.isMainThread) { + dispatch_async(dispatch_get_main_queue(), ^{ [self handleLoadedImage:image]; }); + return; + } + + self.originalImage = image; + // UIKit reads the plain image property for save/drag/copy — it must hold the original + self.image = image; + CGFloat targetWidth = self.isInline ? self.cachedHeight : self.bounds.size.width; + + // Defer processing if we don't have valid bounds yet (common for non-inline block images) + if (!self.isInline && targetWidth <= 0) { + return; + } + + [self processAndApplyImage:image withTargetWidth:targetWidth]; +} + +- (void)processAndApplyImage:(RCTUIImage *)image withTargetWidth:(CGFloat)targetWidth +{ + if (targetWidth <= 0) + return; + + CGFloat boxHeight = self.isInline ? self.cachedHeight : [self resolvedBoxHeightForWidth:targetWidth]; + + NSString *processedKey = + CACHE_KEY_PROCESSED(self.cacheKey, targetWidth, boxHeight, self.cachedBorderRadius, self.cachedResizeMode); + + if ([processedKey isEqualToString:self.lastProcessedKey]) + return; + self.lastProcessedKey = processedKey; + + RCTUIImage *cachedProcessed = [[ENRMImageAttachment processedImageCache] objectForKey:processedKey]; + + if (cachedProcessed) { + self.loadedImage = cachedProcessed; + [self refreshDisplay]; + return; + } + + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + __strong typeof(weakSelf) strongSelf = weakSelf; + if (!strongSelf) + return; + + RCTUIImage *processedImage = [strongSelf createScaledImage:image + toWidth:targetWidth + height:boxHeight + borderRadius:strongSelf.cachedBorderRadius]; + + if (processedImage) { + [[ENRMImageAttachment processedImageCache] setObject:processedImage + forKey:processedKey + cost:ENRMImageByteCost(processedImage)]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + strongSelf.loadedImage = processedImage; + if (strongSelf.isInline) { + strongSelf.bounds = CGRectMake(0, 0, strongSelf.cachedHeight, strongSelf.cachedHeight); + } + [strongSelf refreshDisplay]; + }); + }); +} + +- (RCTUIImage *)createScaledImage:(RCTUIImage *)image + toWidth:(CGFloat)targetWidth + height:(CGFloat)targetHeight + borderRadius:(CGFloat)radius +{ + CGFloat sourceWidth = image.size.width; + CGFloat sourceHeight = image.size.height; + if (sourceWidth <= 0 || sourceHeight <= 0) + return nil; + + CGSize source = CGSizeMake(sourceWidth, sourceHeight); + CGSize box = CGSizeMake(targetWidth, targetHeight); + BOOL legacy = [self isLegacyBlockSizing]; + + CGRect drawingRect; + if (self.isInline || legacy) { + CGFloat drawingWidth, drawingHeight; + if (!self.isInline) { + CGFloat aspectRatioScale = targetWidth / sourceWidth; + drawingWidth = targetWidth; + drawingHeight = sourceHeight * aspectRatioScale; + } else { + drawingWidth = targetWidth; + drawingHeight = targetHeight; + } + drawingRect = CGRectMake((targetWidth - drawingWidth) / 2.0, (targetHeight - drawingHeight) / 2.0, drawingWidth, + drawingHeight); + } else { + drawingRect = [self drawingRectForResizeMode:self.cachedResizeMode source:source box:box]; + } + + RCTUIGraphicsImageRenderer *renderer = ImageRendererForSize(box); + + return [renderer imageWithActions:^(RCTUIGraphicsImageRendererContext *context) { + if (radius > 0) { + CGRect clipRect = CGRectIntersection(CGRectMake(0, 0, targetWidth, targetHeight), drawingRect); + UIBezierPath *path = UIBezierPathWithRoundedRect(clipRect, radius); + [path addClip]; + } + [image drawInRect:drawingRect]; + }]; +} + +- (CGRect)drawingRectForResizeMode:(NSString *)mode source:(CGSize)source box:(CGSize)box +{ + if ([mode isEqualToString:@"stretch"]) { + return CGRectMake(0, 0, box.width, box.height); + } + + CGFloat widthScale = box.width / source.width; + CGFloat heightScale = box.height / source.height; + + CGFloat scale; + if ([mode isEqualToString:@"contain"]) { + scale = MIN(widthScale, heightScale); + } else if ([mode isEqualToString:@"center"]) { + scale = MIN(1.0, MIN(widthScale, heightScale)); + } else if ([mode isEqualToString:@"none"]) { + scale = 1.0; + } else { // cover (default) + scale = MAX(widthScale, heightScale); + } + + CGFloat drawingWidth = source.width * scale; + CGFloat drawingHeight = source.height * scale; + return CGRectMake((box.width - drawingWidth) / 2.0, (box.height - drawingHeight) / 2.0, drawingWidth, drawingHeight); +} + +- (void)startDownloadingImage +{ + if (self.imageURL.length == 0) + return; + + __weak typeof(self) weakSelf = self; + [[ENRMImageDownloader shared] downloadURL:self.imageURL + headers:self.requestHeaders + completion:^(RCTUIImage *image) { [weakSelf handleLoadedImage:image]; }]; +} + +- (void)refreshDisplay +{ + // Notify self-drawing hosts (e.g. a table grid) that rasterize us via + // -drawWithRect: and have no live text view for the invalidation below to reach. + if (self.onImageLoaded) { + self.onImageLoaded(); + } + + UITextView *textView = [self fetchAssociatedTextView]; + if (!textView) + return; + + NSRange range = [self findAttachmentRangeInText:textView.textStorage]; + if (range.location != NSNotFound) { + [textView.layoutManager invalidateDisplayForCharacterRange:range]; + if (!self.isInline) { + [textView.layoutManager invalidateLayoutForCharacterRange:range actualCharacterRange:NULL]; + [self notifyImageLayoutObserver:textView]; + } + } +} + +// With maxHeight/aspectRatio sizing the box height can settle after the image +// loads, while the component was measured (and its size cached) with the +// pre-load fallback. Notify the hosting component so it can re-measure. +// Dispatched async: refreshDisplay can run mid-layout (imageForBounds) and +// re-measuring would re-enter the layout manager. +- (void)notifyImageLayoutObserver:(UITextView *)textView +{ + // Only maxHeight/aspectRatio boxes can change height after load; a fixed + // height box (legacy or explicit resizeMode) never needs a re-measure. + if (self.cachedMaxHeight <= 0 && self.cachedAspectRatio <= 0) + return; + + id observer = [textView enrm_imageLayoutObserver]; + if (!observer) + return; + + dispatch_async(dispatch_get_main_queue(), ^{ [observer imageAttachmentDidResolveLayout]; }); +} + +- (ENRMPlatformTextView *)fetchAssociatedTextView +{ + if (self.textView) + return self.textView; + if (!self.textContainer) + return nil; + self.textView = objc_getAssociatedObject(self.textContainer, kTextViewKey); + return self.textView; +} + +- (void)setupPlaceholder +{ + CGFloat size = self.cachedHeight; + self.bounds = CGRectMake(0, 0, size, size); + RCTUIGraphicsImageRenderer *renderer = [[RCTUIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(1, 1)]; + self.placeholderImage = [renderer imageWithActions:^(RCTUIGraphicsImageRendererContext *ctx){}]; +} + +- (NSRange)findAttachmentRangeInText:(NSAttributedString *)attributedString +{ + __block NSRange foundRange = NSMakeRange(NSNotFound, 0); + [attributedString enumerateAttribute:NSAttachmentAttributeName + inRange:NSMakeRange(0, attributedString.length) + options:0 + usingBlock:^(id value, NSRange range, BOOL *stop) { + if (value == self) { + foundRange = range; + *stop = YES; + } + }]; + return foundRange; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.h new file mode 100644 index 000000000000..985c394e5495 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.h @@ -0,0 +1,47 @@ +#pragma once +#import "ENRMUIKit.h" + +#if !TARGET_OS_OSX +@class LinkVariantConfig; + +NS_ASSUME_NONNULL_BEGIN + +/** + * A link presented as a pill. Like image and inline-math attachments it is a + * single U+FFFC in text storage, laid out and drawn by TextKit natively. + * The link's own rendered text is kept here; ENRMLinkPillText.h puts it back + * wherever text leaves the view (copy, export, accessibility). + */ +@interface ENRMLinkPillAttachment : NSTextAttachment +@property (nonatomic, readonly) CGFloat boxHeight; +/// The minimum line height the pill asks of the block that holds it (`pill.lineHeight`); 0 for none. +@property (nonatomic, assign) CGFloat lineHeight; +/// The text the pill shows. +@property (nonatomic, readonly) NSString *label; +/// Visible label, followed by the original link text when they differ. +@property (nonatomic, readonly) NSString *linkAccessibilityLabel; +@property (nonatomic, readonly) NSAttributedString *originalText; +/// The radius the pill's corners are drawn with. +@property (nonatomic, readonly) CGFloat cornerRadius; +/// Draws nothing while set. The text view sets it while the pill is lifted for its menu, +/// so that the lifted copy is the only one on screen. +@property (nonatomic, assign) BOOL lifted; +/// Called on the main thread when an asynchronously loaded icon settles. For hosts that draw the +/// string themselves (the table grid) and have no text view for the attachment to invalidate. +@property (nonatomic, copy, nullable) void (^onIconLoaded)(void); + +/// `variant.pill` must be non-nil. `label`, `iconUri` and `iconTintColor` are already resolved (per-link content, +/// then variant default). +- (instancetype)initWithOriginalText:(NSAttributedString *)originalText + variant:(LinkVariantConfig *)variant + label:(nullable NSString *)label + iconUri:(nullable NSString *)iconUri + iconTintColor:(nullable UIColor *)iconTintColor + font:(nullable UIFont *)font + requestHeaders:(nullable NSDictionary *)requestHeaders; + +- (void)adoptFont:(nullable UIFont *)font; +@end + +NS_ASSUME_NONNULL_END +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.m new file mode 100644 index 000000000000..7cb026ad0299 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillAttachment.m @@ -0,0 +1,324 @@ +#import "ENRMLinkPillAttachment.h" +#import "ENRMImageAttachment.h" +#import "ENRMImageDownloader.h" +#import "ENRMLinkPillIconCache.h" +#import "ENRMSpoilerTapUtils.h" +#import "RuntimeKeys.h" +#import "StyleConfig.h" +#import + +#if !TARGET_OS_OSX + +// The icon occupies a square of the label's font size plus a quarter of it as a gap. +static const CGFloat kIconSlotRatio = 1.25; + +/// Everything that decides what a drawn pill looks like. Streaming re-renders create new +/// attachments for the same links on every update; keyed like this, they reuse the drawn image. +@interface ENRMLinkPillAppearance : NSObject +@property (nonatomic, strong) LinkVariantConfig *variant; +@property (nonatomic, copy) NSString *label; +@property (nonatomic, strong) UIFont *font; +@property (nonatomic, strong, nullable) UIImage *icon; +@property (nonatomic, strong, nullable) UIColor *iconTint; +@property (nonatomic, assign) BOOL reservesIconSlot; +@property (nonatomic, assign) CGSize size; +@property (nonatomic, assign) UIUserInterfaceStyle interfaceStyle; +@end + +@implementation ENRMLinkPillAppearance +- (NSUInteger)hash +{ + return _label.hash ^ _font.hash ^ (NSUInteger)_variant ^ (NSUInteger)(_size.width * 31 + _size.height); +} + +- (BOOL)isEqual:(id)object +{ + if (![object isKindOfClass:ENRMLinkPillAppearance.class]) + return NO; + ENRMLinkPillAppearance *other = object; + // The variant and icon are compared by identity: both objects live as long as the style and + // the icon cache keep them, and this key retains them, so a match is never a recycled pointer. + BOOL sameTint = _iconTint == other->_iconTint || [_iconTint isEqual:other->_iconTint]; + return _variant == other->_variant && _icon == other->_icon && sameTint && + _reservesIconSlot == other->_reservesIconSlot && _interfaceStyle == other->_interfaceStyle && + CGSizeEqualToSize(_size, other->_size) && [_font isEqual:other->_font] && + [_label isEqualToString:other->_label]; +} +@end + +/// Drawn pills, shared and bounded: the ones on screen are redrawn often, but a long document +/// holds thousands, each a bitmap of 100 KB or more, so pills must not each keep their own. +static NSCache *ENRMRenderedLinkPills(void) +{ + static NSCache *rendered; + static dispatch_once_t once; + dispatch_once(&once, ^{ + rendered = [NSCache new]; + rendered.countLimit = 256; + rendered.totalCostLimit = 8 * 1024 * 1024; + }); + return rendered; +} + +static UIImage *ENRMClearLinkPillImage(void) +{ + static UIImage *clear; + static dispatch_once_t once; + dispatch_once(&once, ^{ + UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat]; + format.opaque = NO; + clear = [[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(1, 1) format:format] + imageWithActions:^(UIGraphicsImageRendererContext *context){}]; + }); + return clear; +} + +/// Streaming renders the same links again on every update; their label widths do not change. +static CGFloat ENRMLinkPillLabelWidth(NSString *label, UIFont *font) +{ + static NSCache *widths; + static dispatch_once_t once; + dispatch_once(&once, ^{ + widths = [NSCache new]; + widths.countLimit = 2048; + }); + NSString *key = [NSString stringWithFormat:@"%@|%.2f|%@", font.fontName, font.pointSize, label]; + NSNumber *cached = [widths objectForKey:key]; + if (cached) + return cached.doubleValue; + CGFloat width = [label sizeWithAttributes:@{NSFontAttributeName : font}].width; + [widths setObject:@(width) forKey:key]; + return width; +} + +@implementation ENRMLinkPillAttachment { + LinkVariantConfig *_variant; + LinkPillConfig *_pill; + UIFont *_font; + UIImage *_icon; + UIColor *_iconTint; + // Space for the icon is held while a remote icon is still loading, so its arrival only needs a redraw. + BOOL _reservesIconSlot; + __weak NSTextContainer *_textContainer; + CGFloat _labelWidth; +} + +- (instancetype)initWithOriginalText:(NSAttributedString *)originalText + variant:(LinkVariantConfig *)variant + label:(NSString *)label + iconUri:(NSString *)iconUri + iconTintColor:(UIColor *)iconTintColor + font:(UIFont *)font + requestHeaders:(NSDictionary *)requestHeaders +{ + self = [super initWithData:nil ofType:nil]; + if (self) { + _variant = variant; + _pill = variant.pill; + _iconTint = iconTintColor; + _originalText = [originalText copy]; + _font = font ?: [UIFont systemFontOfSize:16]; + // The pill is a single line; a label supplied by the app may still carry breaks. + NSString *visible = label.length > 0 ? label : originalText.string; + _label = [[visible componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet] + componentsJoinedByString:@" "]; + [self resolveIcon:iconUri requestHeaders:requestHeaders]; + } + return self; +} + +- (void)resolveIcon:(NSString *)iconUri requestHeaders:(NSDictionary *)requestHeaders +{ + if (iconUri.length == 0) + return; + _icon = ENRMLoadLinkPillIcon(iconUri) ?: ENRMCachedLinkPillIcon(iconUri, requestHeaders); + _reservesIconSlot = _icon != nil; + if (_icon || ENRMLinkPillIconDidFail(iconUri, requestHeaders)) + return; + _reservesIconSlot = YES; + __weak typeof(self) weakSelf = self; + ENRMLoadLinkPillIconAsync(iconUri, requestHeaders, ^(UIImage *icon) { [weakSelf iconDidSettle:icon]; }); +} + +- (void)adoptFont:(UIFont *)font +{ + if (!font || [font isEqual:_font]) + return; + _font = font; + _labelWidth = 0; +} + +- (NSString *)linkAccessibilityLabel +{ + NSString *original = _originalText.string; + return [_label isEqualToString:original] ? original : [NSString stringWithFormat:@"%@, %@", _label, original]; +} + +- (CGFloat)boxHeight +{ + return ceil(_font.ascender - _font.descender + 2 * (_pill.paddingVertical + _pill.borderWidth)); +} + +- (CGFloat)widthForLimit:(CGFloat)available +{ + CGFloat iconWidth = _reservesIconSlot ? _font.pointSize * kIconSlotRatio : 0; + if (_labelWidth <= 0) + _labelWidth = ENRMLinkPillLabelWidth(_label, _font); + CGFloat natural = ceil(_labelWidth + iconWidth + 2 * (_pill.paddingHorizontal + _pill.borderWidth)); + CGFloat limit = _pill.maxWidth > 0 ? MIN(available, _pill.maxWidth) : available; + return MAX(1, MIN(natural, limit)); +} + +- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)container + proposedLineFragment:(CGRect)lineFragment + glyphPosition:(CGPoint)position + characterIndex:(NSUInteger)characterIndex +{ + CGFloat available = CGFLOAT_MAX; + if (container) { + _textContainer = container; + // Use the full container width, not the remainder of the current line. TextKit then moves + // the whole attachment to the next line if it doesn't fit the remainder. + NSTextStorage *storage = container.layoutManager.textStorage; + NSParagraphStyle *paragraph = characterIndex < storage.length ? [storage attribute:NSParagraphStyleAttributeName + atIndex:characterIndex + effectiveRange:NULL] + : nil; + CGFloat indent = MAX(paragraph.firstLineHeadIndent, paragraph.headIndent); + CGFloat tailInset = paragraph.tailIndent < 0 ? -paragraph.tailIndent : 0; + available = MAX(1, container.size.width - 2 * container.lineFragmentPadding - indent - tailInset); + } else if (lineFragment.size.width > 0 && lineFragment.size.width < 1e6) { + // String drawing (table cells) lays out without a text container. + available = lineFragment.size.width; + } + CGFloat inset = _pill.paddingVertical + _pill.borderWidth; + return CGRectMake(0, _font.descender - inset, [self widthForLimit:available], self.boxHeight); +} + +- (CGFloat)cornerRadius +{ + return MIN(_pill.borderRadius, self.boxHeight / 2); +} + +- (UIImage *)imageForBounds:(CGRect)bounds textContainer:(NSTextContainer *)container characterIndex:(NSUInteger)index +{ + if (bounds.size.width <= 0 || bounds.size.height <= 0) + return nil; + if (_lifted) + return ENRMClearLinkPillImage(); + if (container) { + _textContainer = container; + // The spoiler hides text by clearing its color, which this drawing does not use. + NSTextStorage *storage = container.layoutManager.textStorage; + if (index < storage.length && [storage attribute:SpoilerAttributeName atIndex:index effectiveRange:NULL]) + return ENRMClearLinkPillImage(); + } + CGSize size = bounds.size; + UIUserInterfaceStyle interfaceStyle = UITraitCollection.currentTraitCollection.userInterfaceStyle; + ENRMLinkPillAppearance *appearance = [ENRMLinkPillAppearance new]; + appearance.variant = _variant; + appearance.label = _label; + appearance.font = _font; + appearance.icon = _icon; + appearance.iconTint = _iconTint; + appearance.reservesIconSlot = _reservesIconSlot; + appearance.size = size; + appearance.interfaceStyle = interfaceStyle; + UIImage *rendered = [ENRMRenderedLinkPills() objectForKey:appearance]; + if (rendered) + return rendered; + + UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat]; + format.opaque = NO; + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:format]; + UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) { + CGRect rect = (CGRect){CGPointZero, size}; + UIBezierPath *background = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:_pill.borderRadius]; + [_variant.backgroundColor ?: UIColor.clearColor setFill]; + [background fill]; + if (_pill.borderWidth > 0) { + UIBezierPath *border = + [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, _pill.borderWidth / 2, _pill.borderWidth / 2) + cornerRadius:_pill.borderRadius]; + border.lineWidth = _pill.borderWidth; + [_pill.borderColor setStroke]; + [border stroke]; + } + [background addClip]; + CGFloat left = _pill.paddingHorizontal + _pill.borderWidth; + CGFloat right = size.width - left; + if (_reservesIconSlot && right - left >= _font.pointSize) { + CGFloat side = _font.pointSize; + if (_icon) { + CGFloat scale = side / MAX(_icon.size.width, _icon.size.height); + CGSize iconSize = CGSizeMake(_icon.size.width * scale, _icon.size.height * scale); + CGRect iconRect = CGRectMake(left + (side - iconSize.width) / 2, (size.height - iconSize.height) / 2, + iconSize.width, iconSize.height); + UIImage *presented = + _iconTint ? [_icon imageWithTintColor:_iconTint renderingMode:UIImageRenderingModeAlwaysOriginal] : _icon; + [presented drawInRect:iconRect]; + } + left += side * kIconSlotRatio; + } + NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; + paragraph.lineBreakMode = NSLineBreakByTruncatingTail; + NSDictionary *attributes = @{ + NSFontAttributeName : _font, + NSForegroundColorAttributeName : _variant.color ?: UIColor.labelColor, + NSUnderlineStyleAttributeName : @(_variant.underline ? NSUnderlineStyleSingle : NSUnderlineStyleNone), + NSParagraphStyleAttributeName : paragraph, + }; + [_label drawInRect:CGRectMake(left, _pill.paddingVertical + _pill.borderWidth, MAX(0, right - left), size.height) + withAttributes:attributes]; + }]; + [ENRMRenderedLinkPills() setObject:image forKey:appearance cost:ENRMImageByteCost(image)]; + return image; +} + +#pragma mark - Asynchronous icon + +- (void)iconDidSettle:(UIImage *)icon +{ + _icon = icon; + BOOL slotReleased = icon == nil; + if (slotReleased) + _reservesIconSlot = NO; + + if (self.onIconLoaded) + self.onIconLoaded(); + + NSTextContainer *container = _textContainer; + UITextView *textView = container ? objc_getAssociatedObject(container, kTextViewKey) : nil; + if (!textView) + return; + NSRange range = [self rangeInText:textView.textStorage]; + if (range.location == NSNotFound) + return; + if (!slotReleased) { + [textView.layoutManager invalidateDisplayForCharacterRange:range]; + return; + } + // The pill got narrower, so lines can reflow: lay out again and let the host re-measure. + [textView.layoutManager invalidateLayoutForCharacterRange:range actualCharacterRange:NULL]; + id observer = [textView enrm_imageLayoutObserver]; + if (observer) + dispatch_async(dispatch_get_main_queue(), ^{ [observer imageAttachmentDidResolveLayout]; }); +} + +- (NSRange)rangeInText:(NSAttributedString *)text +{ + __block NSRange found = NSMakeRange(NSNotFound, 0); + [text enumerateAttribute:NSAttachmentAttributeName + inRange:NSMakeRange(0, text.length) + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(id value, NSRange range, BOOL *stop) { + if (value == self) { + found = range; + *stop = YES; + } + }]; + return found; +} +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.h new file mode 100644 index 000000000000..aa971677f308 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.h @@ -0,0 +1,28 @@ +#pragma once +#import "ENRMUIKit.h" + +#if !TARGET_OS_OSX +NS_ASSUME_NONNULL_BEGIN + +/// Pill icons, kept small in one bounded cache. Local files decode synchronously, so a bundled +/// icon is there on the first layout; every other source goes through the shared image +/// downloader, like markdown images, and arrives asynchronously. + +/// A local file icon, or nil when the source is not a readable local file. +FOUNDATION_EXPORT UIImage *_Nullable ENRMLoadLinkPillIcon(NSString *_Nullable iconUri); + +FOUNDATION_EXPORT UIImage *_Nullable ENRMCachedLinkPillIcon(NSString *iconUri, + NSDictionary *_Nullable headers); + +/// YES for a while after an asynchronous load of this source failed; callers then do not +/// reserve an icon slot. The source is tried again once that period has passed. +FOUNDATION_EXPORT BOOL ENRMLinkPillIconDidFail(NSString *iconUri, + NSDictionary *_Nullable headers); + +/// Loads through the shared image pipeline. `completion` runs on the main thread; nil means the source failed. +FOUNDATION_EXPORT void ENRMLoadLinkPillIconAsync(NSString *iconUri, + NSDictionary *_Nullable headers, + void (^completion)(UIImage *_Nullable icon)); + +NS_ASSUME_NONNULL_END +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.m new file mode 100644 index 000000000000..69681b5c41f7 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillIconCache.m @@ -0,0 +1,181 @@ +#import "ENRMLinkPillIconCache.h" +#import "ENRMImageDownloader.h" +#import "ENRMLocalImageLoader.h" +#if !TARGET_OS_OSX +#import +#import + +// Icons are drawn at the label's font size, so even a large heading at 3x needs few pixels. +static const CGFloat kMaxIconPixelSize = 128; + +static NSCache *ENRMLinkPillIcons(void) +{ + static NSCache *icons; + static dispatch_once_t once; + dispatch_once(&once, ^{ + icons = [NSCache new]; + icons.countLimit = 64; + icons.totalCostLimit = 8 * 1024 * 1024; + }); + return icons; +} + +// A failed source is left alone for a while, so a broken URL is not requested on every +// render, and then tried again, so a transient failure does not hide the icon for good. +static const CFTimeInterval kFailedIconRetryInterval = 30; + +static NSCache *ENRMFailedLinkPillIcons(void) +{ + static NSCache *failed; + static dispatch_once_t once; + dispatch_once(&once, ^{ + failed = [NSCache new]; + failed.countLimit = 256; + }); + return failed; +} + +// A local icon and the state of its file when it was decoded. +@interface ENRMLocalLinkPillIcon : NSObject +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, copy) NSString *path; +@property (nonatomic, strong, nullable) NSDate *modified; +@property (nonatomic, assign) unsigned long long fileSize; +@property (nonatomic, assign) CFTimeInterval checkedAt; +@end + +@implementation ENRMLocalLinkPillIcon +@end + +// Every render asks for the same icons again, so the file is looked at no more than once +// per interval; a file replaced under the same path is picked up after that. +static const CFTimeInterval kLocalIconRevalidateInterval = 1; + +static NSCache *ENRMLocalLinkPillIcons(void) +{ + static NSCache *icons; + static dispatch_once_t once; + dispatch_once(&once, ^{ + icons = [NSCache new]; + icons.countLimit = 64; + icons.totalCostLimit = 8 * 1024 * 1024; + }); + return icons; +} + +static UIImage *ENRMDecodeLinkPillIcon(NSString *path) +{ + CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], NULL); + if (!source) + return nil; + NSDictionary *options = @{ + (__bridge NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES, + (__bridge NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES, + (__bridge NSString *)kCGImageSourceShouldCacheImmediately : @YES, + (__bridge NSString *)kCGImageSourceThumbnailMaxPixelSize : @(kMaxIconPixelSize), + }; + CGImageRef decoded = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options); + CFRelease(source); + if (!decoded) + return nil; + UIImage *image = [UIImage imageWithCGImage:decoded]; + CGImageRelease(decoded); + return image; +} + +UIImage *ENRMLoadLinkPillIcon(NSString *iconUri) +{ + if (iconUri.length == 0) + return nil; + NSCache *icons = ENRMLocalLinkPillIcons(); + ENRMLocalLinkPillIcon *cached = [icons objectForKey:iconUri]; + CFTimeInterval now = CACurrentMediaTime(); + if (cached && now - cached.checkedAt < kLocalIconRevalidateInterval) + return cached.image; + + NSString *path = cached.path ?: ENRMResolveLocalImagePath(iconUri); + if (!path) + return nil; + NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil]; + NSDate *modified = attributes[NSFileModificationDate]; + unsigned long long fileSize = [attributes[NSFileSize] unsignedLongLongValue]; + if (cached && attributes && cached.fileSize == fileSize && [cached.modified isEqualToDate:modified]) { + cached.checkedAt = now; + return cached.image; + } + + UIImage *image = attributes ? ENRMDecodeLinkPillIcon(path) : nil; + if (!image) { + [icons removeObjectForKey:iconUri]; + return nil; + } + ENRMLocalLinkPillIcon *entry = [ENRMLocalLinkPillIcon new]; + entry.image = image; + entry.path = path; + entry.modified = modified; + entry.fileSize = fileSize; + entry.checkedAt = now; + [icons setObject:entry forKey:iconUri cost:ENRMImageByteCost(image)]; + return image; +} + +UIImage *ENRMCachedLinkPillIcon(NSString *iconUri, NSDictionary *headers) +{ + return [ENRMLinkPillIcons() objectForKey:ENRMImageCacheKey(iconUri, headers)]; +} + +BOOL ENRMLinkPillIconDidFail(NSString *iconUri, NSDictionary *headers) +{ + NSString *key = ENRMImageCacheKey(iconUri, headers); + NSNumber *failedAt = [ENRMFailedLinkPillIcons() objectForKey:key]; + if (!failedAt) + return NO; + if (CACurrentMediaTime() - failedAt.doubleValue < kFailedIconRetryInterval) + return YES; + [ENRMFailedLinkPillIcons() removeObjectForKey:key]; + return NO; +} + +static UIImage *ENRMLinkPillThumbnail(UIImage *image) +{ + CGFloat pixelWidth = image.size.width * image.scale; + CGFloat pixelHeight = image.size.height * image.scale; + CGFloat longest = MAX(pixelWidth, pixelHeight); + if (longest <= kMaxIconPixelSize || longest <= 0) + return image; + CGFloat ratio = kMaxIconPixelSize / longest; + CGSize size = CGSizeMake(MAX(1, floor(pixelWidth * ratio)), MAX(1, floor(pixelHeight * ratio))); + UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat]; + format.scale = 1; + format.opaque = NO; + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:format]; + return [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) { + [image drawInRect:(CGRect){CGPointZero, size}]; + }]; +} + +void ENRMLoadLinkPillIconAsync(NSString *iconUri, NSDictionary *headers, + void (^completion)(UIImage *_Nullable icon)) +{ + NSString *key = ENRMImageCacheKey(iconUri, headers); + [[ENRMImageDownloader shared] downloadURL:iconUri + headers:headers + completion:^(RCTUIImage *image) { + // Drawn pills are cached by icon identity: every pill waiting + // for this icon gets the same image. + UIImage *icon = [ENRMLinkPillIcons() objectForKey:key]; + if (!icon && image) { + icon = ENRMLinkPillThumbnail(image); + [ENRMLinkPillIcons() setObject:icon forKey:key cost:ENRMImageByteCost(icon)]; + } + if (!icon) { + [ENRMFailedLinkPillIcons() setObject:@(CACurrentMediaTime()) forKey:key]; + } + if (NSThread.isMainThread) { + completion(icon); + } else { + dispatch_async(dispatch_get_main_queue(), ^{ completion(icon); }); + } + }]; +} +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.h new file mode 100644 index 000000000000..2b9f9d3a496d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.h @@ -0,0 +1,27 @@ +#pragma once +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * In text storage a link pill is one placeholder character. Wherever text leaves the + * view it must carry the link text again: the Markdown, HTML and RTF exporters expand + * pills themselves, and code that reads plain text out of storage calls these functions. + * On macOS, where pills are not rendered, they return their input unchanged. + */ + +/** + * Returns `text` with every pill placeholder replaced by the link content it stands for, + * or `text` itself when it holds no pills. `ioRange`, when given, is a range in `text` on + * input and the matching range in the result on output. + */ +FOUNDATION_EXPORT NSAttributedString *ENRMAttributedStringByExpandingLinkPills(NSAttributedString *text, + NSRange *_Nullable ioRange); + +FOUNDATION_EXPORT NSString *ENRMStringByExpandingLinkPills(NSAttributedString *text); + +/// Enclosing strong/emphasis restyle the placeholder after the pill was created. Run once +/// rendering is finished so each label uses the font ordinary link text would have. +FOUNDATION_EXPORT void ENRMLinkPillsAdoptPlaceholderFonts(NSAttributedString *text); + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.m new file mode 100644 index 000000000000..172cba2d875b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMLinkPillText.m @@ -0,0 +1,118 @@ +#import "ENRMLinkPillText.h" +#import "ENRMLinkPillAttachment.h" + +#if !TARGET_OS_OSX + +/// Inline parents (strong, emphasis) restyle the placeholder's font after the pill was created; carry that over. +static UIFont *ENRMFontAddingTraits(UIFont *font, UIFontDescriptorSymbolicTraits traits) +{ + UIFontDescriptorSymbolicTraits current = font.fontDescriptor.symbolicTraits; + if ((current & traits) == traits) + return font; + UIFontDescriptor *descriptor = [font.fontDescriptor fontDescriptorWithSymbolicTraits:current | traits]; + return descriptor ? [UIFont fontWithDescriptor:descriptor size:font.pointSize] : font; +} + +static NSAttributedString *ENRMExpandedLinkPill(ENRMLinkPillAttachment *pill, NSDictionary *placeholderAttributes) +{ + NSMutableAttributedString *expanded = [pill.originalText mutableCopy]; + NSRange all = NSMakeRange(0, expanded.length); + // The placeholder started with the font of the link's first character, so only traits it has + // gained since come from an enclosing parent. + UIFont *placeholderFont = placeholderAttributes[NSFontAttributeName]; + UIFont *firstFont = all.length > 0 ? [expanded attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL] : nil; + UIFontDescriptorSymbolicTraits inherited = placeholderFont.fontDescriptor.symbolicTraits & + ~firstFont.fontDescriptor.symbolicTraits & + (UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic); + [placeholderAttributes enumerateKeysAndObjectsUsingBlock:^(NSAttributedStringKey key, id value, BOOL *stop) { + if ([key isEqualToString:NSAttachmentAttributeName]) + return; + BOOL isFont = [key isEqualToString:NSFontAttributeName]; + [pill.originalText enumerateAttribute:key + inRange:all + options:0 + usingBlock:^(id existing, NSRange range, BOOL *innerStop) { + if (!existing) { + [expanded addAttribute:key value:value range:range]; + } else if (isFont && inherited != 0) { + [expanded addAttribute:key + value:ENRMFontAddingTraits(existing, inherited) + range:range]; + } + }]; + }]; + return expanded; +} + +#endif + +void ENRMLinkPillsAdoptPlaceholderFonts(NSAttributedString *text) +{ +#if !TARGET_OS_OSX + [text enumerateAttribute:NSAttachmentAttributeName + inRange:NSMakeRange(0, text.length) + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(id value, NSRange range, BOOL *stop) { + if ([value isKindOfClass:ENRMLinkPillAttachment.class]) + [(ENRMLinkPillAttachment *)value adoptFont:[text attribute:NSFontAttributeName + atIndex:range.location + effectiveRange:NULL]]; + }]; +#endif +} + +NSAttributedString *ENRMAttributedStringByExpandingLinkPills(NSAttributedString *text, NSRange *ioRange) +{ +#if TARGET_OS_OSX + return text; +#else + if (text.length == 0) + return text; + NSMutableArray *ranges = nil; + NSMutableArray *pills = nil; + NSRange all = NSMakeRange(0, text.length); + NSRange cursor = NSMakeRange(0, 0); + while (NSMaxRange(cursor) < text.length) { + id value = [text attribute:NSAttachmentAttributeName + atIndex:NSMaxRange(cursor) + longestEffectiveRange:&cursor + inRange:all]; + if (![value isKindOfClass:ENRMLinkPillAttachment.class]) + continue; + if (!pills) { + ranges = [NSMutableArray new]; + pills = [NSMutableArray new]; + } + [ranges addObject:[NSValue valueWithRange:cursor]]; + [pills addObject:value]; + } + if (!pills) + return text; + + NSMutableAttributedString *result = [text mutableCopy]; + NSRange range = ioRange ? *ioRange : NSMakeRange(0, 0); + NSInteger locationDelta = 0; + NSInteger lengthDelta = 0; + // Back to front, so earlier ranges stay valid while the string grows. + for (NSInteger i = (NSInteger)pills.count - 1; i >= 0; i--) { + NSRange placeholder = ranges[i].rangeValue; + NSAttributedString *expanded = ENRMExpandedLinkPill(pills[i], [text attributesAtIndex:placeholder.location + effectiveRange:NULL]); + [result replaceCharactersInRange:placeholder withAttributedString:expanded]; + NSInteger growth = (NSInteger)expanded.length - (NSInteger)placeholder.length; + if (NSMaxRange(placeholder) <= range.location) { + locationDelta += growth; + } else if (placeholder.location < NSMaxRange(range)) { + lengthDelta += growth; + } + } + if (ioRange) + *ioRange = NSMakeRange(range.location + locationDelta, range.length + lengthDelta); + return result; +#endif +} + +NSString *ENRMStringByExpandingLinkPills(NSAttributedString *text) +{ + return ENRMAttributedStringByExpandingLinkPills(text, NULL).string; +} diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment+macOS.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment+macOS.m new file mode 100644 index 000000000000..324a2ac2f844 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment+macOS.m @@ -0,0 +1,60 @@ +#import "ENRMMathInlineAttachmentShared.h" + +#if ENRICHED_MARKDOWN_MATH && TARGET_OS_OSX + +#if __has_include("ReactNativeEnrichedMarkdown-Swift.h") +#import "ReactNativeEnrichedMarkdown-Swift.h" +#elif __has_include() +#import +#endif + +@implementation ENRMMathInlineAttachment (macOS) + +- (instancetype)init +{ + self = [super init]; + if (self) { + // NSTextAttachment creates a default NSTextAttachmentCell on macOS. + // Clear it so NSLayoutManager falls back to the image/bounds properties + // we set in renderForMacOS. + self.attachmentCell = nil; + } + return self; +} + +- (void)renderForMacOS +{ + RCTUIColor *color = self.mathTextColor ?: [RCTUIColor blackColor]; + ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:self.latex displayMode:NO fontSize:self.fontSize color:color]; + if (!result) + return; + + _renderResult = result; + _mathAscent = result.ascent; + _mathDescent = result.descent; + _cachedSize = CGSizeMake(ceil(result.width), ceil(result.totalHeight)); + + // Render the formula into an NSImage. NSLayoutManager draws self.image + // automatically when attachmentCell is nil, so this is the reliable + // macOS rendering path instead of imageForBounds:textContainer:characterIndex:. + // + // NSImage.lockFocus creates a bottom-left origin Quartz context, but RaTeX + // expects a UIKit-style top-left origin (Y increases downward). Flip the CTM + // so the formula renders right-side up. + NSImage *image = [[NSImage alloc] initWithSize:_cachedSize]; + [image lockFocus]; + CGContextRef ctx = [[NSGraphicsContext currentContext] CGContext]; + CGContextSaveGState(ctx); + CGContextTranslateCTM(ctx, 0, _cachedSize.height); + CGContextScaleCTM(ctx, 1.0, -1.0); + [_renderResult drawIn:ctx]; + CGContextRestoreGState(ctx); + [image unlockFocus]; + + self.image = image; + self.bounds = CGRectMake(0, -_mathDescent, _cachedSize.width, _cachedSize.height); +} + +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.h new file mode 100644 index 000000000000..bccb200bb65c --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.h @@ -0,0 +1,27 @@ +#pragma once +#import "ENRMLatexErrorReporting.h" +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMMathInlineAttachment : NSTextAttachment + +@property (nonatomic, strong) NSString *latex; +@property (nonatomic, assign) CGFloat fontSize; +@property (nonatomic, strong, nullable) RCTUIColor *mathTextColor; +@property (nonatomic, assign) BOOL displayMode; +@property (nonatomic, copy, nullable) ENRMLatexErrorHandler onLatexError; + +@property (nonatomic, readonly) CGFloat boxHeight; + +#if TARGET_OS_OSX +/// Pre-renders the formula into self.image and sets self.bounds. +/// Must be called after latex/fontSize/mathTextColor are set, before the +/// attachment is inserted into an NSAttributedString. On macOS, NSLayoutManager +/// uses the image/bounds properties directly rather than calling imageForBounds:. +- (void)renderForMacOS; +#endif + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.m b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.m new file mode 100644 index 000000000000..9763eca5d423 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachment.m @@ -0,0 +1,105 @@ +#import "ENRMMathFallback.h" +#import "ENRMMathInlineAttachmentShared.h" + +#if ENRICHED_MARKDOWN_MATH + +#if __has_include("ReactNativeEnrichedMarkdown-Swift.h") +#import "ReactNativeEnrichedMarkdown-Swift.h" +#elif __has_include() +#import +#endif + +@implementation ENRMMathInlineAttachment + +- (CGFloat)boxHeight +{ +#if !TARGET_OS_OSX + [self prepareIfNeeded]; +#endif + return _cachedSize.height; +} + +- (void)reportLatexErrorIfNeeded +{ + if (_parseFailed && !_didReportError && self.onLatexError) { + _didReportError = YES; + self.onLatexError(self.latex, _parseMessage ?: @"", self.displayMode); + } +} + +#if !TARGET_OS_OSX + +- (void)prepareIfNeeded +{ + if (_renderResult || _fallbackSource) + return; + + RCTUIColor *color = self.mathTextColor ?: [RCTUIColor blackColor]; + NSError *error = nil; + ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:self.latex + displayMode:self.displayMode + fontSize:self.fontSize + color:color + error:&error]; + if (!result) { + _parseFailed = YES; + _parseMessage = error.localizedDescription ?: @""; + [self reportLatexErrorIfNeeded]; + _fallbackSource = ENRMMathFallbackString(self.latex, @"$", self.fontSize, color); + UIFont *font = [_fallbackSource attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL]; + CGRect bounds = [_fallbackSource boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil]; + _mathAscent = font.ascender; + _mathDescent = -font.descender; + _cachedSize = CGSizeMake(ceil(bounds.size.width), ceil(_mathAscent + _mathDescent)); + return; + } + + _renderResult = result; + _mathAscent = result.ascent; + _mathDescent = result.descent; + _cachedSize = CGSizeMake(ceil(result.width), ceil(result.totalHeight)); +} + +- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer + proposedLineFragment:(CGRect)lineFragment + glyphPosition:(CGPoint)position + characterIndex:(NSUInteger)characterIndex +{ + [self prepareIfNeeded]; + return CGRectMake(0, -_mathDescent, _cachedSize.width, _cachedSize.height); +} + +- (UIImage *)imageForBounds:(CGRect)imageBounds + textContainer:(NSTextContainer *)textContainer + characterIndex:(NSUInteger)characterIndex +{ + [self prepareIfNeeded]; + if (!_renderResult && !_fallbackSource) + return nil; + + UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat]; + format.opaque = NO; + + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:_cachedSize format:format]; + + return [renderer imageWithActions:^(UIGraphicsImageRendererContext *rendererContext) { + if (_renderResult) { + CGContextRef ctx = rendererContext.CGContext; + CGContextSaveGState(ctx); + [_renderResult drawIn:ctx]; + CGContextRestoreGState(ctx); + } else { + [_fallbackSource drawWithRect:CGRectMake(0, 0, _cachedSize.width, _cachedSize.height) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil]; + } + }]; +} + +#endif + +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachmentShared.h b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachmentShared.h new file mode 100644 index 000000000000..9584acedd926 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ENRMMathInlineAttachmentShared.h @@ -0,0 +1,22 @@ +#pragma once +#import "ENRMFeatureFlags.h" +#import "ENRMMathInlineAttachment.h" + +#if ENRICHED_MARKDOWN_MATH + +@class ENRMRaTeXRenderResult; + +@interface ENRMMathInlineAttachment () { + CGSize _cachedSize; + CGFloat _mathAscent; + CGFloat _mathDescent; + ENRMRaTeXRenderResult *_renderResult; + // Visible-source fallback when RaTeX cannot parse the span; see ENRMMathFallback.h. + NSAttributedString *_fallbackSource; + BOOL _didReportError; + BOOL _parseFailed; + NSString *_parseMessage; +} +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.h b/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.h new file mode 100644 index 000000000000..8e8cfac00aa9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.h @@ -0,0 +1,15 @@ +#pragma once +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ThematicBreakAttachment : NSTextAttachment + +@property (nonatomic, strong) RCTUIColor *lineColor; +@property (nonatomic, assign) CGFloat lineHeight; +@property (nonatomic, assign) CGFloat marginTop; +@property (nonatomic, assign) CGFloat marginBottom; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.m b/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.m new file mode 100644 index 000000000000..92cd71f135bf --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/attachments/ThematicBreakAttachment.m @@ -0,0 +1,33 @@ +#import "ThematicBreakAttachment.h" + +@implementation ThematicBreakAttachment + +- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer + proposedLineFragment:(CGRect)lineFrag + glyphPosition:(CGPoint)position + characterIndex:(NSUInteger)charIndex +{ + CGFloat totalHeight = self.marginTop + self.lineHeight + self.marginBottom; + return CGRectMake(0, 0, CGRectGetWidth(lineFrag), totalHeight); +} + +- (RCTUIImage *)imageForBounds:(CGRect)imageBounds + textContainer:(NSTextContainer *)textContainer + characterIndex:(NSUInteger)charIndex +{ + RCTUIGraphicsImageRenderer *renderer = [[RCTUIGraphicsImageRenderer alloc] initWithSize:imageBounds.size]; + + return [renderer imageWithActions:^(RCTUIGraphicsImageRendererContext *_Nonnull rendererContext) { + CGContextRef ctx = rendererContext.CGContext; + + CGFloat lineY = self.marginTop + (self.lineHeight / 2.0); + + [self.lineColor setStroke]; + CGContextSetLineWidth(ctx, self.lineHeight); + CGContextMoveToPoint(ctx, 0, lineY); + CGContextAddLineToPoint(ctx, imageBounds.size.width, lineY); + CGContextStrokePath(ctx); + }]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.cpp b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.cpp new file mode 100644 index 000000000000..4d59d51932cc --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.cpp @@ -0,0 +1,22 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateComponentDescriptorCpp.js + */ + +#include "ComponentDescriptors.h" +#include +#include + +namespace facebook::react { + +void EnrichedMarkdownTextSpec_registerComponentDescriptorsFromCodegen( + std::shared_ptr registry) { + +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.h new file mode 100644 index 000000000000..06510880a0ac --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ComponentDescriptors.h @@ -0,0 +1,24 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateComponentDescriptorH.js + */ + +#pragma once + +#include "ShadowNodes.h" +#include +#include + +namespace facebook::react { + + + +void EnrichedMarkdownTextSpec_registerComponentDescriptorsFromCodegen( + std::shared_ptr registry); + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.cpp b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.cpp new file mode 100644 index 000000000000..94997f7d60b4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.cpp @@ -0,0 +1,455 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateEventEmitterCpp.js + */ + +#include "EventEmitters.h" + + +namespace facebook::react { + +void EnrichedMarkdownEventEmitter::onLinkPress(OnLinkPress event) const { + dispatchEvent("linkPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); + payload.setProperty(runtime, "sourceType", event.sourceType); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onLinkLongPress(OnLinkLongPress event) const { + dispatchEvent("linkLongPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onImagePress(OnImagePress event) const { + dispatchEvent("imagePress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); +payload.setProperty(runtime, "altText", event.altText); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onTaskListItemPress(OnTaskListItemPress event) const { + dispatchEvent("taskListItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "index", event.index); +payload.setProperty(runtime, "checked", event.checked); +payload.setProperty(runtime, "text", event.text); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onCopyPress(OnCopyPress event) const { + dispatchEvent("copyPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "code", event.code); +payload.setProperty(runtime, "language", event.language); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onCodeBlockPress(OnCodeBlockPress event) const { + dispatchEvent("codeBlockPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "code", event.code); +payload.setProperty(runtime, "language", event.language); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onLatexError(OnLatexError event) const { + dispatchEvent("latexError", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "source", event.source); +payload.setProperty(runtime, "message", event.message); +payload.setProperty(runtime, "displayMode", event.displayMode); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onLinkContextMenuItemPress(OnLinkContextMenuItemPress event) const { + dispatchEvent("linkContextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); +payload.setProperty(runtime, "pattern", event.pattern); +payload.setProperty(runtime, "itemText", event.itemText); + return payload; + }); +} + + +void EnrichedMarkdownEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const { + dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "itemText", event.itemText); +payload.setProperty(runtime, "selectedText", event.selectedText); +payload.setProperty(runtime, "selectionStart", event.selectionStart); +payload.setProperty(runtime, "selectionEnd", event.selectionEnd); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onChangeText(OnChangeText event) const { + dispatchEvent("changeText", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "value", event.value); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onChangeMarkdown(OnChangeMarkdown event) const { + dispatchEvent("changeMarkdown", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "value", event.value); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onChangeSelection(OnChangeSelection event) const { + dispatchEvent("changeSelection", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "start", event.start); +payload.setProperty(runtime, "end", event.end); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onInputKeyPress(OnInputKeyPress event) const { + dispatchEvent("inputKeyPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "key", event.key); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onChangeState(OnChangeState event) const { + dispatchEvent("changeState", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + { + auto bold = jsi::Object(runtime); + bold.setProperty(runtime, "isActive", event.bold.isActive); + payload.setProperty(runtime, "bold", bold); +} +{ + auto italic = jsi::Object(runtime); + italic.setProperty(runtime, "isActive", event.italic.isActive); + payload.setProperty(runtime, "italic", italic); +} +{ + auto underline = jsi::Object(runtime); + underline.setProperty(runtime, "isActive", event.underline.isActive); + payload.setProperty(runtime, "underline", underline); +} +{ + auto strikethrough = jsi::Object(runtime); + strikethrough.setProperty(runtime, "isActive", event.strikethrough.isActive); + payload.setProperty(runtime, "strikethrough", strikethrough); +} +{ + auto spoiler = jsi::Object(runtime); + spoiler.setProperty(runtime, "isActive", event.spoiler.isActive); + payload.setProperty(runtime, "spoiler", spoiler); +} +{ + auto link = jsi::Object(runtime); + link.setProperty(runtime, "isActive", event.link.isActive); + link.setProperty(runtime, "destination", event.link.destination); + payload.setProperty(runtime, "link", link); +} +{ + auto heading = jsi::Object(runtime); + heading.setProperty(runtime, "isActive", event.heading.isActive); + heading.setProperty(runtime, "level", event.heading.level); + payload.setProperty(runtime, "heading", heading); +} +{ + auto unorderedList = jsi::Object(runtime); + unorderedList.setProperty(runtime, "isActive", event.unorderedList.isActive); + unorderedList.setProperty(runtime, "depth", event.unorderedList.depth); + payload.setProperty(runtime, "unorderedList", unorderedList); +} +{ + auto orderedList = jsi::Object(runtime); + orderedList.setProperty(runtime, "isActive", event.orderedList.isActive); + orderedList.setProperty(runtime, "depth", event.orderedList.depth); + payload.setProperty(runtime, "orderedList", orderedList); +} + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onInputFocus(OnInputFocus event) const { + dispatchEvent("inputFocus", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "target", event.target); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onInputBlur(OnInputBlur event) const { + dispatchEvent("inputBlur", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "target", event.target); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onRequestMarkdownResult(OnRequestMarkdownResult event) const { + dispatchEvent("requestMarkdownResult", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "requestId", event.requestId); +payload.setProperty(runtime, "markdown", event.markdown); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onRequestCaretRectResult(OnRequestCaretRectResult event) const { + dispatchEvent("requestCaretRectResult", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "requestId", event.requestId); +payload.setProperty(runtime, "x", event.x); +payload.setProperty(runtime, "y", event.y); +payload.setProperty(runtime, "width", event.width); +payload.setProperty(runtime, "height", event.height); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onCaretRectChange(OnCaretRectChange event) const { + dispatchEvent("caretRectChange", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "x", event.x); +payload.setProperty(runtime, "y", event.y); +payload.setProperty(runtime, "width", event.width); +payload.setProperty(runtime, "height", event.height); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const { + dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "itemText", event.itemText); +payload.setProperty(runtime, "selectedText", event.selectedText); +payload.setProperty(runtime, "selectionStart", event.selectionStart); +payload.setProperty(runtime, "selectionEnd", event.selectionEnd); +{ + auto styleState = jsi::Object(runtime); + { + auto bold = jsi::Object(runtime); + bold.setProperty(runtime, "isActive", event.styleState.bold.isActive); + styleState.setProperty(runtime, "bold", bold); + } + { + auto italic = jsi::Object(runtime); + italic.setProperty(runtime, "isActive", event.styleState.italic.isActive); + styleState.setProperty(runtime, "italic", italic); + } + { + auto underline = jsi::Object(runtime); + underline.setProperty(runtime, "isActive", event.styleState.underline.isActive); + styleState.setProperty(runtime, "underline", underline); + } + { + auto strikethrough = jsi::Object(runtime); + strikethrough.setProperty(runtime, "isActive", event.styleState.strikethrough.isActive); + styleState.setProperty(runtime, "strikethrough", strikethrough); + } + { + auto spoiler = jsi::Object(runtime); + spoiler.setProperty(runtime, "isActive", event.styleState.spoiler.isActive); + styleState.setProperty(runtime, "spoiler", spoiler); + } + { + auto link = jsi::Object(runtime); + link.setProperty(runtime, "isActive", event.styleState.link.isActive); + link.setProperty(runtime, "destination", event.styleState.link.destination); + styleState.setProperty(runtime, "link", link); + } + { + auto heading = jsi::Object(runtime); + heading.setProperty(runtime, "isActive", event.styleState.heading.isActive); + heading.setProperty(runtime, "level", event.styleState.heading.level); + styleState.setProperty(runtime, "heading", heading); + } + { + auto unorderedList = jsi::Object(runtime); + unorderedList.setProperty(runtime, "isActive", event.styleState.unorderedList.isActive); + unorderedList.setProperty(runtime, "depth", event.styleState.unorderedList.depth); + styleState.setProperty(runtime, "unorderedList", unorderedList); + } + { + auto orderedList = jsi::Object(runtime); + orderedList.setProperty(runtime, "isActive", event.styleState.orderedList.isActive); + orderedList.setProperty(runtime, "depth", event.styleState.orderedList.depth); + styleState.setProperty(runtime, "orderedList", orderedList); + } + payload.setProperty(runtime, "styleState", styleState); +} + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onLinkDetected(OnLinkDetected event) const { + dispatchEvent("linkDetected", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "text", event.text); +payload.setProperty(runtime, "url", event.url); +payload.setProperty(runtime, "start", event.start); +payload.setProperty(runtime, "end", event.end); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onStartMention(OnStartMention event) const { + dispatchEvent("startMention", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "indicator", event.indicator); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onChangeMention(OnChangeMention event) const { + dispatchEvent("changeMention", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "indicator", event.indicator); +payload.setProperty(runtime, "text", event.text); + return payload; + }); +} + + +void EnrichedMarkdownTextInputEventEmitter::onEndMention(OnEndMention event) const { + dispatchEvent("endMention", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "indicator", event.indicator); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onLinkPress(OnLinkPress event) const { + dispatchEvent("linkPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); + payload.setProperty(runtime, "sourceType", event.sourceType); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onLinkLongPress(OnLinkLongPress event) const { + dispatchEvent("linkLongPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onImagePress(OnImagePress event) const { + dispatchEvent("imagePress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); +payload.setProperty(runtime, "altText", event.altText); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onTaskListItemPress(OnTaskListItemPress event) const { + dispatchEvent("taskListItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "index", event.index); +payload.setProperty(runtime, "checked", event.checked); +payload.setProperty(runtime, "text", event.text); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onCopyPress(OnCopyPress event) const { + dispatchEvent("copyPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "code", event.code); +payload.setProperty(runtime, "language", event.language); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onCodeBlockPress(OnCodeBlockPress event) const { + dispatchEvent("codeBlockPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "code", event.code); +payload.setProperty(runtime, "language", event.language); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onLatexError(OnLatexError event) const { + dispatchEvent("latexError", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "source", event.source); +payload.setProperty(runtime, "message", event.message); +payload.setProperty(runtime, "displayMode", event.displayMode); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onLinkContextMenuItemPress(OnLinkContextMenuItemPress event) const { + dispatchEvent("linkContextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "url", event.url); +payload.setProperty(runtime, "pattern", event.pattern); +payload.setProperty(runtime, "itemText", event.itemText); + return payload; + }); +} + + +void EnrichedMarkdownTextEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const { + dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) { + auto payload = jsi::Object(runtime); + payload.setProperty(runtime, "itemText", event.itemText); +payload.setProperty(runtime, "selectedText", event.selectedText); +payload.setProperty(runtime, "selectionStart", event.selectionStart); +payload.setProperty(runtime, "selectionEnd", event.selectionEnd); + return payload; + }); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.h new file mode 100644 index 000000000000..5935112e7202 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/EventEmitters.h @@ -0,0 +1,366 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateEventEmitterH.js + */ +#pragma once + +#include + + +namespace facebook::react { +class EnrichedMarkdownEventEmitter : public ViewEventEmitter { + public: + using ViewEventEmitter::ViewEventEmitter; + + struct OnLinkPress { + std::string url; + std::string sourceType; + }; + + struct OnLinkLongPress { + std::string url; + }; + + struct OnImagePress { + std::string url; + std::string altText; + }; + + struct OnTaskListItemPress { + int index; + bool checked; + std::string text; + }; + + struct OnCopyPress { + std::string code; + std::string language; + }; + + struct OnCodeBlockPress { + std::string code; + std::string language; + }; + + struct OnLatexError { + std::string source; + std::string message; + bool displayMode; + }; + + struct OnLinkContextMenuItemPress { + std::string url; + std::string pattern; + std::string itemText; + }; + + struct OnContextMenuItemPress { + std::string itemText; + std::string selectedText; + int selectionStart; + int selectionEnd; + }; + void onLinkPress(OnLinkPress value) const; + + void onLinkLongPress(OnLinkLongPress value) const; + + void onImagePress(OnImagePress value) const; + + void onTaskListItemPress(OnTaskListItemPress value) const; + + void onCopyPress(OnCopyPress value) const; + + void onCodeBlockPress(OnCodeBlockPress value) const; + + void onLatexError(OnLatexError value) const; + + void onLinkContextMenuItemPress(OnLinkContextMenuItemPress value) const; + + void onContextMenuItemPress(OnContextMenuItemPress value) const; +}; +class EnrichedMarkdownTextInputEventEmitter : public ViewEventEmitter { + public: + using ViewEventEmitter::ViewEventEmitter; + + struct OnChangeText { + std::string value; + }; + + struct OnChangeMarkdown { + std::string value; + }; + + struct OnChangeSelection { + int start; + int end; + }; + + struct OnInputKeyPress { + std::string key; + }; + + struct OnChangeStateBold { + bool isActive; + }; + + struct OnChangeStateItalic { + bool isActive; + }; + + struct OnChangeStateUnderline { + bool isActive; + }; + + struct OnChangeStateStrikethrough { + bool isActive; + }; + + struct OnChangeStateSpoiler { + bool isActive; + }; + + struct OnChangeStateLink { + bool isActive; + std::string destination; + }; + + struct OnChangeStateHeading { + bool isActive; + int level; + }; + + struct OnChangeStateUnorderedList { + bool isActive; + int depth; + }; + + struct OnChangeStateOrderedList { + bool isActive; + int depth; + }; + + struct OnChangeState { + OnChangeStateBold bold; + OnChangeStateItalic italic; + OnChangeStateUnderline underline; + OnChangeStateStrikethrough strikethrough; + OnChangeStateSpoiler spoiler; + OnChangeStateLink link; + OnChangeStateHeading heading; + OnChangeStateUnorderedList unorderedList; + OnChangeStateOrderedList orderedList; + }; + + struct OnInputFocus { + int target; + }; + + struct OnInputBlur { + int target; + }; + + struct OnRequestMarkdownResult { + int requestId; + std::string markdown; + }; + + struct OnRequestCaretRectResult { + int requestId; + double x; + double y; + double width; + double height; + }; + + struct OnCaretRectChange { + double x; + double y; + double width; + double height; + }; + + struct OnContextMenuItemPressStyleStateBold { + bool isActive; + }; + + struct OnContextMenuItemPressStyleStateItalic { + bool isActive; + }; + + struct OnContextMenuItemPressStyleStateUnderline { + bool isActive; + }; + + struct OnContextMenuItemPressStyleStateStrikethrough { + bool isActive; + }; + + struct OnContextMenuItemPressStyleStateSpoiler { + bool isActive; + }; + + struct OnContextMenuItemPressStyleStateLink { + bool isActive; + std::string destination; + }; + + struct OnContextMenuItemPressStyleStateHeading { + bool isActive; + int level; + }; + + struct OnContextMenuItemPressStyleStateUnorderedList { + bool isActive; + int depth; + }; + + struct OnContextMenuItemPressStyleStateOrderedList { + bool isActive; + int depth; + }; + + struct OnContextMenuItemPressStyleState { + OnContextMenuItemPressStyleStateBold bold; + OnContextMenuItemPressStyleStateItalic italic; + OnContextMenuItemPressStyleStateUnderline underline; + OnContextMenuItemPressStyleStateStrikethrough strikethrough; + OnContextMenuItemPressStyleStateSpoiler spoiler; + OnContextMenuItemPressStyleStateLink link; + OnContextMenuItemPressStyleStateHeading heading; + OnContextMenuItemPressStyleStateUnorderedList unorderedList; + OnContextMenuItemPressStyleStateOrderedList orderedList; + }; + + struct OnContextMenuItemPress { + std::string itemText; + std::string selectedText; + int selectionStart; + int selectionEnd; + OnContextMenuItemPressStyleState styleState; + }; + + struct OnLinkDetected { + std::string text; + std::string url; + int start; + int end; + }; + + struct OnStartMention { + std::string indicator; + }; + + struct OnChangeMention { + std::string indicator; + std::string text; + }; + + struct OnEndMention { + std::string indicator; + }; + void onChangeText(OnChangeText value) const; + + void onChangeMarkdown(OnChangeMarkdown value) const; + + void onChangeSelection(OnChangeSelection value) const; + + void onInputKeyPress(OnInputKeyPress value) const; + + void onChangeState(OnChangeState value) const; + + void onInputFocus(OnInputFocus value) const; + + void onInputBlur(OnInputBlur value) const; + + void onRequestMarkdownResult(OnRequestMarkdownResult value) const; + + void onRequestCaretRectResult(OnRequestCaretRectResult value) const; + + void onCaretRectChange(OnCaretRectChange value) const; + + void onContextMenuItemPress(OnContextMenuItemPress value) const; + + void onLinkDetected(OnLinkDetected value) const; + + void onStartMention(OnStartMention value) const; + + void onChangeMention(OnChangeMention value) const; + + void onEndMention(OnEndMention value) const; +}; +class EnrichedMarkdownTextEventEmitter : public ViewEventEmitter { + public: + using ViewEventEmitter::ViewEventEmitter; + + struct OnLinkPress { + std::string url; + std::string sourceType; + }; + + struct OnLinkLongPress { + std::string url; + }; + + struct OnImagePress { + std::string url; + std::string altText; + }; + + struct OnTaskListItemPress { + int index; + bool checked; + std::string text; + }; + + struct OnCopyPress { + std::string code; + std::string language; + }; + + struct OnCodeBlockPress { + std::string code; + std::string language; + }; + + struct OnLatexError { + std::string source; + std::string message; + bool displayMode; + }; + + struct OnLinkContextMenuItemPress { + std::string url; + std::string pattern; + std::string itemText; + }; + + struct OnContextMenuItemPress { + std::string itemText; + std::string selectedText; + int selectionStart; + int selectionEnd; + }; + void onLinkPress(OnLinkPress value) const; + + void onLinkLongPress(OnLinkLongPress value) const; + + void onImagePress(OnImagePress value) const; + + void onTaskListItemPress(OnTaskListItemPress value) const; + + void onCopyPress(OnCopyPress value) const; + + void onCodeBlockPress(OnCodeBlockPress value) const; + + void onLatexError(OnLatexError value) const; + + void onLinkContextMenuItemPress(OnLinkContextMenuItemPress value) const; + + void onContextMenuItemPress(OnContextMenuItemPress value) const; +}; +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.cpp b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.cpp new file mode 100644 index 000000000000..3e20b67765fc --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.cpp @@ -0,0 +1,510 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GeneratePropsCpp.js + */ + +#include "Props.h" +#include +#include + +namespace facebook::react { + +EnrichedMarkdownProps::EnrichedMarkdownProps( + const PropsParserContext &context, + const EnrichedMarkdownProps &sourceProps, + const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), + + markdown(convertRawProp(context, rawProps, "markdown", sourceProps.markdown, {})), + markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})), + enableImagePress(convertRawProp(context, rawProps, "enableImagePress", sourceProps.enableImagePress, {false})), + enableTaskListItemToggle(convertRawProp(context, rawProps, "enableTaskListItemToggle", sourceProps.enableTaskListItemToggle, {true})), + enableCodeBlockPress(convertRawProp(context, rawProps, "enableCodeBlockPress", sourceProps.enableCodeBlockPress, {false})), + enableBlockContextMenu(convertRawProp(context, rawProps, "enableBlockContextMenu", sourceProps.enableBlockContextMenu, {true})), + enableLinkPreview(convertRawProp(context, rawProps, "enableLinkPreview", sourceProps.enableLinkPreview, {true})), + selectable(convertRawProp(context, rawProps, "selectable", sourceProps.selectable, {false})), + selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})), + selectionHandleColor(convertRawProp(context, rawProps, "selectionHandleColor", sourceProps.selectionHandleColor, {})), + md4cFlags(convertRawProp(context, rawProps, "md4cFlags", sourceProps.md4cFlags, {})), + isGFM(convertRawProp(context, rawProps, "isGFM", sourceProps.isGFM, {true})), + allowFontScaling(convertRawProp(context, rawProps, "allowFontScaling", sourceProps.allowFontScaling, {true})), + maxFontSizeMultiplier(convertRawProp(context, rawProps, "maxFontSizeMultiplier", sourceProps.maxFontSizeMultiplier, {0.0})), + allowTrailingMargin(convertRawProp(context, rawProps, "allowTrailingMargin", sourceProps.allowTrailingMargin, {false})), + streamingAnimation(convertRawProp(context, rawProps, "streamingAnimation", sourceProps.streamingAnimation, {false})), + streamingConfig(convertRawProp(context, rawProps, "streamingConfig", sourceProps.streamingConfig, {})), + spoilerOverlay(convertRawProp(context, rawProps, "spoilerOverlay", sourceProps.spoilerOverlay, {std::string{"particles"}})), + contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})), + imageRequestHeaders(convertRawProp(context, rawProps, "imageRequestHeaders", sourceProps.imageRequestHeaders, {})), + linkPillContent(convertRawProp(context, rawProps, "linkPillContent", sourceProps.linkPillContent, {})), + linkRecognition(convertRawProp(context, rawProps, "linkRecognition", sourceProps.linkRecognition, {})), + linkContextMenuItems(convertRawProp(context, rawProps, "linkContextMenuItems", sourceProps.linkContextMenuItems, {})), + selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})), + accessibilityLabels(convertRawProp(context, rawProps, "accessibilityLabels", sourceProps.accessibilityLabels, {})), + textBreakStrategy(convertRawProp(context, rawProps, "textBreakStrategy", sourceProps.textBreakStrategy, {std::string{"highQuality"}})), + lineBreakStrategyIOS(convertRawProp(context, rawProps, "lineBreakStrategyIOS", sourceProps.lineBreakStrategyIOS, {std::string{"none"}})), + writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})), + numberOfLines(convertRawProp(context, rawProps, "numberOfLines", sourceProps.numberOfLines, {0})), + ellipsizeMode(convertRawProp(context, rawProps, "ellipsizeMode", sourceProps.ellipsizeMode, {std::string{"tail"}})) {} + +#ifdef RN_SERIALIZABLE_STATE +ComponentName EnrichedMarkdownProps::getDiffPropsImplementationTarget() const { + return "EnrichedMarkdown"; +} + +folly::dynamic EnrichedMarkdownProps::getDiffProps( + const Props* prevProps) const { + static const auto defaultProps = EnrichedMarkdownProps(); + const EnrichedMarkdownProps* oldProps = prevProps == nullptr + ? &defaultProps + : static_cast(prevProps); + if (this == oldProps) { + return folly::dynamic::object(); + } + folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps); + + if (markdown != oldProps->markdown) { + result["markdown"] = markdown; + } + + if (markdownStyle != oldProps->markdownStyle) { + result["markdownStyle"] = toDynamic(markdownStyle); + } + + if (enableImagePress != oldProps->enableImagePress) { + result["enableImagePress"] = enableImagePress; + } + + if (enableTaskListItemToggle != oldProps->enableTaskListItemToggle) { + result["enableTaskListItemToggle"] = enableTaskListItemToggle; + } + + if (enableCodeBlockPress != oldProps->enableCodeBlockPress) { + result["enableCodeBlockPress"] = enableCodeBlockPress; + } + + if (enableBlockContextMenu != oldProps->enableBlockContextMenu) { + result["enableBlockContextMenu"] = enableBlockContextMenu; + } + + if (enableLinkPreview != oldProps->enableLinkPreview) { + result["enableLinkPreview"] = enableLinkPreview; + } + + if (selectable != oldProps->selectable) { + result["selectable"] = selectable; + } + + if (selectionColor != oldProps->selectionColor) { + result["selectionColor"] = *selectionColor; + } + + if (selectionHandleColor != oldProps->selectionHandleColor) { + result["selectionHandleColor"] = *selectionHandleColor; + } + + if (md4cFlags != oldProps->md4cFlags) { + result["md4cFlags"] = toDynamic(md4cFlags); + } + + if (isGFM != oldProps->isGFM) { + result["isGFM"] = isGFM; + } + + if (allowFontScaling != oldProps->allowFontScaling) { + result["allowFontScaling"] = allowFontScaling; + } + + if ((maxFontSizeMultiplier != oldProps->maxFontSizeMultiplier) && !(std::isnan(maxFontSizeMultiplier) && std::isnan(oldProps->maxFontSizeMultiplier))) { + result["maxFontSizeMultiplier"] = maxFontSizeMultiplier; + } + + if (allowTrailingMargin != oldProps->allowTrailingMargin) { + result["allowTrailingMargin"] = allowTrailingMargin; + } + + if (streamingAnimation != oldProps->streamingAnimation) { + result["streamingAnimation"] = streamingAnimation; + } + + if (streamingConfig != oldProps->streamingConfig) { + result["streamingConfig"] = toDynamic(streamingConfig); + } + + if (spoilerOverlay != oldProps->spoilerOverlay) { + result["spoilerOverlay"] = spoilerOverlay; + } + + if (contextMenuItems != oldProps->contextMenuItems) { + result["contextMenuItems"] = toDynamic(contextMenuItems); + } + + if (imageRequestHeaders != oldProps->imageRequestHeaders) { + result["imageRequestHeaders"] = toDynamic(imageRequestHeaders); + } + + if (linkPillContent != oldProps->linkPillContent) { + result["linkPillContent"] = toDynamic(linkPillContent); + } + + if (linkRecognition != oldProps->linkRecognition) { + result["linkRecognition"] = toDynamic(linkRecognition); + } + + if (linkContextMenuItems != oldProps->linkContextMenuItems) { + result["linkContextMenuItems"] = toDynamic(linkContextMenuItems); + } + + if (selectionMenuConfig != oldProps->selectionMenuConfig) { + result["selectionMenuConfig"] = toDynamic(selectionMenuConfig); + } + + if (accessibilityLabels != oldProps->accessibilityLabels) { + result["accessibilityLabels"] = toDynamic(accessibilityLabels); + } + + if (textBreakStrategy != oldProps->textBreakStrategy) { + result["textBreakStrategy"] = textBreakStrategy; + } + + if (lineBreakStrategyIOS != oldProps->lineBreakStrategyIOS) { + result["lineBreakStrategyIOS"] = lineBreakStrategyIOS; + } + + if (writingDirection != oldProps->writingDirection) { + result["writingDirection"] = writingDirection; + } + + if (numberOfLines != oldProps->numberOfLines) { + result["numberOfLines"] = numberOfLines; + } + + if (ellipsizeMode != oldProps->ellipsizeMode) { + result["ellipsizeMode"] = ellipsizeMode; + } + return result; +} +#endif +EnrichedMarkdownTextInputProps::EnrichedMarkdownTextInputProps( + const PropsParserContext &context, + const EnrichedMarkdownTextInputProps &sourceProps, + const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), + + defaultValue(convertRawProp(context, rawProps, "defaultValue", sourceProps.defaultValue, {})), + placeholder(convertRawProp(context, rawProps, "placeholder", sourceProps.placeholder, {})), + placeholderTextColor(convertRawProp(context, rawProps, "placeholderTextColor", sourceProps.placeholderTextColor, {})), + editable(convertRawProp(context, rawProps, "editable", sourceProps.editable, {false})), + autoFocus(convertRawProp(context, rawProps, "autoFocus", sourceProps.autoFocus, {false})), + scrollEnabled(convertRawProp(context, rawProps, "scrollEnabled", sourceProps.scrollEnabled, {false})), + markdownShortcuts(convertRawProp(context, rawProps, "markdownShortcuts", sourceProps.markdownShortcuts, {})), + autoCapitalize(convertRawProp(context, rawProps, "autoCapitalize", sourceProps.autoCapitalize, {})), + multiline(convertRawProp(context, rawProps, "multiline", sourceProps.multiline, {false})), + cursorColor(convertRawProp(context, rawProps, "cursorColor", sourceProps.cursorColor, {})), + selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})), + markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})), + color(convertRawProp(context, rawProps, "color", sourceProps.color, {})), + fontSize(convertRawProp(context, rawProps, "fontSize", sourceProps.fontSize, {0.0})), + lineHeight(convertRawProp(context, rawProps, "lineHeight", sourceProps.lineHeight, {0.0})), + fontFamily(convertRawProp(context, rawProps, "fontFamily", sourceProps.fontFamily, {})), + fontWeight(convertRawProp(context, rawProps, "fontWeight", sourceProps.fontWeight, {})), + isOnChangeMarkdownSet(convertRawProp(context, rawProps, "isOnChangeMarkdownSet", sourceProps.isOnChangeMarkdownSet, {false})), + contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})), + selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})), + formatMenuConfig(convertRawProp(context, rawProps, "formatMenuConfig", sourceProps.formatMenuConfig, {})), + linkRegex(convertRawProp(context, rawProps, "linkRegex", sourceProps.linkRegex, {})), + mentionIndicators(convertRawProp(context, rawProps, "mentionIndicators", sourceProps.mentionIndicators, {})), + writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})) {} + +#ifdef RN_SERIALIZABLE_STATE +ComponentName EnrichedMarkdownTextInputProps::getDiffPropsImplementationTarget() const { + return "EnrichedMarkdownTextInput"; +} + +folly::dynamic EnrichedMarkdownTextInputProps::getDiffProps( + const Props* prevProps) const { + static const auto defaultProps = EnrichedMarkdownTextInputProps(); + const EnrichedMarkdownTextInputProps* oldProps = prevProps == nullptr + ? &defaultProps + : static_cast(prevProps); + if (this == oldProps) { + return folly::dynamic::object(); + } + folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps); + + if (defaultValue != oldProps->defaultValue) { + result["defaultValue"] = defaultValue; + } + + if (placeholder != oldProps->placeholder) { + result["placeholder"] = placeholder; + } + + if (placeholderTextColor != oldProps->placeholderTextColor) { + result["placeholderTextColor"] = *placeholderTextColor; + } + + if (editable != oldProps->editable) { + result["editable"] = editable; + } + + if (autoFocus != oldProps->autoFocus) { + result["autoFocus"] = autoFocus; + } + + if (scrollEnabled != oldProps->scrollEnabled) { + result["scrollEnabled"] = scrollEnabled; + } + + if (markdownShortcuts != oldProps->markdownShortcuts) { + result["markdownShortcuts"] = toDynamic(markdownShortcuts); + } + + if (autoCapitalize != oldProps->autoCapitalize) { + result["autoCapitalize"] = autoCapitalize; + } + + if (multiline != oldProps->multiline) { + result["multiline"] = multiline; + } + + if (cursorColor != oldProps->cursorColor) { + result["cursorColor"] = *cursorColor; + } + + if (selectionColor != oldProps->selectionColor) { + result["selectionColor"] = *selectionColor; + } + + if (markdownStyle != oldProps->markdownStyle) { + result["markdownStyle"] = toDynamic(markdownStyle); + } + + if (color != oldProps->color) { + result["color"] = *color; + } + + if ((fontSize != oldProps->fontSize) && !(std::isnan(fontSize) && std::isnan(oldProps->fontSize))) { + result["fontSize"] = fontSize; + } + + if ((lineHeight != oldProps->lineHeight) && !(std::isnan(lineHeight) && std::isnan(oldProps->lineHeight))) { + result["lineHeight"] = lineHeight; + } + + if (fontFamily != oldProps->fontFamily) { + result["fontFamily"] = fontFamily; + } + + if (fontWeight != oldProps->fontWeight) { + result["fontWeight"] = fontWeight; + } + + if (isOnChangeMarkdownSet != oldProps->isOnChangeMarkdownSet) { + result["isOnChangeMarkdownSet"] = isOnChangeMarkdownSet; + } + + if (contextMenuItems != oldProps->contextMenuItems) { + result["contextMenuItems"] = toDynamic(contextMenuItems); + } + + if (selectionMenuConfig != oldProps->selectionMenuConfig) { + result["selectionMenuConfig"] = toDynamic(selectionMenuConfig); + } + + if (formatMenuConfig != oldProps->formatMenuConfig) { + result["formatMenuConfig"] = toDynamic(formatMenuConfig); + } + + if (linkRegex != oldProps->linkRegex) { + result["linkRegex"] = toDynamic(linkRegex); + } + + if (mentionIndicators != oldProps->mentionIndicators) { + result["mentionIndicators"] = toDynamic(mentionIndicators); + } + + if (writingDirection != oldProps->writingDirection) { + result["writingDirection"] = writingDirection; + } + return result; +} +#endif +EnrichedMarkdownTextProps::EnrichedMarkdownTextProps( + const PropsParserContext &context, + const EnrichedMarkdownTextProps &sourceProps, + const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), + + markdown(convertRawProp(context, rawProps, "markdown", sourceProps.markdown, {})), + markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})), + enableImagePress(convertRawProp(context, rawProps, "enableImagePress", sourceProps.enableImagePress, {false})), + enableTaskListItemToggle(convertRawProp(context, rawProps, "enableTaskListItemToggle", sourceProps.enableTaskListItemToggle, {true})), + enableCodeBlockPress(convertRawProp(context, rawProps, "enableCodeBlockPress", sourceProps.enableCodeBlockPress, {false})), + enableBlockContextMenu(convertRawProp(context, rawProps, "enableBlockContextMenu", sourceProps.enableBlockContextMenu, {true})), + enableLinkPreview(convertRawProp(context, rawProps, "enableLinkPreview", sourceProps.enableLinkPreview, {true})), + selectable(convertRawProp(context, rawProps, "selectable", sourceProps.selectable, {false})), + selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})), + selectionHandleColor(convertRawProp(context, rawProps, "selectionHandleColor", sourceProps.selectionHandleColor, {})), + md4cFlags(convertRawProp(context, rawProps, "md4cFlags", sourceProps.md4cFlags, {})), + isGFM(convertRawProp(context, rawProps, "isGFM", sourceProps.isGFM, {false})), + allowFontScaling(convertRawProp(context, rawProps, "allowFontScaling", sourceProps.allowFontScaling, {true})), + maxFontSizeMultiplier(convertRawProp(context, rawProps, "maxFontSizeMultiplier", sourceProps.maxFontSizeMultiplier, {0.0})), + allowTrailingMargin(convertRawProp(context, rawProps, "allowTrailingMargin", sourceProps.allowTrailingMargin, {false})), + streamingAnimation(convertRawProp(context, rawProps, "streamingAnimation", sourceProps.streamingAnimation, {false})), + streamingConfig(convertRawProp(context, rawProps, "streamingConfig", sourceProps.streamingConfig, {})), + spoilerOverlay(convertRawProp(context, rawProps, "spoilerOverlay", sourceProps.spoilerOverlay, {std::string{"particles"}})), + contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})), + imageRequestHeaders(convertRawProp(context, rawProps, "imageRequestHeaders", sourceProps.imageRequestHeaders, {})), + linkPillContent(convertRawProp(context, rawProps, "linkPillContent", sourceProps.linkPillContent, {})), + linkRecognition(convertRawProp(context, rawProps, "linkRecognition", sourceProps.linkRecognition, {})), + linkContextMenuItems(convertRawProp(context, rawProps, "linkContextMenuItems", sourceProps.linkContextMenuItems, {})), + selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})), + accessibilityLabels(convertRawProp(context, rawProps, "accessibilityLabels", sourceProps.accessibilityLabels, {})), + textBreakStrategy(convertRawProp(context, rawProps, "textBreakStrategy", sourceProps.textBreakStrategy, {std::string{"highQuality"}})), + lineBreakStrategyIOS(convertRawProp(context, rawProps, "lineBreakStrategyIOS", sourceProps.lineBreakStrategyIOS, {std::string{"none"}})), + writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})), + numberOfLines(convertRawProp(context, rawProps, "numberOfLines", sourceProps.numberOfLines, {0})), + ellipsizeMode(convertRawProp(context, rawProps, "ellipsizeMode", sourceProps.ellipsizeMode, {std::string{"tail"}})) {} + +#ifdef RN_SERIALIZABLE_STATE +ComponentName EnrichedMarkdownTextProps::getDiffPropsImplementationTarget() const { + return "EnrichedMarkdownText"; +} + +folly::dynamic EnrichedMarkdownTextProps::getDiffProps( + const Props* prevProps) const { + static const auto defaultProps = EnrichedMarkdownTextProps(); + const EnrichedMarkdownTextProps* oldProps = prevProps == nullptr + ? &defaultProps + : static_cast(prevProps); + if (this == oldProps) { + return folly::dynamic::object(); + } + folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps); + + if (markdown != oldProps->markdown) { + result["markdown"] = markdown; + } + + if (markdownStyle != oldProps->markdownStyle) { + result["markdownStyle"] = toDynamic(markdownStyle); + } + + if (enableImagePress != oldProps->enableImagePress) { + result["enableImagePress"] = enableImagePress; + } + + if (enableTaskListItemToggle != oldProps->enableTaskListItemToggle) { + result["enableTaskListItemToggle"] = enableTaskListItemToggle; + } + + if (enableCodeBlockPress != oldProps->enableCodeBlockPress) { + result["enableCodeBlockPress"] = enableCodeBlockPress; + } + + if (enableBlockContextMenu != oldProps->enableBlockContextMenu) { + result["enableBlockContextMenu"] = enableBlockContextMenu; + } + + if (enableLinkPreview != oldProps->enableLinkPreview) { + result["enableLinkPreview"] = enableLinkPreview; + } + + if (selectable != oldProps->selectable) { + result["selectable"] = selectable; + } + + if (selectionColor != oldProps->selectionColor) { + result["selectionColor"] = *selectionColor; + } + + if (selectionHandleColor != oldProps->selectionHandleColor) { + result["selectionHandleColor"] = *selectionHandleColor; + } + + if (md4cFlags != oldProps->md4cFlags) { + result["md4cFlags"] = toDynamic(md4cFlags); + } + + if (isGFM != oldProps->isGFM) { + result["isGFM"] = isGFM; + } + + if (allowFontScaling != oldProps->allowFontScaling) { + result["allowFontScaling"] = allowFontScaling; + } + + if ((maxFontSizeMultiplier != oldProps->maxFontSizeMultiplier) && !(std::isnan(maxFontSizeMultiplier) && std::isnan(oldProps->maxFontSizeMultiplier))) { + result["maxFontSizeMultiplier"] = maxFontSizeMultiplier; + } + + if (allowTrailingMargin != oldProps->allowTrailingMargin) { + result["allowTrailingMargin"] = allowTrailingMargin; + } + + if (streamingAnimation != oldProps->streamingAnimation) { + result["streamingAnimation"] = streamingAnimation; + } + + if (streamingConfig != oldProps->streamingConfig) { + result["streamingConfig"] = toDynamic(streamingConfig); + } + + if (spoilerOverlay != oldProps->spoilerOverlay) { + result["spoilerOverlay"] = spoilerOverlay; + } + + if (contextMenuItems != oldProps->contextMenuItems) { + result["contextMenuItems"] = toDynamic(contextMenuItems); + } + + if (imageRequestHeaders != oldProps->imageRequestHeaders) { + result["imageRequestHeaders"] = toDynamic(imageRequestHeaders); + } + + if (linkPillContent != oldProps->linkPillContent) { + result["linkPillContent"] = toDynamic(linkPillContent); + } + + if (linkRecognition != oldProps->linkRecognition) { + result["linkRecognition"] = toDynamic(linkRecognition); + } + + if (linkContextMenuItems != oldProps->linkContextMenuItems) { + result["linkContextMenuItems"] = toDynamic(linkContextMenuItems); + } + + if (selectionMenuConfig != oldProps->selectionMenuConfig) { + result["selectionMenuConfig"] = toDynamic(selectionMenuConfig); + } + + if (accessibilityLabels != oldProps->accessibilityLabels) { + result["accessibilityLabels"] = toDynamic(accessibilityLabels); + } + + if (textBreakStrategy != oldProps->textBreakStrategy) { + result["textBreakStrategy"] = textBreakStrategy; + } + + if (lineBreakStrategyIOS != oldProps->lineBreakStrategyIOS) { + result["lineBreakStrategyIOS"] = lineBreakStrategyIOS; + } + + if (writingDirection != oldProps->writingDirection) { + result["writingDirection"] = writingDirection; + } + + if (numberOfLines != oldProps->numberOfLines) { + result["numberOfLines"] = numberOfLines; + } + + if (ellipsizeMode != oldProps->ellipsizeMode) { + result["ellipsizeMode"] = ellipsizeMode; + } + return result; +} +#endif + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h new file mode 100644 index 000000000000..bc76c2b19824 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/Props.h @@ -0,0 +1,8153 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GeneratePropsH.js + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +struct EnrichedMarkdownMarkdownStyleParagraphStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleParagraphStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleParagraphStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleParagraphStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleParagraphStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleParagraphStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH1Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH1Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH1Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH1Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH1Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH1Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH2Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH2Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH2Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH2Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH2Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH2Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH3Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH3Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH3Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH3Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH3Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH3Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH4Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH4Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH4Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH4Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH4Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH4Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH5Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH5Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH5Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH5Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH5Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH5Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleH6Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleH6Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleH6Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleH6Struct &value) { + return "[Object EnrichedMarkdownMarkdownStyleH6Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleH6Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct { + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsNoteStruct note{}; + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsTipStruct tip{}; + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsImportantStruct important{}; + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsWarningStruct warning{}; + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsCautionStruct caution{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["note"] = ::facebook::react::toDynamic(note); + result["tip"] = ::facebook::react::toDynamic(tip); + result["important"] = ::facebook::react::toDynamic(important); + result["warning"] = ::facebook::react::toDynamic(warning); + result["caution"] = ::facebook::react::toDynamic(caution); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_note = map.find("note"); + if (tmp_note != map.end()) { + fromRawValue(context, tmp_note->second, result.note); + } + auto tmp_tip = map.find("tip"); + if (tmp_tip != map.end()) { + fromRawValue(context, tmp_tip->second, result.tip); + } + auto tmp_important = map.find("important"); + if (tmp_important != map.end()) { + fromRawValue(context, tmp_important->second, result.important); + } + auto tmp_warning = map.find("warning"); + if (tmp_warning != map.end()) { + fromRawValue(context, tmp_warning->second, result.warning); + } + auto tmp_caution = map.find("caution"); + if (tmp_caution != map.end()) { + fromRawValue(context, tmp_caution->second, result.caution); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleBlockquoteStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor borderColor{}; + Float borderWidth{0.0}; + Float gapWidth{0.0}; + SharedColor backgroundColor{}; + Float borderRadius{0.0}; + Float padding{0.0}; + EnrichedMarkdownMarkdownStyleBlockquoteAdmonitionsStruct admonitions{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleBlockquoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderWidth"] = borderWidth; + result["gapWidth"] = gapWidth; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderRadius"] = borderRadius; + result["padding"] = padding; + result["admonitions"] = ::facebook::react::toDynamic(admonitions); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleBlockquoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_gapWidth = map.find("gapWidth"); + if (tmp_gapWidth != map.end()) { + fromRawValue(context, tmp_gapWidth->second, result.gapWidth); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_admonitions = map.find("admonitions"); + if (tmp_admonitions != map.end()) { + fromRawValue(context, tmp_admonitions->second, result.admonitions); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleBlockquoteStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleBlockquoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleBlockquoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleListStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor bulletColor{}; + Float bulletSize{0.0}; + Float markerMinWidth{0.0}; + SharedColor markerColor{}; + std::string markerFontWeight{}; + Float gapWidth{0.0}; + Float marginLeft{0.0}; + Float itemSpacing{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["bulletColor"] = ::facebook::react::toDynamic(bulletColor); + result["bulletSize"] = bulletSize; + result["markerMinWidth"] = markerMinWidth; + result["markerColor"] = ::facebook::react::toDynamic(markerColor); + result["markerFontWeight"] = markerFontWeight; + result["gapWidth"] = gapWidth; + result["marginLeft"] = marginLeft; + result["itemSpacing"] = itemSpacing; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_bulletColor = map.find("bulletColor"); + if (tmp_bulletColor != map.end()) { + fromRawValue(context, tmp_bulletColor->second, result.bulletColor); + } + auto tmp_bulletSize = map.find("bulletSize"); + if (tmp_bulletSize != map.end()) { + fromRawValue(context, tmp_bulletSize->second, result.bulletSize); + } + auto tmp_markerMinWidth = map.find("markerMinWidth"); + if (tmp_markerMinWidth != map.end()) { + fromRawValue(context, tmp_markerMinWidth->second, result.markerMinWidth); + } + auto tmp_markerColor = map.find("markerColor"); + if (tmp_markerColor != map.end()) { + fromRawValue(context, tmp_markerColor->second, result.markerColor); + } + auto tmp_markerFontWeight = map.find("markerFontWeight"); + if (tmp_markerFontWeight != map.end()) { + fromRawValue(context, tmp_markerFontWeight->second, result.markerFontWeight); + } + auto tmp_gapWidth = map.find("gapWidth"); + if (tmp_gapWidth != map.end()) { + fromRawValue(context, tmp_gapWidth->second, result.gapWidth); + } + auto tmp_marginLeft = map.find("marginLeft"); + if (tmp_marginLeft != map.end()) { + fromRawValue(context, tmp_marginLeft->second, result.marginLeft); + } + auto tmp_itemSpacing = map.find("itemSpacing"); + if (tmp_itemSpacing != map.end()) { + fromRawValue(context, tmp_itemSpacing->second, result.itemSpacing); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleListStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct { + SharedColor keyword{}; + SharedColor operatorColor{}; + SharedColor punctuation{}; + SharedColor string{}; + SharedColor number{}; + SharedColor constant{}; + SharedColor comment{}; + SharedColor function{}; + SharedColor type{}; + SharedColor variable{}; + SharedColor property{}; + SharedColor tag{}; + SharedColor attribute{}; + SharedColor embedded{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["keyword"] = ::facebook::react::toDynamic(keyword); + result["operatorColor"] = ::facebook::react::toDynamic(operatorColor); + result["punctuation"] = ::facebook::react::toDynamic(punctuation); + result["string"] = ::facebook::react::toDynamic(string); + result["number"] = ::facebook::react::toDynamic(number); + result["constant"] = ::facebook::react::toDynamic(constant); + result["comment"] = ::facebook::react::toDynamic(comment); + result["function"] = ::facebook::react::toDynamic(function); + result["type"] = ::facebook::react::toDynamic(type); + result["variable"] = ::facebook::react::toDynamic(variable); + result["property"] = ::facebook::react::toDynamic(property); + result["tag"] = ::facebook::react::toDynamic(tag); + result["attribute"] = ::facebook::react::toDynamic(attribute); + result["embedded"] = ::facebook::react::toDynamic(embedded); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_keyword = map.find("keyword"); + if (tmp_keyword != map.end()) { + fromRawValue(context, tmp_keyword->second, result.keyword); + } + auto tmp_operatorColor = map.find("operatorColor"); + if (tmp_operatorColor != map.end()) { + fromRawValue(context, tmp_operatorColor->second, result.operatorColor); + } + auto tmp_punctuation = map.find("punctuation"); + if (tmp_punctuation != map.end()) { + fromRawValue(context, tmp_punctuation->second, result.punctuation); + } + auto tmp_string = map.find("string"); + if (tmp_string != map.end()) { + fromRawValue(context, tmp_string->second, result.string); + } + auto tmp_number = map.find("number"); + if (tmp_number != map.end()) { + fromRawValue(context, tmp_number->second, result.number); + } + auto tmp_constant = map.find("constant"); + if (tmp_constant != map.end()) { + fromRawValue(context, tmp_constant->second, result.constant); + } + auto tmp_comment = map.find("comment"); + if (tmp_comment != map.end()) { + fromRawValue(context, tmp_comment->second, result.comment); + } + auto tmp_function = map.find("function"); + if (tmp_function != map.end()) { + fromRawValue(context, tmp_function->second, result.function); + } + auto tmp_type = map.find("type"); + if (tmp_type != map.end()) { + fromRawValue(context, tmp_type->second, result.type); + } + auto tmp_variable = map.find("variable"); + if (tmp_variable != map.end()) { + fromRawValue(context, tmp_variable->second, result.variable); + } + auto tmp_property = map.find("property"); + if (tmp_property != map.end()) { + fromRawValue(context, tmp_property->second, result.property); + } + auto tmp_tag = map.find("tag"); + if (tmp_tag != map.end()) { + fromRawValue(context, tmp_tag->second, result.tag); + } + auto tmp_attribute = map.find("attribute"); + if (tmp_attribute != map.end()) { + fromRawValue(context, tmp_attribute->second, result.attribute); + } + auto tmp_embedded = map.find("embedded"); + if (tmp_embedded != map.end()) { + fromRawValue(context, tmp_embedded->second, result.embedded); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleCodeBlockStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; + Float borderRadius{0.0}; + Float borderWidth{0.0}; + Float padding{0.0}; + EnrichedMarkdownMarkdownStyleCodeBlockSyntaxColorsStruct syntaxColors{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleCodeBlockStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderRadius"] = borderRadius; + result["borderWidth"] = borderWidth; + result["padding"] = padding; + result["syntaxColors"] = ::facebook::react::toDynamic(syntaxColors); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleCodeBlockStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_syntaxColors = map.find("syntaxColors"); + if (tmp_syntaxColors != map.end()) { + fromRawValue(context, tmp_syntaxColors->second, result.syntaxColors); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleCodeBlockStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleCodeBlockStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleCodeBlockStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleLinkStruct { + std::string fontFamily{}; + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleLinkStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleLinkStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleLinkStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleLinkStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleLinkStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct { + bool enabled{false}; + std::string label{}; + std::string iconUri{}; + SharedColor iconTintColor{}; + Float borderRadius{0.0}; + Float paddingHorizontal{0.0}; + Float paddingVertical{0.0}; + Float lineHeight{0.0}; + Float borderWidth{0.0}; + SharedColor borderColor{}; + Float maxWidth{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["enabled"] = enabled; + result["label"] = label; + result["iconUri"] = iconUri; + result["iconTintColor"] = ::facebook::react::toDynamic(iconTintColor); + result["borderRadius"] = borderRadius; + result["paddingHorizontal"] = paddingHorizontal; + result["paddingVertical"] = paddingVertical; + result["lineHeight"] = lineHeight; + result["borderWidth"] = borderWidth; + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["maxWidth"] = maxWidth; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_enabled = map.find("enabled"); + if (tmp_enabled != map.end()) { + fromRawValue(context, tmp_enabled->second, result.enabled); + } + auto tmp_label = map.find("label"); + if (tmp_label != map.end()) { + fromRawValue(context, tmp_label->second, result.label); + } + auto tmp_iconUri = map.find("iconUri"); + if (tmp_iconUri != map.end()) { + fromRawValue(context, tmp_iconUri->second, result.iconUri); + } + auto tmp_iconTintColor = map.find("iconTintColor"); + if (tmp_iconTintColor != map.end()) { + fromRawValue(context, tmp_iconTintColor->second, result.iconTintColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_paddingHorizontal = map.find("paddingHorizontal"); + if (tmp_paddingHorizontal != map.end()) { + fromRawValue(context, tmp_paddingHorizontal->second, result.paddingHorizontal); + } + auto tmp_paddingVertical = map.find("paddingVertical"); + if (tmp_paddingVertical != map.end()) { + fromRawValue(context, tmp_paddingVertical->second, result.paddingVertical); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_maxWidth = map.find("maxWidth"); + if (tmp_maxWidth != map.end()) { + fromRawValue(context, tmp_maxWidth->second, result.maxWidth); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleLinkVariantsStruct { + std::string pattern{}; + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + std::string fontFamily{}; + EnrichedMarkdownMarkdownStyleLinkVariantsPillStruct pill{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleLinkVariantsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["fontFamily"] = fontFamily; + result["pill"] = ::facebook::react::toDynamic(pill); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleLinkVariantsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_pill = map.find("pill"); + if (tmp_pill != map.end()) { + fromRawValue(context, tmp_pill->second, result.pill); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleLinkVariantsStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleLinkVariantsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleLinkVariantsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownMarkdownStyleLinkVariantsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownMarkdownStyleStrongStruct { + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleStrongStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleStrongStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleStrongStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleStrongStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleStrongStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleEmStruct { + std::string fontFamily{}; + std::string fontStyle{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleEmStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontStyle"] = fontStyle; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleEmStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontStyle = map.find("fontStyle"); + if (tmp_fontStyle != map.end()) { + fromRawValue(context, tmp_fontStyle->second, result.fontStyle); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleEmStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleEmStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleEmStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleStrikethroughStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleStrikethroughStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleStrikethroughStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleStrikethroughStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleStrikethroughStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleStrikethroughStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleUnderlineStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleUnderlineStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleUnderlineStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleUnderlineStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleUnderlineStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleUnderlineStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; + Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleCodeStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; + result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleCodeStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleCodeStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleCodeStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleCodeStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleImageStruct { + Float height{0.0}; + Float maxHeight{0.0}; + Float aspectRatio{0.0}; + std::string resizeMode{}; + Float borderRadius{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleImageStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["height"] = height; + result["maxHeight"] = maxHeight; + result["aspectRatio"] = aspectRatio; + result["resizeMode"] = resizeMode; + result["borderRadius"] = borderRadius; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleImageStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_height = map.find("height"); + if (tmp_height != map.end()) { + fromRawValue(context, tmp_height->second, result.height); + } + auto tmp_maxHeight = map.find("maxHeight"); + if (tmp_maxHeight != map.end()) { + fromRawValue(context, tmp_maxHeight->second, result.maxHeight); + } + auto tmp_aspectRatio = map.find("aspectRatio"); + if (tmp_aspectRatio != map.end()) { + fromRawValue(context, tmp_aspectRatio->second, result.aspectRatio); + } + auto tmp_resizeMode = map.find("resizeMode"); + if (tmp_resizeMode != map.end()) { + fromRawValue(context, tmp_resizeMode->second, result.resizeMode); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleImageStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleImageStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleImageStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleVideoStruct { + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float borderRadius{0.0}; + Float aspectRatio{0.0}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleVideoStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["borderRadius"] = borderRadius; + result["aspectRatio"] = aspectRatio; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleVideoStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_aspectRatio = map.find("aspectRatio"); + if (tmp_aspectRatio != map.end()) { + fromRawValue(context, tmp_aspectRatio->second, result.aspectRatio); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleVideoStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleVideoStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleVideoStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleInlineImageStruct { + Float size{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleInlineImageStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["size"] = size; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleInlineImageStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_size = map.find("size"); + if (tmp_size != map.end()) { + fromRawValue(context, tmp_size->second, result.size); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleInlineImageStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleInlineImageStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleInlineImageStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleThematicBreakStruct { + SharedColor color{}; + Float height{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleThematicBreakStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["height"] = height; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleThematicBreakStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_height = map.find("height"); + if (tmp_height != map.end()) { + fromRawValue(context, tmp_height->second, result.height); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleThematicBreakStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleThematicBreakStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleThematicBreakStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleTableStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string headerFontFamily{}; + SharedColor headerBackgroundColor{}; + SharedColor headerTextColor{}; + SharedColor rowEvenBackgroundColor{}; + SharedColor rowOddBackgroundColor{}; + SharedColor borderColor{}; + Float borderWidth{0.0}; + Float borderRadius{0.0}; + Float cellPaddingHorizontal{0.0}; + Float cellPaddingVertical{0.0}; + Float horizontalOverflow{0.0}; + std::string align{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleTableStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["headerFontFamily"] = headerFontFamily; + result["headerBackgroundColor"] = ::facebook::react::toDynamic(headerBackgroundColor); + result["headerTextColor"] = ::facebook::react::toDynamic(headerTextColor); + result["rowEvenBackgroundColor"] = ::facebook::react::toDynamic(rowEvenBackgroundColor); + result["rowOddBackgroundColor"] = ::facebook::react::toDynamic(rowOddBackgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderWidth"] = borderWidth; + result["borderRadius"] = borderRadius; + result["cellPaddingHorizontal"] = cellPaddingHorizontal; + result["cellPaddingVertical"] = cellPaddingVertical; + result["horizontalOverflow"] = horizontalOverflow; + result["align"] = align; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleTableStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_headerFontFamily = map.find("headerFontFamily"); + if (tmp_headerFontFamily != map.end()) { + fromRawValue(context, tmp_headerFontFamily->second, result.headerFontFamily); + } + auto tmp_headerBackgroundColor = map.find("headerBackgroundColor"); + if (tmp_headerBackgroundColor != map.end()) { + fromRawValue(context, tmp_headerBackgroundColor->second, result.headerBackgroundColor); + } + auto tmp_headerTextColor = map.find("headerTextColor"); + if (tmp_headerTextColor != map.end()) { + fromRawValue(context, tmp_headerTextColor->second, result.headerTextColor); + } + auto tmp_rowEvenBackgroundColor = map.find("rowEvenBackgroundColor"); + if (tmp_rowEvenBackgroundColor != map.end()) { + fromRawValue(context, tmp_rowEvenBackgroundColor->second, result.rowEvenBackgroundColor); + } + auto tmp_rowOddBackgroundColor = map.find("rowOddBackgroundColor"); + if (tmp_rowOddBackgroundColor != map.end()) { + fromRawValue(context, tmp_rowOddBackgroundColor->second, result.rowOddBackgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_cellPaddingHorizontal = map.find("cellPaddingHorizontal"); + if (tmp_cellPaddingHorizontal != map.end()) { + fromRawValue(context, tmp_cellPaddingHorizontal->second, result.cellPaddingHorizontal); + } + auto tmp_cellPaddingVertical = map.find("cellPaddingVertical"); + if (tmp_cellPaddingVertical != map.end()) { + fromRawValue(context, tmp_cellPaddingVertical->second, result.cellPaddingVertical); + } + auto tmp_horizontalOverflow = map.find("horizontalOverflow"); + if (tmp_horizontalOverflow != map.end()) { + fromRawValue(context, tmp_horizontalOverflow->second, result.horizontalOverflow); + } + auto tmp_align = map.find("align"); + if (tmp_align != map.end()) { + fromRawValue(context, tmp_align->second, result.align); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleTableStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleTableStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleTableStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleTaskListStruct { + SharedColor checkedColor{}; + SharedColor borderColor{}; + Float checkboxSize{0.0}; + Float checkboxBorderRadius{0.0}; + SharedColor checkmarkColor{}; + SharedColor checkedTextColor{}; + bool checkedStrikethrough{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleTaskListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["checkedColor"] = ::facebook::react::toDynamic(checkedColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["checkboxSize"] = checkboxSize; + result["checkboxBorderRadius"] = checkboxBorderRadius; + result["checkmarkColor"] = ::facebook::react::toDynamic(checkmarkColor); + result["checkedTextColor"] = ::facebook::react::toDynamic(checkedTextColor); + result["checkedStrikethrough"] = checkedStrikethrough; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleTaskListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_checkedColor = map.find("checkedColor"); + if (tmp_checkedColor != map.end()) { + fromRawValue(context, tmp_checkedColor->second, result.checkedColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_checkboxSize = map.find("checkboxSize"); + if (tmp_checkboxSize != map.end()) { + fromRawValue(context, tmp_checkboxSize->second, result.checkboxSize); + } + auto tmp_checkboxBorderRadius = map.find("checkboxBorderRadius"); + if (tmp_checkboxBorderRadius != map.end()) { + fromRawValue(context, tmp_checkboxBorderRadius->second, result.checkboxBorderRadius); + } + auto tmp_checkmarkColor = map.find("checkmarkColor"); + if (tmp_checkmarkColor != map.end()) { + fromRawValue(context, tmp_checkmarkColor->second, result.checkmarkColor); + } + auto tmp_checkedTextColor = map.find("checkedTextColor"); + if (tmp_checkedTextColor != map.end()) { + fromRawValue(context, tmp_checkedTextColor->second, result.checkedTextColor); + } + auto tmp_checkedStrikethrough = map.find("checkedStrikethrough"); + if (tmp_checkedStrikethrough != map.end()) { + fromRawValue(context, tmp_checkedStrikethrough->second, result.checkedStrikethrough); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleTaskListStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleTaskListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleTaskListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleMathStruct { + Float fontSize{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + Float padding{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["padding"] = padding; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleMathStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleInlineMathStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleInlineMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleInlineMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleInlineMathStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleInlineMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleInlineMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct { + Float density{0.0}; + Float speed{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["density"] = density; + result["speed"] = speed; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_density = map.find("density"); + if (tmp_density != map.end()) { + fromRawValue(context, tmp_density->second, result.density); + } + auto tmp_speed = map.find("speed"); + if (tmp_speed != map.end()) { + fromRawValue(context, tmp_speed->second, result.speed); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleSpoilerSolidStruct { + Float borderRadius{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleSpoilerSolidStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["borderRadius"] = borderRadius; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleSpoilerSolidStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleSpoilerSolidStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleSpoilerSolidStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleSpoilerSolidStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleSpoilerStruct { + SharedColor color{}; + EnrichedMarkdownMarkdownStyleSpoilerParticlesStruct particles{}; + EnrichedMarkdownMarkdownStyleSpoilerSolidStruct solid{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleSpoilerStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["particles"] = ::facebook::react::toDynamic(particles); + result["solid"] = ::facebook::react::toDynamic(solid); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleSpoilerStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_particles = map.find("particles"); + if (tmp_particles != map.end()) { + fromRawValue(context, tmp_particles->second, result.particles); + } + auto tmp_solid = map.find("solid"); + if (tmp_solid != map.end()) { + fromRawValue(context, tmp_solid->second, result.solid); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleSpoilerStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleSpoilerStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleSpoilerStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleSuperscriptStruct { + Float fontScale{0.0}; + Float baselineOffsetScale{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleSuperscriptStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontScale"] = fontScale; + result["baselineOffsetScale"] = baselineOffsetScale; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleSuperscriptStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_baselineOffsetScale = map.find("baselineOffsetScale"); + if (tmp_baselineOffsetScale != map.end()) { + fromRawValue(context, tmp_baselineOffsetScale->second, result.baselineOffsetScale); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleSuperscriptStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleSuperscriptStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleSuperscriptStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleSubscriptStruct { + Float fontScale{0.0}; + Float baselineOffsetScale{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleSubscriptStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontScale"] = fontScale; + result["baselineOffsetScale"] = baselineOffsetScale; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleSubscriptStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_baselineOffsetScale = map.find("baselineOffsetScale"); + if (tmp_baselineOffsetScale != map.end()) { + fromRawValue(context, tmp_baselineOffsetScale->second, result.baselineOffsetScale); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleSubscriptStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleSubscriptStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleSubscriptStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleHighlightStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleHighlightStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleHighlightStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleHighlightStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleHighlightStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleHighlightStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMarkdownStyleStruct { + EnrichedMarkdownMarkdownStyleParagraphStruct paragraph{}; + EnrichedMarkdownMarkdownStyleH1Struct h1{}; + EnrichedMarkdownMarkdownStyleH2Struct h2{}; + EnrichedMarkdownMarkdownStyleH3Struct h3{}; + EnrichedMarkdownMarkdownStyleH4Struct h4{}; + EnrichedMarkdownMarkdownStyleH5Struct h5{}; + EnrichedMarkdownMarkdownStyleH6Struct h6{}; + EnrichedMarkdownMarkdownStyleBlockquoteStruct blockquote{}; + EnrichedMarkdownMarkdownStyleListStruct list{}; + EnrichedMarkdownMarkdownStyleCodeBlockStruct codeBlock{}; + EnrichedMarkdownMarkdownStyleLinkStruct link{}; + std::vector linkVariants{}; + EnrichedMarkdownMarkdownStyleStrongStruct strong{}; + EnrichedMarkdownMarkdownStyleEmStruct em{}; + EnrichedMarkdownMarkdownStyleStrikethroughStruct strikethrough{}; + EnrichedMarkdownMarkdownStyleUnderlineStruct underline{}; + EnrichedMarkdownMarkdownStyleCodeStruct code{}; + EnrichedMarkdownMarkdownStyleImageStruct image{}; + EnrichedMarkdownMarkdownStyleVideoStruct video{}; + EnrichedMarkdownMarkdownStyleInlineImageStruct inlineImage{}; + EnrichedMarkdownMarkdownStyleThematicBreakStruct thematicBreak{}; + EnrichedMarkdownMarkdownStyleTableStruct table{}; + EnrichedMarkdownMarkdownStyleTaskListStruct taskList{}; + EnrichedMarkdownMarkdownStyleMathStruct math{}; + EnrichedMarkdownMarkdownStyleInlineMathStruct inlineMath{}; + EnrichedMarkdownMarkdownStyleSpoilerStruct spoiler{}; + EnrichedMarkdownMarkdownStyleSuperscriptStruct superscript{}; + EnrichedMarkdownMarkdownStyleSubscriptStruct subscript{}; + EnrichedMarkdownMarkdownStyleHighlightStruct highlight{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMarkdownStyleStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["paragraph"] = ::facebook::react::toDynamic(paragraph); + result["h1"] = ::facebook::react::toDynamic(h1); + result["h2"] = ::facebook::react::toDynamic(h2); + result["h3"] = ::facebook::react::toDynamic(h3); + result["h4"] = ::facebook::react::toDynamic(h4); + result["h5"] = ::facebook::react::toDynamic(h5); + result["h6"] = ::facebook::react::toDynamic(h6); + result["blockquote"] = ::facebook::react::toDynamic(blockquote); + result["list"] = ::facebook::react::toDynamic(list); + result["codeBlock"] = ::facebook::react::toDynamic(codeBlock); + result["link"] = ::facebook::react::toDynamic(link); + result["linkVariants"] = ::facebook::react::toDynamic(linkVariants); + result["strong"] = ::facebook::react::toDynamic(strong); + result["em"] = ::facebook::react::toDynamic(em); + result["strikethrough"] = ::facebook::react::toDynamic(strikethrough); + result["underline"] = ::facebook::react::toDynamic(underline); + result["code"] = ::facebook::react::toDynamic(code); + result["image"] = ::facebook::react::toDynamic(image); + result["video"] = ::facebook::react::toDynamic(video); + result["inlineImage"] = ::facebook::react::toDynamic(inlineImage); + result["thematicBreak"] = ::facebook::react::toDynamic(thematicBreak); + result["table"] = ::facebook::react::toDynamic(table); + result["taskList"] = ::facebook::react::toDynamic(taskList); + result["math"] = ::facebook::react::toDynamic(math); + result["inlineMath"] = ::facebook::react::toDynamic(inlineMath); + result["spoiler"] = ::facebook::react::toDynamic(spoiler); + result["superscript"] = ::facebook::react::toDynamic(superscript); + result["subscript"] = ::facebook::react::toDynamic(subscript); + result["highlight"] = ::facebook::react::toDynamic(highlight); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMarkdownStyleStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_paragraph = map.find("paragraph"); + if (tmp_paragraph != map.end()) { + fromRawValue(context, tmp_paragraph->second, result.paragraph); + } + auto tmp_h1 = map.find("h1"); + if (tmp_h1 != map.end()) { + fromRawValue(context, tmp_h1->second, result.h1); + } + auto tmp_h2 = map.find("h2"); + if (tmp_h2 != map.end()) { + fromRawValue(context, tmp_h2->second, result.h2); + } + auto tmp_h3 = map.find("h3"); + if (tmp_h3 != map.end()) { + fromRawValue(context, tmp_h3->second, result.h3); + } + auto tmp_h4 = map.find("h4"); + if (tmp_h4 != map.end()) { + fromRawValue(context, tmp_h4->second, result.h4); + } + auto tmp_h5 = map.find("h5"); + if (tmp_h5 != map.end()) { + fromRawValue(context, tmp_h5->second, result.h5); + } + auto tmp_h6 = map.find("h6"); + if (tmp_h6 != map.end()) { + fromRawValue(context, tmp_h6->second, result.h6); + } + auto tmp_blockquote = map.find("blockquote"); + if (tmp_blockquote != map.end()) { + fromRawValue(context, tmp_blockquote->second, result.blockquote); + } + auto tmp_list = map.find("list"); + if (tmp_list != map.end()) { + fromRawValue(context, tmp_list->second, result.list); + } + auto tmp_codeBlock = map.find("codeBlock"); + if (tmp_codeBlock != map.end()) { + fromRawValue(context, tmp_codeBlock->second, result.codeBlock); + } + auto tmp_link = map.find("link"); + if (tmp_link != map.end()) { + fromRawValue(context, tmp_link->second, result.link); + } + auto tmp_linkVariants = map.find("linkVariants"); + if (tmp_linkVariants != map.end()) { + fromRawValue(context, tmp_linkVariants->second, result.linkVariants); + } + auto tmp_strong = map.find("strong"); + if (tmp_strong != map.end()) { + fromRawValue(context, tmp_strong->second, result.strong); + } + auto tmp_em = map.find("em"); + if (tmp_em != map.end()) { + fromRawValue(context, tmp_em->second, result.em); + } + auto tmp_strikethrough = map.find("strikethrough"); + if (tmp_strikethrough != map.end()) { + fromRawValue(context, tmp_strikethrough->second, result.strikethrough); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_code = map.find("code"); + if (tmp_code != map.end()) { + fromRawValue(context, tmp_code->second, result.code); + } + auto tmp_image = map.find("image"); + if (tmp_image != map.end()) { + fromRawValue(context, tmp_image->second, result.image); + } + auto tmp_video = map.find("video"); + if (tmp_video != map.end()) { + fromRawValue(context, tmp_video->second, result.video); + } + auto tmp_inlineImage = map.find("inlineImage"); + if (tmp_inlineImage != map.end()) { + fromRawValue(context, tmp_inlineImage->second, result.inlineImage); + } + auto tmp_thematicBreak = map.find("thematicBreak"); + if (tmp_thematicBreak != map.end()) { + fromRawValue(context, tmp_thematicBreak->second, result.thematicBreak); + } + auto tmp_table = map.find("table"); + if (tmp_table != map.end()) { + fromRawValue(context, tmp_table->second, result.table); + } + auto tmp_taskList = map.find("taskList"); + if (tmp_taskList != map.end()) { + fromRawValue(context, tmp_taskList->second, result.taskList); + } + auto tmp_math = map.find("math"); + if (tmp_math != map.end()) { + fromRawValue(context, tmp_math->second, result.math); + } + auto tmp_inlineMath = map.find("inlineMath"); + if (tmp_inlineMath != map.end()) { + fromRawValue(context, tmp_inlineMath->second, result.inlineMath); + } + auto tmp_spoiler = map.find("spoiler"); + if (tmp_spoiler != map.end()) { + fromRawValue(context, tmp_spoiler->second, result.spoiler); + } + auto tmp_superscript = map.find("superscript"); + if (tmp_superscript != map.end()) { + fromRawValue(context, tmp_superscript->second, result.superscript); + } + auto tmp_subscript = map.find("subscript"); + if (tmp_subscript != map.end()) { + fromRawValue(context, tmp_subscript->second, result.subscript); + } + auto tmp_highlight = map.find("highlight"); + if (tmp_highlight != map.end()) { + fromRawValue(context, tmp_highlight->second, result.highlight); + } +} + +static inline std::string toString(const EnrichedMarkdownMarkdownStyleStruct &value) { + return "[Object EnrichedMarkdownMarkdownStyleStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMarkdownStyleStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownMd4cFlagsStruct { + bool underline{false}; + bool superscript{false}; + bool subscript{false}; + bool latexMath{false}; + bool highlight{false}; + bool hardSoftBreaks{false}; + bool preserveBlankLines{false}; + bool admonitions{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownMd4cFlagsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["underline"] = underline; + result["superscript"] = superscript; + result["subscript"] = subscript; + result["latexMath"] = latexMath; + result["highlight"] = highlight; + result["hardSoftBreaks"] = hardSoftBreaks; + result["preserveBlankLines"] = preserveBlankLines; + result["admonitions"] = admonitions; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownMd4cFlagsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_superscript = map.find("superscript"); + if (tmp_superscript != map.end()) { + fromRawValue(context, tmp_superscript->second, result.superscript); + } + auto tmp_subscript = map.find("subscript"); + if (tmp_subscript != map.end()) { + fromRawValue(context, tmp_subscript->second, result.subscript); + } + auto tmp_latexMath = map.find("latexMath"); + if (tmp_latexMath != map.end()) { + fromRawValue(context, tmp_latexMath->second, result.latexMath); + } + auto tmp_highlight = map.find("highlight"); + if (tmp_highlight != map.end()) { + fromRawValue(context, tmp_highlight->second, result.highlight); + } + auto tmp_hardSoftBreaks = map.find("hardSoftBreaks"); + if (tmp_hardSoftBreaks != map.end()) { + fromRawValue(context, tmp_hardSoftBreaks->second, result.hardSoftBreaks); + } + auto tmp_preserveBlankLines = map.find("preserveBlankLines"); + if (tmp_preserveBlankLines != map.end()) { + fromRawValue(context, tmp_preserveBlankLines->second, result.preserveBlankLines); + } + auto tmp_admonitions = map.find("admonitions"); + if (tmp_admonitions != map.end()) { + fromRawValue(context, tmp_admonitions->second, result.admonitions); + } +} + +static inline std::string toString(const EnrichedMarkdownMd4cFlagsStruct &value) { + return "[Object EnrichedMarkdownMd4cFlagsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownMd4cFlagsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownStreamingConfigStruct { + std::string tableMode{}; + std::string codeBlockMode{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownStreamingConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["tableMode"] = tableMode; + result["codeBlockMode"] = codeBlockMode; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownStreamingConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_tableMode = map.find("tableMode"); + if (tmp_tableMode != map.end()) { + fromRawValue(context, tmp_tableMode->second, result.tableMode); + } + auto tmp_codeBlockMode = map.find("codeBlockMode"); + if (tmp_codeBlockMode != map.end()) { + fromRawValue(context, tmp_codeBlockMode->second, result.codeBlockMode); + } +} + +static inline std::string toString(const EnrichedMarkdownStreamingConfigStruct &value) { + return "[Object EnrichedMarkdownStreamingConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownStreamingConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownContextMenuItemsStruct { + std::string text{}; + std::string icon{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownContextMenuItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = text; + result["icon"] = icon; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownContextMenuItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_icon = map.find("icon"); + if (tmp_icon != map.end()) { + fromRawValue(context, tmp_icon->second, result.icon); + } +} + +static inline std::string toString(const EnrichedMarkdownContextMenuItemsStruct &value) { + return "[Object EnrichedMarkdownContextMenuItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownContextMenuItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownContextMenuItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownImageRequestHeadersStruct { + std::string name{}; + std::string value{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownImageRequestHeadersStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["name"] = name; + result["value"] = value; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownImageRequestHeadersStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_name = map.find("name"); + if (tmp_name != map.end()) { + fromRawValue(context, tmp_name->second, result.name); + } + auto tmp_value = map.find("value"); + if (tmp_value != map.end()) { + fromRawValue(context, tmp_value->second, result.value); + } +} + +static inline std::string toString(const EnrichedMarkdownImageRequestHeadersStruct &value) { + return "[Object EnrichedMarkdownImageRequestHeadersStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownImageRequestHeadersStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownImageRequestHeadersStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownLinkPillContentStruct { + std::string url{}; + std::string label{}; + std::string iconUri{}; + SharedColor iconTintColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkPillContentStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["url"] = url; + result["label"] = label; + result["iconUri"] = iconUri; + result["iconTintColor"] = ::facebook::react::toDynamic(iconTintColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkPillContentStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_url = map.find("url"); + if (tmp_url != map.end()) { + fromRawValue(context, tmp_url->second, result.url); + } + auto tmp_label = map.find("label"); + if (tmp_label != map.end()) { + fromRawValue(context, tmp_label->second, result.label); + } + auto tmp_iconUri = map.find("iconUri"); + if (tmp_iconUri != map.end()) { + fromRawValue(context, tmp_iconUri->second, result.iconUri); + } + auto tmp_iconTintColor = map.find("iconTintColor"); + if (tmp_iconTintColor != map.end()) { + fromRawValue(context, tmp_iconTintColor->second, result.iconTintColor); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkPillContentStruct &value) { + return "[Object EnrichedMarkdownLinkPillContentStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkPillContentStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownLinkPillContentStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownLinkRecognitionTextStruct { + std::string pattern{}; + bool caseInsensitive{false}; + bool dotAll{false}; + bool isDisabled{false}; + bool isDefault{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkRecognitionTextStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["caseInsensitive"] = caseInsensitive; + result["dotAll"] = dotAll; + result["isDisabled"] = isDisabled; + result["isDefault"] = isDefault; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkRecognitionTextStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_caseInsensitive = map.find("caseInsensitive"); + if (tmp_caseInsensitive != map.end()) { + fromRawValue(context, tmp_caseInsensitive->second, result.caseInsensitive); + } + auto tmp_dotAll = map.find("dotAll"); + if (tmp_dotAll != map.end()) { + fromRawValue(context, tmp_dotAll->second, result.dotAll); + } + auto tmp_isDisabled = map.find("isDisabled"); + if (tmp_isDisabled != map.end()) { + fromRawValue(context, tmp_isDisabled->second, result.isDisabled); + } + auto tmp_isDefault = map.find("isDefault"); + if (tmp_isDefault != map.end()) { + fromRawValue(context, tmp_isDefault->second, result.isDefault); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkRecognitionTextStruct &value) { + return "[Object EnrichedMarkdownLinkRecognitionTextStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkRecognitionTextStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownLinkRecognitionInlineCodeStruct { + std::string pattern{}; + bool caseInsensitive{false}; + bool dotAll{false}; + bool isDisabled{false}; + bool isDefault{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkRecognitionInlineCodeStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["caseInsensitive"] = caseInsensitive; + result["dotAll"] = dotAll; + result["isDisabled"] = isDisabled; + result["isDefault"] = isDefault; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkRecognitionInlineCodeStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_caseInsensitive = map.find("caseInsensitive"); + if (tmp_caseInsensitive != map.end()) { + fromRawValue(context, tmp_caseInsensitive->second, result.caseInsensitive); + } + auto tmp_dotAll = map.find("dotAll"); + if (tmp_dotAll != map.end()) { + fromRawValue(context, tmp_dotAll->second, result.dotAll); + } + auto tmp_isDisabled = map.find("isDisabled"); + if (tmp_isDisabled != map.end()) { + fromRawValue(context, tmp_isDisabled->second, result.isDisabled); + } + auto tmp_isDefault = map.find("isDefault"); + if (tmp_isDefault != map.end()) { + fromRawValue(context, tmp_isDefault->second, result.isDefault); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkRecognitionInlineCodeStruct &value) { + return "[Object EnrichedMarkdownLinkRecognitionInlineCodeStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkRecognitionInlineCodeStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownLinkRecognitionStruct { + EnrichedMarkdownLinkRecognitionTextStruct text{}; + EnrichedMarkdownLinkRecognitionInlineCodeStruct inlineCode{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkRecognitionStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = ::facebook::react::toDynamic(text); + result["inlineCode"] = ::facebook::react::toDynamic(inlineCode); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkRecognitionStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_inlineCode = map.find("inlineCode"); + if (tmp_inlineCode != map.end()) { + fromRawValue(context, tmp_inlineCode->second, result.inlineCode); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkRecognitionStruct &value) { + return "[Object EnrichedMarkdownLinkRecognitionStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkRecognitionStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownLinkContextMenuItemsItemsStruct { + std::string text{}; + std::string icon{}; + bool disabled{false}; + bool destructive{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkContextMenuItemsItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = text; + result["icon"] = icon; + result["disabled"] = disabled; + result["destructive"] = destructive; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkContextMenuItemsItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_icon = map.find("icon"); + if (tmp_icon != map.end()) { + fromRawValue(context, tmp_icon->second, result.icon); + } + auto tmp_disabled = map.find("disabled"); + if (tmp_disabled != map.end()) { + fromRawValue(context, tmp_disabled->second, result.disabled); + } + auto tmp_destructive = map.find("destructive"); + if (tmp_destructive != map.end()) { + fromRawValue(context, tmp_destructive->second, result.destructive); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkContextMenuItemsItemsStruct &value) { + return "[Object EnrichedMarkdownLinkContextMenuItemsItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkContextMenuItemsItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownLinkContextMenuItemsItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownLinkContextMenuItemsStruct { + std::string pattern{}; + std::vector items{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownLinkContextMenuItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["items"] = ::facebook::react::toDynamic(items); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownLinkContextMenuItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_items = map.find("items"); + if (tmp_items != map.end()) { + fromRawValue(context, tmp_items->second, result.items); + } +} + +static inline std::string toString(const EnrichedMarkdownLinkContextMenuItemsStruct &value) { + return "[Object EnrichedMarkdownLinkContextMenuItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownLinkContextMenuItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownLinkContextMenuItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownSelectionMenuConfigStruct { + bool copyAsMarkdown{false}; + bool copyImageUrl{false}; + std::string copyLabel{}; + std::string copyAsMarkdownLabel{}; + std::string copyImageUrlLabel{}; + std::string copyImageUrlsLabel{}; + std::vector copyImageUrlPluralTemplates{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownSelectionMenuConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["copyAsMarkdown"] = copyAsMarkdown; + result["copyImageUrl"] = copyImageUrl; + result["copyLabel"] = copyLabel; + result["copyAsMarkdownLabel"] = copyAsMarkdownLabel; + result["copyImageUrlLabel"] = copyImageUrlLabel; + result["copyImageUrlsLabel"] = copyImageUrlsLabel; + result["copyImageUrlPluralTemplates"] = ::facebook::react::toDynamic(copyImageUrlPluralTemplates); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownSelectionMenuConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_copyAsMarkdown = map.find("copyAsMarkdown"); + if (tmp_copyAsMarkdown != map.end()) { + fromRawValue(context, tmp_copyAsMarkdown->second, result.copyAsMarkdown); + } + auto tmp_copyImageUrl = map.find("copyImageUrl"); + if (tmp_copyImageUrl != map.end()) { + fromRawValue(context, tmp_copyImageUrl->second, result.copyImageUrl); + } + auto tmp_copyLabel = map.find("copyLabel"); + if (tmp_copyLabel != map.end()) { + fromRawValue(context, tmp_copyLabel->second, result.copyLabel); + } + auto tmp_copyAsMarkdownLabel = map.find("copyAsMarkdownLabel"); + if (tmp_copyAsMarkdownLabel != map.end()) { + fromRawValue(context, tmp_copyAsMarkdownLabel->second, result.copyAsMarkdownLabel); + } + auto tmp_copyImageUrlLabel = map.find("copyImageUrlLabel"); + if (tmp_copyImageUrlLabel != map.end()) { + fromRawValue(context, tmp_copyImageUrlLabel->second, result.copyImageUrlLabel); + } + auto tmp_copyImageUrlsLabel = map.find("copyImageUrlsLabel"); + if (tmp_copyImageUrlsLabel != map.end()) { + fromRawValue(context, tmp_copyImageUrlsLabel->second, result.copyImageUrlsLabel); + } + auto tmp_copyImageUrlPluralTemplates = map.find("copyImageUrlPluralTemplates"); + if (tmp_copyImageUrlPluralTemplates != map.end()) { + fromRawValue(context, tmp_copyImageUrlPluralTemplates->second, result.copyImageUrlPluralTemplates); + } +} + +static inline std::string toString(const EnrichedMarkdownSelectionMenuConfigStruct &value) { + return "[Object EnrichedMarkdownSelectionMenuConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownSelectionMenuConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsListStruct { + std::string bulletPoint{}; + std::string nestedBulletPoint{}; + std::string orderedItem{}; + std::string nestedOrderedItem{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["bulletPoint"] = bulletPoint; + result["nestedBulletPoint"] = nestedBulletPoint; + result["orderedItem"] = orderedItem; + result["nestedOrderedItem"] = nestedOrderedItem; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_bulletPoint = map.find("bulletPoint"); + if (tmp_bulletPoint != map.end()) { + fromRawValue(context, tmp_bulletPoint->second, result.bulletPoint); + } + auto tmp_nestedBulletPoint = map.find("nestedBulletPoint"); + if (tmp_nestedBulletPoint != map.end()) { + fromRawValue(context, tmp_nestedBulletPoint->second, result.nestedBulletPoint); + } + auto tmp_orderedItem = map.find("orderedItem"); + if (tmp_orderedItem != map.end()) { + fromRawValue(context, tmp_orderedItem->second, result.orderedItem); + } + auto tmp_nestedOrderedItem = map.find("nestedOrderedItem"); + if (tmp_nestedOrderedItem != map.end()) { + fromRawValue(context, tmp_nestedOrderedItem->second, result.nestedOrderedItem); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsListStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsBlockquoteStruct { + std::string quote{}; + std::string nestedQuote{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsBlockquoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["quote"] = quote; + result["nestedQuote"] = nestedQuote; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsBlockquoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_quote = map.find("quote"); + if (tmp_quote != map.end()) { + fromRawValue(context, tmp_quote->second, result.quote); + } + auto tmp_nestedQuote = map.find("nestedQuote"); + if (tmp_nestedQuote != map.end()) { + fromRawValue(context, tmp_nestedQuote->second, result.nestedQuote); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsBlockquoteStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsBlockquoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsBlockquoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsTableStruct { + std::string row{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsTableStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["row"] = row; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsTableStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_row = map.find("row"); + if (tmp_row != map.end()) { + fromRawValue(context, tmp_row->second, result.row); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsTableStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsTableStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsTableStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsMathStruct { + std::string equation{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["equation"] = equation; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_equation = map.find("equation"); + if (tmp_equation != map.end()) { + fromRawValue(context, tmp_equation->second, result.equation); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsMathStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsRotorStruct { + std::string headings{}; + std::string links{}; + std::string images{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsRotorStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["headings"] = headings; + result["links"] = links; + result["images"] = images; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsRotorStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_headings = map.find("headings"); + if (tmp_headings != map.end()) { + fromRawValue(context, tmp_headings->second, result.headings); + } + auto tmp_links = map.find("links"); + if (tmp_links != map.end()) { + fromRawValue(context, tmp_links->second, result.links); + } + auto tmp_images = map.find("images"); + if (tmp_images != map.end()) { + fromRawValue(context, tmp_images->second, result.images); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsRotorStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsRotorStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsRotorStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownAccessibilityLabelsStruct { + EnrichedMarkdownAccessibilityLabelsListStruct list{}; + EnrichedMarkdownAccessibilityLabelsBlockquoteStruct blockquote{}; + EnrichedMarkdownAccessibilityLabelsTableStruct table{}; + EnrichedMarkdownAccessibilityLabelsMathStruct math{}; + EnrichedMarkdownAccessibilityLabelsRotorStruct rotor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownAccessibilityLabelsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["list"] = ::facebook::react::toDynamic(list); + result["blockquote"] = ::facebook::react::toDynamic(blockquote); + result["table"] = ::facebook::react::toDynamic(table); + result["math"] = ::facebook::react::toDynamic(math); + result["rotor"] = ::facebook::react::toDynamic(rotor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownAccessibilityLabelsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_list = map.find("list"); + if (tmp_list != map.end()) { + fromRawValue(context, tmp_list->second, result.list); + } + auto tmp_blockquote = map.find("blockquote"); + if (tmp_blockquote != map.end()) { + fromRawValue(context, tmp_blockquote->second, result.blockquote); + } + auto tmp_table = map.find("table"); + if (tmp_table != map.end()) { + fromRawValue(context, tmp_table->second, result.table); + } + auto tmp_math = map.find("math"); + if (tmp_math != map.end()) { + fromRawValue(context, tmp_math->second, result.math); + } + auto tmp_rotor = map.find("rotor"); + if (tmp_rotor != map.end()) { + fromRawValue(context, tmp_rotor->second, result.rotor); + } +} + +static inline std::string toString(const EnrichedMarkdownAccessibilityLabelsStruct &value) { + return "[Object EnrichedMarkdownAccessibilityLabelsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownAccessibilityLabelsStruct &value) { + return value.toDynamic(); +} +#endif +class EnrichedMarkdownProps final : public ViewProps { + public: + EnrichedMarkdownProps() = default; + EnrichedMarkdownProps(const PropsParserContext& context, const EnrichedMarkdownProps &sourceProps, const RawProps &rawProps); + +#pragma mark - Props + + std::string markdown{}; + EnrichedMarkdownMarkdownStyleStruct markdownStyle{}; + bool enableImagePress{false}; + bool enableTaskListItemToggle{true}; + bool enableCodeBlockPress{false}; + bool enableBlockContextMenu{true}; + bool enableLinkPreview{true}; + bool selectable{false}; + SharedColor selectionColor{}; + SharedColor selectionHandleColor{}; + EnrichedMarkdownMd4cFlagsStruct md4cFlags{}; + bool isGFM{true}; + bool allowFontScaling{true}; + Float maxFontSizeMultiplier{0.0}; + bool allowTrailingMargin{false}; + bool streamingAnimation{false}; + EnrichedMarkdownStreamingConfigStruct streamingConfig{}; + std::string spoilerOverlay{std::string{"particles"}}; + std::vector contextMenuItems{}; + std::vector imageRequestHeaders{}; + std::vector linkPillContent{}; + EnrichedMarkdownLinkRecognitionStruct linkRecognition{}; + std::vector linkContextMenuItems{}; + EnrichedMarkdownSelectionMenuConfigStruct selectionMenuConfig{}; + EnrichedMarkdownAccessibilityLabelsStruct accessibilityLabels{}; + std::string textBreakStrategy{std::string{"highQuality"}}; + std::string lineBreakStrategyIOS{std::string{"none"}}; + std::string writingDirection{std::string{"first-strong"}}; + int numberOfLines{0}; + std::string ellipsizeMode{std::string{"tail"}}; + + #ifdef RN_SERIALIZABLE_STATE + ComponentName getDiffPropsImplementationTarget() const override; + + folly::dynamic getDiffProps(const Props* prevProps) const override; + #endif + + +}; + +struct EnrichedMarkdownTextInputMarkdownShortcutsStruct { + bool heading{false}; + bool unorderedList{false}; + bool orderedList{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownShortcutsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["heading"] = heading; + result["unorderedList"] = unorderedList; + result["orderedList"] = orderedList; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownShortcutsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_heading = map.find("heading"); + if (tmp_heading != map.end()) { + fromRawValue(context, tmp_heading->second, result.heading); + } + auto tmp_unorderedList = map.find("unorderedList"); + if (tmp_unorderedList != map.end()) { + fromRawValue(context, tmp_unorderedList->second, result.unorderedList); + } + auto tmp_orderedList = map.find("orderedList"); + if (tmp_orderedList != map.end()) { + fromRawValue(context, tmp_orderedList->second, result.orderedList); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownShortcutsStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownShortcutsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownShortcutsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleStrongStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleStrongStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleStrongStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleStrongStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleStrongStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleStrongStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleEmStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleEmStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleEmStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleEmStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleEmStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleEmStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleLinkStruct { + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleLinkStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleLinkStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleLinkStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleLinkStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleLinkStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct { + std::string pattern{}; + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextInputMarkdownStyleLinkVariantsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH1Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH1Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH1Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH1Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH1Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH1Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH2Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH2Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH2Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH2Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH2Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH2Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH3Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH3Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH3Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH3Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH3Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH3Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH4Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH4Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH4Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH4Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH4Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH4Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH5Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH5Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH5Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH5Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH5Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH5Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleH6Struct { + Float fontSize{0.0}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleH6Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleH6Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleH6Struct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleH6Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleH6Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleListStruct { + Float itemSpacing{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["itemSpacing"] = itemSpacing; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_itemSpacing = map.find("itemSpacing"); + if (tmp_itemSpacing != map.end()) { + fromRawValue(context, tmp_itemSpacing->second, result.itemSpacing); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleListStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputMarkdownStyleStruct { + EnrichedMarkdownTextInputMarkdownStyleStrongStruct strong{}; + EnrichedMarkdownTextInputMarkdownStyleEmStruct em{}; + EnrichedMarkdownTextInputMarkdownStyleLinkStruct link{}; + std::vector linkVariants{}; + EnrichedMarkdownTextInputMarkdownStyleSpoilerStruct spoiler{}; + EnrichedMarkdownTextInputMarkdownStyleH1Struct h1{}; + EnrichedMarkdownTextInputMarkdownStyleH2Struct h2{}; + EnrichedMarkdownTextInputMarkdownStyleH3Struct h3{}; + EnrichedMarkdownTextInputMarkdownStyleH4Struct h4{}; + EnrichedMarkdownTextInputMarkdownStyleH5Struct h5{}; + EnrichedMarkdownTextInputMarkdownStyleH6Struct h6{}; + EnrichedMarkdownTextInputMarkdownStyleListStruct list{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputMarkdownStyleStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["strong"] = ::facebook::react::toDynamic(strong); + result["em"] = ::facebook::react::toDynamic(em); + result["link"] = ::facebook::react::toDynamic(link); + result["linkVariants"] = ::facebook::react::toDynamic(linkVariants); + result["spoiler"] = ::facebook::react::toDynamic(spoiler); + result["h1"] = ::facebook::react::toDynamic(h1); + result["h2"] = ::facebook::react::toDynamic(h2); + result["h3"] = ::facebook::react::toDynamic(h3); + result["h4"] = ::facebook::react::toDynamic(h4); + result["h5"] = ::facebook::react::toDynamic(h5); + result["h6"] = ::facebook::react::toDynamic(h6); + result["list"] = ::facebook::react::toDynamic(list); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputMarkdownStyleStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_strong = map.find("strong"); + if (tmp_strong != map.end()) { + fromRawValue(context, tmp_strong->second, result.strong); + } + auto tmp_em = map.find("em"); + if (tmp_em != map.end()) { + fromRawValue(context, tmp_em->second, result.em); + } + auto tmp_link = map.find("link"); + if (tmp_link != map.end()) { + fromRawValue(context, tmp_link->second, result.link); + } + auto tmp_linkVariants = map.find("linkVariants"); + if (tmp_linkVariants != map.end()) { + fromRawValue(context, tmp_linkVariants->second, result.linkVariants); + } + auto tmp_spoiler = map.find("spoiler"); + if (tmp_spoiler != map.end()) { + fromRawValue(context, tmp_spoiler->second, result.spoiler); + } + auto tmp_h1 = map.find("h1"); + if (tmp_h1 != map.end()) { + fromRawValue(context, tmp_h1->second, result.h1); + } + auto tmp_h2 = map.find("h2"); + if (tmp_h2 != map.end()) { + fromRawValue(context, tmp_h2->second, result.h2); + } + auto tmp_h3 = map.find("h3"); + if (tmp_h3 != map.end()) { + fromRawValue(context, tmp_h3->second, result.h3); + } + auto tmp_h4 = map.find("h4"); + if (tmp_h4 != map.end()) { + fromRawValue(context, tmp_h4->second, result.h4); + } + auto tmp_h5 = map.find("h5"); + if (tmp_h5 != map.end()) { + fromRawValue(context, tmp_h5->second, result.h5); + } + auto tmp_h6 = map.find("h6"); + if (tmp_h6 != map.end()) { + fromRawValue(context, tmp_h6->second, result.h6); + } + auto tmp_list = map.find("list"); + if (tmp_list != map.end()) { + fromRawValue(context, tmp_list->second, result.list); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputMarkdownStyleStruct &value) { + return "[Object EnrichedMarkdownTextInputMarkdownStyleStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputMarkdownStyleStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputContextMenuItemsStruct { + std::string text{}; + std::string icon{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputContextMenuItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = text; + result["icon"] = icon; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputContextMenuItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_icon = map.find("icon"); + if (tmp_icon != map.end()) { + fromRawValue(context, tmp_icon->second, result.icon); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputContextMenuItemsStruct &value) { + return "[Object EnrichedMarkdownTextInputContextMenuItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputContextMenuItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextInputContextMenuItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextInputSelectionMenuConfigStruct { + bool format{false}; + std::string formatLabel{}; + bool copyAsMarkdown{false}; + std::string copyAsMarkdownLabel{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputSelectionMenuConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["format"] = format; + result["formatLabel"] = formatLabel; + result["copyAsMarkdown"] = copyAsMarkdown; + result["copyAsMarkdownLabel"] = copyAsMarkdownLabel; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputSelectionMenuConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_format = map.find("format"); + if (tmp_format != map.end()) { + fromRawValue(context, tmp_format->second, result.format); + } + auto tmp_formatLabel = map.find("formatLabel"); + if (tmp_formatLabel != map.end()) { + fromRawValue(context, tmp_formatLabel->second, result.formatLabel); + } + auto tmp_copyAsMarkdown = map.find("copyAsMarkdown"); + if (tmp_copyAsMarkdown != map.end()) { + fromRawValue(context, tmp_copyAsMarkdown->second, result.copyAsMarkdown); + } + auto tmp_copyAsMarkdownLabel = map.find("copyAsMarkdownLabel"); + if (tmp_copyAsMarkdownLabel != map.end()) { + fromRawValue(context, tmp_copyAsMarkdownLabel->second, result.copyAsMarkdownLabel); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputSelectionMenuConfigStruct &value) { + return "[Object EnrichedMarkdownTextInputSelectionMenuConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputSelectionMenuConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputFormatMenuConfigStruct { + bool bold{false}; + std::string boldLabel{}; + bool italic{false}; + std::string italicLabel{}; + bool underline{false}; + std::string underlineLabel{}; + bool strikethrough{false}; + std::string strikethroughLabel{}; + bool spoiler{false}; + std::string spoilerLabel{}; + bool link{false}; + std::string linkLabel{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputFormatMenuConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["bold"] = bold; + result["boldLabel"] = boldLabel; + result["italic"] = italic; + result["italicLabel"] = italicLabel; + result["underline"] = underline; + result["underlineLabel"] = underlineLabel; + result["strikethrough"] = strikethrough; + result["strikethroughLabel"] = strikethroughLabel; + result["spoiler"] = spoiler; + result["spoilerLabel"] = spoilerLabel; + result["link"] = link; + result["linkLabel"] = linkLabel; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputFormatMenuConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_bold = map.find("bold"); + if (tmp_bold != map.end()) { + fromRawValue(context, tmp_bold->second, result.bold); + } + auto tmp_boldLabel = map.find("boldLabel"); + if (tmp_boldLabel != map.end()) { + fromRawValue(context, tmp_boldLabel->second, result.boldLabel); + } + auto tmp_italic = map.find("italic"); + if (tmp_italic != map.end()) { + fromRawValue(context, tmp_italic->second, result.italic); + } + auto tmp_italicLabel = map.find("italicLabel"); + if (tmp_italicLabel != map.end()) { + fromRawValue(context, tmp_italicLabel->second, result.italicLabel); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_underlineLabel = map.find("underlineLabel"); + if (tmp_underlineLabel != map.end()) { + fromRawValue(context, tmp_underlineLabel->second, result.underlineLabel); + } + auto tmp_strikethrough = map.find("strikethrough"); + if (tmp_strikethrough != map.end()) { + fromRawValue(context, tmp_strikethrough->second, result.strikethrough); + } + auto tmp_strikethroughLabel = map.find("strikethroughLabel"); + if (tmp_strikethroughLabel != map.end()) { + fromRawValue(context, tmp_strikethroughLabel->second, result.strikethroughLabel); + } + auto tmp_spoiler = map.find("spoiler"); + if (tmp_spoiler != map.end()) { + fromRawValue(context, tmp_spoiler->second, result.spoiler); + } + auto tmp_spoilerLabel = map.find("spoilerLabel"); + if (tmp_spoilerLabel != map.end()) { + fromRawValue(context, tmp_spoilerLabel->second, result.spoilerLabel); + } + auto tmp_link = map.find("link"); + if (tmp_link != map.end()) { + fromRawValue(context, tmp_link->second, result.link); + } + auto tmp_linkLabel = map.find("linkLabel"); + if (tmp_linkLabel != map.end()) { + fromRawValue(context, tmp_linkLabel->second, result.linkLabel); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputFormatMenuConfigStruct &value) { + return "[Object EnrichedMarkdownTextInputFormatMenuConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputFormatMenuConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextInputLinkRegexStruct { + std::string pattern{}; + bool caseInsensitive{false}; + bool dotAll{false}; + bool isDisabled{false}; + bool isDefault{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextInputLinkRegexStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["caseInsensitive"] = caseInsensitive; + result["dotAll"] = dotAll; + result["isDisabled"] = isDisabled; + result["isDefault"] = isDefault; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextInputLinkRegexStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_caseInsensitive = map.find("caseInsensitive"); + if (tmp_caseInsensitive != map.end()) { + fromRawValue(context, tmp_caseInsensitive->second, result.caseInsensitive); + } + auto tmp_dotAll = map.find("dotAll"); + if (tmp_dotAll != map.end()) { + fromRawValue(context, tmp_dotAll->second, result.dotAll); + } + auto tmp_isDisabled = map.find("isDisabled"); + if (tmp_isDisabled != map.end()) { + fromRawValue(context, tmp_isDisabled->second, result.isDisabled); + } + auto tmp_isDefault = map.find("isDefault"); + if (tmp_isDefault != map.end()) { + fromRawValue(context, tmp_isDefault->second, result.isDefault); + } +} + +static inline std::string toString(const EnrichedMarkdownTextInputLinkRegexStruct &value) { + return "[Object EnrichedMarkdownTextInputLinkRegexStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextInputLinkRegexStruct &value) { + return value.toDynamic(); +} +#endif +class EnrichedMarkdownTextInputProps final : public ViewProps { + public: + EnrichedMarkdownTextInputProps() = default; + EnrichedMarkdownTextInputProps(const PropsParserContext& context, const EnrichedMarkdownTextInputProps &sourceProps, const RawProps &rawProps); + +#pragma mark - Props + + std::string defaultValue{}; + std::string placeholder{}; + SharedColor placeholderTextColor{}; + bool editable{false}; + bool autoFocus{false}; + bool scrollEnabled{false}; + EnrichedMarkdownTextInputMarkdownShortcutsStruct markdownShortcuts{}; + std::string autoCapitalize{}; + bool multiline{false}; + SharedColor cursorColor{}; + SharedColor selectionColor{}; + EnrichedMarkdownTextInputMarkdownStyleStruct markdownStyle{}; + SharedColor color{}; + Float fontSize{0.0}; + Float lineHeight{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + bool isOnChangeMarkdownSet{false}; + std::vector contextMenuItems{}; + EnrichedMarkdownTextInputSelectionMenuConfigStruct selectionMenuConfig{}; + EnrichedMarkdownTextInputFormatMenuConfigStruct formatMenuConfig{}; + EnrichedMarkdownTextInputLinkRegexStruct linkRegex{}; + std::vector mentionIndicators{}; + std::string writingDirection{std::string{"first-strong"}}; + + #ifdef RN_SERIALIZABLE_STATE + ComponentName getDiffPropsImplementationTarget() const override; + + folly::dynamic getDiffProps(const Props* prevProps) const override; + #endif + + +}; + +struct EnrichedMarkdownTextMarkdownStyleParagraphStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleParagraphStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleParagraphStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleParagraphStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleParagraphStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleParagraphStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH1Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH1Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH1Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH1Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH1Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH1Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH2Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH2Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH2Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH2Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH2Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH2Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH3Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH3Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH3Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH3Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH3Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH3Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH4Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH4Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH4Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH4Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH4Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH4Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH5Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH5Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH5Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH5Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH5Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH5Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleH6Struct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleH6Struct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleH6Struct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleH6Struct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleH6Struct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleH6Struct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct { + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsNoteStruct note{}; + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsTipStruct tip{}; + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsImportantStruct important{}; + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsWarningStruct warning{}; + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsCautionStruct caution{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["note"] = ::facebook::react::toDynamic(note); + result["tip"] = ::facebook::react::toDynamic(tip); + result["important"] = ::facebook::react::toDynamic(important); + result["warning"] = ::facebook::react::toDynamic(warning); + result["caution"] = ::facebook::react::toDynamic(caution); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_note = map.find("note"); + if (tmp_note != map.end()) { + fromRawValue(context, tmp_note->second, result.note); + } + auto tmp_tip = map.find("tip"); + if (tmp_tip != map.end()) { + fromRawValue(context, tmp_tip->second, result.tip); + } + auto tmp_important = map.find("important"); + if (tmp_important != map.end()) { + fromRawValue(context, tmp_important->second, result.important); + } + auto tmp_warning = map.find("warning"); + if (tmp_warning != map.end()) { + fromRawValue(context, tmp_warning->second, result.warning); + } + auto tmp_caution = map.find("caution"); + if (tmp_caution != map.end()) { + fromRawValue(context, tmp_caution->second, result.caution); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleBlockquoteStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor borderColor{}; + Float borderWidth{0.0}; + Float gapWidth{0.0}; + SharedColor backgroundColor{}; + Float borderRadius{0.0}; + Float padding{0.0}; + EnrichedMarkdownTextMarkdownStyleBlockquoteAdmonitionsStruct admonitions{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleBlockquoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderWidth"] = borderWidth; + result["gapWidth"] = gapWidth; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderRadius"] = borderRadius; + result["padding"] = padding; + result["admonitions"] = ::facebook::react::toDynamic(admonitions); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleBlockquoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_gapWidth = map.find("gapWidth"); + if (tmp_gapWidth != map.end()) { + fromRawValue(context, tmp_gapWidth->second, result.gapWidth); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_admonitions = map.find("admonitions"); + if (tmp_admonitions != map.end()) { + fromRawValue(context, tmp_admonitions->second, result.admonitions); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleBlockquoteStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleBlockquoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleBlockquoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleListStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor bulletColor{}; + Float bulletSize{0.0}; + Float markerMinWidth{0.0}; + SharedColor markerColor{}; + std::string markerFontWeight{}; + Float gapWidth{0.0}; + Float marginLeft{0.0}; + Float itemSpacing{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["bulletColor"] = ::facebook::react::toDynamic(bulletColor); + result["bulletSize"] = bulletSize; + result["markerMinWidth"] = markerMinWidth; + result["markerColor"] = ::facebook::react::toDynamic(markerColor); + result["markerFontWeight"] = markerFontWeight; + result["gapWidth"] = gapWidth; + result["marginLeft"] = marginLeft; + result["itemSpacing"] = itemSpacing; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_bulletColor = map.find("bulletColor"); + if (tmp_bulletColor != map.end()) { + fromRawValue(context, tmp_bulletColor->second, result.bulletColor); + } + auto tmp_bulletSize = map.find("bulletSize"); + if (tmp_bulletSize != map.end()) { + fromRawValue(context, tmp_bulletSize->second, result.bulletSize); + } + auto tmp_markerMinWidth = map.find("markerMinWidth"); + if (tmp_markerMinWidth != map.end()) { + fromRawValue(context, tmp_markerMinWidth->second, result.markerMinWidth); + } + auto tmp_markerColor = map.find("markerColor"); + if (tmp_markerColor != map.end()) { + fromRawValue(context, tmp_markerColor->second, result.markerColor); + } + auto tmp_markerFontWeight = map.find("markerFontWeight"); + if (tmp_markerFontWeight != map.end()) { + fromRawValue(context, tmp_markerFontWeight->second, result.markerFontWeight); + } + auto tmp_gapWidth = map.find("gapWidth"); + if (tmp_gapWidth != map.end()) { + fromRawValue(context, tmp_gapWidth->second, result.gapWidth); + } + auto tmp_marginLeft = map.find("marginLeft"); + if (tmp_marginLeft != map.end()) { + fromRawValue(context, tmp_marginLeft->second, result.marginLeft); + } + auto tmp_itemSpacing = map.find("itemSpacing"); + if (tmp_itemSpacing != map.end()) { + fromRawValue(context, tmp_itemSpacing->second, result.itemSpacing); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleListStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct { + SharedColor keyword{}; + SharedColor operatorColor{}; + SharedColor punctuation{}; + SharedColor string{}; + SharedColor number{}; + SharedColor constant{}; + SharedColor comment{}; + SharedColor function{}; + SharedColor type{}; + SharedColor variable{}; + SharedColor property{}; + SharedColor tag{}; + SharedColor attribute{}; + SharedColor embedded{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["keyword"] = ::facebook::react::toDynamic(keyword); + result["operatorColor"] = ::facebook::react::toDynamic(operatorColor); + result["punctuation"] = ::facebook::react::toDynamic(punctuation); + result["string"] = ::facebook::react::toDynamic(string); + result["number"] = ::facebook::react::toDynamic(number); + result["constant"] = ::facebook::react::toDynamic(constant); + result["comment"] = ::facebook::react::toDynamic(comment); + result["function"] = ::facebook::react::toDynamic(function); + result["type"] = ::facebook::react::toDynamic(type); + result["variable"] = ::facebook::react::toDynamic(variable); + result["property"] = ::facebook::react::toDynamic(property); + result["tag"] = ::facebook::react::toDynamic(tag); + result["attribute"] = ::facebook::react::toDynamic(attribute); + result["embedded"] = ::facebook::react::toDynamic(embedded); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_keyword = map.find("keyword"); + if (tmp_keyword != map.end()) { + fromRawValue(context, tmp_keyword->second, result.keyword); + } + auto tmp_operatorColor = map.find("operatorColor"); + if (tmp_operatorColor != map.end()) { + fromRawValue(context, tmp_operatorColor->second, result.operatorColor); + } + auto tmp_punctuation = map.find("punctuation"); + if (tmp_punctuation != map.end()) { + fromRawValue(context, tmp_punctuation->second, result.punctuation); + } + auto tmp_string = map.find("string"); + if (tmp_string != map.end()) { + fromRawValue(context, tmp_string->second, result.string); + } + auto tmp_number = map.find("number"); + if (tmp_number != map.end()) { + fromRawValue(context, tmp_number->second, result.number); + } + auto tmp_constant = map.find("constant"); + if (tmp_constant != map.end()) { + fromRawValue(context, tmp_constant->second, result.constant); + } + auto tmp_comment = map.find("comment"); + if (tmp_comment != map.end()) { + fromRawValue(context, tmp_comment->second, result.comment); + } + auto tmp_function = map.find("function"); + if (tmp_function != map.end()) { + fromRawValue(context, tmp_function->second, result.function); + } + auto tmp_type = map.find("type"); + if (tmp_type != map.end()) { + fromRawValue(context, tmp_type->second, result.type); + } + auto tmp_variable = map.find("variable"); + if (tmp_variable != map.end()) { + fromRawValue(context, tmp_variable->second, result.variable); + } + auto tmp_property = map.find("property"); + if (tmp_property != map.end()) { + fromRawValue(context, tmp_property->second, result.property); + } + auto tmp_tag = map.find("tag"); + if (tmp_tag != map.end()) { + fromRawValue(context, tmp_tag->second, result.tag); + } + auto tmp_attribute = map.find("attribute"); + if (tmp_attribute != map.end()) { + fromRawValue(context, tmp_attribute->second, result.attribute); + } + auto tmp_embedded = map.find("embedded"); + if (tmp_embedded != map.end()) { + fromRawValue(context, tmp_embedded->second, result.embedded); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleCodeBlockStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; + Float borderRadius{0.0}; + Float borderWidth{0.0}; + Float padding{0.0}; + EnrichedMarkdownTextMarkdownStyleCodeBlockSyntaxColorsStruct syntaxColors{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleCodeBlockStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderRadius"] = borderRadius; + result["borderWidth"] = borderWidth; + result["padding"] = padding; + result["syntaxColors"] = ::facebook::react::toDynamic(syntaxColors); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleCodeBlockStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_syntaxColors = map.find("syntaxColors"); + if (tmp_syntaxColors != map.end()) { + fromRawValue(context, tmp_syntaxColors->second, result.syntaxColors); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleCodeBlockStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleCodeBlockStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleCodeBlockStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleLinkStruct { + std::string fontFamily{}; + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleLinkStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleLinkStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleLinkStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleLinkStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleLinkStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct { + bool enabled{false}; + std::string label{}; + std::string iconUri{}; + SharedColor iconTintColor{}; + Float borderRadius{0.0}; + Float paddingHorizontal{0.0}; + Float paddingVertical{0.0}; + Float lineHeight{0.0}; + Float borderWidth{0.0}; + SharedColor borderColor{}; + Float maxWidth{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["enabled"] = enabled; + result["label"] = label; + result["iconUri"] = iconUri; + result["iconTintColor"] = ::facebook::react::toDynamic(iconTintColor); + result["borderRadius"] = borderRadius; + result["paddingHorizontal"] = paddingHorizontal; + result["paddingVertical"] = paddingVertical; + result["lineHeight"] = lineHeight; + result["borderWidth"] = borderWidth; + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["maxWidth"] = maxWidth; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_enabled = map.find("enabled"); + if (tmp_enabled != map.end()) { + fromRawValue(context, tmp_enabled->second, result.enabled); + } + auto tmp_label = map.find("label"); + if (tmp_label != map.end()) { + fromRawValue(context, tmp_label->second, result.label); + } + auto tmp_iconUri = map.find("iconUri"); + if (tmp_iconUri != map.end()) { + fromRawValue(context, tmp_iconUri->second, result.iconUri); + } + auto tmp_iconTintColor = map.find("iconTintColor"); + if (tmp_iconTintColor != map.end()) { + fromRawValue(context, tmp_iconTintColor->second, result.iconTintColor); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_paddingHorizontal = map.find("paddingHorizontal"); + if (tmp_paddingHorizontal != map.end()) { + fromRawValue(context, tmp_paddingHorizontal->second, result.paddingHorizontal); + } + auto tmp_paddingVertical = map.find("paddingVertical"); + if (tmp_paddingVertical != map.end()) { + fromRawValue(context, tmp_paddingVertical->second, result.paddingVertical); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_maxWidth = map.find("maxWidth"); + if (tmp_maxWidth != map.end()) { + fromRawValue(context, tmp_maxWidth->second, result.maxWidth); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct { + std::string pattern{}; + SharedColor color{}; + bool underline{false}; + SharedColor backgroundColor{}; + std::string fontFamily{}; + EnrichedMarkdownTextMarkdownStyleLinkVariantsPillStruct pill{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["color"] = ::facebook::react::toDynamic(color); + result["underline"] = underline; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["fontFamily"] = fontFamily; + result["pill"] = ::facebook::react::toDynamic(pill); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_pill = map.find("pill"); + if (tmp_pill != map.end()) { + fromRawValue(context, tmp_pill->second, result.pill); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextMarkdownStyleLinkVariantsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextMarkdownStyleStrongStruct { + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleStrongStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleStrongStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleStrongStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleStrongStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleStrongStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleEmStruct { + std::string fontFamily{}; + std::string fontStyle{}; + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleEmStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontStyle"] = fontStyle; + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleEmStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontStyle = map.find("fontStyle"); + if (tmp_fontStyle != map.end()) { + fromRawValue(context, tmp_fontStyle->second, result.fontStyle); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleEmStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleEmStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleEmStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleStrikethroughStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleStrikethroughStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleStrikethroughStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleStrikethroughStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleStrikethroughStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleStrikethroughStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleUnderlineStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleUnderlineStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleUnderlineStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleUnderlineStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleUnderlineStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleUnderlineStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleCodeStruct { + std::string fontFamily{}; + Float fontSize{0.0}; + Float fontScale{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + SharedColor borderColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleCodeStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontFamily"] = fontFamily; + result["fontSize"] = fontSize; + result["fontScale"] = fontScale; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleCodeStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleCodeStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleCodeStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleCodeStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleImageStruct { + Float height{0.0}; + Float maxHeight{0.0}; + Float aspectRatio{0.0}; + std::string resizeMode{}; + Float borderRadius{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleImageStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["height"] = height; + result["maxHeight"] = maxHeight; + result["aspectRatio"] = aspectRatio; + result["resizeMode"] = resizeMode; + result["borderRadius"] = borderRadius; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleImageStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_height = map.find("height"); + if (tmp_height != map.end()) { + fromRawValue(context, tmp_height->second, result.height); + } + auto tmp_maxHeight = map.find("maxHeight"); + if (tmp_maxHeight != map.end()) { + fromRawValue(context, tmp_maxHeight->second, result.maxHeight); + } + auto tmp_aspectRatio = map.find("aspectRatio"); + if (tmp_aspectRatio != map.end()) { + fromRawValue(context, tmp_aspectRatio->second, result.aspectRatio); + } + auto tmp_resizeMode = map.find("resizeMode"); + if (tmp_resizeMode != map.end()) { + fromRawValue(context, tmp_resizeMode->second, result.resizeMode); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleImageStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleImageStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleImageStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleVideoStruct { + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float borderRadius{0.0}; + Float aspectRatio{0.0}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleVideoStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["borderRadius"] = borderRadius; + result["aspectRatio"] = aspectRatio; + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleVideoStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_aspectRatio = map.find("aspectRatio"); + if (tmp_aspectRatio != map.end()) { + fromRawValue(context, tmp_aspectRatio->second, result.aspectRatio); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleVideoStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleVideoStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleVideoStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleInlineImageStruct { + Float size{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleInlineImageStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["size"] = size; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleInlineImageStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_size = map.find("size"); + if (tmp_size != map.end()) { + fromRawValue(context, tmp_size->second, result.size); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleInlineImageStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleInlineImageStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleInlineImageStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleThematicBreakStruct { + SharedColor color{}; + Float height{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleThematicBreakStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["height"] = height; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleThematicBreakStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_height = map.find("height"); + if (tmp_height != map.end()) { + fromRawValue(context, tmp_height->second, result.height); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleThematicBreakStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleThematicBreakStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleThematicBreakStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleTableStruct { + Float fontSize{0.0}; + std::string fontFamily{}; + std::string fontWeight{}; + SharedColor color{}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + Float lineHeight{0.0}; + std::string headerFontFamily{}; + SharedColor headerBackgroundColor{}; + SharedColor headerTextColor{}; + SharedColor rowEvenBackgroundColor{}; + SharedColor rowOddBackgroundColor{}; + SharedColor borderColor{}; + Float borderWidth{0.0}; + Float borderRadius{0.0}; + Float cellPaddingHorizontal{0.0}; + Float cellPaddingVertical{0.0}; + Float horizontalOverflow{0.0}; + std::string align{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleTableStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["fontFamily"] = fontFamily; + result["fontWeight"] = fontWeight; + result["color"] = ::facebook::react::toDynamic(color); + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["lineHeight"] = lineHeight; + result["headerFontFamily"] = headerFontFamily; + result["headerBackgroundColor"] = ::facebook::react::toDynamic(headerBackgroundColor); + result["headerTextColor"] = ::facebook::react::toDynamic(headerTextColor); + result["rowEvenBackgroundColor"] = ::facebook::react::toDynamic(rowEvenBackgroundColor); + result["rowOddBackgroundColor"] = ::facebook::react::toDynamic(rowOddBackgroundColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["borderWidth"] = borderWidth; + result["borderRadius"] = borderRadius; + result["cellPaddingHorizontal"] = cellPaddingHorizontal; + result["cellPaddingVertical"] = cellPaddingVertical; + result["horizontalOverflow"] = horizontalOverflow; + result["align"] = align; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleTableStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_fontFamily = map.find("fontFamily"); + if (tmp_fontFamily != map.end()) { + fromRawValue(context, tmp_fontFamily->second, result.fontFamily); + } + auto tmp_fontWeight = map.find("fontWeight"); + if (tmp_fontWeight != map.end()) { + fromRawValue(context, tmp_fontWeight->second, result.fontWeight); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_lineHeight = map.find("lineHeight"); + if (tmp_lineHeight != map.end()) { + fromRawValue(context, tmp_lineHeight->second, result.lineHeight); + } + auto tmp_headerFontFamily = map.find("headerFontFamily"); + if (tmp_headerFontFamily != map.end()) { + fromRawValue(context, tmp_headerFontFamily->second, result.headerFontFamily); + } + auto tmp_headerBackgroundColor = map.find("headerBackgroundColor"); + if (tmp_headerBackgroundColor != map.end()) { + fromRawValue(context, tmp_headerBackgroundColor->second, result.headerBackgroundColor); + } + auto tmp_headerTextColor = map.find("headerTextColor"); + if (tmp_headerTextColor != map.end()) { + fromRawValue(context, tmp_headerTextColor->second, result.headerTextColor); + } + auto tmp_rowEvenBackgroundColor = map.find("rowEvenBackgroundColor"); + if (tmp_rowEvenBackgroundColor != map.end()) { + fromRawValue(context, tmp_rowEvenBackgroundColor->second, result.rowEvenBackgroundColor); + } + auto tmp_rowOddBackgroundColor = map.find("rowOddBackgroundColor"); + if (tmp_rowOddBackgroundColor != map.end()) { + fromRawValue(context, tmp_rowOddBackgroundColor->second, result.rowOddBackgroundColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_borderWidth = map.find("borderWidth"); + if (tmp_borderWidth != map.end()) { + fromRawValue(context, tmp_borderWidth->second, result.borderWidth); + } + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } + auto tmp_cellPaddingHorizontal = map.find("cellPaddingHorizontal"); + if (tmp_cellPaddingHorizontal != map.end()) { + fromRawValue(context, tmp_cellPaddingHorizontal->second, result.cellPaddingHorizontal); + } + auto tmp_cellPaddingVertical = map.find("cellPaddingVertical"); + if (tmp_cellPaddingVertical != map.end()) { + fromRawValue(context, tmp_cellPaddingVertical->second, result.cellPaddingVertical); + } + auto tmp_horizontalOverflow = map.find("horizontalOverflow"); + if (tmp_horizontalOverflow != map.end()) { + fromRawValue(context, tmp_horizontalOverflow->second, result.horizontalOverflow); + } + auto tmp_align = map.find("align"); + if (tmp_align != map.end()) { + fromRawValue(context, tmp_align->second, result.align); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleTableStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleTableStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleTableStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleTaskListStruct { + SharedColor checkedColor{}; + SharedColor borderColor{}; + Float checkboxSize{0.0}; + Float checkboxBorderRadius{0.0}; + SharedColor checkmarkColor{}; + SharedColor checkedTextColor{}; + bool checkedStrikethrough{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleTaskListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["checkedColor"] = ::facebook::react::toDynamic(checkedColor); + result["borderColor"] = ::facebook::react::toDynamic(borderColor); + result["checkboxSize"] = checkboxSize; + result["checkboxBorderRadius"] = checkboxBorderRadius; + result["checkmarkColor"] = ::facebook::react::toDynamic(checkmarkColor); + result["checkedTextColor"] = ::facebook::react::toDynamic(checkedTextColor); + result["checkedStrikethrough"] = checkedStrikethrough; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleTaskListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_checkedColor = map.find("checkedColor"); + if (tmp_checkedColor != map.end()) { + fromRawValue(context, tmp_checkedColor->second, result.checkedColor); + } + auto tmp_borderColor = map.find("borderColor"); + if (tmp_borderColor != map.end()) { + fromRawValue(context, tmp_borderColor->second, result.borderColor); + } + auto tmp_checkboxSize = map.find("checkboxSize"); + if (tmp_checkboxSize != map.end()) { + fromRawValue(context, tmp_checkboxSize->second, result.checkboxSize); + } + auto tmp_checkboxBorderRadius = map.find("checkboxBorderRadius"); + if (tmp_checkboxBorderRadius != map.end()) { + fromRawValue(context, tmp_checkboxBorderRadius->second, result.checkboxBorderRadius); + } + auto tmp_checkmarkColor = map.find("checkmarkColor"); + if (tmp_checkmarkColor != map.end()) { + fromRawValue(context, tmp_checkmarkColor->second, result.checkmarkColor); + } + auto tmp_checkedTextColor = map.find("checkedTextColor"); + if (tmp_checkedTextColor != map.end()) { + fromRawValue(context, tmp_checkedTextColor->second, result.checkedTextColor); + } + auto tmp_checkedStrikethrough = map.find("checkedStrikethrough"); + if (tmp_checkedStrikethrough != map.end()) { + fromRawValue(context, tmp_checkedStrikethrough->second, result.checkedStrikethrough); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleTaskListStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleTaskListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleTaskListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleMathStruct { + Float fontSize{0.0}; + SharedColor color{}; + SharedColor backgroundColor{}; + Float padding{0.0}; + Float marginTop{0.0}; + Float marginBottom{0.0}; + std::string textAlign{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontSize"] = fontSize; + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + result["padding"] = padding; + result["marginTop"] = marginTop; + result["marginBottom"] = marginBottom; + result["textAlign"] = textAlign; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontSize = map.find("fontSize"); + if (tmp_fontSize != map.end()) { + fromRawValue(context, tmp_fontSize->second, result.fontSize); + } + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } + auto tmp_padding = map.find("padding"); + if (tmp_padding != map.end()) { + fromRawValue(context, tmp_padding->second, result.padding); + } + auto tmp_marginTop = map.find("marginTop"); + if (tmp_marginTop != map.end()) { + fromRawValue(context, tmp_marginTop->second, result.marginTop); + } + auto tmp_marginBottom = map.find("marginBottom"); + if (tmp_marginBottom != map.end()) { + fromRawValue(context, tmp_marginBottom->second, result.marginBottom); + } + auto tmp_textAlign = map.find("textAlign"); + if (tmp_textAlign != map.end()) { + fromRawValue(context, tmp_textAlign->second, result.textAlign); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleMathStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleInlineMathStruct { + SharedColor color{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleInlineMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleInlineMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleInlineMathStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleInlineMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleInlineMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct { + Float density{0.0}; + Float speed{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["density"] = density; + result["speed"] = speed; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_density = map.find("density"); + if (tmp_density != map.end()) { + fromRawValue(context, tmp_density->second, result.density); + } + auto tmp_speed = map.find("speed"); + if (tmp_speed != map.end()) { + fromRawValue(context, tmp_speed->second, result.speed); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct { + Float borderRadius{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["borderRadius"] = borderRadius; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_borderRadius = map.find("borderRadius"); + if (tmp_borderRadius != map.end()) { + fromRawValue(context, tmp_borderRadius->second, result.borderRadius); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleSpoilerStruct { + SharedColor color{}; + EnrichedMarkdownTextMarkdownStyleSpoilerParticlesStruct particles{}; + EnrichedMarkdownTextMarkdownStyleSpoilerSolidStruct solid{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleSpoilerStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["particles"] = ::facebook::react::toDynamic(particles); + result["solid"] = ::facebook::react::toDynamic(solid); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleSpoilerStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_particles = map.find("particles"); + if (tmp_particles != map.end()) { + fromRawValue(context, tmp_particles->second, result.particles); + } + auto tmp_solid = map.find("solid"); + if (tmp_solid != map.end()) { + fromRawValue(context, tmp_solid->second, result.solid); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleSpoilerStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleSpoilerStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleSpoilerStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleSuperscriptStruct { + Float fontScale{0.0}; + Float baselineOffsetScale{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleSuperscriptStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontScale"] = fontScale; + result["baselineOffsetScale"] = baselineOffsetScale; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleSuperscriptStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_baselineOffsetScale = map.find("baselineOffsetScale"); + if (tmp_baselineOffsetScale != map.end()) { + fromRawValue(context, tmp_baselineOffsetScale->second, result.baselineOffsetScale); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleSuperscriptStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleSuperscriptStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleSuperscriptStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleSubscriptStruct { + Float fontScale{0.0}; + Float baselineOffsetScale{0.0}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleSubscriptStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["fontScale"] = fontScale; + result["baselineOffsetScale"] = baselineOffsetScale; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleSubscriptStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_fontScale = map.find("fontScale"); + if (tmp_fontScale != map.end()) { + fromRawValue(context, tmp_fontScale->second, result.fontScale); + } + auto tmp_baselineOffsetScale = map.find("baselineOffsetScale"); + if (tmp_baselineOffsetScale != map.end()) { + fromRawValue(context, tmp_baselineOffsetScale->second, result.baselineOffsetScale); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleSubscriptStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleSubscriptStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleSubscriptStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleHighlightStruct { + SharedColor color{}; + SharedColor backgroundColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleHighlightStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["color"] = ::facebook::react::toDynamic(color); + result["backgroundColor"] = ::facebook::react::toDynamic(backgroundColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleHighlightStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_color = map.find("color"); + if (tmp_color != map.end()) { + fromRawValue(context, tmp_color->second, result.color); + } + auto tmp_backgroundColor = map.find("backgroundColor"); + if (tmp_backgroundColor != map.end()) { + fromRawValue(context, tmp_backgroundColor->second, result.backgroundColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleHighlightStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleHighlightStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleHighlightStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMarkdownStyleStruct { + EnrichedMarkdownTextMarkdownStyleParagraphStruct paragraph{}; + EnrichedMarkdownTextMarkdownStyleH1Struct h1{}; + EnrichedMarkdownTextMarkdownStyleH2Struct h2{}; + EnrichedMarkdownTextMarkdownStyleH3Struct h3{}; + EnrichedMarkdownTextMarkdownStyleH4Struct h4{}; + EnrichedMarkdownTextMarkdownStyleH5Struct h5{}; + EnrichedMarkdownTextMarkdownStyleH6Struct h6{}; + EnrichedMarkdownTextMarkdownStyleBlockquoteStruct blockquote{}; + EnrichedMarkdownTextMarkdownStyleListStruct list{}; + EnrichedMarkdownTextMarkdownStyleCodeBlockStruct codeBlock{}; + EnrichedMarkdownTextMarkdownStyleLinkStruct link{}; + std::vector linkVariants{}; + EnrichedMarkdownTextMarkdownStyleStrongStruct strong{}; + EnrichedMarkdownTextMarkdownStyleEmStruct em{}; + EnrichedMarkdownTextMarkdownStyleStrikethroughStruct strikethrough{}; + EnrichedMarkdownTextMarkdownStyleUnderlineStruct underline{}; + EnrichedMarkdownTextMarkdownStyleCodeStruct code{}; + EnrichedMarkdownTextMarkdownStyleImageStruct image{}; + EnrichedMarkdownTextMarkdownStyleVideoStruct video{}; + EnrichedMarkdownTextMarkdownStyleInlineImageStruct inlineImage{}; + EnrichedMarkdownTextMarkdownStyleThematicBreakStruct thematicBreak{}; + EnrichedMarkdownTextMarkdownStyleTableStruct table{}; + EnrichedMarkdownTextMarkdownStyleTaskListStruct taskList{}; + EnrichedMarkdownTextMarkdownStyleMathStruct math{}; + EnrichedMarkdownTextMarkdownStyleInlineMathStruct inlineMath{}; + EnrichedMarkdownTextMarkdownStyleSpoilerStruct spoiler{}; + EnrichedMarkdownTextMarkdownStyleSuperscriptStruct superscript{}; + EnrichedMarkdownTextMarkdownStyleSubscriptStruct subscript{}; + EnrichedMarkdownTextMarkdownStyleHighlightStruct highlight{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMarkdownStyleStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["paragraph"] = ::facebook::react::toDynamic(paragraph); + result["h1"] = ::facebook::react::toDynamic(h1); + result["h2"] = ::facebook::react::toDynamic(h2); + result["h3"] = ::facebook::react::toDynamic(h3); + result["h4"] = ::facebook::react::toDynamic(h4); + result["h5"] = ::facebook::react::toDynamic(h5); + result["h6"] = ::facebook::react::toDynamic(h6); + result["blockquote"] = ::facebook::react::toDynamic(blockquote); + result["list"] = ::facebook::react::toDynamic(list); + result["codeBlock"] = ::facebook::react::toDynamic(codeBlock); + result["link"] = ::facebook::react::toDynamic(link); + result["linkVariants"] = ::facebook::react::toDynamic(linkVariants); + result["strong"] = ::facebook::react::toDynamic(strong); + result["em"] = ::facebook::react::toDynamic(em); + result["strikethrough"] = ::facebook::react::toDynamic(strikethrough); + result["underline"] = ::facebook::react::toDynamic(underline); + result["code"] = ::facebook::react::toDynamic(code); + result["image"] = ::facebook::react::toDynamic(image); + result["video"] = ::facebook::react::toDynamic(video); + result["inlineImage"] = ::facebook::react::toDynamic(inlineImage); + result["thematicBreak"] = ::facebook::react::toDynamic(thematicBreak); + result["table"] = ::facebook::react::toDynamic(table); + result["taskList"] = ::facebook::react::toDynamic(taskList); + result["math"] = ::facebook::react::toDynamic(math); + result["inlineMath"] = ::facebook::react::toDynamic(inlineMath); + result["spoiler"] = ::facebook::react::toDynamic(spoiler); + result["superscript"] = ::facebook::react::toDynamic(superscript); + result["subscript"] = ::facebook::react::toDynamic(subscript); + result["highlight"] = ::facebook::react::toDynamic(highlight); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMarkdownStyleStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_paragraph = map.find("paragraph"); + if (tmp_paragraph != map.end()) { + fromRawValue(context, tmp_paragraph->second, result.paragraph); + } + auto tmp_h1 = map.find("h1"); + if (tmp_h1 != map.end()) { + fromRawValue(context, tmp_h1->second, result.h1); + } + auto tmp_h2 = map.find("h2"); + if (tmp_h2 != map.end()) { + fromRawValue(context, tmp_h2->second, result.h2); + } + auto tmp_h3 = map.find("h3"); + if (tmp_h3 != map.end()) { + fromRawValue(context, tmp_h3->second, result.h3); + } + auto tmp_h4 = map.find("h4"); + if (tmp_h4 != map.end()) { + fromRawValue(context, tmp_h4->second, result.h4); + } + auto tmp_h5 = map.find("h5"); + if (tmp_h5 != map.end()) { + fromRawValue(context, tmp_h5->second, result.h5); + } + auto tmp_h6 = map.find("h6"); + if (tmp_h6 != map.end()) { + fromRawValue(context, tmp_h6->second, result.h6); + } + auto tmp_blockquote = map.find("blockquote"); + if (tmp_blockquote != map.end()) { + fromRawValue(context, tmp_blockquote->second, result.blockquote); + } + auto tmp_list = map.find("list"); + if (tmp_list != map.end()) { + fromRawValue(context, tmp_list->second, result.list); + } + auto tmp_codeBlock = map.find("codeBlock"); + if (tmp_codeBlock != map.end()) { + fromRawValue(context, tmp_codeBlock->second, result.codeBlock); + } + auto tmp_link = map.find("link"); + if (tmp_link != map.end()) { + fromRawValue(context, tmp_link->second, result.link); + } + auto tmp_linkVariants = map.find("linkVariants"); + if (tmp_linkVariants != map.end()) { + fromRawValue(context, tmp_linkVariants->second, result.linkVariants); + } + auto tmp_strong = map.find("strong"); + if (tmp_strong != map.end()) { + fromRawValue(context, tmp_strong->second, result.strong); + } + auto tmp_em = map.find("em"); + if (tmp_em != map.end()) { + fromRawValue(context, tmp_em->second, result.em); + } + auto tmp_strikethrough = map.find("strikethrough"); + if (tmp_strikethrough != map.end()) { + fromRawValue(context, tmp_strikethrough->second, result.strikethrough); + } + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_code = map.find("code"); + if (tmp_code != map.end()) { + fromRawValue(context, tmp_code->second, result.code); + } + auto tmp_image = map.find("image"); + if (tmp_image != map.end()) { + fromRawValue(context, tmp_image->second, result.image); + } + auto tmp_video = map.find("video"); + if (tmp_video != map.end()) { + fromRawValue(context, tmp_video->second, result.video); + } + auto tmp_inlineImage = map.find("inlineImage"); + if (tmp_inlineImage != map.end()) { + fromRawValue(context, tmp_inlineImage->second, result.inlineImage); + } + auto tmp_thematicBreak = map.find("thematicBreak"); + if (tmp_thematicBreak != map.end()) { + fromRawValue(context, tmp_thematicBreak->second, result.thematicBreak); + } + auto tmp_table = map.find("table"); + if (tmp_table != map.end()) { + fromRawValue(context, tmp_table->second, result.table); + } + auto tmp_taskList = map.find("taskList"); + if (tmp_taskList != map.end()) { + fromRawValue(context, tmp_taskList->second, result.taskList); + } + auto tmp_math = map.find("math"); + if (tmp_math != map.end()) { + fromRawValue(context, tmp_math->second, result.math); + } + auto tmp_inlineMath = map.find("inlineMath"); + if (tmp_inlineMath != map.end()) { + fromRawValue(context, tmp_inlineMath->second, result.inlineMath); + } + auto tmp_spoiler = map.find("spoiler"); + if (tmp_spoiler != map.end()) { + fromRawValue(context, tmp_spoiler->second, result.spoiler); + } + auto tmp_superscript = map.find("superscript"); + if (tmp_superscript != map.end()) { + fromRawValue(context, tmp_superscript->second, result.superscript); + } + auto tmp_subscript = map.find("subscript"); + if (tmp_subscript != map.end()) { + fromRawValue(context, tmp_subscript->second, result.subscript); + } + auto tmp_highlight = map.find("highlight"); + if (tmp_highlight != map.end()) { + fromRawValue(context, tmp_highlight->second, result.highlight); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMarkdownStyleStruct &value) { + return "[Object EnrichedMarkdownTextMarkdownStyleStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMarkdownStyleStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextMd4cFlagsStruct { + bool underline{false}; + bool superscript{false}; + bool subscript{false}; + bool latexMath{false}; + bool highlight{false}; + bool hardSoftBreaks{false}; + bool preserveBlankLines{false}; + bool admonitions{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextMd4cFlagsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["underline"] = underline; + result["superscript"] = superscript; + result["subscript"] = subscript; + result["latexMath"] = latexMath; + result["highlight"] = highlight; + result["hardSoftBreaks"] = hardSoftBreaks; + result["preserveBlankLines"] = preserveBlankLines; + result["admonitions"] = admonitions; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextMd4cFlagsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_underline = map.find("underline"); + if (tmp_underline != map.end()) { + fromRawValue(context, tmp_underline->second, result.underline); + } + auto tmp_superscript = map.find("superscript"); + if (tmp_superscript != map.end()) { + fromRawValue(context, tmp_superscript->second, result.superscript); + } + auto tmp_subscript = map.find("subscript"); + if (tmp_subscript != map.end()) { + fromRawValue(context, tmp_subscript->second, result.subscript); + } + auto tmp_latexMath = map.find("latexMath"); + if (tmp_latexMath != map.end()) { + fromRawValue(context, tmp_latexMath->second, result.latexMath); + } + auto tmp_highlight = map.find("highlight"); + if (tmp_highlight != map.end()) { + fromRawValue(context, tmp_highlight->second, result.highlight); + } + auto tmp_hardSoftBreaks = map.find("hardSoftBreaks"); + if (tmp_hardSoftBreaks != map.end()) { + fromRawValue(context, tmp_hardSoftBreaks->second, result.hardSoftBreaks); + } + auto tmp_preserveBlankLines = map.find("preserveBlankLines"); + if (tmp_preserveBlankLines != map.end()) { + fromRawValue(context, tmp_preserveBlankLines->second, result.preserveBlankLines); + } + auto tmp_admonitions = map.find("admonitions"); + if (tmp_admonitions != map.end()) { + fromRawValue(context, tmp_admonitions->second, result.admonitions); + } +} + +static inline std::string toString(const EnrichedMarkdownTextMd4cFlagsStruct &value) { + return "[Object EnrichedMarkdownTextMd4cFlagsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextMd4cFlagsStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextStreamingConfigStruct { + std::string tableMode{}; + std::string codeBlockMode{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextStreamingConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["tableMode"] = tableMode; + result["codeBlockMode"] = codeBlockMode; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextStreamingConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_tableMode = map.find("tableMode"); + if (tmp_tableMode != map.end()) { + fromRawValue(context, tmp_tableMode->second, result.tableMode); + } + auto tmp_codeBlockMode = map.find("codeBlockMode"); + if (tmp_codeBlockMode != map.end()) { + fromRawValue(context, tmp_codeBlockMode->second, result.codeBlockMode); + } +} + +static inline std::string toString(const EnrichedMarkdownTextStreamingConfigStruct &value) { + return "[Object EnrichedMarkdownTextStreamingConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextStreamingConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextContextMenuItemsStruct { + std::string text{}; + std::string icon{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextContextMenuItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = text; + result["icon"] = icon; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextContextMenuItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_icon = map.find("icon"); + if (tmp_icon != map.end()) { + fromRawValue(context, tmp_icon->second, result.icon); + } +} + +static inline std::string toString(const EnrichedMarkdownTextContextMenuItemsStruct &value) { + return "[Object EnrichedMarkdownTextContextMenuItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextContextMenuItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextContextMenuItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextImageRequestHeadersStruct { + std::string name{}; + std::string value{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextImageRequestHeadersStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["name"] = name; + result["value"] = value; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextImageRequestHeadersStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_name = map.find("name"); + if (tmp_name != map.end()) { + fromRawValue(context, tmp_name->second, result.name); + } + auto tmp_value = map.find("value"); + if (tmp_value != map.end()) { + fromRawValue(context, tmp_value->second, result.value); + } +} + +static inline std::string toString(const EnrichedMarkdownTextImageRequestHeadersStruct &value) { + return "[Object EnrichedMarkdownTextImageRequestHeadersStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextImageRequestHeadersStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextImageRequestHeadersStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextLinkPillContentStruct { + std::string url{}; + std::string label{}; + std::string iconUri{}; + SharedColor iconTintColor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkPillContentStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["url"] = url; + result["label"] = label; + result["iconUri"] = iconUri; + result["iconTintColor"] = ::facebook::react::toDynamic(iconTintColor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkPillContentStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_url = map.find("url"); + if (tmp_url != map.end()) { + fromRawValue(context, tmp_url->second, result.url); + } + auto tmp_label = map.find("label"); + if (tmp_label != map.end()) { + fromRawValue(context, tmp_label->second, result.label); + } + auto tmp_iconUri = map.find("iconUri"); + if (tmp_iconUri != map.end()) { + fromRawValue(context, tmp_iconUri->second, result.iconUri); + } + auto tmp_iconTintColor = map.find("iconTintColor"); + if (tmp_iconTintColor != map.end()) { + fromRawValue(context, tmp_iconTintColor->second, result.iconTintColor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkPillContentStruct &value) { + return "[Object EnrichedMarkdownTextLinkPillContentStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkPillContentStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextLinkPillContentStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextLinkRecognitionTextStruct { + std::string pattern{}; + bool caseInsensitive{false}; + bool dotAll{false}; + bool isDisabled{false}; + bool isDefault{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkRecognitionTextStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["caseInsensitive"] = caseInsensitive; + result["dotAll"] = dotAll; + result["isDisabled"] = isDisabled; + result["isDefault"] = isDefault; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkRecognitionTextStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_caseInsensitive = map.find("caseInsensitive"); + if (tmp_caseInsensitive != map.end()) { + fromRawValue(context, tmp_caseInsensitive->second, result.caseInsensitive); + } + auto tmp_dotAll = map.find("dotAll"); + if (tmp_dotAll != map.end()) { + fromRawValue(context, tmp_dotAll->second, result.dotAll); + } + auto tmp_isDisabled = map.find("isDisabled"); + if (tmp_isDisabled != map.end()) { + fromRawValue(context, tmp_isDisabled->second, result.isDisabled); + } + auto tmp_isDefault = map.find("isDefault"); + if (tmp_isDefault != map.end()) { + fromRawValue(context, tmp_isDefault->second, result.isDefault); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkRecognitionTextStruct &value) { + return "[Object EnrichedMarkdownTextLinkRecognitionTextStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkRecognitionTextStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextLinkRecognitionInlineCodeStruct { + std::string pattern{}; + bool caseInsensitive{false}; + bool dotAll{false}; + bool isDisabled{false}; + bool isDefault{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkRecognitionInlineCodeStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["caseInsensitive"] = caseInsensitive; + result["dotAll"] = dotAll; + result["isDisabled"] = isDisabled; + result["isDefault"] = isDefault; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkRecognitionInlineCodeStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_caseInsensitive = map.find("caseInsensitive"); + if (tmp_caseInsensitive != map.end()) { + fromRawValue(context, tmp_caseInsensitive->second, result.caseInsensitive); + } + auto tmp_dotAll = map.find("dotAll"); + if (tmp_dotAll != map.end()) { + fromRawValue(context, tmp_dotAll->second, result.dotAll); + } + auto tmp_isDisabled = map.find("isDisabled"); + if (tmp_isDisabled != map.end()) { + fromRawValue(context, tmp_isDisabled->second, result.isDisabled); + } + auto tmp_isDefault = map.find("isDefault"); + if (tmp_isDefault != map.end()) { + fromRawValue(context, tmp_isDefault->second, result.isDefault); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkRecognitionInlineCodeStruct &value) { + return "[Object EnrichedMarkdownTextLinkRecognitionInlineCodeStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkRecognitionInlineCodeStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextLinkRecognitionStruct { + EnrichedMarkdownTextLinkRecognitionTextStruct text{}; + EnrichedMarkdownTextLinkRecognitionInlineCodeStruct inlineCode{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkRecognitionStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = ::facebook::react::toDynamic(text); + result["inlineCode"] = ::facebook::react::toDynamic(inlineCode); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkRecognitionStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_inlineCode = map.find("inlineCode"); + if (tmp_inlineCode != map.end()) { + fromRawValue(context, tmp_inlineCode->second, result.inlineCode); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkRecognitionStruct &value) { + return "[Object EnrichedMarkdownTextLinkRecognitionStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkRecognitionStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextLinkContextMenuItemsItemsStruct { + std::string text{}; + std::string icon{}; + bool disabled{false}; + bool destructive{false}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkContextMenuItemsItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["text"] = text; + result["icon"] = icon; + result["disabled"] = disabled; + result["destructive"] = destructive; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkContextMenuItemsItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_text = map.find("text"); + if (tmp_text != map.end()) { + fromRawValue(context, tmp_text->second, result.text); + } + auto tmp_icon = map.find("icon"); + if (tmp_icon != map.end()) { + fromRawValue(context, tmp_icon->second, result.icon); + } + auto tmp_disabled = map.find("disabled"); + if (tmp_disabled != map.end()) { + fromRawValue(context, tmp_disabled->second, result.disabled); + } + auto tmp_destructive = map.find("destructive"); + if (tmp_destructive != map.end()) { + fromRawValue(context, tmp_destructive->second, result.destructive); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkContextMenuItemsItemsStruct &value) { + return "[Object EnrichedMarkdownTextLinkContextMenuItemsItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkContextMenuItemsItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextLinkContextMenuItemsItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextLinkContextMenuItemsStruct { + std::string pattern{}; + std::vector items{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextLinkContextMenuItemsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["pattern"] = pattern; + result["items"] = ::facebook::react::toDynamic(items); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextLinkContextMenuItemsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_pattern = map.find("pattern"); + if (tmp_pattern != map.end()) { + fromRawValue(context, tmp_pattern->second, result.pattern); + } + auto tmp_items = map.find("items"); + if (tmp_items != map.end()) { + fromRawValue(context, tmp_items->second, result.items); + } +} + +static inline std::string toString(const EnrichedMarkdownTextLinkContextMenuItemsStruct &value) { + return "[Object EnrichedMarkdownTextLinkContextMenuItemsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextLinkContextMenuItemsStruct &value) { + return value.toDynamic(); +} +#endif + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { + auto items = (std::vector)value; + for (const auto &item : items) { + EnrichedMarkdownTextLinkContextMenuItemsStruct newItem; + fromRawValue(context, item, newItem); + result.emplace_back(newItem); + } +} + + +struct EnrichedMarkdownTextSelectionMenuConfigStruct { + bool copyAsMarkdown{false}; + bool copyImageUrl{false}; + std::string copyLabel{}; + std::string copyAsMarkdownLabel{}; + std::string copyImageUrlLabel{}; + std::string copyImageUrlsLabel{}; + std::vector copyImageUrlPluralTemplates{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextSelectionMenuConfigStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["copyAsMarkdown"] = copyAsMarkdown; + result["copyImageUrl"] = copyImageUrl; + result["copyLabel"] = copyLabel; + result["copyAsMarkdownLabel"] = copyAsMarkdownLabel; + result["copyImageUrlLabel"] = copyImageUrlLabel; + result["copyImageUrlsLabel"] = copyImageUrlsLabel; + result["copyImageUrlPluralTemplates"] = ::facebook::react::toDynamic(copyImageUrlPluralTemplates); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextSelectionMenuConfigStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_copyAsMarkdown = map.find("copyAsMarkdown"); + if (tmp_copyAsMarkdown != map.end()) { + fromRawValue(context, tmp_copyAsMarkdown->second, result.copyAsMarkdown); + } + auto tmp_copyImageUrl = map.find("copyImageUrl"); + if (tmp_copyImageUrl != map.end()) { + fromRawValue(context, tmp_copyImageUrl->second, result.copyImageUrl); + } + auto tmp_copyLabel = map.find("copyLabel"); + if (tmp_copyLabel != map.end()) { + fromRawValue(context, tmp_copyLabel->second, result.copyLabel); + } + auto tmp_copyAsMarkdownLabel = map.find("copyAsMarkdownLabel"); + if (tmp_copyAsMarkdownLabel != map.end()) { + fromRawValue(context, tmp_copyAsMarkdownLabel->second, result.copyAsMarkdownLabel); + } + auto tmp_copyImageUrlLabel = map.find("copyImageUrlLabel"); + if (tmp_copyImageUrlLabel != map.end()) { + fromRawValue(context, tmp_copyImageUrlLabel->second, result.copyImageUrlLabel); + } + auto tmp_copyImageUrlsLabel = map.find("copyImageUrlsLabel"); + if (tmp_copyImageUrlsLabel != map.end()) { + fromRawValue(context, tmp_copyImageUrlsLabel->second, result.copyImageUrlsLabel); + } + auto tmp_copyImageUrlPluralTemplates = map.find("copyImageUrlPluralTemplates"); + if (tmp_copyImageUrlPluralTemplates != map.end()) { + fromRawValue(context, tmp_copyImageUrlPluralTemplates->second, result.copyImageUrlPluralTemplates); + } +} + +static inline std::string toString(const EnrichedMarkdownTextSelectionMenuConfigStruct &value) { + return "[Object EnrichedMarkdownTextSelectionMenuConfigStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextSelectionMenuConfigStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsListStruct { + std::string bulletPoint{}; + std::string nestedBulletPoint{}; + std::string orderedItem{}; + std::string nestedOrderedItem{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsListStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["bulletPoint"] = bulletPoint; + result["nestedBulletPoint"] = nestedBulletPoint; + result["orderedItem"] = orderedItem; + result["nestedOrderedItem"] = nestedOrderedItem; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsListStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_bulletPoint = map.find("bulletPoint"); + if (tmp_bulletPoint != map.end()) { + fromRawValue(context, tmp_bulletPoint->second, result.bulletPoint); + } + auto tmp_nestedBulletPoint = map.find("nestedBulletPoint"); + if (tmp_nestedBulletPoint != map.end()) { + fromRawValue(context, tmp_nestedBulletPoint->second, result.nestedBulletPoint); + } + auto tmp_orderedItem = map.find("orderedItem"); + if (tmp_orderedItem != map.end()) { + fromRawValue(context, tmp_orderedItem->second, result.orderedItem); + } + auto tmp_nestedOrderedItem = map.find("nestedOrderedItem"); + if (tmp_nestedOrderedItem != map.end()) { + fromRawValue(context, tmp_nestedOrderedItem->second, result.nestedOrderedItem); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsListStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsListStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsListStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct { + std::string quote{}; + std::string nestedQuote{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["quote"] = quote; + result["nestedQuote"] = nestedQuote; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_quote = map.find("quote"); + if (tmp_quote != map.end()) { + fromRawValue(context, tmp_quote->second, result.quote); + } + auto tmp_nestedQuote = map.find("nestedQuote"); + if (tmp_nestedQuote != map.end()) { + fromRawValue(context, tmp_nestedQuote->second, result.nestedQuote); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsTableStruct { + std::string row{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsTableStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["row"] = row; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsTableStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_row = map.find("row"); + if (tmp_row != map.end()) { + fromRawValue(context, tmp_row->second, result.row); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsTableStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsTableStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsTableStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsMathStruct { + std::string equation{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsMathStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["equation"] = equation; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsMathStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_equation = map.find("equation"); + if (tmp_equation != map.end()) { + fromRawValue(context, tmp_equation->second, result.equation); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsMathStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsMathStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsMathStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsRotorStruct { + std::string headings{}; + std::string links{}; + std::string images{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsRotorStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["headings"] = headings; + result["links"] = links; + result["images"] = images; + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsRotorStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_headings = map.find("headings"); + if (tmp_headings != map.end()) { + fromRawValue(context, tmp_headings->second, result.headings); + } + auto tmp_links = map.find("links"); + if (tmp_links != map.end()) { + fromRawValue(context, tmp_links->second, result.links); + } + auto tmp_images = map.find("images"); + if (tmp_images != map.end()) { + fromRawValue(context, tmp_images->second, result.images); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsRotorStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsRotorStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsRotorStruct &value) { + return value.toDynamic(); +} +#endif + +struct EnrichedMarkdownTextAccessibilityLabelsStruct { + EnrichedMarkdownTextAccessibilityLabelsListStruct list{}; + EnrichedMarkdownTextAccessibilityLabelsBlockquoteStruct blockquote{}; + EnrichedMarkdownTextAccessibilityLabelsTableStruct table{}; + EnrichedMarkdownTextAccessibilityLabelsMathStruct math{}; + EnrichedMarkdownTextAccessibilityLabelsRotorStruct rotor{}; + + +#ifdef RN_SERIALIZABLE_STATE + bool operator==(const EnrichedMarkdownTextAccessibilityLabelsStruct&) const = default; + + folly::dynamic toDynamic() const { + folly::dynamic result = folly::dynamic::object(); + result["list"] = ::facebook::react::toDynamic(list); + result["blockquote"] = ::facebook::react::toDynamic(blockquote); + result["table"] = ::facebook::react::toDynamic(table); + result["math"] = ::facebook::react::toDynamic(math); + result["rotor"] = ::facebook::react::toDynamic(rotor); + return result; + } +#endif +}; + +static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnrichedMarkdownTextAccessibilityLabelsStruct &result) { + auto map = (std::unordered_map)value; + + auto tmp_list = map.find("list"); + if (tmp_list != map.end()) { + fromRawValue(context, tmp_list->second, result.list); + } + auto tmp_blockquote = map.find("blockquote"); + if (tmp_blockquote != map.end()) { + fromRawValue(context, tmp_blockquote->second, result.blockquote); + } + auto tmp_table = map.find("table"); + if (tmp_table != map.end()) { + fromRawValue(context, tmp_table->second, result.table); + } + auto tmp_math = map.find("math"); + if (tmp_math != map.end()) { + fromRawValue(context, tmp_math->second, result.math); + } + auto tmp_rotor = map.find("rotor"); + if (tmp_rotor != map.end()) { + fromRawValue(context, tmp_rotor->second, result.rotor); + } +} + +static inline std::string toString(const EnrichedMarkdownTextAccessibilityLabelsStruct &value) { + return "[Object EnrichedMarkdownTextAccessibilityLabelsStruct]"; +} + +#ifdef RN_SERIALIZABLE_STATE +static inline folly::dynamic toDynamic(const EnrichedMarkdownTextAccessibilityLabelsStruct &value) { + return value.toDynamic(); +} +#endif +class EnrichedMarkdownTextProps final : public ViewProps { + public: + EnrichedMarkdownTextProps() = default; + EnrichedMarkdownTextProps(const PropsParserContext& context, const EnrichedMarkdownTextProps &sourceProps, const RawProps &rawProps); + +#pragma mark - Props + + std::string markdown{}; + EnrichedMarkdownTextMarkdownStyleStruct markdownStyle{}; + bool enableImagePress{false}; + bool enableTaskListItemToggle{true}; + bool enableCodeBlockPress{false}; + bool enableBlockContextMenu{true}; + bool enableLinkPreview{true}; + bool selectable{false}; + SharedColor selectionColor{}; + SharedColor selectionHandleColor{}; + EnrichedMarkdownTextMd4cFlagsStruct md4cFlags{}; + bool isGFM{false}; + bool allowFontScaling{true}; + Float maxFontSizeMultiplier{0.0}; + bool allowTrailingMargin{false}; + bool streamingAnimation{false}; + EnrichedMarkdownTextStreamingConfigStruct streamingConfig{}; + std::string spoilerOverlay{std::string{"particles"}}; + std::vector contextMenuItems{}; + std::vector imageRequestHeaders{}; + std::vector linkPillContent{}; + EnrichedMarkdownTextLinkRecognitionStruct linkRecognition{}; + std::vector linkContextMenuItems{}; + EnrichedMarkdownTextSelectionMenuConfigStruct selectionMenuConfig{}; + EnrichedMarkdownTextAccessibilityLabelsStruct accessibilityLabels{}; + std::string textBreakStrategy{std::string{"highQuality"}}; + std::string lineBreakStrategyIOS{std::string{"none"}}; + std::string writingDirection{std::string{"first-strong"}}; + int numberOfLines{0}; + std::string ellipsizeMode{std::string{"tail"}}; + + #ifdef RN_SERIALIZABLE_STATE + ComponentName getDiffPropsImplementationTarget() const override; + + folly::dynamic getDiffProps(const Props* prevProps) const override; + #endif + + +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/RCTComponentViewHelpers.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/RCTComponentViewHelpers.h new file mode 100644 index 000000000000..58b4356dc351 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/RCTComponentViewHelpers.h @@ -0,0 +1,466 @@ +/** +* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). +* +* Do not edit this file as changes may cause incorrect behavior and will be lost +* once the code is regenerated. +* +* @generated by codegen project: GenerateComponentHObjCpp.js +*/ + +#import +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol RCTEnrichedMarkdownViewProtocol + +@end + +@protocol RCTEnrichedMarkdownTextInputViewProtocol +- (void)focus; +- (void)blur; +- (void)setValue:(NSString *)markdown; +- (void)setSelection:(NSInteger)start end:(NSInteger)end; +- (void)toggleBold; +- (void)toggleItalic; +- (void)toggleUnderline; +- (void)toggleStrikethrough; +- (void)toggleSpoiler; +- (void)toggleHeading:(NSInteger)level; +- (void)toggleUnorderedList; +- (void)toggleOrderedList; +- (void)indentList; +- (void)outdentList; +- (void)setLink:(NSString *)url; +- (void)insertLink:(NSString *)text url:(NSString *)url; +- (void)insertText:(NSString *)text; +- (void)insertMention:(NSString *)displayText url:(NSString *)url; +- (void)startMention:(NSString *)indicator; +- (void)removeLink; +- (void)copyToClipboard; +- (void)requestMarkdown:(NSInteger)requestId; +- (void)requestCaretRect:(NSInteger)requestId; +@end + +RCT_EXTERN inline void RCTEnrichedMarkdownTextInputHandleCommand( + id componentView, + NSString const *commandName, + NSArray const *args) +{ + if ([commandName isEqualToString:@"focus"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView focus]; + return; +} + +if ([commandName isEqualToString:@"blur"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView blur]; + return; +} + +if ([commandName isEqualToString:@"setValue"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * markdown = (NSString *)arg0; + + [componentView setValue:markdown]; + return; +} + +if ([commandName isEqualToString:@"setSelection"]) { +#if RCT_DEBUG + if ([args count] != 2) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 2); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @"number", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSInteger start = [(NSNumber *)arg0 intValue]; + +NSObject *arg1 = args[1]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg1, [NSNumber class], @"number", @"EnrichedMarkdownTextInput", commandName, @"2nd")) { + return; + } +#endif + NSInteger end = [(NSNumber *)arg1 intValue]; + + [componentView setSelection:start end:end]; + return; +} + +if ([commandName isEqualToString:@"toggleBold"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleBold]; + return; +} + +if ([commandName isEqualToString:@"toggleItalic"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleItalic]; + return; +} + +if ([commandName isEqualToString:@"toggleUnderline"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleUnderline]; + return; +} + +if ([commandName isEqualToString:@"toggleStrikethrough"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleStrikethrough]; + return; +} + +if ([commandName isEqualToString:@"toggleSpoiler"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleSpoiler]; + return; +} + +if ([commandName isEqualToString:@"toggleHeading"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @"number", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSInteger level = [(NSNumber *)arg0 intValue]; + + [componentView toggleHeading:level]; + return; +} + +if ([commandName isEqualToString:@"toggleUnorderedList"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleUnorderedList]; + return; +} + +if ([commandName isEqualToString:@"toggleOrderedList"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView toggleOrderedList]; + return; +} + +if ([commandName isEqualToString:@"indentList"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView indentList]; + return; +} + +if ([commandName isEqualToString:@"outdentList"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView outdentList]; + return; +} + +if ([commandName isEqualToString:@"setLink"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * url = (NSString *)arg0; + + [componentView setLink:url]; + return; +} + +if ([commandName isEqualToString:@"insertLink"]) { +#if RCT_DEBUG + if ([args count] != 2) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 2); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * text = (NSString *)arg0; + +NSObject *arg1 = args[1]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg1, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"2nd")) { + return; + } +#endif + NSString * url = (NSString *)arg1; + + [componentView insertLink:text url:url]; + return; +} + +if ([commandName isEqualToString:@"insertText"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * text = (NSString *)arg0; + + [componentView insertText:text]; + return; +} + +if ([commandName isEqualToString:@"insertMention"]) { +#if RCT_DEBUG + if ([args count] != 2) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 2); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * displayText = (NSString *)arg0; + +NSObject *arg1 = args[1]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg1, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"2nd")) { + return; + } +#endif + NSString * url = (NSString *)arg1; + + [componentView insertMention:displayText url:url]; + return; +} + +if ([commandName isEqualToString:@"startMention"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSString class], @"string", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSString * indicator = (NSString *)arg0; + + [componentView startMention:indicator]; + return; +} + +if ([commandName isEqualToString:@"removeLink"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView removeLink]; + return; +} + +if ([commandName isEqualToString:@"copyToClipboard"]) { +#if RCT_DEBUG + if ([args count] != 0) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 0); + return; + } +#endif + + + + [componentView copyToClipboard]; + return; +} + +if ([commandName isEqualToString:@"requestMarkdown"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @"number", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSInteger requestId = [(NSNumber *)arg0 intValue]; + + [componentView requestMarkdown:requestId]; + return; +} + +if ([commandName isEqualToString:@"requestCaretRect"]) { +#if RCT_DEBUG + if ([args count] != 1) { + RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"EnrichedMarkdownTextInput", commandName, (int)[args count], 1); + return; + } +#endif + + NSObject *arg0 = args[0]; +#if RCT_DEBUG + if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @"number", @"EnrichedMarkdownTextInput", commandName, @"1st")) { + return; + } +#endif + NSInteger requestId = [(NSNumber *)arg0 intValue]; + + [componentView requestCaretRect:requestId]; + return; +} + +#if RCT_DEBUG + RCTLogError(@"%@ received command %@, which is not a supported command.", @"EnrichedMarkdownTextInput", commandName); +#endif +} + +@protocol RCTEnrichedMarkdownTextViewProtocol + +@end + +NS_ASSUME_NONNULL_END \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.cpp b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.cpp new file mode 100644 index 000000000000..feadde330961 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.cpp @@ -0,0 +1,17 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateShadowNodeCpp.js + */ + +#include "ShadowNodes.h" + +namespace facebook::react { + + + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.h new file mode 100644 index 000000000000..615dfa650f45 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/ShadowNodes.h @@ -0,0 +1,23 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateShadowNodeH.js + */ + +#pragma once + +#include "EventEmitters.h" +#include "Props.h" +#include "States.h" +#include +#include + +namespace facebook::react { + + + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.cpp b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.cpp new file mode 100644 index 000000000000..1dbb184cbddb --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.cpp @@ -0,0 +1,16 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateStateCpp.js + */ +#include "States.h" + +namespace facebook::react { + + + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.h b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.h new file mode 100644 index 000000000000..2e55bce75651 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/generated/ReactCodegen/EnrichedMarkdownTextSpec/States.h @@ -0,0 +1,20 @@ +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateStateH.js + */ +#pragma once + +#include +#ifdef RN_SERIALIZABLE_STATE +#include +#endif + +namespace facebook::react { + + + +} // namespace facebook::react \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.h b/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.h new file mode 100644 index 000000000000..fd601ac2445e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.h @@ -0,0 +1,33 @@ +#pragma once + +#import "ENRMFormattingStore.h" +#import "ENRMLinkCoordinator.h" +#import "ENRMLinkRegexConfig.h" +#import "ENRMTextDetector.h" +#import + +@class ENRMInputFormatterStyle; + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^ENRMAutoLinkCallback)(NSString *text, NSString *url, NSRange range); + +@interface ENRMAutoLinkDetector : NSObject + +- (instancetype)initWithTextStorage:(NSTextStorage *)textStorage + formattingStore:(ENRMFormattingStore *)store + style:(ENRMInputFormatterStyle *)style; + +- (void)setRegexConfig:(ENRMLinkRegexConfig *)config; + +/// Callback invoked when a new auto-link is detected. +/// Set by the input view to bridge detections to JS event emission. +@property (nonatomic, copy, nullable) ENRMAutoLinkCallback onLinkDetected; + +/// Remove any auto-link marker attribute in the given range. +/// Call when a manual link is applied over an auto-detected one. +- (void)clearAutoLinkInRange:(NSRange)range; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.mm b/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.mm new file mode 100644 index 000000000000..2d1bb66addb5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMAutoLinkDetector.mm @@ -0,0 +1,249 @@ +#import "ENRMAutoLinkDetector.h" + +#import "ENRMFormattingRange.h" +#import "InputStylePropsUtils.h" + +static NSAttributedStringKey const ENRMAutomaticLinkAttributeName = @"ENRMAutomaticLink"; + +@implementation ENRMAutoLinkDetector { + __weak NSTextStorage *_textStorage; + __weak ENRMFormattingStore *_formattingStore; + __weak ENRMInputFormatterStyle *_style; + ENRMLinkRegexConfig *_regexConfig; +} + +- (instancetype)initWithTextStorage:(NSTextStorage *)textStorage + formattingStore:(ENRMFormattingStore *)store + style:(ENRMInputFormatterStyle *)style +{ + self = [super init]; + if (self) { + _textStorage = textStorage; + _formattingStore = store; + _style = style; + } + return self; +} + +- (void)setRegexConfig:(ENRMLinkRegexConfig *)config +{ + _regexConfig = config; +} + +#pragma mark - ENRMTextDetector + +- (void)processWord:(ENRMWordResult *)wordResult +{ + NSRange matchedRange = NSMakeRange(NSNotFound, 0); + NSString *detectedUrl = [self detectNewLinkAtRange:wordResult.range + inText:wordResult.word + matchedRange:&matchedRange]; + if (detectedUrl != nil && _onLinkDetected != nil) { + // Emit the actual linked slice, not the whole whitespace token — surrounding + // punctuation is not part of the link. + BOOL hasSlice = matchedRange.location != NSNotFound; + NSString *matchedText = hasSlice ? [wordResult.word substringWithRange:matchedRange] : wordResult.word; + NSRange absoluteRange = hasSlice + ? NSMakeRange(wordResult.range.location + matchedRange.location, matchedRange.length) + : wordResult.range; + _onLinkDetected(matchedText, detectedUrl, absoluteRange); + } +} + +- (void)refreshStyling +{ + NSTextStorage *textStorage = _textStorage; + if (textStorage == nil || textStorage.length == 0) { + return; + } + + [textStorage beginEditing]; + [textStorage enumerateAttribute:ENRMAutomaticLinkAttributeName + inRange:NSMakeRange(0, textStorage.length) + options:0 + usingBlock:^(id value, NSRange range, BOOL *stop) { + if (value != nil) { + [self applyVisualStylingToRange:range]; + } + }]; + [textStorage endEditing]; +} + +- (NSArray *)transientFormattingRanges +{ + NSTextStorage *textStorage = _textStorage; + if (textStorage == nil || textStorage.length == 0) { + return @[]; + } + + NSMutableArray *ranges = [NSMutableArray array]; + [textStorage enumerateAttribute:ENRMAutomaticLinkAttributeName + inRange:NSMakeRange(0, textStorage.length) + options:0 + usingBlock:^(id value, NSRange range, BOOL *stop) { + if (value != nil && [value isKindOfClass:[NSString class]]) { + ENRMFormattingRange *fmtRange = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink + range:range + url:value]; + [ranges addObject:fmtRange]; + } + }]; + return ranges; +} + +- (void)clearAutoLinkInRange:(NSRange)range +{ + NSTextStorage *textStorage = _textStorage; + if (textStorage == nil || NSMaxRange(range) > textStorage.length) { + return; + } + [textStorage removeAttribute:ENRMAutomaticLinkAttributeName range:range]; +} + +#pragma mark - Link matching + +- (nullable NSString *)detectNewLinkAtRange:(NSRange)wordRange + inText:(NSString *)word + matchedRange:(NSRange *)outMatchedRange +{ + if (outMatchedRange != NULL) { + *outMatchedRange = NSMakeRange(NSNotFound, 0); + } + + if (_regexConfig != nil && _regexConfig.isDisabled) { + return nil; + } + + NSTextStorage *textStorage = _textStorage; + if (textStorage == nil) { + return nil; + } + + if (NSMaxRange(wordRange) > textStorage.length) { + return nil; + } + + // Tokens carrying markdown link syntax (e.g. "[label](url)") belong to the + // parser, not the auto-linker. Auto-linking them re-wraps the destination and + // yields a corrupted URL like "https://[label](url)" on serialize. + if ([word hasPrefix:@"["] || [word rangeOfString:@"]("].location != NSNotFound) { + [self clearAutoLinkInRange:wordRange]; + return nil; + } + + NSRange localMatch = NSMakeRange(NSNotFound, 0); + NSString *matchedUrl = [self tryMatchWord:word matchedRange:&localMatch]; + + if (matchedUrl == nil || localMatch.location == NSNotFound) { + [self clearAutoLinkInRange:wordRange]; + return nil; + } + + NSRange matchRange = NSMakeRange(wordRange.location + localMatch.location, localMatch.length); + + // A manual link overlapping the matched slice takes precedence — test the + // whole slice, not just its first character. + ENRMFormattingStore *store = _formattingStore; + if (store != nil && [store isStyleActive:ENRMInputStyleTypeLink inRange:matchRange]) { + [self clearAutoLinkInRange:wordRange]; + return nil; + } + + NSRange effectiveRange; + id existing = [textStorage attribute:ENRMAutomaticLinkAttributeName + atIndex:matchRange.location + effectiveRange:&effectiveRange]; + BOOL alreadyApplied = [matchedUrl isEqual:existing] && NSEqualRanges(effectiveRange, matchRange); + + if (!alreadyApplied) { + [textStorage beginEditing]; + [textStorage removeAttribute:ENRMAutomaticLinkAttributeName range:wordRange]; + [textStorage addAttribute:ENRMAutomaticLinkAttributeName value:matchedUrl range:matchRange]; + [self applyVisualStylingToRange:matchRange]; + [textStorage endEditing]; + } + + if (outMatchedRange != NULL) { + *outMatchedRange = localMatch; + } + return matchedUrl; +} + +- (nullable NSString *)tryMatchWord:(NSString *)word matchedRange:(NSRange *)outRange +{ + if (outRange != NULL) { + *outRange = NSMakeRange(NSNotFound, 0); + } + + if (word.length == 0) { + return nil; + } + + NSRange fullRange = NSMakeRange(0, word.length); + + // A custom regex describes the whole-token contract, so keep whole-word + // semantics for it. The default detector extracts just the matched URL slice + // so surrounding punctuation isn't swallowed into the link. + BOOL customExact = _regexConfig != nil && !_regexConfig.isDefault && _regexConfig.parsedRegex != nil; + NSRegularExpression *regex = customExact ? _regexConfig.parsedRegex : [ENRMAutoLinkDetector defaultRegex]; + if (regex == nil) { + return nil; + } + + NSTextCheckingResult *match = [regex firstMatchInString:word options:0 range:fullRange]; + if (match == nil || match.range.location == NSNotFound) { + return nil; + } + + NSRange matchRange = customExact ? fullRange : match.range; + if (outRange != NULL) { + *outRange = matchRange; + } + return [ENRMAutoLinkDetector normalizeUrl:[word substringWithRange:matchRange]]; +} + ++ (NSString *)normalizeUrl:(NSString *)url +{ + if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]) { + return url; + } + return [@"https://" stringByAppendingString:url]; +} + +#pragma mark - Visual styling + +- (void)applyVisualStylingToRange:(NSRange)range +{ + NSTextStorage *textStorage = _textStorage; + ENRMInputFormatterStyle *style = _style; + if (textStorage == nil || style == nil) { + return; + } + + [textStorage addAttribute:NSForegroundColorAttributeName value:style.linkColor range:range]; + if (style.linkUnderline) { + [textStorage addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; + } +} + +#pragma mark - Default regex + ++ (NSRegularExpression *)defaultRegex +{ + static NSRegularExpression *regex; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSError *error = nil; + regex = [NSRegularExpression + regularExpressionWithPattern: + @"(?:https?://[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_\\+.~#?&//=]*" + @"|www\\.[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_\\+.~#?&//=]*" + @"|[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_\\+.~#?&//=]*)" + options:NSRegularExpressionCaseInsensitive + error:&error]; + NSCAssert(regex != nil, @"ENRMAutoLinkDetector: failed to compile default regex: %@", error); + }); + return regex; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.h b/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.h new file mode 100644 index 000000000000..d7c31af04c52 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.h @@ -0,0 +1,71 @@ +#pragma once + +#import "ENRMInputBlockType.h" +#import + +@class ENRMBlockStore; +@class ENRMBlockRange; + +NS_ASSUME_NONNULL_BEGIN + +/// Result of a depth-change operation. +typedef NS_ENUM(NSInteger, ENRMDepthChangeResult) { + ENRMDepthChangeResultChanged, + ENRMDepthChangeResultStartedList, + ENRMDepthChangeResultExitedList, + ENRMDepthChangeResultNoOp, +}; + +/// Encapsulates block-editing operations: toggling block types, adjusting list +/// depth, and querying the block at a given position. The view delegates here +/// and applies UI-level consequences (formatting, anchor sync, typing +/// attributes) based on the returned result. +/// +/// All mutating methods normalize stores to line bounds before returning, so the +/// caller can re-stamp block spans immediately. +@interface ENRMBlockEditCoordinator : NSObject + +- (instancetype)initWithBlockStore:(ENRMBlockStore *)blockStore; + +// ── Queries ────────────────────────────────────────────────────────── + +/// The block owning the paragraph at `position`, or nil. +- (nullable ENRMBlockRange *)blockAtPosition:(NSUInteger)position inText:(NSString *)text; + +/// The list-item block at `position`, or nil if the paragraph is not a list item. +- (nullable ENRMBlockRange *)listBlockAtPosition:(NSUInteger)position inText:(NSString *)text; + +/// Heading level (1-6) at `position`, or 0 for non-heading paragraphs. +- (NSInteger)headingLevelAtPosition:(NSUInteger)position inText:(NSString *)text; + +/// Whether the paragraph at `position` is a list item of `type`, and its depth. +- (BOOL)listStateOfType:(ENRMInputBlockType)type + atPosition:(NSUInteger)position + inText:(NSString *)text + depth:(nullable NSInteger *)outDepth; + +// ── Mutations ──────────────────────────────────────────────────────── + +/// Toggles `type` at `level` on the paragraphs the selection touches. +/// Returns YES when the block was already active (i.e. it was turned off). +- (BOOL)toggleBlockType:(ENRMInputBlockType)type + level:(NSInteger)level + selectionRange:(NSRange)selection + inText:(NSString *)text; + +/// Toggles a list of `type` on the selection. +/// Returns YES when the list was turned off. +- (BOOL)toggleListType:(ENRMInputBlockType)type + cursorPosition:(NSUInteger)cursorPos + selectionRange:(NSRange)selection + inText:(NSString *)text; + +/// Adjusts list depth by `delta` on the selected lines. +- (ENRMDepthChangeResult)changeDepthBy:(NSInteger)delta + cursorPosition:(NSUInteger)cursorPos + selectionRange:(NSRange)selection + inText:(NSString *)text; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.mm b/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.mm new file mode 100644 index 000000000000..38c235fafe8f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockEditCoordinator.mm @@ -0,0 +1,195 @@ +#import "ENRMBlockEditCoordinator.h" +#import "ENRMBlockRange.h" +#import "ENRMBlockStore.h" + +@implementation ENRMBlockEditCoordinator { + ENRMBlockStore *_blockStore; +} + +- (instancetype)initWithBlockStore:(ENRMBlockStore *)blockStore +{ + self = [super init]; + if (self) { + _blockStore = blockStore; + } + return self; +} + +// ── Queries ────────────────────────────────────────────────────────── + +- (nullable ENRMBlockRange *)blockAtPosition:(NSUInteger)position inText:(NSString *)text +{ + if (position > text.length) { + return nil; + } + NSRange paragraph = [text paragraphRangeForRange:NSMakeRange(position, 0)]; + return [_blockStore blockStartingAtLocation:paragraph.location]; +} + +- (nullable ENRMBlockRange *)listBlockAtPosition:(NSUInteger)position inText:(NSString *)text +{ + ENRMBlockRange *block = [self blockAtPosition:position inText:text]; + return (block != nil && ENRMBlockTypeIsListItem(block.type)) ? block : nil; +} + +- (NSInteger)headingLevelAtPosition:(NSUInteger)position inText:(NSString *)text +{ + ENRMBlockRange *block = [self blockAtPosition:position inText:text]; + return block != nil ? ENRMHeadingLevelForBlockType(block.type) : 0; +} + +- (BOOL)listStateOfType:(ENRMInputBlockType)type + atPosition:(NSUInteger)position + inText:(NSString *)text + depth:(nullable NSInteger *)outDepth +{ + ENRMBlockRange *block = [self listBlockAtPosition:position inText:text]; + BOOL match = block != nil && block.type == type; + if (outDepth) { + *outDepth = match ? block.level : 0; + } + return match; +} + +// ── Mutations ──────────────────────────────────────────────────────── + +- (BOOL)toggleBlockType:(ENRMInputBlockType)type + level:(NSInteger)level + selectionRange:(NSRange)selection + inText:(NSString *)text +{ + NSRange paragraphRange = [text paragraphRangeForRange:selection]; + + ENRMBlockRange *current = [_blockStore blockStartingAtLocation:paragraphRange.location]; + BOOL alreadyActive = current != nil && current.type == type; + + if (alreadyActive) { + [_blockStore removeBlockInParagraphRange:paragraphRange inText:text]; + } else if (paragraphRange.length == 0) { + NSInteger resolvedLevel = level; + if (ENRMBlockTypeIsListItem(type) && current != nil && ENRMBlockTypeIsListItem(current.type)) { + resolvedLevel = current.level; + } + [_blockStore setBlockType:type level:resolvedLevel forParagraphRange:paragraphRange inText:text]; + } else { + [text + enumerateSubstringsInRange:paragraphRange + options:NSStringEnumerationByParagraphs | NSStringEnumerationSubstringNotRequired + usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { + NSInteger paragraphLevel = level; + if (ENRMBlockTypeIsListItem(type)) { + ENRMBlockRange *existing = [self listBlockAtPosition:substringRange.location inText:text]; + if (existing != nil) { + paragraphLevel = existing.level; + } + } + [self->_blockStore setBlockType:type + level:paragraphLevel + forParagraphRange:substringRange + inText:text]; + }]; + } + + [_blockStore normalizeToLineBoundsInText:text]; + return alreadyActive; +} + +- (BOOL)toggleListType:(ENRMInputBlockType)type + cursorPosition:(NSUInteger)cursorPos + selectionRange:(NSRange)selection + inText:(NSString *)text +{ + ENRMBlockRange *cursorBlock = [self listBlockAtPosition:cursorPos inText:text]; + BOOL turningOff = cursorBlock != nil && cursorBlock.type == type; + NSRange paragraphRange = [text paragraphRangeForRange:selection]; + + if (turningOff) { + if (paragraphRange.length == 0) { + [_blockStore removeBlockInParagraphRange:paragraphRange inText:text]; + } else { + [text enumerateSubstringsInRange:paragraphRange + options:NSStringEnumerationByParagraphs | NSStringEnumerationSubstringNotRequired + usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, + BOOL *stop) { + [self->_blockStore removeBlockInParagraphRange:substringRange inText:text]; + }]; + } + } else { + if (paragraphRange.length == 0) { + NSInteger existingLevel = 0; + ENRMBlockRange *existing = [self listBlockAtPosition:paragraphRange.location inText:text]; + if (existing != nil) { + existingLevel = existing.level; + } + [_blockStore setBlockType:type level:existingLevel forParagraphRange:paragraphRange inText:text]; + } else { + [text enumerateSubstringsInRange:paragraphRange + options:NSStringEnumerationByParagraphs | NSStringEnumerationSubstringNotRequired + usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, + BOOL *stop) { + NSInteger existingLevel = 0; + ENRMBlockRange *existing = [self listBlockAtPosition:substringRange.location inText:text]; + if (existing != nil) { + existingLevel = existing.level; + } + [self->_blockStore setBlockType:type + level:existingLevel + forParagraphRange:substringRange + inText:text]; + }]; + } + } + + [_blockStore normalizeToLineBoundsInText:text]; + return turningOff; +} + +- (ENRMDepthChangeResult)changeDepthBy:(NSInteger)delta + cursorPosition:(NSUInteger)cursorPos + selectionRange:(NSRange)selection + inText:(NSString *)text +{ + ENRMBlockRange *cursorBlock = [self listBlockAtPosition:cursorPos inText:text]; + if (cursorBlock == nil) { + if (delta > 0 && [self headingLevelAtPosition:cursorPos inText:text] == 0) { + [self toggleListType:ENRMInputBlockTypeUnorderedListItem + cursorPosition:cursorPos + selectionRange:selection + inText:text]; + return ENRMDepthChangeResultStartedList; + } + return ENRMDepthChangeResultNoOp; + } + + if (delta < 0 && cursorBlock.level == 0) { + [self toggleListType:cursorBlock.type cursorPosition:cursorPos selectionRange:selection inText:text]; + return ENRMDepthChangeResultExitedList; + } + + NSRange paragraphRange = [text paragraphRangeForRange:selection]; + + if (paragraphRange.length == 0) { + NSInteger newDepth = MIN(MAX(cursorBlock.level + delta, (NSInteger)0), kENRMMaxListDepth); + [_blockStore setBlockType:cursorBlock.type level:newDepth forParagraphRange:paragraphRange inText:text]; + } else { + [text + enumerateSubstringsInRange:paragraphRange + options:NSStringEnumerationByParagraphs | NSStringEnumerationSubstringNotRequired + usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { + ENRMBlockRange *block = [self listBlockAtPosition:substringRange.location inText:text]; + if (block == nil) { + return; + } + NSInteger newDepth = MIN(MAX(block.level + delta, (NSInteger)0), kENRMMaxListDepth); + [self->_blockStore setBlockType:block.type + level:newDepth + forParagraphRange:substringRange + inText:text]; + }]; + } + + [_blockStore normalizeToLineBoundsInText:text]; + return ENRMDepthChangeResultChanged; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.h b/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.h new file mode 100644 index 000000000000..6dc010feafc1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.h @@ -0,0 +1,28 @@ +#pragma once + +#import "ENRMInputBlockType.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +/// A block-level element occupying a paragraph/line range. Mirrors +/// ENRMFormattingRange but for block scope: the range always covers whole lines. +@interface ENRMBlockRange : NSObject + +@property (nonatomic, assign) ENRMInputBlockType type; +@property (nonatomic, assign) NSRange range; + +/// Generic integer payload for the block. 0 by default. Headings use it for the +/// H-level (1-6); list items use it for nesting depth. +@property (nonatomic, assign) NSInteger level; + +/// 1-based position of an ordered item among its adjacent same-depth siblings; +/// recomputed by the block store's list-metadata pass. +@property (nonatomic, assign) NSInteger ordinal; + ++ (instancetype)rangeWithType:(ENRMInputBlockType)type range:(NSRange)range; ++ (instancetype)rangeWithType:(ENRMInputBlockType)type range:(NSRange)range level:(NSInteger)level; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.mm b/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.mm new file mode 100644 index 000000000000..8d8569e02f06 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockRange.mm @@ -0,0 +1,30 @@ +#import "ENRMBlockRange.h" + +@implementation ENRMBlockRange + ++ (instancetype)rangeWithType:(ENRMInputBlockType)type range:(NSRange)range +{ + return [self rangeWithType:type range:range level:0]; +} + ++ (instancetype)rangeWithType:(ENRMInputBlockType)type range:(NSRange)range level:(NSInteger)level +{ + ENRMBlockRange *blockRange = [[ENRMBlockRange alloc] init]; + blockRange.type = type; + blockRange.range = range; + blockRange.level = level; + blockRange.ordinal = 1; + return blockRange; +} + +- (id)copyWithZone:(NSZone *)zone +{ + ENRMBlockRange *copy = [[ENRMBlockRange allocWithZone:zone] init]; + copy.type = _type; + copy.range = _range; + copy.level = _level; + copy.ordinal = _ordinal; + return copy; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.h b/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.h new file mode 100644 index 000000000000..e3f77c168d0f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.h @@ -0,0 +1,56 @@ +#pragma once + +#import "ENRMBlockRange.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Stores the block-level (paragraph-scoped) ranges for the editor, mirroring +/// ENRMFormattingStore. Unlike inline ranges, block ranges never overlap: at +/// most one block covers any given paragraph, and ranges are kept normalized to +/// whole-line boundaries. +@interface ENRMBlockStore : NSObject + +@property (nonatomic, readonly) NSArray *allRanges; + +/// Returns the block whose paragraph starts exactly at `location`, or nil. +/// Ranges are kept sorted by start, so this is an O(log n) binary search — the +/// single lookup callers use instead of linearly scanning `allRanges`. Relies on +/// the one-block-per-paragraph invariant (paragraph starts are unique). +- (nullable ENRMBlockRange *)blockStartingAtLocation:(NSUInteger)location; + +- (void)setRanges:(NSArray *)ranges; +- (void)clearAll; + +/// Sets/replaces the block on every paragraph the given range touches, expanding +/// to whole-line boundaries within `text`. Removes any block previously covering +/// those paragraphs. +- (void)setBlockType:(ENRMInputBlockType)type + level:(NSInteger)level + forParagraphRange:(NSRange)range + inText:(NSString *)text; + +/// Clears any block on the paragraphs the given range touches (reverting them to +/// the implicit paragraph default). +- (void)removeBlockInParagraphRange:(NSRange)range inText:(NSString *)text; + +/// Shifts/clips block ranges to follow a text edit (shared +/// ENRMRangeEditAdjustment classification), with heading persistence: a heading +/// deleted exactly to its end collapses to a zero-length anchor at the edit +/// location (its line survives), and existing anchors shift/keep/drop with +/// their line. +- (void)adjustForEditAtLocation:(NSUInteger)location + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength; + +/// Snaps every stored range to the line bounds of its start position. +/// Absorbs edge-typed chars, clips split ranges to first line, drops +/// duplicates. On an empty line a heading persists as a zero-length anchor; +/// any other collapsed range is dropped. List depths are clamped so an item +/// nests at most one level under the previous adjacent item (CommonMark cannot +/// represent orphan nesting). Call after adjustForEditAtLocation: once text is +/// final. Idempotent. +- (void)normalizeToLineBoundsInText:(NSString *)text; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.mm b/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.mm new file mode 100644 index 000000000000..14180f77db82 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.mm @@ -0,0 +1,275 @@ +#import "ENRMBlockStore.h" +#import "ENRMRangeEditAdjustment.h" +#import "ENRMRangeStoreUtils.h" + +/// Expands a selection to cover whole paragraphs (line-scoped block boundaries). +/// Clamps unconditionally so out-of-bounds input can't reach +/// paragraphRangeForRange: (which raises on an invalid range). +static NSRange paragraphBoundsForRange(NSRange range, NSString *text) +{ + if (text.length == 0) { + return NSMakeRange(0, 0); + } + NSUInteger location = MIN(range.location, text.length); + NSUInteger length = MIN(range.length, text.length - location); + return [text paragraphRangeForRange:NSMakeRange(location, length)]; +} + +@implementation ENRMBlockStore { + NSMutableArray *_ranges; +} + +- (instancetype)init +{ + if (self = [super init]) { + _ranges = [NSMutableArray array]; + } + return self; +} + +- (NSArray *)allRanges +{ + return [_ranges copy]; +} + +- (nullable ENRMBlockRange *)blockStartingAtLocation:(NSUInteger)location +{ + NSInteger lo = 0; + NSInteger hi = (NSInteger)_ranges.count - 1; + while (lo <= hi) { + NSInteger mid = (lo + hi) / 2; + NSUInteger start = _ranges[(NSUInteger)mid].range.location; + if (start < location) { + lo = mid + 1; + } else if (start > location) { + hi = mid - 1; + } else { + return _ranges[(NSUInteger)mid]; + } + } + return nil; +} + +// Incoming ranges are trusted to be non-overlapping and line-scoped — the +// parser owns that invariant (md4c block structure never overlaps at the same +// nesting level, and nested containers are not yet mapped). Revisit enforcement +// here if a container block type (list, blockquote) is added. +- (void)setRanges:(NSArray *)ranges +{ + _ranges = [[ranges sortedArrayUsingComparator:^NSComparisonResult(ENRMBlockRange *first, ENRMBlockRange *second) { + if (first.range.location < second.range.location) + return NSOrderedAscending; + if (first.range.location > second.range.location) + return NSOrderedDescending; + return NSOrderedSame; + }] mutableCopy]; + [self recomputeListMetadata]; +} + +- (void)clearAll +{ + [_ranges removeAllObjects]; +} + +/// Drops any stored block overlapping `paragraphRange` so a replacement can be +/// inserted cleanly. Blocks are line-scoped and never partially overlap, so a +/// touched block is removed wholesale. +- (void)removeBlocksOverlappingRange:(NSRange)paragraphRange +{ + NSUInteger removeStart = paragraphRange.location; + NSUInteger removeEnd = NSMaxRange(paragraphRange); + NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet]; + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMBlockRange *existing = _ranges[idx]; + NSUInteger existingStart = existing.range.location; + NSUInteger existingEnd = NSMaxRange(existing.range); + + // A zero-length anchor occupies a point, so the half-open overlap test + // never matches it; drop one whose anchor lies within the removal bounds. + if (existing.range.length == 0) { + if (existingStart >= removeStart && existingStart <= removeEnd) { + [indexesToRemove addIndex:idx]; + } + continue; + } + + if (existingEnd <= removeStart || existingStart >= removeEnd) { + continue; + } + [indexesToRemove addIndex:idx]; + } + + ENRMRemoveIndexesInReverse(_ranges, indexesToRemove); +} + +- (void)setBlockType:(ENRMInputBlockType)type + level:(NSInteger)level + forParagraphRange:(NSRange)range + inText:(NSString *)text +{ + NSRange paragraphRange = paragraphBoundsForRange(range, text); + [self removeBlocksOverlappingRange:paragraphRange]; + + paragraphRange = ENRMTrimLineTerminators(paragraphRange, text); + + if (paragraphRange.length == 0 && !ENRMBlockTypePersistsWhenEmpty(type)) { + return; + } + + ENRMBlockRange *blockRange = [ENRMBlockRange rangeWithType:type range:paragraphRange level:level]; + NSUInteger insertAt = ENRMSortedInsertionIndex( + _ranges, blockRange.range.location, ^NSUInteger(id range) { return ((ENRMBlockRange *)range).range.location; }); + [_ranges insertObject:blockRange atIndex:insertAt]; +} + +- (void)removeBlockInParagraphRange:(NSRange)range inText:(NSString *)text +{ + NSRange paragraphRange = paragraphBoundsForRange(range, text); + [self removeBlocksOverlappingRange:paragraphRange]; +} + +- (void)adjustForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength +{ + if (deletedLength == 0 && insertedLength == 0) + return; + + NSUInteger deleteEnd = editLocation + deletedLength; + NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet]; + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMBlockRange *blockRange = _ranges[idx]; + BOOL persists = ENRMBlockTypePersistsWhenEmpty(blockRange.type); + + // Zero-length anchors don't follow the shared adjustment: one at the edit + // location stays put (normalize grows it over the typed text), one past + // the edit shifts with it, one inside the deletion is dropped. + if (blockRange.range.length == 0) { + if (!persists) { + [indexesToRemove addIndex:idx]; + } else if (blockRange.range.location >= deleteEnd && blockRange.range.location > editLocation) { + blockRange.range = NSMakeRange(blockRange.range.location - deletedLength + insertedLength, 0); + } else if (blockRange.range.location > editLocation) { + [indexesToRemove addIndex:idx]; // anchor sat inside the deleted region + } + continue; + } + + ENRMAdjustedRange adjusted = ENRMAdjustRangeForEdit(blockRange.range, editLocation, deletedLength, insertedLength, + /* inheritsReplacementAtStart */ YES, + /* growsAtStartOnInsert */ YES); + if (adjusted.shouldRemove) { + // A persisting block deleted exactly to its end collapses to a zero-length + // anchor (the line's newline survived, so the line stays the block); a + // deletion running past its end removed the line, so drop the block with it. + if (persists && NSMaxRange(blockRange.range) == deleteEnd && blockRange.range.location >= editLocation) { + blockRange.range = NSMakeRange(editLocation, 0); + } else { + [indexesToRemove addIndex:idx]; + } + continue; + } + blockRange.range = adjusted.range; + } + + ENRMRemoveIndexesInReverse(_ranges, indexesToRemove); + + // Prune zero-length ranges, but keep zero-length persisting blocks: they anchor + // an emptied-but-still-present heading/bullet line (see the collapse rule above). + NSMutableIndexSet *emptyIndexes = [NSMutableIndexSet indexSet]; + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMBlockRange *range = _ranges[idx]; + if (range.range.length == 0 && !ENRMBlockTypePersistsWhenEmpty(range.type)) { + [emptyIndexes addIndex:idx]; + } + } + if (emptyIndexes.count > 0) { + ENRMRemoveIndexesInReverse(_ranges, emptyIndexes); + } +} + +- (void)normalizeToLineBoundsInText:(NSString *)text +{ + if (_ranges.count == 0) { + return; + } + + NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet]; + NSInteger previousEnd = -1; + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMBlockRange *blockRange = _ranges[idx]; + NSRange lineRange = paragraphBoundsForRange(NSMakeRange(blockRange.range.location, 0), text); + + lineRange = ENRMTrimLineTerminators(lineRange, text); + + BOOL emptyLine = lineRange.length == 0; + if ((emptyLine && !ENRMBlockTypePersistsWhenEmpty(blockRange.type)) || + (NSInteger)lineRange.location <= previousEnd) { + // Dedup: drop a range that resolves to an already-claimed paragraph. This is a + // legitimate self-heal path (a heading anchor and the block it merges into can + // briefly share a start after a line-join), so it is deliberately silent — it + // cannot distinguish that benign case from genuine corruption, so it does not + // assert here. + [indexesToRemove addIndex:idx]; + continue; + } + + blockRange.range = lineRange; + previousEnd = (NSInteger)NSMaxRange(lineRange); + } + + ENRMRemoveIndexesInReverse(_ranges, indexesToRemove); + [self recomputeListMetadata]; +} + +/// Clamps list depths to valid ancestry (an item nests at most one level under +/// the previous adjacent list item — CommonMark cannot represent orphan nesting) +/// and renumbers ordered items among their adjacent same-depth, same-type run. +- (void)recomputeListMetadata +{ + NSInteger prevEnd = -2; + NSInteger prevDepth = -1; + NSInteger counters[kENRMMaxListDepth + 2]; + ENRMInputBlockType counterTypes[kENRMMaxListDepth + 2]; + memset(counters, 0, sizeof(counters)); + memset(counterTypes, 0, sizeof(counterTypes)); + + for (ENRMBlockRange *blockRange in _ranges) { + if (!ENRMBlockTypeIsListItem(blockRange.type)) { + prevDepth = -1; + continue; + } + BOOL adjacent = prevDepth >= 0 && (NSInteger)blockRange.range.location == prevEnd + 1; + if (!adjacent) { + memset(counters, 0, sizeof(counters)); + memset(counterTypes, 0, sizeof(counterTypes)); + } + // Coerce into [0, kENRMMaxListDepth] before ancestry-clamping: parser and + // indent commands cap their depths, but this pass indexes the counter + // arrays by depth, so an out-of-bounds level must never survive it. + NSInteger maxDepth = MIN(adjacent ? prevDepth + 1 : 0, kENRMMaxListDepth); + if (blockRange.level > maxDepth) { + blockRange.level = maxDepth; + } else if (blockRange.level < 0) { + blockRange.level = 0; + } + NSInteger depth = blockRange.level; + for (NSInteger i = depth + 1; i <= kENRMMaxListDepth + 1; i++) { + counters[i] = 0; + counterTypes[i] = (ENRMInputBlockType)0; + } + if (counterTypes[depth] != blockRange.type) { + counters[depth] = 0; + counterTypes[depth] = blockRange.type; + } + counters[depth]++; + blockRange.ordinal = counters[depth]; + prevEnd = (NSInteger)NSMaxRange(blockRange.range); + prevDepth = blockRange.level; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.h b/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.h new file mode 100644 index 000000000000..2dc229a6548e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.h @@ -0,0 +1,37 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMFormattingRange.h" +#import + +@class ENRMFormattingStore; +@class ENRMBlockStore; +@class ENRMInputFormatter; +@protocol ENRMDetectorPipelineTransientRanges; + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMTransientRangeProvider +- (NSArray *)allTransientFormattingRanges; +@end + +@interface ENRMClipboardCoordinator : NSObject + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + blockStore:(ENRMBlockStore *)blockStore + transientRangeProvider:(id)transientRangeProvider + formatter:(ENRMInputFormatter *)formatter; + +- (NSArray *)allRangesIncludingTransient; + +- (NSString *)serializeText:(NSString *)text + ranges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges; + +- (NSString *)serializeFullDocument:(NSString *)plainText; + +- (nullable NSString *)serializeSelectedRange:(NSRange)selection inText:(NSString *)fullText; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.mm b/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.mm new file mode 100644 index 000000000000..d3440fe2d12d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMClipboardCoordinator.mm @@ -0,0 +1,97 @@ +#import "ENRMClipboardCoordinator.h" +#import "ENRMBlockStore.h" +#import "ENRMFormattingStore.h" +#import "ENRMInputFormatter.h" +#import "ENRMMarkdownSerializer.h" +#import "styles/ENRMBlockHandler.h" + +@implementation ENRMClipboardCoordinator { + ENRMFormattingStore *_formattingStore; + ENRMBlockStore *_blockStore; + id _transientRangeProvider; + ENRMInputFormatter *_formatter; +} + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + blockStore:(ENRMBlockStore *)blockStore + transientRangeProvider:(id)transientRangeProvider + formatter:(ENRMInputFormatter *)formatter +{ + if (self = [super init]) { + _formattingStore = formattingStore; + _blockStore = blockStore; + _transientRangeProvider = transientRangeProvider; + _formatter = formatter; + } + return self; +} + +- (NSArray *)allRangesIncludingTransient +{ + NSArray *transient = [_transientRangeProvider allTransientFormattingRanges]; + if (transient.count == 0) { + return _formattingStore.allRanges; + } + NSMutableArray *merged = [_formattingStore.allRanges mutableCopy]; + [merged addObjectsFromArray:transient]; + return merged; +} + +- (NSString *)serializeText:(NSString *)text + ranges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges +{ + ENRMInputFormatter *formatter = _formatter; + return [ENRMMarkdownSerializer serializePlainText:text + ranges:ranges + blockRanges:blockRanges + blockPrefixProvider:^NSString *(ENRMBlockRange *blockRange) { + id handler = [formatter handlerForBlockType:blockRange.type]; + return [handler markdownLinePrefixForBlockRange:blockRange]; + }]; +} + +- (NSString *)serializeFullDocument:(NSString *)plainText +{ + return [self serializeText:plainText ranges:[self allRangesIncludingTransient] blockRanges:_blockStore.allRanges]; +} + +- (nullable NSString *)serializeSelectedRange:(NSRange)selection inText:(NSString *)fullText +{ + if (selection.length == 0) { + return nil; + } + + NSString *selectedText = [fullText substringWithRange:selection]; + NSUInteger selEnd = NSMaxRange(selection); + + NSMutableArray *clippedRanges = [NSMutableArray array]; + for (ENRMFormattingRange *range in [self allRangesIncludingTransient]) { + NSUInteger rangeStart = range.range.location; + NSUInteger rangeEnd = NSMaxRange(range.range); + if (rangeEnd <= selection.location || rangeStart >= selEnd) { + continue; + } + NSUInteger clippedStart = MAX(rangeStart, selection.location); + NSUInteger clippedEnd = MIN(rangeEnd, selEnd); + NSRange shifted = NSMakeRange(clippedStart - selection.location, clippedEnd - clippedStart); + [clippedRanges addObject:[ENRMFormattingRange rangeWithType:range.type range:shifted url:range.url]]; + } + + NSMutableArray *clippedBlockRanges = [NSMutableArray array]; + for (ENRMBlockRange *blockRange in _blockStore.allRanges) { + NSUInteger rangeStart = blockRange.range.location; + NSUInteger rangeEnd = NSMaxRange(blockRange.range); + if (rangeEnd <= selection.location || rangeStart >= selEnd) { + continue; + } + NSUInteger clippedStart = MAX(rangeStart, selection.location); + NSUInteger clippedEnd = MIN(rangeEnd, selEnd); + NSRange shifted = NSMakeRange(clippedStart - selection.location, clippedEnd - clippedStart); + [clippedBlockRanges addObject:[ENRMBlockRange rangeWithType:blockRange.type range:shifted level:blockRange.level]]; + } + + return [self serializeText:selectedText ranges:clippedRanges blockRanges:clippedBlockRanges]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.h b/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.h new file mode 100644 index 000000000000..e60e712b5633 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.h @@ -0,0 +1,29 @@ +#pragma once + +#import "ENRMClipboardCoordinator.h" +#import "ENRMFormattingRange.h" +#import "ENRMTextDetector.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +/// Coordinates a set of ENRMTextDetector instances. The input view calls +/// this pipeline instead of individual detectors. +@interface ENRMDetectorPipeline : NSObject + +- (void)addDetector:(id)detector; + +/// Run all detectors over the affected words for a given modification range. +- (void)processTextChange:(NSString *)text modificationRange:(NSRange)range; + +/// Re-apply visual styling for all detectors after the formatter +/// resets base attributes. Call right after applyFormattingRanges. +- (void)refreshAllStyling; + +/// Collect transient formatting ranges from every detector, +/// suitable for merging with FormattingStore ranges before serialization. +- (NSArray *)allTransientFormattingRanges; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.mm b/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.mm new file mode 100644 index 000000000000..de0ac103120d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMDetectorPipeline.mm @@ -0,0 +1,53 @@ +#import "ENRMDetectorPipeline.h" + +#import "ENRMWordsUtils.h" + +@implementation ENRMDetectorPipeline { + NSMutableArray> *_detectors; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + _detectors = [NSMutableArray array]; + } + return self; +} + +- (void)addDetector:(id)detector +{ + [_detectors addObject:detector]; +} + +- (void)processTextChange:(NSString *)text modificationRange:(NSRange)range +{ + NSArray *words = [ENRMWordsUtils getAffectedWordsFromText:text modificationRange:range]; + + for (ENRMWordResult *wordResult in words) { + for (id detector in _detectors) { + [detector processWord:wordResult]; + } + } +} + +- (void)refreshAllStyling +{ + for (id detector in _detectors) { + [detector refreshStyling]; + } +} + +- (NSArray *)allTransientFormattingRanges +{ + NSMutableArray *all = [NSMutableArray array]; + for (id detector in _detectors) { + NSArray *ranges = [detector transientFormattingRanges]; + if (ranges.count > 0) { + [all addObjectsFromArray:ranges]; + } + } + return all; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.h b/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.h new file mode 100644 index 000000000000..2ccbc435cf82 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.h @@ -0,0 +1,76 @@ +#import "ENRMInputBlockType.h" +#import + +@class ENRMBlockStore; +@class ENRMFormattingStore; +@class ENRMInputFormatter; +@class ENRMDetectorPipeline; +@class ENRMBlockRange; + +NS_ASSUME_NONNULL_BEGIN + +/// Immutable snapshot of everything the pipeline needs to process a single text change. +@interface ENRMEditContext : NSObject +@property (nonatomic, readonly) NSUInteger editLocation; +@property (nonatomic, readonly) NSUInteger deletedLength; +@property (nonatomic, readonly) NSUInteger insertedLength; +@property (nonatomic, readonly) BOOL preEditReplacedNewline; +@property (nonatomic, readonly) ENRMInputBlockType preEditBlockType; +@property (nonatomic, readonly) NSInteger preEditBlockLevel; +@property (nonatomic, readonly) BOOL preEditParagraphWasEmpty; +@property (nonatomic, readonly) NSSet *pendingStyles; +@property (nonatomic, readonly) NSSet *pendingStyleRemovals; + +- (instancetype)initWithEditLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength + preEditReplacedNewline:(BOOL)preEditReplacedNewline + preEditBlockType:(ENRMInputBlockType)preEditBlockType + preEditBlockLevel:(NSInteger)preEditBlockLevel + preEditParagraphWasEmpty:(BOOL)preEditParagraphWasEmpty + pendingStyles:(NSSet *)pendingStyles + pendingStyleRemovals:(NSSet *)pendingStyleRemovals; +@end + +/// View-specific operations the pipeline delegates back to its host. +@protocol ENRMEditPipelineHost +- (NSString *)plainText; +- (NSTextStorage *)textStorage; +@end + +/// Orchestrates the data-model phases of the per-keystroke edit pipeline: +/// store adjustment, orphan pruning, pending styles, and block continuation. +/// +/// Formatting (which needs `_textView`, `_formatterStyle`, `ENRMEditPhaseFormatting`) +/// and UI updates (typing attributes, placeholder, events, height) stay on the view. +/// The pipeline tells the view whether the edit touched a newline so the view can +/// pick full vs scoped formatting. +@interface ENRMEditPipeline : NSObject + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + blockStore:(ENRMBlockStore *)blockStore + formatter:(ENRMInputFormatter *)formatter + detectorPipeline:(ENRMDetectorPipeline *)detectorPipeline + host:(id)host; + +/// Runs the data-model phases of the edit pipeline and returns YES if the edit +/// touched a newline (so the view should do a full-document reformat rather than +/// a scoped one). +- (BOOL)processTextChangeWithContext:(ENRMEditContext *)context; + +/// Drops anchored blocks no longer at a line start. Exposed so the view's +/// `adjustStoresForEditAtLocation:` can call it too. +- (void)pruneOrphanedBlockAnchors; + +/// Adjusts both stores for an edit delta, prunes orphans, normalizes. +/// Exposed for the view's programmatic text-mutation path. +- (NSString *)adjustStoresForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength; + +/// Runs the detector pipeline on the edited portion of the text. +- (void)detectLinksAtLocation:(NSUInteger)editLocation insertedLength:(NSUInteger)insertedLength; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.mm b/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.mm new file mode 100644 index 000000000000..8dfc44c71253 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMEditPipeline.mm @@ -0,0 +1,228 @@ +#import "ENRMEditPipeline.h" +#import "ENRMBlockHandler.h" +#import "ENRMBlockStore.h" +#import "ENRMDetectorPipeline.h" +#import "ENRMFormattingRange.h" +#import "ENRMFormattingStore.h" +#import "ENRMInputFormatter.h" +#import "ENRMUIKit.h" + +@implementation ENRMEditContext + +- (instancetype)initWithEditLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength + preEditReplacedNewline:(BOOL)preEditReplacedNewline + preEditBlockType:(ENRMInputBlockType)preEditBlockType + preEditBlockLevel:(NSInteger)preEditBlockLevel + preEditParagraphWasEmpty:(BOOL)preEditParagraphWasEmpty + pendingStyles:(NSSet *)pendingStyles + pendingStyleRemovals:(NSSet *)pendingStyleRemovals +{ + if (self = [super init]) { + _editLocation = editLocation; + _deletedLength = deletedLength; + _insertedLength = insertedLength; + _preEditReplacedNewline = preEditReplacedNewline; + _preEditBlockType = preEditBlockType; + _preEditBlockLevel = preEditBlockLevel; + _preEditParagraphWasEmpty = preEditParagraphWasEmpty; + _pendingStyles = [pendingStyles copy]; + _pendingStyleRemovals = [pendingStyleRemovals copy]; + } + return self; +} + +@end + +@implementation ENRMEditPipeline { + ENRMFormattingStore *_formattingStore; + ENRMBlockStore *_blockStore; + ENRMInputFormatter *_formatter; + ENRMDetectorPipeline *_detectorPipeline; + __weak id _host; +} + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + blockStore:(ENRMBlockStore *)blockStore + formatter:(ENRMInputFormatter *)formatter + detectorPipeline:(ENRMDetectorPipeline *)detectorPipeline + host:(id)host +{ + if (self = [super init]) { + _formattingStore = formattingStore; + _blockStore = blockStore; + _formatter = formatter; + _detectorPipeline = detectorPipeline; + _host = host; + } + return self; +} + +#pragma mark - Public API + +- (BOOL)processTextChangeWithContext:(ENRMEditContext *)context +{ + NSUInteger editLocation = context.editLocation; + NSUInteger insertedLength = context.insertedLength; + + [self adjustStoresForEditAtLocation:editLocation deletedLength:context.deletedLength insertedLength:insertedLength]; + + NSString *plainText = [_host plainText]; + + if (insertedLength > 0) { + BOOL insertedHasGlyphContent = [self insertedHasGlyphContentAtLocation:editLocation + length:insertedLength + text:plainText]; + [self applyPendingStylesWithContext:context plainText:plainText hasGlyphContent:insertedHasGlyphContent]; + + if (!insertedHasGlyphContent && insertedLength == 1) { + [self reconcileBlockContinuationAfterNewlineAt:editLocation + previousItemWasEmpty:context.preEditParagraphWasEmpty + preEditBlockType:context.preEditBlockType + preEditBlockLevel:context.preEditBlockLevel]; + // Continuation re-seeds fresh block ranges whose ordinal defaults to 1; + // normalize again so the list-metadata pass renumbers the adjacent run. + [_blockStore normalizeToLineBoundsInText:[_host plainText]]; + } + } + + // Determine whether the edit touched a newline (for full-vs-scoped formatting). + BOOL touchedNewline = context.preEditReplacedNewline; + if (!touchedNewline && insertedLength > 0) { + NSString *postEditText = [_host plainText]; + NSUInteger insertedEnd = MIN(editLocation + insertedLength, postEditText.length); + if (editLocation < insertedEnd) { + NSRange insertedRun = NSMakeRange(editLocation, insertedEnd - editLocation); + touchedNewline = [postEditText rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet] + options:0 + range:insertedRun] + .location != NSNotFound; + } + } + + return touchedNewline; +} + +- (NSString *)adjustStoresForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength +{ + [_formattingStore adjustForEditAtLocation:editLocation deletedLength:deletedLength insertedLength:insertedLength]; + [_blockStore adjustForEditAtLocation:editLocation deletedLength:deletedLength insertedLength:insertedLength]; + [self pruneOrphanedBlockAnchors]; + NSString *plainText = [_host plainText]; + [_blockStore normalizeToLineBoundsInText:plainText]; + return plainText; +} + +- (void)pruneOrphanedBlockAnchors +{ + NSString *text = [_host textStorage].string; + for (ENRMBlockRange *block in _blockStore.allRanges) { + if (!ENRMBlockTypePersistsWhenEmpty(block.type)) { + continue; + } + NSUInteger anchor = MIN(block.range.location, text.length); + BOOL atLineStart = [text paragraphRangeForRange:NSMakeRange(anchor, 0)].location == anchor; + if (!atLineStart) { + [_blockStore removeBlockInParagraphRange:NSMakeRange(anchor, 0) inText:text]; + } + } +} + +- (void)detectLinksAtLocation:(NSUInteger)editLocation insertedLength:(NSUInteger)insertedLength +{ + NSString *currentText = [_host plainText]; + NSUInteger clampedEditLocation = MIN(editLocation, currentText.length); + NSUInteger clampedInsertedLength = MIN(insertedLength, currentText.length - clampedEditLocation); + [_detectorPipeline processTextChange:currentText + modificationRange:NSMakeRange(clampedEditLocation, clampedInsertedLength)]; +} + +#pragma mark - Pending styles (private) + +- (void)applyPendingStylesWithContext:(ENRMEditContext *)context + plainText:(NSString *)plainText + hasGlyphContent:(BOOL)insertedHasGlyphContent +{ + NSRange insertedRange = NSMakeRange(context.editLocation, context.insertedLength); + + if (insertedHasGlyphContent) { + for (NSNumber *styleNum in context.pendingStyles) { + ENRMFormattingRange *newRange = [ENRMFormattingRange rangeWithType:(ENRMInputStyleType)styleNum.integerValue + range:insertedRange]; + [_formattingStore addRange:newRange]; + } + } + + // adjustForEditAtLocation may have expanded an existing range to cover + // the insertion — carve out the inserted portion for removed styles. + for (NSNumber *styleNum in context.pendingStyleRemovals) { + [_formattingStore removeType:(ENRMInputStyleType)styleNum.integerValue inRange:insertedRange]; + } +} + +- (BOOL)insertedHasGlyphContentAtLocation:(NSUInteger)location length:(NSUInteger)length text:(NSString *)text +{ + NSUInteger insertedEnd = location + length; + if (insertedEnd > text.length) + return NO; + NSCharacterSet *newlines = [NSCharacterSet newlineCharacterSet]; + for (NSUInteger i = location; i < insertedEnd; i++) { + if (![newlines characterIsMember:[text characterAtIndex:i]]) { + return YES; + } + } + return NO; +} + +#pragma mark - Block continuation (private) + +/// Reconciles blocks after Return: a non-empty item continues as a new item at +/// the same depth, an empty item exits the list (both lines revert to plain +/// paragraphs). Whether a type continues is the handler's continuesOnNewline. +- (void)reconcileBlockContinuationAfterNewlineAt:(NSUInteger)newlineLocation + previousItemWasEmpty:(BOOL)previousWasEmpty + preEditBlockType:(ENRMInputBlockType)blockType + preEditBlockLevel:(NSInteger)blockLevel +{ + id handler = [_formatter handlerForBlockType:blockType]; + if (!handler || ![handler respondsToSelector:@selector(continuesOnNewline)] || !handler.continuesOnNewline) { + return; + } + + NSString *text = [_host plainText]; + NSUInteger newLineLocation = newlineLocation + 1; + if (newLineLocation > text.length) { + return; + } + NSRange originalParagraph = [text paragraphRangeForRange:NSMakeRange(newlineLocation, 0)]; + NSRange newParagraph = [text paragraphRangeForRange:NSMakeRange(newLineLocation, 0)]; + + if (previousWasEmpty) { + // Exit: drop the block from both lines and strip their list paragraph style. + // Empty lines carry no stamped block-marker attribute for applyFormatting to + // key off, so the manual strip is the only thing that clears the leftover indent. + [_blockStore removeBlockInParagraphRange:originalParagraph inText:text]; + [_blockStore removeBlockInParagraphRange:newParagraph inText:text]; + + NSTextStorage *storage = [_host textStorage]; + [storage beginEditing]; + NSRange clamped = NSIntersectionRange(originalParagraph, NSMakeRange(0, storage.length)); + if (clamped.length > 0) { + [storage removeAttribute:NSParagraphStyleAttributeName range:clamped]; + } + clamped = NSIntersectionRange(newParagraph, NSMakeRange(0, storage.length)); + if (clamped.length > 0) { + [storage removeAttribute:NSParagraphStyleAttributeName range:clamped]; + } + [storage endEditing]; + return; + } + + [_blockStore setBlockType:blockType level:blockLevel forParagraphRange:originalParagraph inText:text]; + [_blockStore setBlockType:blockType level:blockLevel forParagraphRange:newParagraph inText:text]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.h b/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.h new file mode 100644 index 000000000000..ebaa07e674fd --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.h @@ -0,0 +1,36 @@ +#import "ENRMUIKit.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, ENRMEditPhase) { + ENRMEditPhaseIdle, + ENRMEditPhaseProcessing, + ENRMEditPhaseFormatting, + ENRMEditPhaseImporting, +}; + +/// Tracks the current editing phase and exposes computed suppression queries. +/// Replaces the scattered boolean flags (`_isApplyingFormatting`, `_isTextChanging`, +/// `blockEmitting`, `_lastTextChangeTime`) that previously guarded re-entrant +/// code paths in the view. +@interface ENRMEditSession : NSObject + +@property (nonatomic, readonly) ENRMEditPhase phase; + +- (instancetype)initWithTextView:(ENRMPlatformTextView *)textView; + +- (void)enterPhase:(ENRMEditPhase)newPhase; +- (void)exitPhase; + +- (void)recordTextChange; + +@property (nonatomic, readonly) BOOL isComposing; +@property (nonatomic, readonly) BOOL isPostEditGracePeriod; +@property (nonatomic, readonly) BOOL shouldSuppressFormatting; +@property (nonatomic, readonly) BOOL shouldSuppressEvents; +@property (nonatomic, readonly) BOOL shouldSuppressSelectionSideEffects; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.mm b/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.mm new file mode 100644 index 000000000000..31e04b70eee1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMEditSession.mm @@ -0,0 +1,63 @@ +#import "ENRMEditSession.h" + +static const CFTimeInterval kPostEditGracePeriod = 0.1; + +@implementation ENRMEditSession { + __weak ENRMPlatformTextView *_textView; + CFTimeInterval _lastTextChangeTime; +} + +- (instancetype)initWithTextView:(ENRMPlatformTextView *)textView +{ + if (self = [super init]) { + _textView = textView; + _phase = ENRMEditPhaseIdle; + _lastTextChangeTime = 0; + } + return self; +} + +- (void)enterPhase:(ENRMEditPhase)newPhase +{ + _phase = newPhase; +} + +- (void)exitPhase +{ + _phase = ENRMEditPhaseIdle; +} + +- (void)recordTextChange +{ + _lastTextChangeTime = CACurrentMediaTime(); +} + +- (BOOL)isComposing +{ + ENRMPlatformTextView *tv = _textView; + if (!tv) + return NO; + return ENRMHasMarkedText(tv); +} + +- (BOOL)isPostEditGracePeriod +{ + return _lastTextChangeTime > 0 && (CACurrentMediaTime() - _lastTextChangeTime) < kPostEditGracePeriod; +} + +- (BOOL)shouldSuppressFormatting +{ + return _phase == ENRMEditPhaseFormatting || _phase == ENRMEditPhaseImporting; +} + +- (BOOL)shouldSuppressEvents +{ + return _phase == ENRMEditPhaseImporting; +} + +- (BOOL)shouldSuppressSelectionSideEffects +{ + return _phase != ENRMEditPhaseIdle; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.h b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.h new file mode 100644 index 000000000000..903d8a7c01b6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.h @@ -0,0 +1,19 @@ +#pragma once + +#import "ENRMInputStyledRange.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMFormattingRange : NSObject + +@property (nonatomic, assign) ENRMInputStyleType type; +@property (nonatomic, assign) NSRange range; +@property (nonatomic, strong, nullable) NSString *url; + ++ (instancetype)rangeWithType:(ENRMInputStyleType)type range:(NSRange)range; ++ (instancetype)rangeWithType:(ENRMInputStyleType)type range:(NSRange)range url:(nullable NSString *)url; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.mm b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.mm new file mode 100644 index 000000000000..f7fb715e3151 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingRange.mm @@ -0,0 +1,28 @@ +#import "ENRMFormattingRange.h" + +@implementation ENRMFormattingRange + ++ (instancetype)rangeWithType:(ENRMInputStyleType)type range:(NSRange)range +{ + return [self rangeWithType:type range:range url:nil]; +} + ++ (instancetype)rangeWithType:(ENRMInputStyleType)type range:(NSRange)range url:(nullable NSString *)url +{ + ENRMFormattingRange *formattingRange = [[ENRMFormattingRange alloc] init]; + formattingRange.type = type; + formattingRange.range = range; + formattingRange.url = url; + return formattingRange; +} + +- (id)copyWithZone:(NSZone *)zone +{ + ENRMFormattingRange *copy = [[ENRMFormattingRange allocWithZone:zone] init]; + copy.type = _type; + copy.range = _range; + copy.url = [_url copy]; + return copy; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.h b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.h new file mode 100644 index 000000000000..d51f7c6c4fde --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.h @@ -0,0 +1,51 @@ +#pragma once + +#import "ENRMFormattingRange.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMFormattingStore : NSObject + +@property (nonatomic, readonly) NSArray *allRanges; + +- (void)setRanges:(NSArray *)ranges; +- (void)clearAll; + +- (nullable ENRMFormattingRange *)rangeOfType:(ENRMInputStyleType)type containingPosition:(NSUInteger)position; +- (BOOL)isStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position; +- (BOOL)isStyleActive:(ENRMInputStyleType)type inRange:(NSRange)range; +- (BOOL)isStyleAdjacentBefore:(ENRMInputStyleType)type position:(NSUInteger)position; +- (NSArray *)rangesOfType:(ENRMInputStyleType)type; + +/// Snaps a selection so it never partially overlaps an atomic link: a partial selection expands to +/// the whole link, a caret inside a link moves to its end (unchanged when no adjustment is needed). +- (NSRange)selectionAdjustedForAtomicLinks:(NSRange)selection; + +/// YES when the entire `range` is covered by adjacent/overlapping ranges of `type`. +- (BOOL)isStyleFullyActive:(ENRMInputStyleType)type inRange:(NSRange)range; + +/// Toggles `type` on `range`. For a selection (length > 0), removes the style +/// when fully active, otherwise strips `conflictingStyles` and adds it. +/// For a caret (length == 0), reports the current state without mutating. +/// Returns YES when the style was active (removed / pending removal). +- (BOOL)toggleStyle:(ENRMInputStyleType)type + inRange:(NSRange)range + conflictingStyles:(NSSet *)conflictingStyles; + +/// YES when toggling `type` ON at `position` should be refused because one of +/// the `blockingStyles` is active there. Toggling OFF is never blocked. +- (BOOL)isToggleBlocked:(ENRMInputStyleType)type + atPosition:(NSUInteger)position + blockingStyles:(NSSet *)blockingStyles; + +- (void)addRange:(ENRMFormattingRange *)range; +- (void)removeType:(ENRMInputStyleType)type inRange:(NSRange)range; +- (void)removeRange:(ENRMFormattingRange *)range; + +- (void)adjustForEditAtLocation:(NSUInteger)location + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.mm b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.mm new file mode 100644 index 000000000000..92a4fbe06893 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMFormattingStore.mm @@ -0,0 +1,302 @@ +#import "ENRMFormattingStore.h" +#import "ENRMRangeEditAdjustment.h" +#import "ENRMRangeStoreUtils.h" + +@implementation ENRMFormattingStore { + NSMutableArray *_ranges; +} + +- (instancetype)init +{ + if (self = [super init]) { + _ranges = [NSMutableArray array]; + } + return self; +} + +- (NSArray *)allRanges +{ + return [_ranges copy]; +} + +- (NSArray *)rangesOfType:(ENRMInputStyleType)type +{ + NSMutableArray *result = [NSMutableArray array]; + for (ENRMFormattingRange *formattingRange in _ranges) { + if (formattingRange.type == type) { + [result addObject:formattingRange]; + } + } + return result; +} + +- (void)setRanges:(NSArray *)ranges +{ + _ranges = + [[ranges sortedArrayUsingComparator:^NSComparisonResult(ENRMFormattingRange *first, ENRMFormattingRange *second) { + if (first.range.location < second.range.location) + return NSOrderedAscending; + if (first.range.location > second.range.location) + return NSOrderedDescending; + return NSOrderedSame; + }] mutableCopy]; +} + +- (void)clearAll +{ + [_ranges removeAllObjects]; +} + +- (nullable ENRMFormattingRange *)rangeOfType:(ENRMInputStyleType)type containingPosition:(NSUInteger)position +{ + for (ENRMFormattingRange *formattingRange in _ranges) { + if (formattingRange.type != type) + continue; + if (position >= formattingRange.range.location && position < NSMaxRange(formattingRange.range)) { + return formattingRange; + } + } + return nil; +} + +- (NSRange)selectionAdjustedForAtomicLinks:(NSRange)selection +{ + if (selection.length > 0) { + NSUInteger start = selection.location; + NSUInteger end = NSMaxRange(selection); + ENRMFormattingRange *startLink = [self rangeOfType:ENRMInputStyleTypeLink containingPosition:start]; + if (startLink != nil) { + start = MIN(start, startLink.range.location); + } + if (end > 0) { + ENRMFormattingRange *endLink = [self rangeOfType:ENRMInputStyleTypeLink containingPosition:(end - 1)]; + if (endLink != nil) { + end = MAX(end, NSMaxRange(endLink.range)); + } + } + return NSMakeRange(start, end - start); + } + ENRMFormattingRange *caretLink = [self rangeOfType:ENRMInputStyleTypeLink containingPosition:selection.location]; + if (caretLink != nil && selection.location > caretLink.range.location && + selection.location < NSMaxRange(caretLink.range)) { + return NSMakeRange(NSMaxRange(caretLink.range), 0); + } + return selection; +} + +- (BOOL)isStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position +{ + return [self rangeOfType:type containingPosition:position] != nil; +} + +- (BOOL)isStyleActive:(ENRMInputStyleType)type inRange:(NSRange)range +{ + for (ENRMFormattingRange *formattingRange in _ranges) { + if (formattingRange.type == type && NSIntersectionRange(formattingRange.range, range).length > 0) { + return YES; + } + } + return NO; +} + +- (BOOL)isStyleAdjacentBefore:(ENRMInputStyleType)type position:(NSUInteger)position +{ + if (position == 0) { + return NO; + } + return [self rangeOfType:type containingPosition:position] != nil || [self rangeOfType:type + containingPosition:position - 1] != nil; +} + +- (BOOL)isStyleFullyActive:(ENRMInputStyleType)type inRange:(NSRange)range +{ + NSUInteger pos = range.location; + NSUInteger end = NSMaxRange(range); + while (pos < end) { + ENRMFormattingRange *match = [self rangeOfType:type containingPosition:pos]; + if (match == nil) { + return NO; + } + pos = NSMaxRange(match.range); + } + return YES; +} + +- (BOOL)toggleStyle:(ENRMInputStyleType)type + inRange:(NSRange)range + conflictingStyles:(NSSet *)conflictingStyles +{ + BOOL wasActive; + if (range.length > 0) { + wasActive = [self isStyleFullyActive:type inRange:range]; + if (wasActive) { + [self removeType:type inRange:range]; + } else { + for (NSNumber *conflict in conflictingStyles) { + [self removeType:(ENRMInputStyleType)conflict.integerValue inRange:range]; + } + [self addRange:[ENRMFormattingRange rangeWithType:type range:range]]; + } + } else { + wasActive = [self isStyleActive:type atPosition:range.location]; + } + return wasActive; +} + +- (BOOL)isToggleBlocked:(ENRMInputStyleType)type + atPosition:(NSUInteger)position + blockingStyles:(NSSet *)blockingStyles +{ + if (blockingStyles.count == 0) { + return NO; + } + if ([self isStyleActive:type atPosition:position]) { + return NO; + } + for (NSNumber *blocker in blockingStyles) { + if ([self isStyleActive:(ENRMInputStyleType)blocker.integerValue atPosition:position]) { + return YES; + } + } + return NO; +} + +- (void)addRange:(ENRMFormattingRange *)newRange +{ + NSMutableIndexSet *mergeIndexes = [NSMutableIndexSet indexSet]; + NSUInteger mergedStart = newRange.range.location; + NSUInteger mergedEnd = NSMaxRange(newRange.range); + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMFormattingRange *existing = _ranges[idx]; + if (existing.type != newRange.type) + continue; + + NSUInteger existingEnd = NSMaxRange(existing.range); + if (existing.range.location <= mergedEnd && existingEnd >= mergedStart) { + mergedStart = MIN(mergedStart, existing.range.location); + mergedEnd = MAX(mergedEnd, existingEnd); + [mergeIndexes addIndex:idx]; + } + } + + ENRMRemoveIndexesInReverse(_ranges, mergeIndexes); + + ENRMFormattingRange *merged = [ENRMFormattingRange rangeWithType:newRange.type + range:NSMakeRange(mergedStart, mergedEnd - mergedStart) + url:newRange.url]; + + NSUInteger insertAt = ENRMSortedInsertionIndex( + _ranges, merged.range.location, ^NSUInteger(id range) { return ((ENRMFormattingRange *)range).range.location; }); + [_ranges insertObject:merged atIndex:insertAt]; +} + +- (void)removeType:(ENRMInputStyleType)type inRange:(NSRange)removeRange +{ + NSMutableArray *remainders = [NSMutableArray array]; + NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet]; + + NSUInteger removeStart = removeRange.location; + NSUInteger removeEnd = NSMaxRange(removeRange); + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMFormattingRange *existing = _ranges[idx]; + if (existing.type != type) + continue; + + NSUInteger existingStart = existing.range.location; + NSUInteger existingEnd = NSMaxRange(existing.range); + + if (existingEnd <= removeStart || existingStart >= removeEnd) { + continue; + } + + [indexesToRemove addIndex:idx]; + + if (existingStart < removeStart) { + [remainders addObject:[ENRMFormattingRange rangeWithType:type + range:NSMakeRange(existingStart, removeStart - existingStart) + url:existing.url]]; + } + if (existingEnd > removeEnd) { + [remainders addObject:[ENRMFormattingRange rangeWithType:type + range:NSMakeRange(removeEnd, existingEnd - removeEnd) + url:existing.url]]; + } + } + + ENRMRemoveIndexesInReverse(_ranges, indexesToRemove); + + // Remainders are fragments of a just-removed range and cannot overlap others. + for (ENRMFormattingRange *remainder in remainders) { + NSUInteger insertAt = ENRMSortedInsertionIndex(_ranges, remainder.range.location, ^NSUInteger(id range) { + return ((ENRMFormattingRange *)range).range.location; + }); + [_ranges insertObject:remainder atIndex:insertAt]; + } +} + +- (void)removeRange:(ENRMFormattingRange *)range +{ + [_ranges removeObject:range]; +} + +- (void)adjustForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength +{ + if (deletedLength == 0 && insertedLength == 0) + return; + + NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet]; + + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMFormattingRange *formattingRange = _ranges[idx]; + BOOL inheritsReplacement = formattingRange.type != ENRMInputStyleTypeLink; + ENRMAdjustedRange adjusted = ENRMAdjustRangeForEdit(formattingRange.range, editLocation, deletedLength, + insertedLength, inheritsReplacement, NO); + formattingRange.range = adjusted.range; + if (adjusted.shouldRemove) { + [indexesToRemove addIndex:idx]; + } + } + + ENRMRemoveIndexesInReverse(_ranges, indexesToRemove); + + NSMutableIndexSet *emptyIndexes = [NSMutableIndexSet indexSet]; + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + if (_ranges[idx].range.length == 0) { + [emptyIndexes addIndex:idx]; + } + } + if (emptyIndexes.count > 0) { + ENRMRemoveIndexesInReverse(_ranges, emptyIndexes); + } + + [self coalesceAdjacentSameTypeRanges]; +} + +/// Merge same-type (and same-url) ranges left adjacent or overlapping by an +/// edit — e.g. deleting the space in "**foo** **bar**" leaves two touching +/// bold ranges that would serialize as "**foo****bar**". `addRange:` keeps +/// this invariant on insert; the edit path must too. +- (void)coalesceAdjacentSameTypeRanges +{ + for (NSUInteger idx = 0; idx < _ranges.count; idx++) { + ENRMFormattingRange *current = _ranges[idx]; + NSUInteger next = idx + 1; + while (next < _ranges.count && _ranges[next].range.location <= NSMaxRange(current.range)) { + ENRMFormattingRange *candidate = _ranges[next]; + BOOL sameUrl = (current.url == candidate.url) || [current.url isEqualToString:candidate.url]; + if (candidate.type == current.type && sameUrl) { + NSUInteger mergedEnd = MAX(NSMaxRange(current.range), NSMaxRange(candidate.range)); + current.range = NSMakeRange(current.range.location, mergedEnd - current.range.location); + [_ranges removeObjectAtIndex:next]; + } else { + next++; + } + } + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.h new file mode 100644 index 000000000000..092da49e0316 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.h @@ -0,0 +1,91 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// Block-level (paragraph-scoped) element types. A block covers whole lines, +/// unlike inline styles (ENRMInputStyleType) which cover character ranges. +/// +/// Paragraph is the default: every line is a paragraph until a block handler +/// claims it. Concrete block types (headings, list items, etc.) are appended +/// here as their handlers are added — each new case must have a matching +/// id registered in ENRMInputFormatter. +typedef NS_ENUM(NSInteger, ENRMInputBlockType) { + ENRMInputBlockTypeParagraph = 0, + ENRMInputBlockTypeHeading1 = 1, + ENRMInputBlockTypeHeading2 = 2, + ENRMInputBlockTypeHeading3 = 3, + ENRMInputBlockTypeHeading4 = 4, + ENRMInputBlockTypeHeading5 = 5, + ENRMInputBlockTypeHeading6 = 6, + ENRMInputBlockTypeUnorderedListItem = 7, + ENRMInputBlockTypeOrderedListItem = 8, +}; + +/// Whether the type is a list item (nesting depth rides in the range's level). +static inline BOOL ENRMBlockTypeIsListItem(ENRMInputBlockType type) +{ + return type == ENRMInputBlockTypeUnorderedListItem || type == ENRMInputBlockTypeOrderedListItem; +} + +/// Maximum bullet-list nesting depth (0-based). Depth is carried as the block's +/// level payload (ENRMBlockRange.level), clamped into [0, kENRMMaxListDepth]. +static const NSInteger kENRMMaxListDepth = 5; + +/// Bullet-list layout metrics (points). Shared by the list block handler (which +/// reserves the head-indent column via the paragraph style) and the layout +/// manager (which draws the marker glyph into that column). Text for a list item +/// at depth d starts at (d + 1) * kENRMListIndentPerDepth from the leading edge; +/// the marker is centered kENRMListBulletGap before the text. +static const CGFloat kENRMListIndentPerDepth = 18.0; +static const CGFloat kENRMListBulletGap = 9.0; + +/// Maps a heading level (1-6) to its ENRMInputBlockType. Levels outside 1-6 are +/// clamped into range. The contiguous Heading1..Heading6 enum values make this a +/// simple offset from the Heading1 base. +static inline ENRMInputBlockType ENRMBlockTypeForHeadingLevel(NSInteger level) +{ + if (level < 1) { + level = 1; + } else if (level > 6) { + level = 6; + } + return (ENRMInputBlockType)(ENRMInputBlockTypeHeading1 + (level - 1)); +} + +/// The heading level (1-6) for a heading block type, or 0 if the type is not a +/// heading. Inverse of ENRMBlockTypeForHeadingLevel. +static inline NSInteger ENRMHeadingLevelForBlockType(ENRMInputBlockType type) +{ + if (type >= ENRMInputBlockTypeHeading1 && type <= ENRMInputBlockTypeHeading6) { + return (NSInteger)(type - ENRMInputBlockTypeHeading1) + 1; + } + return 0; +} + +/// Whether an emptied line of this type keeps a zero-length anchor (an emptied +/// heading stays a heading, an emptied bullet keeps its marker) instead of +/// reverting to a plain paragraph. +static inline BOOL ENRMBlockTypePersistsWhenEmpty(ENRMInputBlockType type) +{ + return (type >= ENRMInputBlockTypeHeading1 && type <= ENRMInputBlockTypeHeading6) || ENRMBlockTypeIsListItem(type); +} + +/// NSAttributedString attribute carrying the ENRMInputBlockType (boxed NSNumber) +/// of the paragraph a character belongs to. Set by ENRMInputFormatter on the +/// paragraphs a block claims; the next block pass uses it to find and strip the +/// previous pass's styling before re-applying. +extern NSAttributedStringKey const ENRMBlockTypeAttributeName; + +/// NSAttributedString attribute carrying the block's integer payload (boxed +/// NSNumber) — e.g. heading level or list depth. See ENRMBlockRange.level. +/// Applied and stripped alongside ENRMBlockTypeAttributeName. +extern NSAttributedStringKey const ENRMBlockLevelAttributeName; + +/// NSAttributedString attribute carrying an ordered item's 1-based ordinal +/// (boxed NSNumber) so the layout manager can draw its number. Applied and +/// stripped alongside ENRMBlockTypeAttributeName. +extern NSAttributedStringKey const ENRMBlockOrdinalAttributeName; + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.mm new file mode 100644 index 000000000000..60d1645b870e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputBlockType.mm @@ -0,0 +1,5 @@ +#import "ENRMInputBlockType.h" + +NSAttributedStringKey const ENRMBlockTypeAttributeName = @"ENRMBlockType"; +NSAttributedStringKey const ENRMBlockLevelAttributeName = @"ENRMBlockLevel"; +NSAttributedStringKey const ENRMBlockOrdinalAttributeName = @"ENRMBlockOrdinal"; diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputDecorationDrawer.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputDecorationDrawer.h new file mode 100644 index 000000000000..033754d967e8 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputDecorationDrawer.h @@ -0,0 +1,18 @@ +#pragma once + +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Draws decorations (markers, borders, backgrounds) for the input layout manager. +@protocol ENRMInputDecorationDrawer + +- (void)drawDecorationsForGlyphRange:(NSRange)glyphRange + layoutManager:(NSLayoutManager *)layoutManager + atPoint:(CGPoint)origin; + +- (void)drawEmptyEditorDecorationsWithInset:(UIEdgeInsets)inset layoutManager:(NSLayoutManager *)layoutManager; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.h new file mode 100644 index 000000000000..23a598cc169f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.h @@ -0,0 +1,52 @@ +#pragma once + +#import "ENRMInputStyleStateBuilder.h" +#import "ENRMUIKit.h" +#import + +#ifdef __cplusplus +#import +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMInputEventEmitterDataSource + +#ifdef __cplusplus +- (std::shared_ptr)fabricEventEmitter; +#endif + +- (NSString *)plainText; +- (NSString *)currentMarkdown; +- (CGRect)computeCaretRect; + +@end + +@interface ENRMInputEventEmitter : NSObject + +@property (nonatomic, assign) BOOL emitMarkdown; + +- (instancetype)initWithDataSource:(id)dataSource; + +- (void)emitOnChangeText; +- (void)emitOnKeyPress:(NSString *)text; +- (void)emitOnChangeMarkdown; +- (void)emitOnChangeSelection; +- (void)emitOnChangeState; +- (void)emitFormattingChanged; +- (void)emitCaretRectChangeIfNeeded; +- (void)invalidateCachedState; +- (void)emitContextMenuItemPress:(NSString *)itemText; +- (void)emitOnFocus; +- (void)emitOnBlur; +- (void)emitOnLinkDetectedWithText:(NSString *)text url:(NSString *)url range:(NSRange)range; +- (void)emitOnStartMention:(NSString *)indicator; +- (void)emitOnChangeMentionWithIndicator:(NSString *)indicator text:(NSString *)text; +- (void)emitOnEndMention:(NSString *)indicator; +- (void)requestMarkdown:(NSInteger)requestId; +- (void)requestCaretRect:(NSInteger)requestId; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.mm new file mode 100644 index 000000000000..370e1a45c296 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputEventEmitter.mm @@ -0,0 +1,286 @@ +#import "ENRMInputEventEmitter.h" + +using namespace facebook::react; + +static EnrichedMarkdownTextInputEventEmitter::OnChangeState ENRMFabricChangeState(ENRMInputStyleSnapshot s) +{ + return { + .bold = {.isActive = s.bold}, + .italic = {.isActive = s.italic}, + .underline = {.isActive = s.underline}, + .strikethrough = {.isActive = s.strikethrough}, + .spoiler = {.isActive = s.spoiler}, + .link = {.isActive = s.link, .destination = s.linkDestination}, + .heading = {.isActive = s.headingLevel > 0, .level = static_cast(s.headingLevel)}, + .unorderedList = {.isActive = s.unorderedList, .depth = static_cast(s.unorderedList ? s.listDepth : 0)}, + .orderedList = {.isActive = s.orderedList, .depth = static_cast(s.orderedList ? s.listDepth : 0)}, + }; +} + +static EnrichedMarkdownTextInputEventEmitter::OnContextMenuItemPressStyleState +ENRMFabricContextMenuStyleState(ENRMInputStyleSnapshot s) +{ + return { + .bold = {.isActive = s.bold}, + .italic = {.isActive = s.italic}, + .underline = {.isActive = s.underline}, + .strikethrough = {.isActive = s.strikethrough}, + .spoiler = {.isActive = s.spoiler}, + .link = {.isActive = s.link, .destination = s.linkDestination}, + .heading = {.isActive = s.headingLevel > 0, .level = static_cast(s.headingLevel)}, + .unorderedList = {.isActive = s.unorderedList, .depth = static_cast(s.unorderedList ? s.listDepth : 0)}, + .orderedList = {.isActive = s.orderedList, .depth = static_cast(s.orderedList ? s.listDepth : 0)}, + }; +} + +#define ENRM_GUARD_EMITTER(name) \ + auto name = [self emitter]; \ + if (name == nullptr) { \ + return; \ + } + +@implementation ENRMInputEventEmitter { + __weak id _dataSource; + + struct { + BOOL bold, italic, underline, strikethrough, spoiler, link, initialized; + std::string linkDestination; + NSInteger headingLevel; + BOOL unorderedList; + NSInteger unorderedListDepth; + BOOL orderedList; + NSInteger orderedListDepth; + } _prevState; + + std::optional _prevCaretRect; +} + +- (instancetype)initWithDataSource:(id)dataSource +{ + self = [super init]; + if (self) { + _dataSource = dataSource; + } + return self; +} + +#pragma mark - Private + +- (std::shared_ptr)emitter +{ + return [_dataSource fabricEventEmitter]; +} + +#pragma mark - Simple emitters + +- (void)emitOnChangeText +{ + ENRM_GUARD_EMITTER(emitter); + NSString *plainText = [_dataSource plainText]; + emitter->onChangeText({.value = std::string([plainText UTF8String] ?: "")}); +} + +/// Maps the replacement text of a pending edit to RN TextInput's +/// `onKeyPress` key names: empty text means deletion ("Backspace"), and +/// leading \n, \t and ESC map to "Enter", "Tab" and "Escape". +- (void)emitOnKeyPress:(NSString *)text +{ + ENRM_GUARD_EMITTER(emitter); + NSString *key; + if (text.length == 0) { + key = @"Backspace"; + } else { + switch ([text characterAtIndex:0]) { + case '\n': + key = @"Enter"; + break; + case '\t': + key = @"Tab"; + break; + case 0x1B: + key = @"Escape"; + break; + default: + key = text; + break; + } + } + emitter->onInputKeyPress({.key = std::string([key UTF8String] ?: "")}); +} + +- (void)emitOnChangeMarkdown +{ + ENRM_GUARD_EMITTER(emitter); + NSString *markdown = [_dataSource currentMarkdown]; + emitter->onChangeMarkdown({.value = std::string([markdown UTF8String] ?: "")}); +} + +- (void)emitOnChangeSelection +{ + ENRM_GUARD_EMITTER(emitter); + NSRange selection = [_dataSource selectedRange]; + emitter->onChangeSelection({ + .start = static_cast(selection.location), + .end = static_cast(NSMaxRange(selection)), + }); +} + +- (void)emitOnFocus +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onInputFocus({}); +} + +- (void)emitOnBlur +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onInputBlur({}); +} + +- (void)emitOnLinkDetectedWithText:(NSString *)text url:(NSString *)url range:(NSRange)range +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onLinkDetected({ + .text = std::string([text UTF8String] ?: ""), + .url = std::string([url UTF8String] ?: ""), + .start = static_cast(range.location), + .end = static_cast(range.location + range.length), + }); +} + +- (void)emitOnStartMention:(NSString *)indicator +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onStartMention({.indicator = std::string([indicator UTF8String] ?: "")}); +} + +- (void)emitOnChangeMentionWithIndicator:(NSString *)indicator text:(NSString *)text +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onChangeMention({ + .indicator = std::string([indicator UTF8String] ?: ""), + .text = std::string([text UTF8String] ?: ""), + }); +} + +- (void)emitOnEndMention:(NSString *)indicator +{ + ENRM_GUARD_EMITTER(emitter); + emitter->onEndMention({.indicator = std::string([indicator UTF8String] ?: "")}); +} + +#pragma mark - Stateful emitters + +- (void)emitOnChangeState +{ + ENRM_GUARD_EMITTER(emitter); + + ENRMInputStyleSnapshot snapshot = [ENRMInputStyleStateBuilder snapshotAtCurrentCursor:_dataSource]; + + if (_prevState.initialized && _prevState.bold == snapshot.bold && _prevState.italic == snapshot.italic && + _prevState.underline == snapshot.underline && _prevState.strikethrough == snapshot.strikethrough && + _prevState.spoiler == snapshot.spoiler && _prevState.link == snapshot.link && + _prevState.linkDestination == snapshot.linkDestination && _prevState.headingLevel == snapshot.headingLevel && + _prevState.unorderedList == snapshot.unorderedList && _prevState.unorderedListDepth == snapshot.listDepth && + _prevState.orderedList == snapshot.orderedList && _prevState.orderedListDepth == snapshot.listDepth) { + return; + } + + _prevState.bold = snapshot.bold; + _prevState.italic = snapshot.italic; + _prevState.underline = snapshot.underline; + _prevState.strikethrough = snapshot.strikethrough; + _prevState.spoiler = snapshot.spoiler; + _prevState.link = snapshot.link; + _prevState.linkDestination = snapshot.linkDestination; + _prevState.headingLevel = snapshot.headingLevel; + _prevState.unorderedList = snapshot.unorderedList; + _prevState.unorderedListDepth = snapshot.listDepth; + _prevState.orderedList = snapshot.orderedList; + _prevState.orderedListDepth = snapshot.listDepth; + _prevState.initialized = YES; + + emitter->onChangeState(ENRMFabricChangeState(snapshot)); +} + +- (void)emitCaretRectChangeIfNeeded +{ + ENRM_GUARD_EMITTER(emitter); + + CGRect caretRect = [_dataSource computeCaretRect]; + + if (_prevCaretRect.has_value() && CGRectEqualToRect(_prevCaretRect.value(), caretRect)) { + return; + } + + _prevCaretRect = caretRect; + + emitter->onCaretRectChange({ + .x = caretRect.origin.x, + .y = caretRect.origin.y, + .width = caretRect.size.width, + .height = caretRect.size.height, + }); +} + +- (void)invalidateCachedState +{ + _prevState.initialized = NO; + _prevCaretRect.reset(); +} + +- (void)emitContextMenuItemPress:(NSString *)itemText +{ + ENRM_GUARD_EMITTER(eventEmitter); + + NSRange selectedRange = [_dataSource selectedRange]; + NSString *selectedText = selectedRange.length > 0 ? [[_dataSource plainText] substringWithRange:selectedRange] : @""; + + ENRMInputStyleSnapshot snapshot = [ENRMInputStyleStateBuilder snapshotForRange:selectedRange dataSource:_dataSource]; + + eventEmitter->onContextMenuItemPress({ + .itemText = std::string(itemText.UTF8String), + .selectedText = std::string(selectedText.UTF8String), + .selectionStart = static_cast(selectedRange.location), + .selectionEnd = static_cast(NSMaxRange(selectedRange)), + .styleState = ENRMFabricContextMenuStyleState(snapshot), + }); +} + +#pragma mark - Compound helpers + +- (void)emitFormattingChanged +{ + [self emitOnChangeState]; + if (_emitMarkdown) { + [self emitOnChangeMarkdown]; + } +} + +#pragma mark - Request-response + +- (void)requestMarkdown:(NSInteger)requestId +{ + ENRM_GUARD_EMITTER(emitter); + NSString *markdown = [_dataSource currentMarkdown]; + emitter->onRequestMarkdownResult({ + .requestId = static_cast(requestId), + .markdown = std::string([markdown UTF8String] ?: ""), + }); +} + +- (void)requestCaretRect:(NSInteger)requestId +{ + ENRM_GUARD_EMITTER(emitter); + + CGRect caretRect = [_dataSource computeCaretRect]; + emitter->onRequestCaretRectResult({ + .requestId = static_cast(requestId), + .x = caretRect.origin.x, + .y = caretRect.origin.y, + .width = caretRect.size.width, + .height = caretRect.size.height, + }); +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.h new file mode 100644 index 000000000000..f7166a42af2a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.h @@ -0,0 +1,48 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMFormattingRange.h" +#import "ENRMInputFormatterStyle.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMStyleHandler; +@protocol ENRMBlockHandler; + +@interface ENRMInputFormatter : NSObject + +- (nullable id)handlerForStyleType:(ENRMInputStyleType)type; +- (nullable id)handlerForBlockType:(ENRMInputBlockType)type; + +- (void)applyFormattingRanges:(NSArray *)ranges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style; + +/// Same as above, but resets and re-applies attributes only within `scope` +/// (ranges straddling the boundary are clipped — attributes outside the scope +/// are already consistent because they move with the text on edits). Pass the +/// full text range for a wholesale re-apply (import / style change). +- (void)applyFormattingRanges:(NSArray *)ranges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style + scopedToRange:(NSRange)scope; + +/// Applies paragraph-level attributes for each block range via its handler, +/// after first stripping the attributes applied on the previous pass (so +/// removed blocks don't leave stale paragraph styling behind). With no +/// handlers registered (PR1) this is a no-op. +- (void)applyBlockRanges:(NSArray *)blockRanges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style; + +/// Same as above, scoped: strips markers only within `scope` and re-applies +/// only the block ranges intersecting it. `scope` must cover whole lines +/// (blocks are line-scoped) — pass a line-expanded edit window. +- (void)applyBlockRanges:(NSArray *)blockRanges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style + scopedToRange:(NSRange)scope; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.mm new file mode 100644 index 000000000000..237e123118b2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatter.mm @@ -0,0 +1,445 @@ +#import "ENRMInputFormatter.h" +#import "ENRMBlockHandler.h" +#import "ENRMBoldStyleHandler.h" +#import "ENRMHeadingBlockHandler.h" +#import "ENRMInputBlockType.h" +#import "ENRMItalicStyleHandler.h" +#import "ENRMLinkStyleHandler.h" +#import "ENRMOrderedListBlockHandler.h" +#import "ENRMSpoilerStyleHandler.h" +#import "ENRMStrikethroughStyleHandler.h" +#import "ENRMStyleHandler.h" +#import "ENRMUnderlineStyleHandler.h" +#import "ENRMUnorderedListBlockHandler.h" +#import "ParagraphStyleUtils.h" + +/// Sets `key` to `value` only on sub-runs whose value differs, recording each +/// written range in `changed` so the caller can invalidate just what changed. +static void ENRMSetAttributeIfChanged(NSMutableAttributedString *storage, NSAttributedStringKey key, id value, + NSRange range, NSMutableIndexSet *changed) +{ + if (range.length == 0) { + return; + } + NSMutableArray *rangesToSet = [NSMutableArray array]; + [storage enumerateAttribute:key + inRange:range + options:0 + usingBlock:^(id current, NSRange subRange, BOOL *stop) { + BOOL equal = (current == value) || (current != nil && [current isEqual:value]); + if (!equal) { + [rangesToSet addObject:[NSValue valueWithRange:subRange]]; + } + }]; + for (NSValue *rangeValue in rangesToSet) { + NSRange subRange = rangeValue.rangeValue; + [storage addAttribute:key value:value range:subRange]; + [changed addIndexesInRange:subRange]; + } +} + +/// Removes `key` only where present, recording cleared ranges in `changed`. +static void ENRMRemoveAttributeIfPresent(NSMutableAttributedString *storage, NSAttributedStringKey key, NSRange range, + NSMutableIndexSet *changed) +{ + if (range.length == 0) { + return; + } + NSMutableArray *rangesToClear = [NSMutableArray array]; + [storage enumerateAttribute:key + inRange:range + options:0 + usingBlock:^(id current, NSRange subRange, BOOL *stop) { + if (current != nil) { + [rangesToClear addObject:[NSValue valueWithRange:subRange]]; + } + }]; + for (NSValue *rangeValue in rangesToClear) { + NSRange subRange = rangeValue.rangeValue; + [storage removeAttribute:key range:subRange]; + [changed addIndexesInRange:subRange]; + } +} + +@implementation ENRMInputFormatter { + NSDictionary> *_styleHandlers; + NSDictionary> *_blockHandlers; +} + +- (instancetype)init +{ + if (self = [super init]) { + NSArray> *handlers = @[ + [[ENRMBoldStyleHandler alloc] init], + [[ENRMItalicStyleHandler alloc] init], + [[ENRMUnderlineStyleHandler alloc] init], + [[ENRMStrikethroughStyleHandler alloc] init], + [[ENRMLinkStyleHandler alloc] init], + [[ENRMSpoilerStyleHandler alloc] init], + ]; + NSMutableDictionary> *map = [NSMutableDictionary dictionary]; + for (id handler in handlers) { + map[@(handler.styleType)] = handler; + } + _styleHandlers = [map copy]; + + ENRMHeadingBlockHandler *headingHandler = [[ENRMHeadingBlockHandler alloc] init]; + NSMutableDictionary> *blockMap = [NSMutableDictionary dictionary]; + for (NSInteger level = 1; level <= 6; level++) { + blockMap[@(ENRMBlockTypeForHeadingLevel(level))] = headingHandler; + } + blockMap[@(ENRMInputBlockTypeUnorderedListItem)] = [[ENRMUnorderedListBlockHandler alloc] init]; + blockMap[@(ENRMInputBlockTypeOrderedListItem)] = [[ENRMOrderedListBlockHandler alloc] init]; + _blockHandlers = [blockMap copy]; + } + return self; +} + +- (nullable id)handlerForStyleType:(ENRMInputStyleType)type +{ + return _styleHandlers[@(type)]; +} + +- (nullable id)handlerForBlockType:(ENRMInputBlockType)type +{ + return _blockHandlers[@(type)]; +} + +- (void)applyFormattingRanges:(NSArray *)ranges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style +{ + [self applyFormattingRanges:ranges + toTextView:textView + style:style + scopedToRange:NSMakeRange(0, textView.textStorage.length)]; +} + +- (void)applyFormattingRanges:(NSArray *)ranges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style + scopedToRange:(NSRange)scope +{ + NSTextStorage *textStorage = textView.textStorage; + NSUInteger textLength = textStorage.length; + + if (textLength == 0) { + return; + } + + NSUInteger scopeStart = MIN(scope.location, textLength); + NSUInteger scopeEnd = MIN(NSMaxRange(scope), textLength); + if (scopeEnd <= scopeStart) { + return; + } + NSRange scopeRange = NSMakeRange(scopeStart, scopeEnd - scopeStart); + NSUInteger scopeLength = scopeRange.length; + + // Diff every write and invalidate only what changed, so unchanged content in + // scope (e.g. a table below a plain-paragraph edit) is not re-laid out (#739). + NSMutableIndexSet *changed = [NSMutableIndexSet indexSet]; + + [textStorage beginEditing]; + + // Reset to base; fonts are resolved per trait run below. + ENRMSetAttributeIfChanged(textStorage, NSForegroundColorAttributeName, style.baseTextColor, scopeRange, changed); + ENRMRemoveAttributeIfPresent(textStorage, NSUnderlineStyleAttributeName, scopeRange, changed); + ENRMRemoveAttributeIfPresent(textStorage, NSStrikethroughStyleAttributeName, scopeRange, changed); + ENRMRemoveAttributeIfPresent(textStorage, NSBackgroundColorAttributeName, scopeRange, changed); + + UIFontDescriptorSymbolicTraits *traitMap = + (UIFontDescriptorSymbolicTraits *)calloc(scopeLength, sizeof(UIFontDescriptorSymbolicTraits)); + if (!traitMap) { + [textStorage endEditing]; + return; + } + + for (ENRMFormattingRange *formattingRange in ranges) { + if (formattingRange.range.length == 0 || NSMaxRange(formattingRange.range) > textLength) { + continue; + } + + // Ranges straddling the scope boundary are clipped: attributes are + // per-character and the out-of-scope part is untouched by the reset above. + NSRange clipped = NSIntersectionRange(formattingRange.range, scopeRange); + if (clipped.length == 0) { + continue; + } + + id handler = _styleHandlers[@(formattingRange.type)]; + if (!handler) { + continue; + } + + UIFontDescriptorSymbolicTraits traits = [handler fontTraits]; + if (traits != 0) { + NSUInteger start = clipped.location; + NSUInteger end = NSMaxRange(clipped); + for (NSUInteger i = start; i < end; i++) { + traitMap[i - scopeStart] |= traits; + } + } + + // Handler writes are not diffed; mark the styled run changed to keep its invalidation. + [handler applyNonFontAttributesToTextStorage:textStorage range:clipped formattingRange:formattingRange style:style]; + [changed addIndexesInRange:clipped]; + } + + // Resolve the final font per trait run (base or styled), diffed. + NSUInteger runStart = 0; + UIFontDescriptorSymbolicTraits currentTraits = traitMap[0]; + + for (NSUInteger i = 1; i <= scopeLength; i++) { + UIFontDescriptorSymbolicTraits nextTraits = (i < scopeLength) ? traitMap[i] : ~currentTraits; + if (nextTraits != currentTraits) { + UIFont *font = (currentTraits != 0) ? [style fontForTraits:currentTraits] : style.baseFont; + ENRMSetAttributeIfChanged(textStorage, NSFontAttributeName, font, + NSMakeRange(scopeStart + runStart, i - runStart), changed); + runStart = i; + currentTraits = (i < scopeLength) ? traitMap[i] : 0; + } + } + + free(traitMap); + + [self applyBaseLineHeight:style.baseLineHeight toNonHeadingParagraphsInTextStorage:textStorage range:scopeRange]; + + [textStorage endEditing]; + + NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject; + if (layoutManager) { + // Invalidate only changed ranges; ensureLayout over the scope only realizes + // already-dirty runs, so the inserted line still lays out. + [changed enumerateRangesUsingBlock:^(NSRange changedRange, BOOL *stop) { + [layoutManager invalidateLayoutForCharacterRange:changedRange actualCharacterRange:NULL]; + }]; + [layoutManager ensureLayoutForCharacterRange:scopeRange]; + } + + ENRMSetNeedsDisplay(textView); +} + +- (void)applyBlockRanges:(NSArray *)blockRanges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style +{ + [self applyBlockRanges:blockRanges + toTextView:textView + style:style + scopedToRange:NSMakeRange(0, textView.textStorage.length)]; +} + +- (void)applyBlockRanges:(NSArray *)blockRanges + toTextView:(ENRMPlatformTextView *)textView + style:(ENRMInputFormatterStyle *)style + scopedToRange:(NSRange)scope +{ + if (_blockHandlers.count == 0) { + return; + } + + NSTextStorage *textStorage = textView.textStorage; + NSUInteger textLength = textStorage.length; + if (textLength == 0) { + return; + } + + NSUInteger scopeStart = MIN(scope.location, textLength); + NSUInteger scopeEnd = MIN(NSMaxRange(scope), textLength); + if (scopeEnd <= scopeStart) { + return; + } + NSRange scopeRange = NSMakeRange(scopeStart, scopeEnd - scopeStart); + + [textStorage beginEditing]; + + // Reset pass: strip everything the previous block pass applied — paragraphs + // are found via the ENRMBlockTypeAttributeName marker — so a removed or moved + // block doesn't leave stale paragraph styling behind. Character-level + // attributes (fonts, colors) are already reset by the inline pass, which runs + // first. This runs even with zero current ranges: deleting the last block + // must still clear its styling. + NSMutableArray *previouslyClaimedRanges = [NSMutableArray array]; + [textStorage enumerateAttribute:ENRMBlockTypeAttributeName + inRange:scopeRange + options:0 + usingBlock:^(id value, NSRange range, BOOL *stop) { + if (value != nil) { + [previouslyClaimedRanges addObject:[NSValue valueWithRange:range]]; + } + }]; + for (NSValue *rangeValue in previouslyClaimedRanges) { + NSRange range = rangeValue.rangeValue; + [textStorage removeAttribute:ENRMBlockTypeAttributeName range:range]; + [textStorage removeAttribute:ENRMBlockLevelAttributeName range:range]; + [textStorage removeAttribute:ENRMBlockOrdinalAttributeName range:range]; + [textStorage removeAttribute:NSParagraphStyleAttributeName range:range]; + [textStorage removeAttribute:NSBaselineOffsetAttributeName range:range]; + } + + for (ENRMBlockRange *blockRange in blockRanges) { + BOOL isHeadingAnchor = blockRange.range.length == 0 && ENRMHeadingLevelForBlockType(blockRange.type) > 0; + + if (!isHeadingAnchor && (blockRange.range.length == 0 || NSMaxRange(blockRange.range) > textLength)) { + continue; + } + if (isHeadingAnchor && blockRange.range.location > textLength) { + continue; + } + + // Scope check: normal blocks are line-scoped and either fully inside or + // outside; a zero-length heading anchor is in-scope when its point falls + // within [scopeStart, scopeEnd] inclusive. + if (isHeadingAnchor) { + if (blockRange.range.location < scopeRange.location || blockRange.range.location > NSMaxRange(scopeRange)) { + continue; + } + } else if (NSIntersectionRange(blockRange.range, scopeRange).length == 0) { + continue; + } + + id handler = _blockHandlers[@(blockRange.type)]; + if (!handler) { + continue; + } + + NSUInteger attrIndex = blockRange.range.location; + if (attrIndex >= textLength) { + attrIndex = textLength > 0 ? textLength - 1 : 0; + } + + NSParagraphStyle *existingStyle = [textStorage attribute:NSParagraphStyleAttributeName + atIndex:attrIndex + effectiveRange:NULL]; + NSMutableParagraphStyle *paragraphStyle = + existingStyle ? [existingStyle mutableCopy] : [[NSMutableParagraphStyle alloc] init]; + NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; + + [handler applyAttributesToParagraphStyle:paragraphStyle attributes:attributes blockRange:blockRange style:style]; + + attributes[NSParagraphStyleAttributeName] = paragraphStyle; + attributes[ENRMBlockTypeAttributeName] = @(blockRange.type); + attributes[ENRMBlockLevelAttributeName] = @(blockRange.level); + attributes[ENRMBlockOrdinalAttributeName] = @(blockRange.ordinal); + + // For a zero-length heading anchor on an empty line, stamp onto the line + // terminator so the paragraph style (heading font size) takes effect. + NSRange applyRange = blockRange.range; + if (isHeadingAnchor && applyRange.location < textLength) { + applyRange = NSMakeRange(applyRange.location, 1); + } + + UIFont *blockFont = attributes[NSFontAttributeName]; + if (blockFont) { + [attributes removeObjectForKey:NSFontAttributeName]; + if (applyRange.length > 0) { + [self mergeFontSize:blockFont overRange:applyRange inTextStorage:textStorage]; + } + } + + if (applyRange.length > 0) { + [textStorage addAttributes:attributes range:applyRange]; + if (paragraphStyle.minimumLineHeight > 0) { + applyBaselineOffset(textStorage, applyRange); + } + } + } + + // Default body line height on lists and plain paragraphs after block styles + // (indent, heading override) are reconciled. + [self applyBaseLineHeight:style.baseLineHeight toNonHeadingParagraphsInTextStorage:textStorage range:scopeRange]; + + [textStorage endEditing]; + + ENRMSetNeedsDisplay(textView); +} + +/// Body line height on every paragraph that is not a heading. Lists share this +/// default so toggling a list cannot drop line height. Headings keep the +/// derived height from the heading handler. When lineHeight is <= 0, clears a +/// previously applied body line height. Writes only what differs, so unchanged +/// paragraphs are not re-laid out. +- (void)applyBaseLineHeight:(CGFloat)lineHeight + toNonHeadingParagraphsInTextStorage:(NSTextStorage *)textStorage + range:(NSRange)scopeRange +{ + if (scopeRange.length == 0) { + return; + } + + NSString *string = textStorage.string; + NSUInteger position = scopeRange.location; + NSUInteger scopeEnd = NSMaxRange(scopeRange); + while (position < scopeEnd) { + NSRange paragraphRange = [string paragraphRangeForRange:NSMakeRange(position, 0)]; + paragraphRange = NSIntersectionRange(paragraphRange, scopeRange); + if (paragraphRange.length == 0) { + break; + } + + id blockType = [textStorage attribute:ENRMBlockTypeAttributeName + atIndex:paragraphRange.location + effectiveRange:NULL]; + NSInteger headingLevel = 0; + if ([blockType isKindOfClass:[NSNumber class]]) { + headingLevel = ENRMHeadingLevelForBlockType((ENRMInputBlockType)[blockType integerValue]); + } + if (headingLevel == 0) { + // Unlike applyLineHeight, overwrite the line height left by an earlier + // pass, or clear it when lineHeight is <= 0. Leave paragraphs that never + // had a line height without a paragraph style. + NSMutableParagraphStyle *paragraphStyle = getOrCreateParagraphStyle(textStorage, paragraphRange.location); + if (lineHeight > 0 || paragraphStyle.minimumLineHeight > 0) { + paragraphStyle.minimumLineHeight = 0; + paragraphStyle.maximumLineHeight = 0; + ENRMApplyLineHeightToParagraphStyle(paragraphStyle, lineHeight); + ENRMSetAttributeIfChanged(textStorage, NSParagraphStyleAttributeName, paragraphStyle, paragraphRange, nil); + } + + // Unlike applyBaselineOffset, overwrite an offset centered for a previous + // line height or font, and clear it when none is needed. Unlike the text renderer, + // the input has no block images or super/subscript offsets to preserve. + CGFloat baselineOffset = calculateBaselineOffset(textStorage, paragraphRange); + if (baselineOffset > 0) { + ENRMSetAttributeIfChanged(textStorage, NSBaselineOffsetAttributeName, @(baselineOffset), paragraphRange, nil); + } else { + ENRMRemoveAttributeIfPresent(textStorage, NSBaselineOffsetAttributeName, paragraphRange, nil); + } + } + + NSUInteger nextPosition = NSMaxRange(paragraphRange); + if (nextPosition <= position) { + break; + } + position = nextPosition; + } +} + +/// Applies `blockFont` over `range` while preserving the symbolic traits already +/// present on each existing font run (set by the inline formatting pass). The +/// resulting font takes its size and descriptor from `blockFont` but unions in +/// the run's traits, so inline bold/italic survives the block's size change. +- (void)mergeFontSize:(UIFont *)blockFont overRange:(NSRange)range inTextStorage:(NSTextStorage *)textStorage +{ + UIFontDescriptorSymbolicTraits blockTraits = blockFont.fontDescriptor.symbolicTraits; + + [textStorage enumerateAttribute:NSFontAttributeName + inRange:range + options:0 + usingBlock:^(UIFont *_Nullable runFont, NSRange runRange, BOOL *_Nonnull stop) { + UIFontDescriptorSymbolicTraits runTraits = runFont ? runFont.fontDescriptor.symbolicTraits : 0; + UIFontDescriptorSymbolicTraits mergedTraits = blockTraits | runTraits; + + UIFont *resolved = blockFont; + if (mergedTraits != blockTraits) { + UIFontDescriptor *descriptor = + [blockFont.fontDescriptor fontDescriptorWithSymbolicTraits:mergedTraits]; + if (descriptor) { + resolved = [UIFont fontWithDescriptor:descriptor size:0]; + } + } + [textStorage addAttribute:NSFontAttributeName value:resolved range:runRange]; + }]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.h new file mode 100644 index 000000000000..bc4eb686ccf4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.h @@ -0,0 +1,69 @@ +#pragma once + +#import "ENRMUIKit.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMInputLinkVariantStyle : NSObject + +@property (nonatomic, copy) NSString *pattern; +@property (nonatomic, strong) RCTUIColor *color; +@property (nonatomic, assign) BOOL underline; +@property (nonatomic, strong, nullable) RCTUIColor *backgroundColor; +@property (nonatomic, strong, nullable) NSRegularExpression *regex; + +@end + +@interface ENRMInputFormatterStyle : NSObject + +/// Base text properties +@property (nonatomic, strong) UIFont *baseFont; +@property (nonatomic, strong) RCTUIColor *baseTextColor; +@property (nonatomic, assign) CGFloat baseLineHeight; + +/// Bold — color override (nil = inherit baseTextColor) +@property (nonatomic, strong, nullable) RCTUIColor *boldColor; + +/// Italic — color override (nil = inherit baseTextColor) +@property (nonatomic, strong, nullable) RCTUIColor *italicColor; + +/// Link +@property (nonatomic, strong, nullable) RCTUIColor *linkColor; +@property (nonatomic, assign) BOOL linkUnderline; +@property (nonatomic, strong, nullable) RCTUIColor *linkBackgroundColor; +@property (nonatomic, copy) NSArray *linkVariants; + +/// Spoiler +@property (nonatomic, strong, nullable) RCTUIColor *spoilerColor; +@property (nonatomic, strong, nullable) RCTUIColor *spoilerBackgroundColor; + +/// Vertical spacing (points) added above each list item via the paragraph +/// style's paragraphSpacingBefore, so bullets read as separate rows. Configured +/// from the `markdownStyle.list.itemSpacing` prop; defaults to 0 (items pack tightly). +@property (nonatomic, assign) CGFloat listItemSpacing; + +/// Per-level heading config, indexed by level 1-6. A nil/0 entry means the level +/// uses a built-in default derived from the base font. Configured from the +/// `markdownStyle.h1..h6` props. +- (void)setHeadingFontSize:(CGFloat)fontSize forLevel:(NSInteger)level; +- (void)setHeadingFontWeight:(nullable NSString *)fontWeight forLevel:(NSInteger)level; +- (void)setHeadingColor:(nullable RCTUIColor *)color forLevel:(NSInteger)level; + +/// Resolved foreground color for a heading level, or nil to inherit baseTextColor. +- (nullable RCTUIColor *)headingColorForLevel:(NSInteger)level; + +/// Font for a heading level, built over the base font at the configured per-level +/// size and weight (from markdownStyle h1..h6). Does not carry inline traits — +/// those are merged on top in the formatter's font pass. +- (UIFont *)headingFontForLevel:(NSInteger)level; + +/// Line height for a heading level: headingFontSize + (baseLineHeight - baseFontSize). +- (CGFloat)derivedLineHeightForHeadingLevel:(NSInteger)level; + +- (UIFont *)fontForTraits:(UIFontDescriptorSymbolicTraits)traits; +- (void)invalidateFontCache; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.mm new file mode 100644 index 000000000000..0707f37b2ccc --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputFormatterStyle.mm @@ -0,0 +1,176 @@ +#import "ENRMInputFormatterStyle.h" +#import "FontUtils.h" + +@implementation ENRMInputLinkVariantStyle +@end + +@implementation ENRMInputFormatterStyle { + NSMutableDictionary *_fontCache; + UIFont *_lastBaseFont; + CGFloat _headingFontSizes[7]; + NSString *_headingFontWeights[7]; + RCTUIColor *_headingColors[7]; + UIFont *_headingFontCache[7]; +} + +- (instancetype)init +{ + if (self = [super init]) { + _baseFont = [UIFont systemFontOfSize:16.0]; + _baseTextColor = [RCTUIColor labelColor]; + _linkVariants = @[]; + _fontCache = [NSMutableDictionary dictionary]; + for (NSInteger level = 0; level <= 6; level++) { + _headingFontSizes[level] = 0.0; + _headingFontWeights[level] = nil; + _headingColors[level] = nil; + } + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone +{ + ENRMInputFormatterStyle *copy = [[ENRMInputFormatterStyle allocWithZone:zone] init]; + copy.baseFont = _baseFont; + copy.baseTextColor = _baseTextColor; + copy.baseLineHeight = _baseLineHeight; + copy.boldColor = _boldColor; + copy.italicColor = _italicColor; + copy.linkColor = _linkColor; + copy.linkUnderline = _linkUnderline; + copy.linkBackgroundColor = _linkBackgroundColor; + copy.linkVariants = [_linkVariants copy]; + copy.spoilerColor = _spoilerColor; + copy.spoilerBackgroundColor = _spoilerBackgroundColor; + copy.listItemSpacing = _listItemSpacing; + for (NSInteger level = 1; level <= 6; level++) { + [copy setHeadingFontSize:_headingFontSizes[level] forLevel:level]; + [copy setHeadingFontWeight:_headingFontWeights[level] forLevel:level]; + [copy setHeadingColor:_headingColors[level] forLevel:level]; + } + return copy; +} + +- (BOOL)isValidHeadingLevel:(NSInteger)level +{ + return level >= 1 && level <= 6; +} + +- (void)setHeadingFontSize:(CGFloat)fontSize forLevel:(NSInteger)level +{ + if ([self isValidHeadingLevel:level]) { + _headingFontSizes[level] = fontSize; + _headingFontCache[level] = nil; + } +} + +- (void)setHeadingFontWeight:(nullable NSString *)fontWeight forLevel:(NSInteger)level +{ + if ([self isValidHeadingLevel:level]) { + _headingFontWeights[level] = [fontWeight copy]; + _headingFontCache[level] = nil; + } +} + +- (void)setHeadingColor:(nullable RCTUIColor *)color forLevel:(NSInteger)level +{ + if ([self isValidHeadingLevel:level]) { + _headingColors[level] = color; + } +} + +- (RCTUIColor *)headingColorForLevel:(NSInteger)level +{ + return [self isValidHeadingLevel:level] ? _headingColors[level] : nil; +} + +- (UIFont *)headingFontForLevel:(NSInteger)level +{ + if (![self isValidHeadingLevel:level]) { + return _baseFont; + } + + [self invalidateCacheIfNeeded]; + + UIFont *cached = _headingFontCache[level]; + if (cached) { + return cached; + } + + CGFloat size = _headingFontSizes[level]; + if (size <= 0.0) { + size = _baseFont.pointSize; + } + + NSString *weightString = _headingFontWeights[level]; + UIFont *font; + if (weightString.length > 0) { + UIFontWeight weight = ENRMFontWeightFromString(weightString); + UIFontDescriptor *descriptor = [_baseFont.fontDescriptor + fontDescriptorByAddingAttributes:@{UIFontDescriptorTraitsAttribute : @{UIFontWeightTrait : @(weight)}}]; + font = descriptor ? [UIFont fontWithDescriptor:descriptor size:size] : [UIFont systemFontOfSize:size weight:weight]; + } else { + font = [_baseFont fontWithSize:size]; + } + _headingFontCache[level] = font; + return font; +} + +- (CGFloat)derivedLineHeightForHeadingLevel:(NSInteger)level +{ + if (_baseLineHeight <= 0 || ![self isValidHeadingLevel:level]) { + return 0; + } + + // Use the font the heading is actually drawn with, so this can't drift from + // headingFontForLevel's own size fallback. + CGFloat headingFontSize = [self headingFontForLevel:level].pointSize; + return headingFontSize + (_baseLineHeight - _baseFont.pointSize); +} + +- (void)clearHeadingFontCache +{ + for (NSInteger level = 0; level <= 6; level++) { + _headingFontCache[level] = nil; + } +} + +- (void)invalidateCacheIfNeeded +{ + if (_lastBaseFont != _baseFont) { + [_fontCache removeAllObjects]; + [self clearHeadingFontCache]; + _lastBaseFont = _baseFont; + } +} + +- (void)invalidateFontCache +{ + [_fontCache removeAllObjects]; + [self clearHeadingFontCache]; + _lastBaseFont = nil; +} + +- (UIFont *)fontForTraits:(UIFontDescriptorSymbolicTraits)traits +{ + [self invalidateCacheIfNeeded]; + + if (traits == 0) { + return _baseFont; + } + + NSNumber *key = @(traits); + UIFont *cached = _fontCache[key]; + if (cached) { + return cached; + } + + UIFontDescriptor *descriptor = + [_baseFont.fontDescriptor fontDescriptorWithSymbolicTraits:_baseFont.fontDescriptor.symbolicTraits | traits]; + UIFont *derived = descriptor ? [UIFont fontWithDescriptor:descriptor size:0] : _baseFont; + _fontCache[key] = derived; + return derived; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.h new file mode 100644 index 000000000000..42a9174c8531 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.h @@ -0,0 +1,20 @@ +#pragma once + +#import "ENRMInputDecorationDrawer.h" +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +@class ENRMInputListMarkerDrawer; + +/// Thin orchestrator that iterates registered decoration drawers during the draw pass. +@interface ENRMInputLayoutManager : NSLayoutManager + +@property (nonatomic, strong, readonly) ENRMInputListMarkerDrawer *listMarkerDrawer; +@property (nonatomic, copy) NSArray> *decorationDrawers; + +- (void)drawEmptyEditorDecorationsWithInset:(UIEdgeInsets)inset; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.mm new file mode 100644 index 000000000000..218bff515f20 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputLayoutManager.mm @@ -0,0 +1,35 @@ +#import "ENRMInputLayoutManager.h" +#import "ENRMInputListMarkerDrawer.h" + +@implementation ENRMInputLayoutManager + +- (instancetype)init +{ + if (self = [super init]) { + _listMarkerDrawer = [[ENRMInputListMarkerDrawer alloc] init]; + _decorationDrawers = @[ _listMarkerDrawer ]; + } + return self; +} + +#pragma mark - NSLayoutManager Overrides + +- (void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin +{ + [super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin]; + + for (id drawer in _decorationDrawers) { + [drawer drawDecorationsForGlyphRange:glyphsToShow layoutManager:self atPoint:origin]; + } +} + +#pragma mark - Empty Editor + +- (void)drawEmptyEditorDecorationsWithInset:(UIEdgeInsets)inset +{ + for (id drawer in _decorationDrawers) { + [drawer drawEmptyEditorDecorationsWithInset:inset layoutManager:self]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.h new file mode 100644 index 000000000000..f6c7ca0087c5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.h @@ -0,0 +1,9 @@ +#pragma once + +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +void ENRMShowLinkPrompt(RCTUIView *sourceView, NSString *_Nullable existingURL, void (^completion)(NSString *url)); + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.mm new file mode 100644 index 000000000000..bebb902f2b40 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputLinkPrompt.mm @@ -0,0 +1,71 @@ +#import "ENRMInputLinkPrompt.h" + +static const CGFloat kMacOSURLFieldWidth = 260; +static const CGFloat kMacOSURLFieldHeight = 24; + +void ENRMShowLinkPrompt(RCTUIView *sourceView, NSString *existingURL, void (^completion)(NSString *url)) +{ + BOOL isEditing = existingURL.length > 0; + NSString *title = isEditing ? @"Edit Link" : @"Add Link"; + NSString *confirmTitle = isEditing ? @"Update" : @"Add"; + +#if !TARGET_OS_OSX + UIAlertController *alert = [UIAlertController alertControllerWithTitle:title + message:nil + preferredStyle:UIAlertControllerStyleAlert]; + + [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { + textField.placeholder = @"URL"; + textField.text = existingURL ?: @""; + textField.keyboardType = UIKeyboardTypeURL; + textField.autocapitalizationType = UITextAutocapitalizationTypeNone; + textField.autocorrectionType = UITextAutocorrectionTypeNo; + }]; + + UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:confirmTitle + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action) { + NSString *url = alert.textFields.firstObject.text; + completion(url); + }]; + confirmAction.enabled = isEditing; + + [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]]; + [alert addAction:confirmAction]; + + UITextField *urlField = alert.textFields.firstObject; + [NSNotificationCenter.defaultCenter + addObserverForName:UITextFieldTextDidChangeNotification + object:urlField + queue:NSOperationQueue.mainQueue + usingBlock:^(NSNotification *note) { confirmAction.enabled = urlField.text.length > 0; }]; + + UIViewController *presenter = sourceView.window.rootViewController; + while (presenter.presentedViewController) { + presenter = presenter.presentedViewController; + } + [presenter presentViewController:alert animated:YES completion:nil]; +#else + NSAlert *alert = [[NSAlert alloc] init]; + alert.messageText = title; + alert.informativeText = @"Enter the URL for the link."; + [alert addButtonWithTitle:confirmTitle]; + [alert addButtonWithTitle:@"Cancel"]; + + NSTextField *urlField = + [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, kMacOSURLFieldWidth, kMacOSURLFieldHeight)]; + urlField.placeholderString = @"URL"; + urlField.stringValue = existingURL ?: @""; + alert.accessoryView = urlField; + + [alert beginSheetModalForWindow:sourceView.window + completionHandler:^(NSModalResponse returnCode) { + if (returnCode == NSAlertFirstButtonReturn) { + NSString *url = urlField.stringValue; + if (url.length > 0) { + completion(url); + } + } + }]; +#endif +} diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.h new file mode 100644 index 000000000000..8440372caef1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.h @@ -0,0 +1,32 @@ +#pragma once + +#import "ENRMInputDecorationDrawer.h" +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Draws list markers (bullets / ordered numbers) into the head-indent column. +@interface ENRMInputListMarkerDrawer : NSObject + +@property (nonatomic, assign) NSInteger emptyBulletDepth; +@property (nonatomic, assign) BOOL emptyBulletOrdered; +@property (nonatomic, assign) NSInteger emptyBulletOrdinal; +@property (nonatomic, assign) NSUInteger emptyBulletLocation; +@property (nonatomic, strong, nullable) UIFont *emptyBulletFont; +@property (nonatomic, strong, nullable) RCTUIColor *emptyBulletColor; +@property (nonatomic, assign) BOOL emptyBulletRTL; +@property (nonatomic, assign) CGFloat listItemSpacing; + +#if !TARGET_OS_OSX +/// Shows or updates a subview overlay that draws the trailing empty line's +/// bullet. drawGlyphsForGlyphRange: clips to the glyph area, which excludes +/// the extra line fragment -- a subview is immune to that clipping. +- (void)showTrailingBulletInTextView:(UITextView *)textView + textContainer:(NSTextContainer *)container + usedRect:(CGRect)usedRect; +- (void)hideTrailingBullet; +#endif + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.mm new file mode 100644 index 000000000000..ec26198d7f23 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputListMarkerDrawer.mm @@ -0,0 +1,426 @@ +#import "ENRMInputListMarkerDrawer.h" +#import "ENRMInputBlockType.h" +#import "ParagraphStyleUtils.h" + +static UIFont *ENRMFallbackFont(void) +{ + return [UIFont systemFontOfSize:16]; +} + +static RCTUIColor *ENRMFallbackColor(void) +{ + return [RCTUIColor labelColor]; +} + +static CGFloat ENRMTrailingMarkerX(CGPoint origin, NSTextContainer *container, CGFloat leadingOffset) +{ + return origin.x + container.size.width - leadingOffset; +} + +@interface ENRMInputListMarkerDrawer () +- (void)drawTrailingBulletMarkerInRect:(CGRect)bounds; +@end + +#if !TARGET_OS_OSX + +#pragma mark - Trailing bullet overlay + +/// A lightweight overlay that draws the trailing empty line's list marker. +/// drawGlyphsForGlyphRange: clips its context to the glyph area, which excludes +/// the extra line fragment. A subview is immune to that clipping. +@interface ENRMTrailingBulletView : UIView +@property (nonatomic, weak) ENRMInputListMarkerDrawer *drawer; +@end + +@implementation ENRMTrailingBulletView + +- (void)drawRect:(CGRect)rect +{ + [_drawer drawTrailingBulletMarkerInRect:self.bounds]; +} + +@end + +#endif + +#pragma mark - + +@implementation ENRMInputListMarkerDrawer { + NSMutableSet *_drawnParagraphLocations; +#if !TARGET_OS_OSX + ENRMTrailingBulletView *_trailingBulletView; + __weak NSTextContainer *_trailingBulletTextContainer; + CGFloat _trailingBulletInsetLeft; + CGFloat _trailingBulletHeadIndent; +#endif +} + +- (instancetype)init +{ + if (self = [super init]) { + _emptyBulletDepth = -1; + _drawnParagraphLocations = [NSMutableSet set]; + } + return self; +} + +#pragma mark - Primitive Drawing + +- (void)drawBulletAtX:(CGFloat)markerX + centerY:(CGFloat)centerY + depth:(NSInteger)depth + font:(UIFont *)font + color:(RCTUIColor *)color +{ + CGContextRef ctx = UIGraphicsGetCurrentContext(); + if (!ctx || isnan(markerX) || isnan(centerY)) { + return; + } + + CGFloat size = MAX(4.0, font.pointSize * 0.30); + CGRect bulletRect = CGRectMake(markerX - size / 2.0, centerY - size / 2.0, size, size); + + CGContextSaveGState(ctx); + NSInteger style = depth >= 2 ? 2 : depth; + switch (style) { + case 0: + [color setFill]; + CGContextFillEllipseInRect(ctx, bulletRect); + break; + case 1: { + CGFloat lineWidth = MAX(1.0, size * 0.15); + [color setStroke]; + CGContextSetLineWidth(ctx, lineWidth); + CGContextStrokeEllipseInRect(ctx, CGRectInset(bulletRect, lineWidth / 2.0, lineWidth / 2.0)); + break; + } + default: + [color setFill]; + CGContextFillRect(ctx, bulletRect); + break; + } + CGContextRestoreGState(ctx); +} + +- (void)drawOrderedMarkerEndingAtX:(CGFloat)markerRight + baselineY:(CGFloat)baselineY + ordinal:(NSInteger)ordinal + font:(UIFont *)font + color:(RCTUIColor *)color +{ + NSString *label = [NSString stringWithFormat:@"%ld.", (long)MAX(ordinal, (NSInteger)1)]; + NSDictionary *attrs = @{NSFontAttributeName : font, NSForegroundColorAttributeName : color}; + CGSize labelSize = [label sizeWithAttributes:attrs]; + [label drawAtPoint:CGPointMake(markerRight - labelSize.width, baselineY - font.ascender) withAttributes:attrs]; +} + +- (void)drawOrderedMarkerStartingAtX:(CGFloat)markerLeft + baselineY:(CGFloat)baselineY + ordinal:(NSInteger)ordinal + font:(UIFont *)font + color:(RCTUIColor *)color +{ + NSString *label = [NSString stringWithFormat:@".%ld", (long)MAX(ordinal, (NSInteger)1)]; + NSDictionary *attrs = @{NSFontAttributeName : font, NSForegroundColorAttributeName : color}; + [label drawAtPoint:CGPointMake(markerLeft, baselineY - font.ascender) withAttributes:attrs]; +} + +#pragma mark - Composite Marker + +- (void)drawListMarkerOrdered:(BOOL)isOrdered + depth:(NSInteger)depth + ordinal:(NSInteger)ordinal + rtl:(BOOL)isRTL + baselineY:(CGFloat)baselineY + origin:(CGPoint)origin + usedRect:(CGRect)usedRect + container:(NSTextContainer *)container + font:(UIFont *)font + color:(RCTUIColor *)color +{ + CGFloat leadingOffset = container.lineFragmentPadding + (depth + 1) * kENRMListIndentPerDepth; + + if (isOrdered) { + if (isRTL) { + CGFloat anchorX = ENRMTrailingMarkerX(origin, container, leadingOffset) + kENRMListBulletGap / 2.0; + [self drawOrderedMarkerStartingAtX:anchorX baselineY:baselineY ordinal:ordinal font:font color:color]; + } else { + CGFloat anchorX = origin.x + usedRect.origin.x - kENRMListBulletGap / 2.0; + [self drawOrderedMarkerEndingAtX:anchorX baselineY:baselineY ordinal:ordinal font:font color:color]; + } + return; + } + + CGFloat markerX = isRTL ? ENRMTrailingMarkerX(origin, container, leadingOffset) + kENRMListBulletGap + : origin.x + usedRect.origin.x - kENRMListBulletGap; + CGFloat centerY = baselineY - (font.xHeight + font.capHeight) / 4.0; + [self drawBulletAtX:markerX centerY:centerY depth:depth font:font color:color]; +} + +#pragma mark - Attribute Resolution + +- (BOOL)readListAttributesAtIndex:(NSUInteger)charIndex + storage:(NSTextStorage *)storage + paraStart:(NSUInteger)paraStart + isOrdered:(out BOOL *)outOrdered + depth:(out NSInteger *)outDepth + ordinal:(out NSInteger *)outOrdinal +{ + if (charIndex >= storage.length) { + return NO; + } + + NSNumber *type = [storage attribute:ENRMBlockTypeAttributeName atIndex:charIndex effectiveRange:NULL]; + if (!type || !ENRMBlockTypeIsListItem((ENRMInputBlockType)type.integerValue) || charIndex != paraStart) { + return NO; + } + + *outOrdered = (type.integerValue == ENRMInputBlockTypeOrderedListItem); + + NSNumber *depthValue = [storage attribute:ENRMBlockLevelAttributeName atIndex:charIndex effectiveRange:NULL]; + *outDepth = depthValue ? depthValue.integerValue : 0; + + NSNumber *ordinalValue = [storage attribute:ENRMBlockOrdinalAttributeName atIndex:charIndex effectiveRange:NULL]; + *outOrdinal = ordinalValue ? ordinalValue.integerValue : 1; + + return YES; +} + +- (void)resolveMarkerFont:(out UIFont **)outFont + color:(out RCTUIColor **)outColor + atIndex:(NSUInteger)charIndex + storage:(NSTextStorage *)storage + isEmptyListLine:(BOOL)isEmptyListLine +{ + UIFont *font = nil; + RCTUIColor *color = nil; + + if (isEmptyListLine) { + font = self.emptyBulletFont; + color = self.emptyBulletColor; + } + if (!font && charIndex < storage.length) { + font = [storage attribute:NSFontAttributeName atIndex:charIndex effectiveRange:NULL]; + } + if (!color && charIndex < storage.length) { + color = [storage attribute:NSForegroundColorAttributeName atIndex:charIndex effectiveRange:NULL]; + } + + *outFont = font ?: ENRMFallbackFont(); + *outColor = color ?: ENRMFallbackColor(); +} + +#pragma mark - Fragment Processing + +- (void)processLineFragmentRect:(CGRect)rect + usedRect:(CGRect)usedRect + container:(NSTextContainer *)container + glyphRange:(NSRange)glyphRange + origin:(CGPoint)origin + layoutManager:(NSLayoutManager *)layoutManager + storage:(NSTextStorage *)storage + string:(NSString *)string +{ + NSRange charRange = [layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL]; + if (charRange.location == NSNotFound) { + return; + } + + NSRange paraRange = (charRange.location < string.length) ? [string paragraphRangeForRange:charRange] + : NSMakeRange(charRange.location, 0); + + if ([_drawnParagraphLocations containsObject:@(paraRange.location)]) { + return; + } + + BOOL isOrdered = NO; + NSInteger depth = 0; + NSInteger ordinal = 1; + BOOL isAttributedListLine = [self readListAttributesAtIndex:charRange.location + storage:storage + paraStart:paraRange.location + isOrdered:&isOrdered + depth:&depth + ordinal:&ordinal]; + + BOOL isEmptyListLine = + !isAttributedListLine && self.emptyBulletDepth >= 0 && charRange.location == self.emptyBulletLocation; + if (isEmptyListLine) { + depth = self.emptyBulletDepth; + isOrdered = self.emptyBulletOrdered; + ordinal = self.emptyBulletOrdinal; + } + + if (!isAttributedListLine && !isEmptyListLine) { + return; + } + [_drawnParagraphLocations addObject:@(paraRange.location)]; + + UIFont *font; + RCTUIColor *color; + [self resolveMarkerFont:&font + color:&color + atIndex:charRange.location + storage:storage + isEmptyListLine:isEmptyListLine]; + + CGFloat baselineOffset = isEmptyListLine ? self.listItemSpacing + font.ascender + : [layoutManager locationForGlyphAtIndex:glyphRange.location].y; + CGFloat baselineY = origin.y + rect.origin.y + baselineOffset; + + BOOL isRTL = isEmptyListLine ? self.emptyBulletRTL + : ENRMParagraphIsRTL([storage attribute:NSParagraphStyleAttributeName + atIndex:charRange.location + effectiveRange:NULL]); + + [self drawListMarkerOrdered:isOrdered + depth:depth + ordinal:ordinal + rtl:isRTL + baselineY:baselineY + origin:origin + usedRect:usedRect + container:container + font:font + color:color]; +} + +#pragma mark - ENRMInputDecorationDrawer + +- (void)drawDecorationsForGlyphRange:(NSRange)glyphRange + layoutManager:(NSLayoutManager *)layoutManager + atPoint:(CGPoint)origin +{ + NSTextStorage *storage = layoutManager.textStorage; + NSString *string = storage.string; + [_drawnParagraphLocations removeAllObjects]; + + [layoutManager enumerateLineFragmentsForGlyphRange:glyphRange + usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *container, + NSRange fragmentGlyphRange, __unused BOOL *stop) { + [self processLineFragmentRect:rect + usedRect:usedRect + container:container + glyphRange:fragmentGlyphRange + origin:origin + layoutManager:layoutManager + storage:storage + string:string]; + }]; + +#if TARGET_OS_OSX + if (self.emptyBulletDepth >= 0 && self.emptyBulletLocation >= storage.length && + layoutManager.extraLineFragmentTextContainer != nil) { + UIFont *font = self.emptyBulletFont ?: ENRMFallbackFont(); + RCTUIColor *color = self.emptyBulletColor ?: ENRMFallbackColor(); + CGRect used = layoutManager.extraLineFragmentUsedRect; + CGFloat baselineY = origin.y + used.origin.y + font.ascender; + [self drawListMarkerOrdered:self.emptyBulletOrdered + depth:self.emptyBulletDepth + ordinal:self.emptyBulletOrdinal + rtl:self.emptyBulletRTL + baselineY:baselineY + origin:origin + usedRect:used + container:layoutManager.extraLineFragmentTextContainer + font:font + color:color]; + } +#endif +} + +- (void)drawEmptyEditorDecorationsWithInset:(UIEdgeInsets)inset layoutManager:(NSLayoutManager *)layoutManager +{ + if (self.emptyBulletDepth < 0) { + return; + } + + UIFont *font = self.emptyBulletFont ?: ENRMFallbackFont(); + RCTUIColor *color = self.emptyBulletColor ?: ENRMFallbackColor(); + NSTextContainer *container = layoutManager.textContainers.firstObject; + BOOL isRTL = self.emptyBulletRTL && container != nil; + + CGFloat headIndent = (self.emptyBulletDepth + 1) * kENRMListIndentPerDepth; + CGFloat padding = container ? container.lineFragmentPadding : 0; + CGRect syntheticUsedRect = CGRectMake(padding + headIndent, 0, 0, 0); + CGPoint syntheticOrigin = CGPointMake(inset.left, 0); + NSTextContainer *drawContainer = container ?: [[NSTextContainer alloc] initWithSize:CGSizeMake(0, CGFLOAT_MAX)]; + + CGFloat baselineY = inset.top + font.ascender; + + [self drawListMarkerOrdered:self.emptyBulletOrdered + depth:self.emptyBulletDepth + ordinal:self.emptyBulletOrdinal + rtl:isRTL + baselineY:baselineY + origin:syntheticOrigin + usedRect:syntheticUsedRect + container:drawContainer + font:font + color:color]; +} + +#if !TARGET_OS_OSX + +#pragma mark - Trailing Bullet Overlay + +- (void)drawTrailingBulletMarkerInRect:(CGRect)bounds +{ + if (self.emptyBulletDepth < 0 || !_trailingBulletTextContainer) { + return; + } + + UIFont *font = self.emptyBulletFont ?: ENRMFallbackFont(); + RCTUIColor *color = self.emptyBulletColor ?: ENRMFallbackColor(); + + CGRect usedRect = CGRectMake(_trailingBulletHeadIndent, 0, 0, bounds.size.height); + CGPoint origin = CGPointMake(_trailingBulletInsetLeft, 0); + + [self drawListMarkerOrdered:self.emptyBulletOrdered + depth:self.emptyBulletDepth + ordinal:self.emptyBulletOrdinal + rtl:self.emptyBulletRTL + baselineY:font.ascender + origin:origin + usedRect:usedRect + container:_trailingBulletTextContainer + font:font + color:color]; +} + +- (void)showTrailingBulletInTextView:(UITextView *)textView + textContainer:(NSTextContainer *)container + usedRect:(CGRect)usedRect +{ + if (!_trailingBulletView) { + _trailingBulletView = [[ENRMTrailingBulletView alloc] init]; + _trailingBulletView.backgroundColor = [RCTUIColor clearColor]; + _trailingBulletView.opaque = NO; + _trailingBulletView.userInteractionEnabled = NO; + } + + if (_trailingBulletView.superview != textView) { + [_trailingBulletView removeFromSuperview]; + [textView addSubview:_trailingBulletView]; + } + + UIEdgeInsets inset = textView.textContainerInset; + _trailingBulletView.frame = + CGRectMake(0, inset.top + usedRect.origin.y, textView.bounds.size.width, usedRect.size.height); + _trailingBulletView.drawer = self; + _trailingBulletTextContainer = container; + _trailingBulletInsetLeft = inset.left; + _trailingBulletHeadIndent = usedRect.origin.x; + _trailingBulletView.hidden = NO; + [textView bringSubviewToFront:_trailingBulletView]; + [_trailingBulletView setNeedsDisplay]; +} + +- (void)hideTrailingBullet +{ + _trailingBulletView.hidden = YES; +} + +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.h new file mode 100644 index 000000000000..65e8cf5adffd --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.h @@ -0,0 +1,21 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMInputMentionCandidate : NSObject + +@property (nonatomic, copy) NSString *indicator; +@property (nonatomic, assign) NSUInteger start; +@property (nonatomic, assign) NSUInteger end; +@property (nonatomic, copy) NSString *text; + ++ (instancetype)candidateWithIndicator:(NSString *)indicator + start:(NSUInteger)start + end:(NSUInteger)end + text:(NSString *)text; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.mm new file mode 100644 index 000000000000..9e94e1c76021 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputMentionCandidate.mm @@ -0,0 +1,18 @@ +#import "ENRMInputMentionCandidate.h" + +@implementation ENRMInputMentionCandidate + ++ (instancetype)candidateWithIndicator:(NSString *)indicator + start:(NSUInteger)start + end:(NSUInteger)end + text:(NSString *)text +{ + ENRMInputMentionCandidate *candidate = [[self alloc] init]; + candidate.indicator = indicator; + candidate.start = start; + candidate.end = end; + candidate.text = text; + return candidate; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.h new file mode 100644 index 000000000000..1f823bd5bd7e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.h @@ -0,0 +1,22 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMFormattingRange.h" +#import "ENRMInputStyledRange.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMParseResult : NSObject +@property (nonatomic, strong, readonly) NSString *plainText; +@property (nonatomic, strong, readonly) NSArray *formattingRanges; +@property (nonatomic, strong, readonly) NSArray *blockRanges; +@end + +@interface ENRMInputParser : NSObject + +- (ENRMParseResult *)parseToPlainTextAndRanges:(NSString *)markdown; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.mm new file mode 100644 index 000000000000..f82e72b3b838 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputParser.mm @@ -0,0 +1,646 @@ +#import "ENRMInputParser.h" +#import "ENRMFormattingRange.h" +#import "ENRMInputRemend.h" +#include "md4c.h" +#include +#include +#include + +@interface ENRMParseResult () +@property (nonatomic, strong, readwrite) NSString *plainText; +@property (nonatomic, strong, readwrite) NSArray *formattingRanges; +@property (nonatomic, strong, readwrite) NSArray *blockRanges; +@end + +@implementation ENRMParseResult +@end + +namespace { + +static const size_t kByteOffsetUnset = SIZE_MAX; + +struct SpanTypeMapping { + MD_SPANTYPE md4cType; + ENRMInputStyleType styleType; +}; + +static const SpanTypeMapping kSupportedSpans[] = { + {MD_SPAN_STRONG, ENRMInputStyleTypeStrong}, {MD_SPAN_EM, ENRMInputStyleTypeEmphasis}, + {MD_SPAN_U, ENRMInputStyleTypeUnderline}, {MD_SPAN_DEL, ENRMInputStyleTypeStrikethrough}, + {MD_SPAN_A, ENRMInputStyleTypeLink}, {MD_SPAN_SPOILER, ENRMInputStyleTypeSpoiler}, +}; +static const size_t kSupportedSpanCount = sizeof(kSupportedSpans) / sizeof(kSupportedSpans[0]); + +static bool isSupportedSpan(MD_SPANTYPE md4cType, ENRMInputStyleType &outStyleType) +{ + for (size_t index = 0; index < kSupportedSpanCount; index++) { + if (kSupportedSpans[index].md4cType == md4cType) { + outStyleType = kSupportedSpans[index].styleType; + return true; + } + } + return false; +} + +// Block-type mapping mirrors kSupportedSpans for the inline pipeline. A block +// handler extends recognition by adding its md4c block here and, if leveled, +// reading its detail in resolveBlockLevel below. MD_BLOCK_P maps to the +// implicit Paragraph default and produces no stored block range. +struct BlockTypeMapping { + MD_BLOCKTYPE md4cType; + ENRMInputBlockType blockType; +}; + +static const BlockTypeMapping kSupportedBlocks[] = { + {MD_BLOCK_P, ENRMInputBlockTypeParagraph}, + // MD_BLOCK_H maps to a representative heading type; onEnterBlock resolves the + // level (via resolveBlockLevel) and rewrites the type to the level-specific + // ENRMInputBlockTypeHeadingN. + {MD_BLOCK_H, ENRMInputBlockTypeHeading1}, +}; +static const size_t kSupportedBlockCount = sizeof(kSupportedBlocks) / sizeof(kSupportedBlocks[0]); + +static bool isSupportedBlock(MD_BLOCKTYPE md4cType, ENRMInputBlockType &outBlockType) +{ + for (size_t index = 0; index < kSupportedBlockCount; index++) { + if (kSupportedBlocks[index].md4cType == md4cType) { + outBlockType = kSupportedBlocks[index].blockType; + return true; + } + } + return false; +} + +// Per-block integer payload (heading level, list depth). md4c exposes this in +// the block's MD_BLOCK_*_DETAIL struct. Headings read MD_BLOCK_H_DETAIL.level +// (1-6); other blocks have no level and return 0. +static NSInteger resolveBlockLevel(MD_BLOCKTYPE blockType, void *detail) +{ + if (blockType == MD_BLOCK_H && detail) { + return (NSInteger)(static_cast(detail)->level); + } + return 0; +} + +struct InlineSpanInfo { + ENRMInputStyleType type; + size_t openingDelimiterByteOffset; + size_t contentStartByteOffset = kByteOffsetUnset; + size_t contentEndByteOffset = kByteOffsetUnset; + std::string linkURL; +}; + +struct BlockInfo { + ENRMInputBlockType type; + NSInteger level; + size_t contentStartByteOffset = kByteOffsetUnset; + size_t contentEndByteOffset = kByteOffsetUnset; +}; + +struct ParseContext { + const char *buffer; + size_t bufferLength; + size_t originalLength; + std::vector openStack; + std::vector resolved; + std::vector openBlockStack; + std::vector resolvedBlocks; + std::vector textStartOffsets; + // Byte offsets of backslashes md4c resolved as escape sequences (the '\' of "\*"), + // stripped from the plain text alongside inline/block delimiters. + std::vector escapeByteOffsets; + size_t lastTextEnd = 0; + // Open list containers, innermost last (true = ordered). An item's depth is + // the stack size - 1 and its type the innermost container's; md4c carries no + // per-item depth, so both derive from the open UL/OL ancestors. + std::vector listContainerStack; +}; + +static std::vector buildByteToUTF16Map(const char *utf8, size_t byteLength) +{ + std::vector map(byteLength + 1, 0); + NSUInteger utf16Index = 0; + size_t byteIndex = 0; + + while (byteIndex < byteLength) { + unsigned char leadByte = (unsigned char)utf8[byteIndex]; + size_t sequenceLength; + + if (leadByte < 0x80) { + sequenceLength = 1; + } else if ((leadByte & 0xE0) == 0xC0) { + sequenceLength = 2; + } else if ((leadByte & 0xF0) == 0xE0) { + sequenceLength = 3; + } else { + sequenceLength = 4; + } + + for (size_t offset = 0; offset < sequenceLength && (byteIndex + offset) <= byteLength; offset++) { + map[byteIndex + offset] = utf16Index; + } + + // 4-byte UTF-8 sequences encode codepoints above U+FFFF, which need a surrogate pair in UTF-16 + utf16Index += (sequenceLength == 4) ? 2 : 1; + byteIndex += sequenceLength; + } + + map[byteLength] = utf16Index; + return map; +} + +static inline NSUInteger mapByteOffset(const std::vector &map, size_t offset, size_t maxOffset) +{ + return map[std::min(offset, maxOffset)]; +} + +static size_t closingDelimiterEndByte(const ParseContext &context, const InlineSpanInfo &span) +{ + size_t position = span.contentEndByteOffset; + + if (span.type == ENRMInputStyleTypeLink) { + while (position < context.bufferLength && context.buffer[position] != ')') { + position++; + } + return (position < context.bufferLength) ? position + 1 : position; + } + + // Markdown delimiter bytes occupy the gap between content end and the next emitted text run + // (md4c never emits syntax bytes as text). Anchoring here — rather than adding a + // fixed per-type length — keeps stacked closers of co-terminating spans (e.g. + // "***", "**~~x~~**") from overlapping and leaking a trailing marker. + auto next = std::lower_bound(context.textStartOffsets.begin(), context.textStartOffsets.end(), position); + return (next != context.textStartOffsets.end()) ? *next : context.bufferLength; +} + +// Block tracking. md4c's enter_block gives no byte offset, so a block's content +// range is bounded by the text spans it encloses: onText records the first/last +// text offset into the currently open block(s). On leave_block the block is +// resolved with whatever text range it accumulated; empty blocks (no text) are +// discarded later when building results. +static int onEnterBlock(MD_BLOCKTYPE blockType, void *detail, void *userdata) +{ + auto *context = static_cast(userdata); + + // List nesting is tracked by the container stack, not stored as its own + // block: the UL/OL container only frames the items that read it. + if (blockType == MD_BLOCK_UL || blockType == MD_BLOCK_OL) { + context->listContainerStack.push_back(blockType == MD_BLOCK_OL); + return 0; + } + + // Tag the item itself, not its inner paragraph: md4c emits MD_BLOCK_P inside + // items only for *loose* lists, so a tight list has no paragraph to tag. The + // item's range is clipped back to its own first line when building results. + if (blockType == MD_BLOCK_LI) { + BlockInfo blockInfo; + BOOL ordered = !context->listContainerStack.empty() && context->listContainerStack.back(); + blockInfo.type = ordered ? ENRMInputBlockTypeOrderedListItem : ENRMInputBlockTypeUnorderedListItem; + // Clamp to the shared max depth (matches Android's parser): markdown can + // nest deeper than the editor represents, and downstream metadata passes + // size their counters by kENRMMaxListDepth. + blockInfo.level = context->listContainerStack.empty() + ? 0 + : MIN((NSInteger)context->listContainerStack.size() - 1, kENRMMaxListDepth); + context->openBlockStack.push_back(blockInfo); + return 0; + } + + ENRMInputBlockType mappedType; + if (!isSupportedBlock(blockType, mappedType)) { + return 0; + } + + BlockInfo blockInfo; + blockInfo.level = resolveBlockLevel(blockType, detail); + // Headings share one md4c block type but split into six ENRMInputBlockTypes by + // level; map the resolved level onto the concrete heading type. + blockInfo.type = (blockType == MD_BLOCK_H) ? ENRMBlockTypeForHeadingLevel(blockInfo.level) : mappedType; + context->openBlockStack.push_back(blockInfo); + return 0; +} + +static int onLeaveBlock(MD_BLOCKTYPE blockType, void *, void *userdata) +{ + auto *context = static_cast(userdata); + + if (blockType == MD_BLOCK_UL || blockType == MD_BLOCK_OL) { + if (!context->listContainerStack.empty()) { + context->listContainerStack.pop_back(); + } + return 0; + } + + // List items are tagged in onEnterBlock (not via isSupportedBlock); resolve + // them here the same way as supported blocks. + if (blockType == MD_BLOCK_LI) { + if (!context->openBlockStack.empty()) { + context->resolvedBlocks.push_back(context->openBlockStack.back()); + context->openBlockStack.pop_back(); + } + return 0; + } + + ENRMInputBlockType mappedType; + if (!isSupportedBlock(blockType, mappedType)) { + return 0; + } + + if (context->openBlockStack.empty()) { + return 0; + } + + context->resolvedBlocks.push_back(context->openBlockStack.back()); + context->openBlockStack.pop_back(); + return 0; +} + +static int onEnterSpan(MD_SPANTYPE spanType, void *detail, void *userdata) +{ + ENRMInputStyleType styleType; + if (!isSupportedSpan(spanType, styleType)) { + return 0; + } + + auto *context = static_cast(userdata); + InlineSpanInfo spanInfo; + spanInfo.type = styleType; + spanInfo.openingDelimiterByteOffset = context->lastTextEnd; + + if (spanType == MD_SPAN_A && detail) { + auto *linkDetail = static_cast(detail); + if (linkDetail->href.text && linkDetail->href.size > 0) { + spanInfo.linkURL = std::string(linkDetail->href.text, linkDetail->href.size); + } + } + + context->openStack.push_back(spanInfo); + return 0; +} + +static int onLeaveSpan(MD_SPANTYPE spanType, void *, void *userdata) +{ + ENRMInputStyleType styleType; + if (!isSupportedSpan(spanType, styleType)) { + return 0; + } + + auto *context = static_cast(userdata); + if (context->openStack.empty()) { + return 0; + } + + context->resolved.push_back(context->openStack.back()); + context->openStack.pop_back(); + return 0; +} + +static int onText(MD_TEXTTYPE, const MD_CHAR *text, MD_SIZE size, void *userdata) +{ + if (!text || size == 0) { + return 0; + } + auto *context = static_cast(userdata); + + // md4c passes pointers outside the input buffer for synthetic tokens + // (e.g. MD_TEXT_SOFTBR, MD_TEXT_BR use a string literal "\n"). + // Pointer arithmetic against context->buffer would underflow, corrupting offsets. + // + // Skipping out-of-buffer tokens means lastTextEnd doesn't advance past + // synthetic newlines. Inline-span offsets stay correct because spans never + // straddle a synthetic break; block offsets are derived from real text below. + bool insideBuffer = (text >= context->buffer && text < context->buffer + context->bufferLength); + if (!insideBuffer) { + return 0; + } + + size_t textStart = text - context->buffer; + size_t textEnd = textStart + size; + context->textStartOffsets.push_back(textStart); + + if (textStart > 0 && context->buffer[textStart - 1] == '\\' && (textStart - 1) >= context->lastTextEnd) { + context->escapeByteOffsets.push_back(textStart - 1); + } + + for (auto &openSpan : context->openStack) { + if (openSpan.contentStartByteOffset == kByteOffsetUnset) { + openSpan.contentStartByteOffset = textStart; + } + openSpan.contentEndByteOffset = textEnd; + } + for (auto &openBlock : context->openBlockStack) { + if (openBlock.contentStartByteOffset == kByteOffsetUnset) { + openBlock.contentStartByteOffset = textStart; + } + openBlock.contentEndByteOffset = textEnd; + } + context->lastTextEnd = textEnd; + return 0; +} + +static bool runMd4cParse(NSString *markdown, ParseContext &context) +{ + NSString *completed = ENRMInputRemendComplete(markdown); + const char *completedUTF8 = [completed UTF8String]; + size_t completedLength = strlen(completedUTF8); + size_t originalLength = [markdown lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + context.buffer = completedUTF8; + context.bufferLength = completedLength; + context.originalLength = originalLength; + + MD_PARSER parser = { + .abi_version = 0, + .flags = MD_FLAG_NOHTML | MD_FLAG_UNDERLINE | MD_FLAG_STRIKETHROUGH | MD_FLAG_SPOILERS, + .enter_block = onEnterBlock, + .leave_block = onLeaveBlock, + .enter_span = onEnterSpan, + .leave_span = onLeaveSpan, + .text = onText, + .debug_log = nullptr, + .syntax = nullptr, + }; + + return md_parse(completedUTF8, (MD_SIZE)completedLength, &parser, &context) == 0; +} + +// Builds inline styled ranges (raw-markdown UTF-16 coords) from a completed +// parse. Split out so parseToPlainTextAndRanges: can derive inline and block +// ranges from ONE md4c run instead of parsing twice. +static NSArray *styledRangesFromContext(const ParseContext &context, + const std::vector &byteMap) +{ + NSMutableArray *results = [NSMutableArray arrayWithCapacity:context.resolved.size()]; + + for (const auto &spanInfo : context.resolved) { + if (spanInfo.contentStartByteOffset == kByteOffsetUnset || spanInfo.contentEndByteOffset == kByteOffsetUnset || + spanInfo.contentStartByteOffset > context.originalLength) { + continue; + } + + ENRMInputStyledRange *styledRange = [[ENRMInputStyledRange alloc] init]; + styledRange.type = spanInfo.type; + + if (spanInfo.type == ENRMInputStyleTypeLink && !spanInfo.linkURL.empty()) { + styledRange.url = [NSString stringWithUTF8String:spanInfo.linkURL.c_str()]; + } + + NSUInteger contentStart = mapByteOffset(byteMap, spanInfo.contentStartByteOffset, context.bufferLength); + NSUInteger contentEnd = mapByteOffset(byteMap, spanInfo.contentEndByteOffset, context.bufferLength); + styledRange.contentRange = NSMakeRange(contentStart, contentEnd - contentStart); + + NSUInteger openStart = mapByteOffset(byteMap, spanInfo.openingDelimiterByteOffset, context.bufferLength); + NSRange openingRange = NSMakeRange(openStart, contentStart - openStart); + + size_t closingEndByte = std::min(closingDelimiterEndByte(context, spanInfo), context.bufferLength); + NSUInteger closingStart = mapByteOffset(byteMap, spanInfo.contentEndByteOffset, context.bufferLength); + NSUInteger closingEnd = mapByteOffset(byteMap, closingEndByte, context.bufferLength); + NSRange closingRange = NSMakeRange(closingStart, closingEnd - closingStart); + + styledRange.syntaxRanges = @[ [NSValue valueWithRange:openingRange], [NSValue valueWithRange:closingRange] ]; + + NSUInteger fullStart = openingRange.location; + NSUInteger fullEnd = NSMaxRange(closingRange); + styledRange.fullRange = NSMakeRange(fullStart, fullEnd - fullStart); + + styledRange.isComplete = (closingEndByte <= context.originalLength); + + [results addObject:styledRange]; + } + + [results sortUsingComparator:^NSComparisonResult(ENRMInputStyledRange *first, ENRMInputStyledRange *second) { + NSUInteger a = first.fullRange.location, b = second.fullRange.location; + return (a < b) ? NSOrderedAscending : (a > b) ? NSOrderedDescending : NSOrderedSame; + }]; + + return results; +} + +// Builds block-level ranges (raw-markdown UTF-16 coords) from the same +// completed parse, mirroring styledRangesFromContext for inline spans. +// Paragraph blocks (the implicit default) are omitted — only blocks a handler +// claims are returned. +static NSArray *blockRangesFromContext(const ParseContext &context, + const std::vector &byteMap, NSString *markdown) +{ + NSMutableArray *results = [NSMutableArray arrayWithCapacity:context.resolvedBlocks.size()]; + + for (const auto &blockInfo : context.resolvedBlocks) { + if (blockInfo.type == ENRMInputBlockTypeParagraph) { + continue; + } + if (blockInfo.contentStartByteOffset == kByteOffsetUnset || blockInfo.contentEndByteOffset == kByteOffsetUnset || + blockInfo.contentStartByteOffset > context.originalLength) { + continue; + } + + NSUInteger contentStart = mapByteOffset(byteMap, blockInfo.contentStartByteOffset, context.bufferLength); + NSUInteger contentEnd = mapByteOffset(byteMap, blockInfo.contentEndByteOffset, context.bufferLength); + if (contentEnd <= contentStart) { + continue; + } + + // A list item accumulates all text in its subtree, so a parent item's range + // runs through its nested sublist. Clip each item to its own first line so + // nested items keep their own (deeper) depth rather than being overwritten + // by the parent's range. Input list items are single-line. + if (ENRMBlockTypeIsListItem(blockInfo.type) && contentEnd <= markdown.length) { + NSRange newline = [markdown rangeOfString:@"\n" + options:0 + range:NSMakeRange(contentStart, contentEnd - contentStart)]; + if (newline.location != NSNotFound) { + contentEnd = newline.location; + } + if (contentEnd <= contentStart) { + continue; + } + } + + [results addObject:[ENRMBlockRange rangeWithType:blockInfo.type + range:NSMakeRange(contentStart, contentEnd - contentStart) + level:blockInfo.level]]; + } + + return results; +} + +} // namespace + +@implementation ENRMInputParser + +- (NSArray *)parse:(NSString *)markdown +{ + if (markdown.length == 0) { + return @[]; + } + + ParseContext context; + if (!runMd4cParse(markdown, context)) { + return @[]; + } + + auto byteMap = buildByteToUTF16Map(context.buffer, context.bufferLength); + return styledRangesFromContext(context, byteMap); +} + +- (ENRMParseResult *)parseToPlainTextAndRanges:(NSString *)markdown +{ + ENRMParseResult *parseResult = [[ENRMParseResult alloc] init]; + + if (markdown.length == 0) { + parseResult.plainText = @""; + parseResult.formattingRanges = @[]; + parseResult.blockRanges = @[]; + return parseResult; + } + + // One md4c run feeds both pipelines: inline styled ranges and block ranges + // are derived from the same ParseContext. + ParseContext context; + NSArray *styledRanges = @[]; + NSArray *rawBlockRanges = @[]; + NSMutableIndexSet *escapeIndexes = [NSMutableIndexSet indexSet]; + if (runMd4cParse(markdown, context)) { + auto byteMap = buildByteToUTF16Map(context.buffer, context.bufferLength); + styledRanges = styledRangesFromContext(context, byteMap); + rawBlockRanges = blockRangesFromContext(context, byteMap, markdown); + for (size_t escapeByte : context.escapeByteOffsets) { + NSUInteger escapeIndex = mapByteOffset(byteMap, escapeByte, context.bufferLength); + if (escapeIndex < markdown.length) { + [escapeIndexes addIndex:escapeIndex]; + } + } + } + + NSUInteger rawLength = markdown.length; + + NSMutableIndexSet *syntaxIndexes = [NSMutableIndexSet indexSet]; + for (ENRMInputStyledRange *styledRange in styledRanges) { + if (!styledRange.isComplete) + continue; + for (NSValue *syntaxValue in styledRange.syntaxRanges) { + NSRange syntaxRange = [syntaxValue rangeValue]; + if (NSMaxRange(syntaxRange) > rawLength) { + syntaxRange.length = (syntaxRange.location < rawLength) ? rawLength - syntaxRange.location : 0; + } + if (syntaxRange.length > 0) { + [syntaxIndexes addIndexesInRange:syntaxRange]; + } + } + } + + // Strip block markers (e.g. "# ") from plain text — same as inline delimiters. + // Without this the marker survives and the serializer doubles it ("# # "). + for (ENRMBlockRange *rawBlock in rawBlockRanges) { + NSUInteger contentStart = rawBlock.range.location; + if (contentStart == 0 || contentStart > rawLength) { + continue; + } + NSUInteger lineStart = contentStart; + while (lineStart > 0) { + unichar previous = [markdown characterAtIndex:lineStart - 1]; + if (previous == '\n' || previous == '\r') { + break; + } + lineStart--; + } + if (contentStart > lineStart) { + [syntaxIndexes addIndexesInRange:NSMakeRange(lineStart, contentStart - lineStart)]; + } + } + + [syntaxIndexes addIndexes:escapeIndexes]; + + // Strip \n/\r from syntax ranges — newlines are structural content, not + // markdown syntax, and must survive into the plain text. + NSMutableIndexSet *newlineIndexes = [NSMutableIndexSet indexSet]; + [syntaxIndexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) { + if (index < rawLength) { + unichar character = [markdown characterAtIndex:index]; + if (character == '\n' || character == '\r') { + [newlineIndexes addIndex:index]; + } + } + }]; + [syntaxIndexes removeIndexes:newlineIndexes]; + + NSMutableString *plainText = [NSMutableString stringWithCapacity:rawLength]; + __block std::vector rawToPlainMap(rawLength + 1, 0); + + __block NSUInteger plainPosition = 0; + __block NSUInteger previousEnd = 0; + + [syntaxIndexes enumerateRangesUsingBlock:^(NSRange syntaxRange, BOOL *stop) { + if (syntaxRange.location > previousEnd) { + NSRange visibleRange = NSMakeRange(previousEnd, syntaxRange.location - previousEnd); + [plainText appendString:[markdown substringWithRange:visibleRange]]; + for (NSUInteger rawIndex = previousEnd; rawIndex < syntaxRange.location; rawIndex++) { + rawToPlainMap[rawIndex] = plainPosition++; + } + } + for (NSUInteger rawIndex = syntaxRange.location; rawIndex < NSMaxRange(syntaxRange); rawIndex++) { + rawToPlainMap[rawIndex] = plainPosition; + } + previousEnd = NSMaxRange(syntaxRange); + }]; + + if (previousEnd < rawLength) { + [plainText appendString:[markdown substringFromIndex:previousEnd]]; + for (NSUInteger rawIndex = previousEnd; rawIndex < rawLength; rawIndex++) { + rawToPlainMap[rawIndex] = plainPosition++; + } + } + rawToPlainMap[rawLength] = plainPosition; + + NSMutableArray *formattingRanges = [NSMutableArray arrayWithCapacity:styledRanges.count]; + + for (ENRMInputStyledRange *styledRange in styledRanges) { + if (!styledRange.isComplete) + continue; + + NSUInteger contentStart = styledRange.contentRange.location; + NSUInteger contentEnd = NSMaxRange(styledRange.contentRange); + + if (contentStart > rawLength || contentEnd > rawLength) + continue; + + NSUInteger plainStart = rawToPlainMap[contentStart]; + NSUInteger plainEnd = rawToPlainMap[contentEnd]; + + if (plainEnd <= plainStart) + continue; + + ENRMFormattingRange *formattingRange = + [ENRMFormattingRange rangeWithType:styledRange.type + range:NSMakeRange(plainStart, plainEnd - plainStart) + url:styledRange.url]; + [formattingRanges addObject:formattingRange]; + } + + // Map block content ranges (raw-markdown coords) onto plain-text coords. The + // block's marker syntax was stripped above, so the content range maps cleanly + // onto the post-strip text and the block no longer covers the marker. + NSMutableArray *blockRanges = [NSMutableArray arrayWithCapacity:rawBlockRanges.count]; + for (ENRMBlockRange *rawBlock in rawBlockRanges) { + NSUInteger contentStart = rawBlock.range.location; + NSUInteger contentEnd = NSMaxRange(rawBlock.range); + if (contentStart > rawLength || contentEnd > rawLength) + continue; + + NSUInteger plainStart = rawToPlainMap[contentStart]; + NSUInteger plainEnd = rawToPlainMap[contentEnd]; + if (plainEnd <= plainStart) + continue; + + [blockRanges addObject:[ENRMBlockRange rangeWithType:rawBlock.type + range:NSMakeRange(plainStart, plainEnd - plainStart) + level:rawBlock.level]]; + } + + parseResult.plainText = plainText; + parseResult.formattingRanges = formattingRanges; + parseResult.blockRanges = blockRanges; + return parseResult; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.h new file mode 100644 index 000000000000..3b22b16a5950 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.h @@ -0,0 +1,9 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +NSString *ENRMInputRemendComplete(NSString *markdown); + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.mm new file mode 100644 index 000000000000..c9ec5decb9c3 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputRemend.mm @@ -0,0 +1,173 @@ +#import "ENRMInputRemend.h" + +typedef struct { + NSString *__unsafe_unretained open; + NSString *__unsafe_unretained close; + BOOL symmetric; + // Emphasis-family delimiters (*, _, ~~) only open when left-flanking; code spans + // and spoilers open regardless of surrounding whitespace, so they skip the check. + BOOL flanking; +} ENRMDelimiterPair; + +static const ENRMDelimiterPair kDelimiterPairs[] = { + {@"***", @"***", YES, YES}, {@"**", @"**", YES, YES}, {@"*", @"*", YES, YES}, {@"_", @"_", YES, YES}, + {@"~~", @"~~", YES, YES}, {@"||", @"||", YES, NO}, {@"`", @"`", YES, NO}, {@"[", @"]", NO, NO}, +}; +static const NSUInteger kDelimiterPairCount = sizeof(kDelimiterPairs) / sizeof(kDelimiterPairs[0]); + +static NSString *closingForStackEntry(NSString *entry) +{ + for (NSUInteger i = 0; i < kDelimiterPairCount; i++) { + if ([entry isEqualToString:kDelimiterPairs[i].open]) { + return kDelimiterPairs[i].close; + } + } + return entry; +} + +// 0 = whitespace or out-of-bounds boundary, 1 = punctuation, 2 = letter/digit. +static int flankingLevelAt(NSString *markdown, NSInteger index) +{ + if (index < 0 || index >= (NSInteger)markdown.length) { + return 0; + } + unichar c = [markdown characterAtIndex:(NSUInteger)index]; + if ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:c]) { + return 0; + } + if ([[NSCharacterSet alphanumericCharacterSet] characterIsMember:c]) { + return 2; + } + return 1; +} + +// Mirrors md4c's emphasis opener test so completion only closes a delimiter md4c +// would actually treat as an opener: the run is a potential opener when its right +// side is "stronger" than its left (rightLevel > 0 and rightLevel >= leftLevel), +// where each side is scored 0 = whitespace/boundary, 1 = punctuation, 2 = other. +// Intraword underscore (both sides "other") never opens. This rejects lone or +// whitespace/punctuation-flanked delimiters (control*, 2 * 3, a*., a_b) that would +// otherwise fabricate a marker. Intraword * (a*b) is a genuine md4c opener, so it is +// not (and cannot be) rejected here. +static BOOL isEmphasisOpener(NSString *markdown, NSUInteger start, NSString *open) +{ + int leftLevel = flankingLevelAt(markdown, (NSInteger)start - 1); + int rightLevel = flankingLevelAt(markdown, (NSInteger)start + (NSInteger)open.length); + if ([open isEqualToString:@"_"] && leftLevel == 2 && rightLevel == 2) { + return NO; + } + return rightLevel > 0 && rightLevel >= leftLevel; +} + +NSString *ENRMInputRemendComplete(NSString *markdown) +{ + if (markdown.length == 0) { + return markdown; + } + + NSMutableArray *stack = [[NSMutableArray alloc] init]; + BOOL inLinkParen = NO; + NSUInteger length = markdown.length; + NSUInteger i = 0; + + while (i < length) { + unichar c = [markdown characterAtIndex:i]; + + if (c == '\\' && i + 1 < length) { + i += 2; + continue; + } + + // Link URL parentheses are a special two-character transition from "](" + if (c == ']' && !inLinkParen && i + 1 < length && [markdown characterAtIndex:i + 1] == '(') { + NSUInteger bracketIndex = NSNotFound; + for (NSUInteger idx = stack.count; idx > 0; idx--) { + if ([stack[idx - 1] isEqualToString:@"["]) { + bracketIndex = idx - 1; + break; + } + } + if (bracketIndex != NSNotFound) { + [stack removeObjectsInRange:NSMakeRange(bracketIndex, stack.count - bracketIndex)]; + } + inLinkParen = YES; + i += 2; + continue; + } + + if (inLinkParen && c == ')') { + inLinkParen = NO; + i++; + continue; + } + + if (inLinkParen) { + i++; + continue; + } + + BOOL matched = NO; + for (NSUInteger p = 0; p < kDelimiterPairCount; p++) { + ENRMDelimiterPair pair = kDelimiterPairs[p]; + NSUInteger openLen = pair.open.length; + + if (i + openLen > length) { + continue; + } + + NSString *substring = [markdown substringWithRange:NSMakeRange(i, openLen)]; + + if (pair.symmetric) { + if ([substring isEqualToString:pair.open]) { + if (stack.count > 0 && [stack.lastObject isEqualToString:pair.open]) { + [stack removeLastObject]; + } else if (!pair.flanking || isEmphasisOpener(markdown, i, pair.open)) { + [stack addObject:pair.open]; + } + i += openLen; + matched = YES; + break; + } + } else { + if ([substring isEqualToString:pair.open]) { + [stack addObject:pair.open]; + i += openLen; + matched = YES; + break; + } + NSUInteger closeLen = pair.close.length; + if (i + closeLen <= length) { + NSString *closeSub = [markdown substringWithRange:NSMakeRange(i, closeLen)]; + if ([closeSub isEqualToString:pair.close]) { + if (stack.count > 0 && [stack.lastObject isEqualToString:pair.open]) { + [stack removeLastObject]; + } + i += closeLen; + matched = YES; + break; + } + } + } + } + + if (!matched) { + i++; + } + } + + NSMutableString *closingSuffix = [NSMutableString string]; + + if (inLinkParen) { + [closingSuffix appendString:@")"]; + } + + for (NSString *entry in [stack reverseObjectEnumerator]) { + [closingSuffix appendString:closingForStackEntry(entry)]; + } + + if (closingSuffix.length == 0) { + return markdown; + } + + return [markdown stringByAppendingString:closingSuffix]; +} diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.h new file mode 100644 index 000000000000..4c08245e939a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.h @@ -0,0 +1,46 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMFormattingRange.h" +#import "ENRMInputStyledRange.h" +#import +#include + +NS_ASSUME_NONNULL_BEGIN + +typedef struct { + BOOL bold; + BOOL italic; + BOOL underline; + BOOL strikethrough; + BOOL spoiler; + BOOL link; + /// URL of the link at the selection. Note that this can be an empty string + /// for a link with an empty URL. + std::string linkDestination; + NSInteger headingLevel; + BOOL unorderedList; + BOOL orderedList; + NSInteger listDepth; +} ENRMInputStyleSnapshot; + +@protocol ENRMInputStyleStateDataSource + +- (NSRange)selectedRange; +- (BOOL)isEffectiveStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position; +- (BOOL)isStyleActive:(ENRMInputStyleType)type inRange:(NSRange)range; +- (NSInteger)headingLevelForCursorParagraph; +- (nullable ENRMBlockRange *)listBlockForCursorParagraph; +- (nullable ENRMFormattingRange *)linkForSelection:(NSRange)selection; + +@end + +@interface ENRMInputStyleStateBuilder : NSObject + ++ (ENRMInputStyleSnapshot)snapshotAtCurrentCursor:(id)dataSource; + ++ (ENRMInputStyleSnapshot)snapshotForRange:(NSRange)range dataSource:(id)dataSource; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.mm new file mode 100644 index 000000000000..eb6768d963ee --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyleStateBuilder.mm @@ -0,0 +1,68 @@ +#import "ENRMInputStyleStateBuilder.h" + +@implementation ENRMInputStyleStateBuilder + ++ (void)setLinkStateOnSnapshot:(ENRMInputStyleSnapshot *)snapshot + forSelection:(NSRange)selection + dataSource:(id)dataSource +{ + ENRMFormattingRange *link = [dataSource linkForSelection:selection]; + snapshot->link = link != nil; + snapshot->linkDestination = link.url.UTF8String ?: ""; +} + ++ (ENRMInputStyleSnapshot)snapshotAtCurrentCursor:(id)dataSource +{ + NSUInteger cursor = [dataSource selectedRange].location; + ENRMInputStyleSnapshot snapshot = {}; + if (cursor == NSNotFound) { + return snapshot; + } + snapshot.bold = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeStrong atPosition:cursor]; + snapshot.italic = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeEmphasis atPosition:cursor]; + snapshot.underline = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeUnderline atPosition:cursor]; + snapshot.strikethrough = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeStrikethrough atPosition:cursor]; + snapshot.spoiler = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeSpoiler atPosition:cursor]; + [self setLinkStateOnSnapshot:&snapshot forSelection:[dataSource selectedRange] dataSource:dataSource]; + snapshot.headingLevel = [dataSource headingLevelForCursorParagraph]; + + ENRMBlockRange *listBlock = [dataSource listBlockForCursorParagraph]; + snapshot.unorderedList = listBlock != nil && listBlock.type == ENRMInputBlockTypeUnorderedListItem; + snapshot.orderedList = listBlock != nil && listBlock.type == ENRMInputBlockTypeOrderedListItem; + snapshot.listDepth = listBlock != nil ? listBlock.level : 0; + + return snapshot; +} + ++ (ENRMInputStyleSnapshot)snapshotForRange:(NSRange)range dataSource:(id)dataSource +{ + ENRMInputStyleSnapshot snapshot = {}; + if (range.location == NSNotFound) { + return snapshot; + } + if (range.length > 0) { + snapshot.bold = [dataSource isStyleActive:ENRMInputStyleTypeStrong inRange:range]; + snapshot.italic = [dataSource isStyleActive:ENRMInputStyleTypeEmphasis inRange:range]; + snapshot.underline = [dataSource isStyleActive:ENRMInputStyleTypeUnderline inRange:range]; + snapshot.strikethrough = [dataSource isStyleActive:ENRMInputStyleTypeStrikethrough inRange:range]; + snapshot.spoiler = [dataSource isStyleActive:ENRMInputStyleTypeSpoiler inRange:range]; + } else { + snapshot.bold = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeStrong atPosition:range.location]; + snapshot.italic = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeEmphasis atPosition:range.location]; + snapshot.underline = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeUnderline atPosition:range.location]; + snapshot.strikethrough = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeStrikethrough + atPosition:range.location]; + snapshot.spoiler = [dataSource isEffectiveStyleActive:ENRMInputStyleTypeSpoiler atPosition:range.location]; + } + [self setLinkStateOnSnapshot:&snapshot forSelection:range dataSource:dataSource]; + snapshot.headingLevel = [dataSource headingLevelForCursorParagraph]; + + ENRMBlockRange *listBlock = [dataSource listBlockForCursorParagraph]; + snapshot.unorderedList = listBlock != nil && listBlock.type == ENRMInputBlockTypeUnorderedListItem; + snapshot.orderedList = listBlock != nil && listBlock.type == ENRMInputBlockTypeOrderedListItem; + snapshot.listDepth = listBlock != nil ? listBlock.level : 0; + + return snapshot; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.h new file mode 100644 index 000000000000..41e28ff64132 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.h @@ -0,0 +1,29 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, ENRMInputStyleType) { + ENRMInputStyleTypeStrong, + ENRMInputStyleTypeEmphasis, + ENRMInputStyleTypeUnderline, + ENRMInputStyleTypeStrikethrough, + ENRMInputStyleTypeLink, + ENRMInputStyleTypeSpoiler, +}; + +@interface ENRMInputStyledRange : NSObject + +@property (nonatomic, assign) ENRMInputStyleType type; +@property (nonatomic, assign) NSRange contentRange; +@property (nonatomic, strong) NSArray *syntaxRanges; +@property (nonatomic, assign) NSRange fullRange; +@property (nonatomic, strong, nullable) NSString *url; + +/// YES if both delimiters are present in the original text (before remend completion). +@property (nonatomic, assign) BOOL isComplete; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.mm new file mode 100644 index 000000000000..60d40ce07682 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputStyledRange.mm @@ -0,0 +1,4 @@ +#import "ENRMInputStyledRange.h" + +@implementation ENRMInputStyledRange +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.h new file mode 100644 index 000000000000..ba83d43c2c7e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.h @@ -0,0 +1,15 @@ +#pragma once + +#import "ENRMUIKit.h" + +@class EnrichedMarkdownTextInput; + +NS_ASSUME_NONNULL_BEGIN + +extern NSString *const kENRMMarkdownPasteboardType; + +@interface ENRMInputTextView : ENRMPlatformTextView +@property (nonatomic, weak, nullable) EnrichedMarkdownTextInput *markdownTextInput; +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.mm new file mode 100644 index 000000000000..a5391c7e8a6b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputTextView.mm @@ -0,0 +1,251 @@ +#import "ENRMInputTextView.h" +#import "ENRMInputLayoutManager.h" +#import "EnrichedMarkdownTextInput+Internal.h" +#import "EnrichedMarkdownTextInput.h" +#import "PasteboardUtils.h" +#if TARGET_OS_OSX +#import +#endif + +NSString *const kENRMMarkdownPasteboardType = @"com.swmansion.enriched-markdown.markdown"; + +#if !TARGET_OS_OSX + +@implementation ENRMInputTextView { + CGFloat _lastLayoutWidth; +} + +- (void)copy:(id)sender +{ + NSRange selection = self.selectedRange; + if (selection.length == 0) { + return; + } + + NSString *plainText = [self.text substringWithRange:selection]; + NSString *markdown = [self.markdownTextInput markdownForSelectedRange]; + NSMutableDictionary *items = [NSMutableDictionary dictionary]; + items[kUTIPlainText] = plainText; + if (markdown.length > 0) { + items[kENRMMarkdownPasteboardType] = markdown; + } + copyItemsToPasteboard(items); +} + +- (void)cut:(id)sender +{ + [self copy:sender]; + [self.markdownTextInput replaceSelectedTextWith:@"" formattingRanges:@[]]; +} + +- (void)paste:(id)sender +{ + UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; + + NSString *markdown = nil; + id markdownValue = [pasteboard valueForPasteboardType:kENRMMarkdownPasteboardType]; + if ([markdownValue isKindOfClass:[NSString class]]) { + markdown = markdownValue; + } else if ([markdownValue isKindOfClass:[NSData class]]) { + markdown = [[NSString alloc] initWithData:markdownValue encoding:NSUTF8StringEncoding]; + } + + if (markdown.length > 0 && self.markdownTextInput != nil) { + [self.markdownTextInput pasteMarkdown:markdown]; + return; + } + + // External plain text is treated as markdown so pasted syntax ("- ", "#", + // "**") formats instead of landing literal; syntax-free text is unchanged. + NSString *plainText = pasteboard.string; + if (plainText.length > 0 && self.markdownTextInput != nil) { + [self.markdownTextInput pasteMarkdown:plainText]; + } else if (plainText.length > 0) { + [self replaceRange:self.selectedTextRange withText:plainText]; + } +} + +- (BOOL)canPerformAction:(SEL)action withSender:(id)sender +{ + if (action == @selector(paste:)) { + UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; + if (pasteboard.hasStrings || [pasteboard containsPasteboardTypes:@[ kENRMMarkdownPasteboardType ]]) { + return YES; + } + } + return [super canPerformAction:action withSender:sender]; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + CGFloat currentWidth = self.bounds.size.width; + if (self.markdownTextInput != nil && fabs(currentWidth - _lastLayoutWidth) > 0.5) { + _lastLayoutWidth = currentWidth; + [self.markdownTextInput scheduleRelayoutIfNeeded]; + } +} + +- (void)deleteBackward +{ + // Backspace at the very start of the document doesn't fire the text-change + // delegate (nothing precedes the caret), so removing/outdenting the first + // line's list marker has to be handled here. + if (self.markdownTextInput != nil && [self.markdownTextInput handleBackspaceAtDocumentStart]) { + return; + } + [super deleteBackward]; +} + +/// Hardware-keyboard Tab / Shift+Tab indent and outdent the current list item. +/// UIKeyCommand only fires for an attached keyboard; on-screen Tab/Backspace go +/// through the text-change delegate (see handleListKeyForReplacementRange:). +- (NSArray *)keyCommands +{ + return @[ + [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:0 action:@selector(enrmIndentList:)], + [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:UIKeyModifierShift action:@selector(enrmOutdentList:)], + ]; +} + +- (void)enrmIndentList:(UIKeyCommand *)command +{ + [self.markdownTextInput indentList]; +} + +- (void)enrmOutdentList:(UIKeyCommand *)command +{ + [self.markdownTextInput outdentList]; +} + +- (void)drawRect:(CGRect)rect +{ + [super drawRect:rect]; + // A wholly empty editor has no glyphs, so the layout manager's + // drawGlyphsForGlyphRange: never runs — draw decorations here instead. + if (self.text.length == 0) { + NSLayoutManager *layoutManager = self.layoutManager; + if ([layoutManager isKindOfClass:[ENRMInputLayoutManager class]]) { + [(ENRMInputLayoutManager *)layoutManager drawEmptyEditorDecorationsWithInset:self.textContainerInset]; + } + } +} + +@end + +#else // TARGET_OS_OSX + +@implementation ENRMInputTextView { + CGFloat _lastLayoutWidth; +} + +- (void)copy:(id)sender +{ + NSRange selection = self.selectedRange; + if (selection.length == 0) { + return; + } + + NSString *plainText = [self.string substringWithRange:selection]; + NSString *markdown = [self.markdownTextInput markdownForSelectedRange]; + NSMutableDictionary *items = [NSMutableDictionary dictionary]; + items[kUTIPlainText] = plainText; + if (markdown.length > 0) { + items[kENRMMarkdownPasteboardType] = markdown; + } + copyItemsToPasteboard(items); +} + +- (void)cut:(id)sender +{ + [self copy:sender]; + [self.markdownTextInput replaceSelectedTextWith:@"" formattingRanges:@[]]; +} + +- (void)paste:(id)sender +{ + NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; + + NSString *markdown = [pasteboard stringForType:kENRMMarkdownPasteboardType]; + if (markdown.length > 0 && self.markdownTextInput != nil) { + [self.markdownTextInput pasteMarkdown:markdown]; + return; + } + + // External plain text is treated as markdown so pasted syntax ("- ", "#", + // "**") formats instead of landing literal; syntax-free text is unchanged. + NSString *plainText = [pasteboard stringForType:NSPasteboardTypeString]; + if (plainText.length > 0 && self.markdownTextInput != nil) { + [self.markdownTextInput pasteMarkdown:plainText]; + } else if (plainText.length > 0) { + [self insertText:plainText replacementRange:self.selectedRange]; + } +} + +- (BOOL)validateMenuItem:(NSMenuItem *)menuItem +{ + if (menuItem.action == @selector(paste:)) { + NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; + return ([pasteboard stringForType:NSPasteboardTypeString] != nil || + [pasteboard stringForType:kENRMMarkdownPasteboardType] != nil); + } + return [super validateMenuItem:menuItem]; +} + +- (BOOL)acceptsFirstResponder +{ + return self.isEditable; +} + +- (void)mouseDown:(NSEvent *)event +{ + if (self.window != nil) { + [self.window makeFirstResponder:self]; + } + [super mouseDown:event]; +} + +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + NSMenu *menu = [super menuForEvent:event]; + if (self.markdownTextInput != nil) { + return [self.markdownTextInput enrichedMenuForEvent:event defaultMenu:menu textView:self]; + } + return menu; +} + +- (void)setTypingAttributes:(NSDictionary *)typingAttributes +{ + // RCTUITextView's override discards the value and always resets to + // defaultTextAttributes. We need the actual value (e.g. list paragraph + // indent) to reach NSTextView so the caret positions correctly. + struct objc_super superSuper = {self, [NSTextView class]}; + ((void (*)(struct objc_super *, SEL, NSDictionary *))objc_msgSendSuper)(&superSuper, _cmd, typingAttributes); +} + +- (void)layout +{ + [super layout]; + CGFloat currentWidth = self.bounds.size.width; + if (self.markdownTextInput != nil && fabs(currentWidth - _lastLayoutWidth) > 0.5) { + _lastLayoutWidth = currentWidth; + [self.markdownTextInput scheduleRelayoutIfNeeded]; + } +} + +- (void)drawRect:(NSRect)rect +{ + [super drawRect:rect]; + if (self.string.length == 0) { + NSLayoutManager *lm = self.layoutManager; + if ([lm isKindOfClass:[ENRMInputLayoutManager class]]) { + NSEdgeInsets insets = self.textContainerInsets; + insets.left += self.textContainer.lineFragmentPadding; + [(ENRMInputLayoutManager *)lm drawEmptyEditorDecorationsWithInset:insets]; + } + } +} + +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.h b/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.h new file mode 100644 index 000000000000..e7e23593c51f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.h @@ -0,0 +1,42 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMEditSession.h" +#import "ENRMInputFormatterStyle.h" +#import "ENRMInputStyledRange.h" +#import "ENRMInputTextView.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMInputTypingAttributesDataSource + +- (NSRange)selectedRange; +- (NSInteger)headingLevelForCursorParagraph; +- (nullable ENRMBlockRange *)listBlockForCursorParagraph; +- (BOOL)isStyleAdjacentBefore:(ENRMInputStyleType)type position:(NSUInteger)position; +- (BOOL)isStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position; + +@end + +@interface ENRMInputTypingAttributesController : NSObject + +- (instancetype)initWithTextView:(ENRMPlatformTextView *)textView + formatterStyle:(ENRMInputFormatterStyle *)style + dataSource:(id)dataSource + editSession:(ENRMEditSession *)editSession; + +- (BOOL)isEffectiveStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position; +- (void)togglePendingStyle:(ENRMInputStyleType)type wasActive:(BOOL)wasActive hasSelection:(BOOL)hasSelection; +- (void)clearPendingStyle:(ENRMInputStyleType)type; +- (void)syncWithCursorBlock; +- (void)syncWithPendingStyles; +- (void)resetForSelectionChange; +- (void)clearListParagraphStyle; + +@property (nonatomic, readonly) NSSet *pendingStyles; +@property (nonatomic, readonly) NSSet *pendingStyleRemovals; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.mm b/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.mm new file mode 100644 index 000000000000..55a7f561f794 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMInputTypingAttributesController.mm @@ -0,0 +1,225 @@ +#import "ENRMInputTypingAttributesController.h" +#import "ENRMInputBlockType.h" +#import "InputStylePropsUtils.h" + +@implementation ENRMInputTypingAttributesController { + __weak ENRMPlatformTextView *_textView; + __weak id _dataSource; + ENRMInputFormatterStyle *_formatterStyle; + ENRMEditSession *_editSession; + + NSMutableSet *_pendingStyles; + NSMutableSet *_pendingStyleRemovals; +} + +- (instancetype)initWithTextView:(ENRMPlatformTextView *)textView + formatterStyle:(ENRMInputFormatterStyle *)style + dataSource:(id)dataSource + editSession:(ENRMEditSession *)editSession +{ + self = [super init]; + if (self) { + _textView = textView; + _formatterStyle = style; + _dataSource = dataSource; + _editSession = editSession; + _pendingStyles = [NSMutableSet set]; + _pendingStyleRemovals = [NSMutableSet set]; + } + return self; +} + +#pragma mark - Properties + +- (NSSet *)pendingStyles +{ + return [_pendingStyles copy]; +} + +- (NSSet *)pendingStyleRemovals +{ + return [_pendingStyleRemovals copy]; +} + +#pragma mark - Style queries + +- (BOOL)isEffectiveStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position +{ + BOOL inRange = [_dataSource isStyleActive:type atPosition:position]; + NSNumber *key = @(type); + if ([_pendingStyleRemovals containsObject:key]) { + return NO; + } + if ([_pendingStyles containsObject:key]) { + return YES; + } + return inRange; +} + +#pragma mark - Pending style mutations + +- (void)togglePendingStyle:(ENRMInputStyleType)type wasActive:(BOOL)wasActive hasSelection:(BOOL)hasSelection +{ + NSNumber *key = @(type); + if (hasSelection) { + [_pendingStyles removeObject:key]; + [_pendingStyleRemovals removeObject:key]; + } else { + if ([_pendingStyleRemovals containsObject:key]) { + [_pendingStyleRemovals removeObject:key]; + } else if ([_pendingStyles containsObject:key]) { + [_pendingStyles removeObject:key]; + } else if (wasActive) { + [_pendingStyleRemovals addObject:key]; + } else { + [_pendingStyles addObject:key]; + } + } +} + +- (void)clearPendingStyle:(ENRMInputStyleType)type +{ + NSNumber *key = @(type); + [_pendingStyles removeObject:key]; + [_pendingStyleRemovals removeObject:key]; +} + +#pragma mark - Typing attribute synchronization + +- (void)syncWithCursorBlock +{ + UIFontDescriptorSymbolicTraits traits = 0; + if ([_pendingStyles containsObject:@(ENRMInputStyleTypeStrong)]) { + traits |= UIFontDescriptorTraitBold; + } + if ([_pendingStyles containsObject:@(ENRMInputStyleTypeEmphasis)]) { + traits |= UIFontDescriptorTraitItalic; + } + + NSInteger headingLevel = [_dataSource headingLevelForCursorParagraph]; + + UIFont *font; + if (headingLevel >= 1 && headingLevel <= 6) { + UIFont *headingFont = [_formatterStyle headingFontForLevel:headingLevel]; + UIFontDescriptorSymbolicTraits merged = headingFont.fontDescriptor.symbolicTraits | traits; + UIFontDescriptor *descriptor = [headingFont.fontDescriptor fontDescriptorWithSymbolicTraits:merged]; + font = descriptor ? [UIFont fontWithDescriptor:descriptor size:0] : headingFont; + } else { + font = [_formatterStyle fontForTraits:traits]; + } + + NSMutableDictionary *attrs = [_textView.typingAttributes mutableCopy]; + attrs[NSFontAttributeName] = font; + RCTUIColor *headingColor = headingLevel >= 1 ? [_formatterStyle headingColorForLevel:headingLevel] : nil; + attrs[NSForegroundColorAttributeName] = headingColor ?: _formatterStyle.baseTextColor; + + ENRMBlockRange *typingListBlock = [_dataSource listBlockForCursorParagraph]; + if (typingListBlock != nil) { + NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; + CGFloat indent = (typingListBlock.level + 1) * kENRMListIndentPerDepth; + paragraph.firstLineHeadIndent = indent; + paragraph.headIndent = indent; + paragraph.paragraphSpacingBefore = _formatterStyle.listItemSpacing; + ENRMApplyLineHeightToParagraphStyle(paragraph, _formatterStyle.baseLineHeight); + attrs[NSParagraphStyleAttributeName] = paragraph; + } else { + [self setNonListParagraphStyleInAttributes:attrs headingLevel:headingLevel]; + } + + if (![attrs isEqualToDictionary:_textView.typingAttributes]) { + _textView.typingAttributes = attrs; + } +} + +- (void)syncWithPendingStyles +{ + UIFontDescriptorSymbolicTraits traits = 0; + if ([_pendingStyles containsObject:@(ENRMInputStyleTypeStrong)]) { + traits |= UIFontDescriptorTraitBold; + } + if ([_pendingStyles containsObject:@(ENRMInputStyleTypeEmphasis)]) { + traits |= UIFontDescriptorTraitItalic; + } + + NSMutableDictionary *attrs = [_textView.typingAttributes mutableCopy]; + attrs[NSFontAttributeName] = [_formatterStyle fontForTraits:traits]; + _textView.typingAttributes = attrs; +} + +- (void)resetForSelectionChange +{ + if (_editSession.isPostEditGracePeriod) { + return; + } + [_pendingStyles removeAllObjects]; + [_pendingStyleRemovals removeAllObjects]; + [self rebuildFromContext]; + if ([_dataSource selectedRange].length == 0) { + [self syncWithCursorBlock]; + } +} + +- (void)clearListParagraphStyle +{ + if (_textView.typingAttributes[NSParagraphStyleAttributeName] == nil) { + return; + } + // Drop the list indent but keep the line height, which also sizes the caret + // on an empty trailing line and in an empty editor. + NSMutableDictionary *attrs = [_textView.typingAttributes mutableCopy]; + [self setNonListParagraphStyleInAttributes:attrs headingLevel:[_dataSource headingLevelForCursorParagraph]]; + if (![attrs isEqualToDictionary:_textView.typingAttributes]) { + _textView.typingAttributes = attrs; + } +} + +#pragma mark - Private + +/// Paragraph style for a non-list paragraph: the heading's derived line height, +/// or the base line height, or none when no line height is set. +- (void)setNonListParagraphStyleInAttributes:(NSMutableDictionary *)attrs headingLevel:(NSInteger)headingLevel +{ + CGFloat lineHeight = (headingLevel >= 1 && headingLevel <= 6) + ? [_formatterStyle derivedLineHeightForHeadingLevel:headingLevel] + : _formatterStyle.baseLineHeight; + if (lineHeight > 0) { + NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; + ENRMApplyLineHeightToParagraphStyle(paragraph, lineHeight); + attrs[NSParagraphStyleAttributeName] = paragraph; + } else { + [attrs removeObjectForKey:NSParagraphStyleAttributeName]; + } +} + +- (void)rebuildFromContext +{ + static const ENRMInputStyleType inlineStyles[] = { + ENRMInputStyleTypeStrong, ENRMInputStyleTypeEmphasis, ENRMInputStyleTypeUnderline, + ENRMInputStyleTypeStrikethrough, ENRMInputStyleTypeSpoiler, + }; + + NSRange selection = [_dataSource selectedRange]; + + if (selection.length > 0) { + for (NSUInteger i = 0; i < sizeof(inlineStyles) / sizeof(inlineStyles[0]); i++) { + ENRMInputStyleType type = inlineStyles[i]; + if ([_dataSource isStyleActive:type atPosition:selection.location]) { + [_pendingStyles addObject:@(type)]; + } + } + return; + } + + if (selection.location == 0) { + return; + } + + for (NSUInteger i = 0; i < sizeof(inlineStyles) / sizeof(inlineStyles[0]); i++) { + ENRMInputStyleType type = inlineStyles[i]; + if ([_dataSource isStyleAdjacentBefore:type position:selection.location]) { + [_pendingStyles addObject:@(type)]; + } + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.h b/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.h new file mode 100644 index 000000000000..6cb29ae29d0f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.h @@ -0,0 +1,43 @@ +#pragma once + +#import "ENRMFormattingRange.h" +#import "ENRMFormattingStore.h" +#import + +@class AutoLinkDetector; + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMAutoLinkDetecting +- (void)clearAutoLinkInRange:(NSRange)range; +@end + +@interface ENRMLinkCoordinator : NSObject + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + autoLinkDetector:(id)autoLinkDetector; + +- (NSString *)sanitizeURL:(NSString *)url; + +/// The link a caret or selection refers to, shared by everything that acts on +/// "the current link" (style state, the link prompt, setting and removing a +/// link) so they always agree. For a selection it is the link containing the +/// first selected character. For a collapsed caret it is the link the caret is +/// inside or right after: ranges are half-open, and the caret often lands at +/// NSMaxRange(link) after tapping a link. +- (nullable ENRMFormattingRange *)linkForSelection:(NSRange)selection; + +/// Updates the URL of the link at the selection if the selection lies within +/// it, or otherwise adds a link over a non-empty selection. Returns YES if a +/// mutation occurred. +- (BOOL)setLinkURL:(NSString *)url forSelection:(NSRange)selection; + +/// Removes the link at the selection. Returns YES if a link was found and removed. +- (BOOL)removeLinkForSelection:(NSRange)selection; + +/// Returns the link range containing `position - 1`, for atomic link deletion. +- (nullable ENRMFormattingRange *)linkRangeForDeletionAtPosition:(NSUInteger)position; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.mm b/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.mm new file mode 100644 index 000000000000..bc24dff5c1d1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMLinkCoordinator.mm @@ -0,0 +1,75 @@ +#import "ENRMLinkCoordinator.h" + +@implementation ENRMLinkCoordinator { + ENRMFormattingStore *_formattingStore; + id _autoLinkDetector; +} + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore + autoLinkDetector:(id)autoLinkDetector +{ + if (self = [super init]) { + _formattingStore = formattingStore; + _autoLinkDetector = autoLinkDetector; + } + return self; +} + +- (NSString *)sanitizeURL:(NSString *)url +{ + NSString *result = [url stringByReplacingOccurrencesOfString:@"(" withString:@"%28"]; + return [result stringByReplacingOccurrencesOfString:@")" withString:@"%29"]; +} + +- (nullable ENRMFormattingRange *)linkForSelection:(NSRange)selection +{ + ENRMFormattingRange *link = [_formattingStore rangeOfType:ENRMInputStyleTypeLink + containingPosition:selection.location]; + if (link == nil && selection.length == 0 && selection.location > 0) { + link = [_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:selection.location - 1]; + } + return link; +} + +- (BOOL)setLinkURL:(NSString *)url forSelection:(NSRange)selection +{ + ENRMFormattingRange *activeLink = [self linkForSelection:selection]; + + // Update the link if selection is entirely within it + if (activeLink != nil && selection.location >= activeLink.range.location && + NSMaxRange(selection) <= NSMaxRange(activeLink.range)) { + activeLink.url = url; + [_autoLinkDetector clearAutoLinkInRange:activeLink.range]; + return YES; + } + + // Insert a link at the selection (removing any existing links that overlap) + if (selection.length > 0) { + ENRMFormattingRange *linkRange = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink range:selection url:url]; + [_formattingStore addRange:linkRange]; + [_autoLinkDetector clearAutoLinkInRange:selection]; + return YES; + } + + return NO; +} + +- (BOOL)removeLinkForSelection:(NSRange)selection +{ + ENRMFormattingRange *activeLink = [self linkForSelection:selection]; + if (activeLink == nil) { + return NO; + } + [_formattingStore removeRange:activeLink]; + return YES; +} + +- (nullable ENRMFormattingRange *)linkRangeForDeletionAtPosition:(NSUInteger)position +{ + if (position == 0) { + return nil; + } + return [_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:position - 1]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.h b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.h new file mode 100644 index 000000000000..be301c358ed3 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.h @@ -0,0 +1,24 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMFormattingRange.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMMarkdownSerializer : NSObject + ++ (NSString *)serializePlainText:(NSString *)text ranges:(NSArray *)ranges; + +/// Block-aware serialization: serializes inline styles exactly as the inline-only +/// overload, then prepends each line's block prefix. `prefixProvider` is asked, +/// per block range, for the markdown line marker (e.g. @"# ", @"- "); returning +/// @"" or nil leaves the line unprefixed. With empty `blockRanges` the output is +/// identical to the inline-only overload. ++ (NSString *)serializePlainText:(NSString *)text + ranges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges + blockPrefixProvider:(NSString *_Nullable (^_Nullable)(ENRMBlockRange *blockRange))prefixProvider; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.mm b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.mm new file mode 100644 index 000000000000..3eed9c8a82ee --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownSerializer.mm @@ -0,0 +1,290 @@ +#import "ENRMMarkdownSerializer.h" + +static NSString *openingDelimiterForType(ENRMInputStyleType type) +{ + switch (type) { + case ENRMInputStyleTypeStrong: + return @"**"; + case ENRMInputStyleTypeEmphasis: + return @"*"; + case ENRMInputStyleTypeUnderline: + return @"_"; + case ENRMInputStyleTypeStrikethrough: + return @"~~"; + case ENRMInputStyleTypeLink: + return @"["; + case ENRMInputStyleTypeSpoiler: + return @"||"; + default: + return @""; + } +} + +static NSString *closingDelimiterForType(ENRMInputStyleType type, NSString *url) +{ + switch (type) { + case ENRMInputStyleTypeStrong: + return @"**"; + case ENRMInputStyleTypeEmphasis: + return @"*"; + case ENRMInputStyleTypeUnderline: + return @"_"; + case ENRMInputStyleTypeStrikethrough: + return @"~~"; + case ENRMInputStyleTypeLink: + return [NSString stringWithFormat:@"](%@)", url ?: @""]; + case ENRMInputStyleTypeSpoiler: + return @"||"; + default: + return @""; + } +} + +/// Lower value = outermost wrapper. Font styles wrap around structural styles (link). +static int nestingPriorityForType(ENRMInputStyleType type) +{ + switch (type) { + case ENRMInputStyleTypeEmphasis: + return 0; + case ENRMInputStyleTypeStrong: + return 1; + case ENRMInputStyleTypeUnderline: + return 2; + case ENRMInputStyleTypeStrikethrough: + return 3; + case ENRMInputStyleTypeSpoiler: + return 4; + case ENRMInputStyleTypeLink: + return 5; + default: + return 99; + } +} + +typedef struct { + NSUInteger position; + BOOL isOpening; + ENRMInputStyleType type; + NSString *__unsafe_unretained url; +} BoundaryEvent; + +static int compareBoundaryEvents(const void *first, const void *second) +{ + const BoundaryEvent *eventA = (const BoundaryEvent *)first; + const BoundaryEvent *eventB = (const BoundaryEvent *)second; + + if (eventA->position != eventB->position) { + return eventA->position < eventB->position ? -1 : 1; + } + // Closing events before opening events at the same position + if (eventA->isOpening != eventB->isOpening) { + return eventA->isOpening ? 1 : -1; + } + // Among openings: outer first (lower priority emitted first) + // Among closings: inner first (higher priority emitted first) — LIFO order + int priorityA = nestingPriorityForType(eventA->type); + int priorityB = nestingPriorityForType(eventB->type); + if (eventA->isOpening) { + return priorityA - priorityB; + } else { + return priorityB - priorityA; + } +} + +static NSCharacterSet *whitespaceSet(void) +{ + static NSCharacterSet *set; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ set = [NSCharacterSet whitespaceAndNewlineCharacterSet]; }); + return set; +} + +/// Split formatting ranges at paragraph breaks (\n\n) so each segment gets +/// its own delimiters — CommonMark delimiters can't span paragraphs. +/// NOTE: This only handles inline styles (bold, italic, etc.). Block-level +/// elements (lists, blockquotes, headings) are prefix-based and will need +/// a separate serialization path. +static NSArray *splitRangesAtParagraphBreaks(NSArray *ranges, + NSString *text) +{ + NSMutableArray *result = [NSMutableArray arrayWithCapacity:ranges.count]; + + NSUInteger textLength = text.length; + + for (ENRMFormattingRange *formattingRange in ranges) { + NSUInteger rangeStart = MIN(formattingRange.range.location, textLength); + NSUInteger rangeEnd = MIN(NSMaxRange(formattingRange.range), textLength); + + NSUInteger segStart = rangeStart; + while (segStart < rangeEnd) { + NSUInteger segEnd = segStart; + while (segEnd < rangeEnd) { + if (segEnd + 1 < rangeEnd && [text characterAtIndex:segEnd] == '\n' && + [text characterAtIndex:segEnd + 1] == '\n') { + break; + } + segEnd++; + } + + if (segEnd > segStart) { + [result addObject:[ENRMFormattingRange rangeWithType:formattingRange.type + range:NSMakeRange(segStart, segEnd - segStart) + url:formattingRange.url]]; + } + + segStart = (segEnd < rangeEnd && segEnd + 1 < rangeEnd && [text characterAtIndex:segEnd] == '\n' && + [text characterAtIndex:segEnd + 1] == '\n') + ? segEnd + 2 + : segEnd; + } + } + + return result; +} + +@implementation ENRMMarkdownSerializer + ++ (NSString *)serializePlainText:(NSString *)text ranges:(NSArray *)ranges +{ + if (ranges.count == 0) { + return text; + } + + NSArray *splitRanges = splitRangesAtParagraphBreaks(ranges, text); + + NSUInteger textLength = text.length; + NSUInteger eventCount = splitRanges.count * 2; + + BoundaryEvent *events = (BoundaryEvent *)malloc(sizeof(BoundaryEvent) * eventCount); + if (!events) + return text; + + NSCharacterSet *ws = whitespaceSet(); + NSUInteger eventIndex = 0; + for (ENRMFormattingRange *formattingRange in splitRanges) { + NSUInteger start = MIN(formattingRange.range.location, textLength); + NSUInteger end = MIN(NSMaxRange(formattingRange.range), textLength); + + while (start < end && [ws characterIsMember:[text characterAtIndex:start]]) { + start++; + } + while (end > start && [ws characterIsMember:[text characterAtIndex:end - 1]]) { + end--; + } + + if (start >= end) { + continue; + } + + events[eventIndex++] = (BoundaryEvent){ + .position = start, + .isOpening = YES, + .type = formattingRange.type, + .url = formattingRange.url, + }; + events[eventIndex++] = (BoundaryEvent){ + .position = end, + .isOpening = NO, + .type = formattingRange.type, + .url = formattingRange.url, + }; + } + + qsort(events, eventIndex, sizeof(BoundaryEvent), compareBoundaryEvents); + + NSMutableString *markdown = [NSMutableString stringWithCapacity:textLength + eventCount * 4]; + NSUInteger lastPosition = 0; + + for (NSUInteger currentEvent = 0; currentEvent < eventIndex; currentEvent++) { + BoundaryEvent event = events[currentEvent]; + NSUInteger position = MIN(event.position, textLength); + + if (position > lastPosition) { + [markdown appendString:[text substringWithRange:NSMakeRange(lastPosition, position - lastPosition)]]; + lastPosition = position; + } + + if (event.isOpening) { + [markdown appendString:openingDelimiterForType(event.type)]; + } else { + [markdown appendString:closingDelimiterForType(event.type, event.url)]; + } + } + + if (lastPosition < textLength) { + [markdown appendString:[text substringFromIndex:lastPosition]]; + } + + free(events); + return markdown; +} + ++ (NSString *)serializePlainText:(NSString *)text + ranges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges + blockPrefixProvider:(NSString *_Nullable (^_Nullable)(ENRMBlockRange *blockRange))prefixProvider +{ + NSString *inlineMarkdown = [self serializePlainText:text ranges:ranges]; + + if (blockRanges.count == 0 || prefixProvider == nil) { + return inlineMarkdown; + } + + // Block prefixes attach per line. Inline serialization only inserts inline + // delimiters (never newlines), so the serialized output has the same line + // count as the plain text — we map a block's plain-text range to line indices + // and prefix the corresponding serialized lines. + NSArray *plainLines = [text componentsSeparatedByString:@"\n"]; + NSMutableArray *markdownLines = [[inlineMarkdown componentsSeparatedByString:@"\n"] mutableCopy]; + + // Inline delimiters never cross a newline, so the line partition is preserved. + // If this ever breaks, prefixes would land on the wrong lines. Contract on + // both platforms: assert in debug, log and fall back to inline-only output in + // release — a library must not crash the host app over lost block prefixes. + NSCAssert(plainLines.count == markdownLines.count, + @"Block serialization line-count invariant violated: plain=%lu markdown=%lu", + (unsigned long)plainLines.count, (unsigned long)markdownLines.count); + if (plainLines.count != markdownLines.count) { + NSLog(@"[EnrichedMarkdown] Block serialization line-count invariant violated: plain=%lu markdown=%lu", + (unsigned long)plainLines.count, (unsigned long)markdownLines.count); + return inlineMarkdown; + } + + NSMutableArray *lineStartOffsets = [NSMutableArray arrayWithCapacity:plainLines.count]; + NSUInteger runningOffset = 0; + for (NSString *line in plainLines) { + [lineStartOffsets addObject:@(runningOffset)]; + runningOffset += line.length + 1; // +1 for the '\n' separator + } + + for (ENRMBlockRange *blockRange in blockRanges) { + NSString *prefix = prefixProvider(blockRange); + if (prefix.length == 0) { + continue; + } + + NSUInteger blockStart = blockRange.range.location; + NSUInteger blockEnd = NSMaxRange(blockRange.range); + BOOL isZeroLength = blockRange.range.length == 0; + BOOL isListItem = ENRMBlockTypeIsListItem(blockRange.type); + + for (NSUInteger lineIndex = 0; lineIndex < plainLines.count; lineIndex++) { + NSUInteger lineStart = lineStartOffsets[lineIndex].unsignedIntegerValue; + NSUInteger lineEnd = lineStart + plainLines[lineIndex].length; + BOOL overlaps = isZeroLength ? (lineStart == blockStart) : (lineEnd >= blockStart && lineStart < blockEnd); + if (overlaps) { + // A marker-only list line ("- " with no content) re-parses as a setext + // underline for the previous line; emit an empty list line bare. An + // empty "# " heading is valid ATX and keeps its prefix. + if (isListItem && plainLines[lineIndex].length == 0) { + continue; + } + markdownLines[lineIndex] = [prefix stringByAppendingString:markdownLines[lineIndex]]; + } + } + } + + return [markdownLines componentsJoinedByString:@"\n"]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.h b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.h new file mode 100644 index 000000000000..41e5291072b0 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.h @@ -0,0 +1,39 @@ +#pragma once + +#import "ENRMInputBlockType.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +/// Which shortcut families are enabled, normalized on the JS side so native +/// never sees the public `boolean | MarkdownShortcutsConfig` union. +typedef struct { + BOOL heading; + BOOL unorderedList; + BOOL orderedList; +} ENRMMarkdownShortcutsConfig; + +static inline BOOL ENRMMarkdownShortcutsEnabled(ENRMMarkdownShortcutsConfig config) +{ + return config.heading || config.unorderedList || config.orderedList; +} + +/// Recognizes the markdown block prefixes a user types at the start of a +/// paragraph — `#`…`######`, `-`/`*`/`+`, `1.`/`1)` — so the input can turn the +/// paragraph into the matching block and drop the prefix (Notion-style +/// markdown shortcuts). Pure text matching; the caller owns the mutation. +@interface ENRMMarkdownShortcutMatcher : NSObject + +/// Matches `prefix` (the paragraph text before the space the user just typed, +/// with no leading whitespace) against the shortcut grammar. Returns YES and +/// fills `outType`/`outLevel` on a match whose family `config` enables. Ordered +/// items match any number — the block store renumbers ordinals, so `3.` on a +/// fresh line still starts at 1. ++ (BOOL)matchPrefix:(NSString *)prefix + config:(ENRMMarkdownShortcutsConfig)config + outType:(ENRMInputBlockType *)outType + outLevel:(NSInteger *)outLevel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.mm b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.mm new file mode 100644 index 000000000000..606c51d32d4f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMarkdownShortcutMatcher.mm @@ -0,0 +1,66 @@ +#import "ENRMMarkdownShortcutMatcher.h" + +/// Upper bound on the digits accepted before `.`/`)`. Anything longer is a +/// number the user is writing, not a list marker. +static const NSUInteger kENRMMaxOrderedMarkerDigits = 9; + +@implementation ENRMMarkdownShortcutMatcher + ++ (BOOL)matchPrefix:(NSString *)prefix + config:(ENRMMarkdownShortcutsConfig)config + outType:(ENRMInputBlockType *)outType + outLevel:(NSInteger *)outLevel +{ + NSUInteger length = prefix.length; + if (length == 0) { + return NO; + } + + unichar first = [prefix characterAtIndex:0]; + + // `#`{1,6} → heading at that level. + if (first == '#') { + if (!config.heading || length > 6) { + return NO; + } + for (NSUInteger i = 1; i < length; i++) { + if ([prefix characterAtIndex:i] != '#') { + return NO; + } + } + *outType = ENRMBlockTypeForHeadingLevel((NSInteger)length); + *outLevel = (NSInteger)length; + return YES; + } + + // `-`, `*`, `+` → bullet item at depth 0. + if (length == 1 && (first == '-' || first == '*' || first == '+')) { + if (!config.unorderedList) { + return NO; + } + *outType = ENRMInputBlockTypeUnorderedListItem; + *outLevel = 0; + return YES; + } + + // digits followed by `.` or `)` → numbered item at depth 0. + unichar last = [prefix characterAtIndex:length - 1]; + if ((last == '.' || last == ')') && length >= 2 && length - 1 <= kENRMMaxOrderedMarkerDigits) { + for (NSUInteger i = 0; i < length - 1; i++) { + unichar c = [prefix characterAtIndex:i]; + if (c < '0' || c > '9') { + return NO; + } + } + if (!config.orderedList) { + return NO; + } + *outType = ENRMInputBlockTypeOrderedListItem; + *outLevel = 0; + return YES; + } + + return NO; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.h b/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.h new file mode 100644 index 000000000000..481f1628c066 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.h @@ -0,0 +1,45 @@ +#pragma once + +#import "ENRMFormattingStore.h" +#import "ENRMInputMentionCandidate.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, ENRMMentionEventType) { + ENRMMentionEventStart, + ENRMMentionEventChange, + ENRMMentionEventEnd, +}; + +@interface ENRMMentionEvent : NSObject +@property (nonatomic, assign) ENRMMentionEventType type; +@property (nonatomic, copy) NSString *indicator; +@property (nonatomic, copy, nullable) NSString *text; ++ (instancetype)startWithIndicator:(NSString *)indicator; ++ (instancetype)changeWithIndicator:(NSString *)indicator text:(NSString *)text; ++ (instancetype)endWithIndicator:(NSString *)indicator; +@end + +@interface ENRMMentionCoordinator : NSObject + +@property (nonatomic, readonly, nullable) NSString *activeIndicator; +@property (nonatomic, readonly) NSRange activeRange; +@property (nonatomic, readonly, copy) NSString *activeText; +@property (nonatomic, readonly) BOOL isActive; + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore; + +- (BOOL)containsIndicator:(NSString *)indicator; +- (NSArray *)setIndicators:(NSArray *)indicators; + +/// Re-evaluates the active mention. Returns events for the view to dispatch. +- (NSArray *)updateWithText:(nullable NSString *)plainText selectedRange:(NSRange)selectedRange; + +- (NSArray *)clearWithIndicatorOverride:(nullable NSString *)indicatorOverride; + +- (nullable ENRMInputMentionCandidate *)detectCandidateInText:(NSString *)plainText atCursor:(NSUInteger)cursor; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.mm b/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.mm new file mode 100644 index 000000000000..99303495ad96 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMMentionCoordinator.mm @@ -0,0 +1,167 @@ +#import "ENRMMentionCoordinator.h" +#import "ENRMWordsUtils.h" + +@implementation ENRMMentionEvent + ++ (instancetype)startWithIndicator:(NSString *)indicator +{ + ENRMMentionEvent *e = [[ENRMMentionEvent alloc] init]; + e.type = ENRMMentionEventStart; + e.indicator = indicator; + return e; +} + ++ (instancetype)changeWithIndicator:(NSString *)indicator text:(NSString *)text +{ + ENRMMentionEvent *e = [[ENRMMentionEvent alloc] init]; + e.type = ENRMMentionEventChange; + e.indicator = indicator; + e.text = text; + return e; +} + ++ (instancetype)endWithIndicator:(NSString *)indicator +{ + ENRMMentionEvent *e = [[ENRMMentionEvent alloc] init]; + e.type = ENRMMentionEventEnd; + e.indicator = indicator; + return e; +} + +@end + +@implementation ENRMMentionCoordinator { + ENRMFormattingStore *_formattingStore; + NSArray *_indicators; + NSString *_activeIndicator; + NSRange _activeRange; + NSString *_activeText; +} + +- (instancetype)initWithFormattingStore:(ENRMFormattingStore *)formattingStore +{ + if (self = [super init]) { + _formattingStore = formattingStore; + _indicators = @[]; + _activeRange = NSMakeRange(NSNotFound, 0); + _activeText = @""; + } + return self; +} + +- (NSString *)activeIndicator +{ + return _activeIndicator; +} + +- (NSRange)activeRange +{ + return _activeRange; +} + +- (NSString *)activeText +{ + return _activeText; +} + +- (BOOL)isActive +{ + return _activeIndicator != nil; +} + +- (BOOL)containsIndicator:(NSString *)indicator +{ + return [_indicators containsObject:indicator]; +} + +- (NSArray *)setIndicators:(NSArray *)indicators +{ + if ([indicators isEqualToArray:_indicators]) { + return @[]; + } + _indicators = [indicators copy]; + NSMutableArray *events = [NSMutableArray array]; + if (_activeIndicator != nil && ![_indicators containsObject:_activeIndicator]) { + [events addObjectsFromArray:[self clearWithIndicatorOverride:_activeIndicator]]; + } + return events; +} + +- (NSArray *)updateWithText:(nullable NSString *)plainText selectedRange:(NSRange)selectedRange +{ + if (plainText == nil || selectedRange.length != 0) { + return [self clearWithIndicatorOverride:nil]; + } + NSUInteger cursor = selectedRange.location; + if (cursor > plainText.length) { + return [self clearWithIndicatorOverride:nil]; + } + + ENRMInputMentionCandidate *candidate = [self detectCandidateInText:plainText atCursor:cursor]; + if (candidate == nil) { + return [self clearWithIndicatorOverride:nil]; + } + + NSMutableArray *events = [NSMutableArray array]; + + if (_activeIndicator == nil || ![_activeIndicator isEqualToString:candidate.indicator] || + _activeRange.location != candidate.start) { + if (_activeIndicator != nil) { + [events addObject:[ENRMMentionEvent endWithIndicator:_activeIndicator]]; + } + _activeIndicator = candidate.indicator; + [events addObject:[ENRMMentionEvent startWithIndicator:candidate.indicator]]; + } + + _activeRange = NSMakeRange(candidate.start, candidate.end - candidate.start); + + if (![_activeText isEqualToString:candidate.text]) { + _activeText = candidate.text; + [events addObject:[ENRMMentionEvent changeWithIndicator:candidate.indicator text:candidate.text]]; + } + + return events; +} + +- (NSArray *)clearWithIndicatorOverride:(nullable NSString *)indicatorOverride +{ + NSString *indicator = indicatorOverride ?: _activeIndicator; + _activeIndicator = nil; + _activeRange = NSMakeRange(NSNotFound, 0); + _activeText = @""; + if (indicator.length > 0) { + return @[ [ENRMMentionEvent endWithIndicator:indicator] ]; + } + return @[]; +} + +- (nullable ENRMInputMentionCandidate *)detectCandidateInText:(NSString *)plainText atCursor:(NSUInteger)cursor +{ + if (_indicators.count == 0) { + return nil; + } + + NSUInteger start = [ENRMWordsUtils tokenStartInText:plainText beforePosition:cursor]; + NSString *token = [plainText substringWithRange:NSMakeRange(start, cursor - start)]; + NSString *matchedIndicator = nil; + for (NSString *indicator in _indicators) { + if ([token hasPrefix:indicator]) { + matchedIndicator = indicator; + break; + } + } + if (matchedIndicator == nil) { + return nil; + } + + if ([_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:start] != nil) { + return nil; + } + + return [ENRMInputMentionCandidate candidateWithIndicator:matchedIndicator + start:start + end:cursor + text:[token substringFromIndex:matchedIndicator.length]]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.h b/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.h new file mode 100644 index 000000000000..3add4e39e044 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.h @@ -0,0 +1,38 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef struct { + NSRange range; + BOOL shouldRemove; +} ENRMAdjustedRange; + +/// Shared shift/clip logic applied to a stored range after a text edit that +/// replaced `deletedLength` characters at `editLocation` with `insertedLength` +/// characters. Both ENRMFormattingStore and ENRMBlockStore delegate here so the +/// overlap classification lives in exactly one place. `shouldRemove` is set +/// when the range was deleted outright or clipped to zero length. +/// +/// Insert-only edits at exactly the range end do NOT grow the range — the typed +/// characters stay outside it. An insert at exactly the range start grows the +/// range only when `growsAtStartOnInsert` is YES; otherwise the range shifts and +/// the typed characters stay outside it. Whether boundary text joins the range is +/// otherwise decided elsewhere: pending styles for inline ranges, line +/// re-normalization for block ranges. +/// +/// `inheritsReplacementAtStart`: when YES, a replacement whose deletion starts +/// at the range start lets the inserted text join the range (UIKit attribute +/// inheritance); when NO, the old clip/remove behavior applies. +/// +/// `growsAtStartOnInsert`: when YES, a pure insert at the range start grows the +/// range to cover the inserted text instead of shifting the range past it. Block +/// ranges own their whole line, so a character typed at the line start must keep +/// the line's block; inline styles must NOT set this (a character typed before a +/// bold run must not become bold). +ENRMAdjustedRange ENRMAdjustRangeForEdit(NSRange range, NSUInteger editLocation, NSUInteger deletedLength, + NSUInteger insertedLength, BOOL inheritsReplacementAtStart, + BOOL growsAtStartOnInsert); + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.mm b/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.mm new file mode 100644 index 000000000000..56c4deab3909 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMRangeEditAdjustment.mm @@ -0,0 +1,91 @@ +#import "ENRMRangeEditAdjustment.h" + +typedef NS_ENUM(NSInteger, EditOverlap) { + EditOverlapBeforeEdit, + EditOverlapAfterEdit, + EditOverlapFullyDeleted, + EditOverlapDeletedInside, + EditOverlapClippedEnd, + EditOverlapClippedStart, +}; + +static EditOverlap classifyOverlap(NSUInteger rangeStart, NSUInteger rangeEnd, NSUInteger editLocation, + NSUInteger deleteEnd) +{ + if (rangeEnd <= editLocation) + return EditOverlapBeforeEdit; + if (rangeStart >= deleteEnd) + return EditOverlapAfterEdit; + if (rangeStart >= editLocation && rangeEnd <= deleteEnd) + return EditOverlapFullyDeleted; + if (rangeStart < editLocation && rangeEnd > deleteEnd) + return EditOverlapDeletedInside; + if (rangeStart < editLocation && rangeEnd <= deleteEnd) + return EditOverlapClippedEnd; + return EditOverlapClippedStart; +} + +ENRMAdjustedRange ENRMAdjustRangeForEdit(NSRange range, NSUInteger editLocation, NSUInteger deletedLength, + NSUInteger insertedLength, BOOL inheritsReplacementAtStart, + BOOL growsAtStartOnInsert) +{ + ENRMAdjustedRange result = {range, NO}; + NSUInteger rangeStart = range.location; + NSUInteger rangeEnd = NSMaxRange(range); + + if (deletedLength > 0) { + NSUInteger deleteEnd = editLocation + deletedLength; + BOOL inheritsReplacement = inheritsReplacementAtStart && insertedLength > 0 && rangeStart == editLocation; + + switch (classifyOverlap(rangeStart, rangeEnd, editLocation, deleteEnd)) { + case EditOverlapBeforeEdit: + break; + + case EditOverlapAfterEdit: + result.range = NSMakeRange(rangeStart - deletedLength + insertedLength, range.length); + break; + + case EditOverlapFullyDeleted: + if (inheritsReplacement) { + result.range = NSMakeRange(editLocation, insertedLength); + } else { + result.shouldRemove = YES; + } + break; + + case EditOverlapDeletedInside: + result.range = NSMakeRange(rangeStart, range.length - deletedLength + insertedLength); + break; + + case EditOverlapClippedEnd: { + NSUInteger newEnd = editLocation + insertedLength; + NSUInteger newLength = newEnd > rangeStart ? newEnd - rangeStart : 0; + result.range = NSMakeRange(rangeStart, newLength); + result.shouldRemove = (newLength == 0); + break; + } + + case EditOverlapClippedStart: { + NSUInteger charsClipped = deleteEnd - rangeStart; + NSUInteger survivingLength = range.length - charsClipped; + if (inheritsReplacement) { + result.range = NSMakeRange(editLocation, insertedLength + survivingLength); + } else { + result.range = NSMakeRange(editLocation + insertedLength, survivingLength); + result.shouldRemove = (survivingLength == 0); + } + break; + } + } + } else if (insertedLength > 0) { + if (rangeStart == editLocation && growsAtStartOnInsert) { + result.range = NSMakeRange(rangeStart, range.length + insertedLength); + } else if (rangeStart >= editLocation) { + result.range = NSMakeRange(rangeStart + insertedLength, range.length); + } else if (editLocation < rangeEnd) { + result.range = NSMakeRange(rangeStart, range.length + insertedLength); + } + } + + return result; +} diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMRangeStoreUtils.h b/packages/react-native-enriched-markdown/ios/input/ENRMRangeStoreUtils.h new file mode 100644 index 000000000000..e4d660495d45 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMRangeStoreUtils.h @@ -0,0 +1,39 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +NS_INLINE NSUInteger ENRMSortedInsertionIndex(NSArray *ranges, NSUInteger location, + NSUInteger (^locationOfRange)(id range)) +{ + NSUInteger index = 0; + for (id existing in ranges) { + if (locationOfRange(existing) > location) + break; + index++; + } + return index; +} + +NS_INLINE void ENRMRemoveIndexesInReverse(NSMutableArray *array, NSMutableIndexSet *indexes) +{ + [indexes enumerateIndexesWithOptions:NSEnumerationReverse + usingBlock:^(NSUInteger idx, BOOL *stop) { [array removeObjectAtIndex:idx]; }]; +} + +/// paragraphRangeForRange: includes the line terminator; this strips it +/// to match the parser's content-only range convention. +NS_INLINE NSRange ENRMTrimLineTerminators(NSRange range, NSString *text) +{ + while (range.length > 0) { + unichar last = [text characterAtIndex:NSMaxRange(range) - 1]; + if (last != '\n' && last != '\r') { + break; + } + range.length--; + } + return range; +} + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMTextDetector.h b/packages/react-native-enriched-markdown/ios/input/ENRMTextDetector.h new file mode 100644 index 000000000000..0726de70cb92 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMTextDetector.h @@ -0,0 +1,30 @@ +#pragma once + +#import "ENRMWordsUtils.h" +#import + +@class ENRMFormattingRange; + +NS_ASSUME_NONNULL_BEGIN + +/// Protocol for pluggable text detectors that run after each text edit. +/// Each detector scans affected words, can refresh its own visual styling +/// after the formatter resets base attributes, and contributes transient +/// formatting ranges for markdown serialization. +@protocol ENRMTextDetector + +/// Process a single word at the given range after a text edit. +/// Called once per affected word in the modification range. +- (void)processWord:(ENRMWordResult *)wordResult; + +/// Re-apply any visual styling owned by this detector. +/// Called after the formatter resets base text attributes. +- (void)refreshStyling; + +/// Return transient formatting ranges that should be merged +/// with the FormattingStore ranges during markdown serialization. +- (NSArray *)transientFormattingRanges; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.h b/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.h new file mode 100644 index 000000000000..3d1ef44e3660 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.h @@ -0,0 +1,28 @@ +#pragma once + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMWordResult : NSObject + +@property (nonatomic, copy, readonly) NSString *word; +@property (nonatomic, assign, readonly) NSRange range; + ++ (instancetype)resultWithWord:(NSString *)word range:(NSRange)range; + +@end + +@interface ENRMWordsUtils : NSObject + +/// Returns the start index of the non-whitespace token that ends at [position]. +/// If [position] is directly after whitespace or at the start of text, returns [position]. ++ (NSUInteger)tokenStartInText:(NSString *)text beforePosition:(NSUInteger)position; + +/// Expands the modification range to word boundaries, then splits into +/// individual ENRMWordResult objects. ++ (NSArray *)getAffectedWordsFromText:(NSString *)text modificationRange:(NSRange)range; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.mm b/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.mm new file mode 100644 index 000000000000..9340f5745f75 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/ENRMWordsUtils.mm @@ -0,0 +1,88 @@ +#import "ENRMWordsUtils.h" + +@implementation ENRMWordResult + ++ (instancetype)resultWithWord:(NSString *)word range:(NSRange)range +{ + ENRMWordResult *result = [[ENRMWordResult alloc] init]; + result->_word = [word copy]; + result->_range = range; + return result; +} + +@end + +@implementation ENRMWordsUtils + ++ (NSUInteger)tokenStartInText:(NSString *)text beforePosition:(NSUInteger)position +{ + NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; + NSUInteger start = position; + while (start > 0) { + unichar previous = [text characterAtIndex:start - 1]; + if ([whitespace characterIsMember:previous]) { + break; + } + start--; + } + return start; +} + ++ (NSArray *)getAffectedWordsFromText:(NSString *)text modificationRange:(NSRange)range +{ + NSUInteger textLength = text.length; + if (textLength == 0) { + return @[]; + } + + NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; + NSCharacterSet *nonWhitespace = [whitespace invertedSet]; + + NSUInteger left = range.location; + if (left > 0) { + NSRange searchRange = NSMakeRange(0, left); + NSRange whitespaceHit = [text rangeOfCharacterFromSet:whitespace options:NSBackwardsSearch range:searchRange]; + left = (whitespaceHit.location != NSNotFound) ? NSMaxRange(whitespaceHit) : 0; + } + + NSUInteger right = MIN(range.location + range.length, textLength); + if (right < textLength) { + NSRange searchRange = NSMakeRange(right, textLength - right); + NSRange whitespaceHit = [text rangeOfCharacterFromSet:whitespace options:0 range:searchRange]; + right = (whitespaceHit.location != NSNotFound) ? whitespaceHit.location : textLength; + } + + if (left >= right) { + return @[]; + } + + NSMutableArray *results = [NSMutableArray array]; + + NSUInteger scanStart = left; + while (scanStart < right) { + NSRange scanRange = NSMakeRange(scanStart, right - scanStart); + NSRange wordStart = [text rangeOfCharacterFromSet:nonWhitespace options:0 range:scanRange]; + if (wordStart.location == NSNotFound) { + break; + } + + NSRange remaining = NSMakeRange(NSMaxRange(wordStart), right - NSMaxRange(wordStart)); + NSRange wordEnd; + if (remaining.length > 0) { + wordEnd = [text rangeOfCharacterFromSet:whitespace options:0 range:remaining]; + } else { + wordEnd.location = NSNotFound; + } + + NSUInteger wordEndPosition = (wordEnd.location != NSNotFound) ? wordEnd.location : right; + NSRange wordRange = NSMakeRange(wordStart.location, wordEndPosition - wordStart.location); + NSString *word = [text substringWithRange:wordRange]; + + [results addObject:[ENRMWordResult resultWithWord:word range:wordRange]]; + scanStart = wordEndPosition; + } + + return results; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+ContextMenu.mm b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+ContextMenu.mm new file mode 100644 index 000000000000..e86bf44e44a9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+ContextMenu.mm @@ -0,0 +1,175 @@ +#import "ContextMenuUtils.h" +#import "ENRMUIKit.h" +#import "EnrichedMarkdownTextInput+Internal.h" +#import "PasteboardUtils.h" + +@implementation EnrichedMarkdownTextInput (ContextMenu) + +- (void)copySelectedRangeAsMarkdown +{ + NSString *markdown = [self markdownForSelectedRange]; + if (markdown) { + copyStringToPasteboard(markdown); + } +} + +// TODO: Remove API_AVAILABLE(ios(16.0)) guard when the minimum iOS deployment target in RN is bumped to 16. +#if !TARGET_OS_OSX +- (UIMenu *)textView:(UITextView *)textView + editMenuForTextInRange:(NSRange)range + suggestedActions:(NSArray *)suggestedActions API_AVAILABLE(ios(16.0)) +{ + if (range.length == 0) { + return nil; + } + + ENRMInputSelectionMenuConfig menuConfig = [self inputSelectionMenuConfig]; + ENRMFormatMenuConfig fmtConfig = [self formatMenuConfig]; + __weak EnrichedMarkdownTextInput *weakSelf = self; + + const struct { + NSString *title; + NSString *icon; + ENRMInputStyleType styleType; + BOOL visible; + } formatItems[] = { + {fmtConfig.boldLabel, @"bold", ENRMInputStyleTypeStrong, fmtConfig.bold}, + {fmtConfig.italicLabel, @"italic", ENRMInputStyleTypeEmphasis, fmtConfig.italic}, + {fmtConfig.underlineLabel, @"underline", ENRMInputStyleTypeUnderline, fmtConfig.underline}, + {fmtConfig.strikethroughLabel, @"strikethrough", ENRMInputStyleTypeStrikethrough, fmtConfig.strikethrough}, + {fmtConfig.spoilerLabel, @"eye.slash", ENRMInputStyleTypeSpoiler, fmtConfig.spoiler}, + {fmtConfig.linkLabel, @"link", ENRMInputStyleTypeLink, fmtConfig.link}, + }; + const NSUInteger formatItemCount = sizeof(formatItems) / sizeof(formatItems[0]); + + NSMutableArray *formatActions = [NSMutableArray arrayWithCapacity:formatItemCount]; + for (NSUInteger i = 0; i < formatItemCount; i++) { + if (!formatItems[i].visible) { + continue; + } + ENRMInputStyleType styleType = formatItems[i].styleType; + UIAction *action = [UIAction actionWithTitle:formatItems[i].title + image:[UIImage systemImageNamed:formatItems[i].icon] + identifier:nil + handler:^(__kindof UIAction *_) { + if (styleType == ENRMInputStyleTypeLink) { + [weakSelf showLinkPrompt]; + } else { + [weakSelf toggleInlineStyle:styleType]; + } + }]; + [formatActions addObject:action]; + } + UIMenu *formatMenu = [UIMenu menuWithTitle:menuConfig.formatLabel + image:[UIImage systemImageNamed:@"textformat"] + identifier:@"com.enrichedmarkdown.format" + options:0 + children:formatActions]; + + UIAction *copyMarkdownAction = + [UIAction actionWithTitle:menuConfig.copyAsMarkdownLabel + image:[UIImage systemImageNamed:@"doc.text"] + identifier:@"com.enrichedmarkdown.copyMarkdown" + handler:^(__kindof UIAction *action) { [self copySelectedRangeAsMarkdown]; }]; + + NSArray *customItemTexts = [self contextMenuItemTexts]; + NSArray *customItemIcons = [self contextMenuItemIcons]; + NSMutableArray *allActions = [NSMutableArray arrayWithCapacity:customItemTexts.count]; + [customItemTexts enumerateObjectsUsingBlock:^(NSString *itemText, NSUInteger index, BOOL *_) { + NSString *iconName = index < customItemIcons.count ? customItemIcons[index] : nil; + UIImage *image = iconName.length > 0 ? [UIImage systemImageNamed:iconName] : nil; + UIAction *customAction = [UIAction + actionWithTitle:itemText + image:image + identifier:nil + handler:^(__kindof UIAction *_) { [weakSelf.inputEventEmitter emitContextMenuItemPress:itemText]; }]; + [allActions addObject:customAction]; + }]; + + NSUInteger insertIndex = suggestedActions.count; + NSMutableArray *systemActions = [suggestedActions mutableCopy]; + for (NSUInteger i = 0; i < systemActions.count; i++) { + if ([systemActions[i] isKindOfClass:[UIMenu class]]) { + insertIndex = i + 1; + break; + } + } + if (menuConfig.format) { + [systemActions insertObject:formatMenu atIndex:insertIndex]; + insertIndex++; + } + if (menuConfig.copyAsMarkdown) { + [systemActions insertObject:copyMarkdownAction atIndex:insertIndex]; + } + [allActions addObjectsFromArray:systemActions]; + + return [UIMenu menuWithChildren:allActions]; +} +#else +- (NSMenu *)enrichedMenuForEvent:(NSEvent *)event defaultMenu:(NSMenu *)menu textView:(NSTextView *)textView +{ + if (textView.selectedRange.length == 0) { + return menu; + } + + ENRMInputSelectionMenuConfig menuConfig = [self inputSelectionMenuConfig]; + ENRMFormatMenuConfig fmtConfig = [self formatMenuConfig]; + __weak EnrichedMarkdownTextInput *weakSelf = self; + NSArray *customItems = + ENRMBuildContextMenuItems([self contextMenuItemTexts], [self contextMenuItemIcons], textView, + ^(NSString *itemText, NSString *_, NSUInteger __, NSUInteger ___) { + [weakSelf.inputEventEmitter emitContextMenuItemPress:itemText]; + }); + ENRMPrependMenuItems(menu, customItems); + + [menu addItem:[NSMenuItem separatorItem]]; + + if (menuConfig.copyAsMarkdown) { + NSMenuItem *copyMarkdownItem = [[NSMenuItem alloc] initWithTitle:menuConfig.copyAsMarkdownLabel + action:@selector(copySelectedRangeAsMarkdown) + keyEquivalent:@""]; + copyMarkdownItem.target = self; + [menu addItem:copyMarkdownItem]; + } + + if (menuConfig.format) { + NSMenu *formatSubmenu = [[NSMenu alloc] initWithTitle:menuConfig.formatLabel]; + const struct { + NSString *title; + SEL action; + NSString *key; + NSEventModifierFlags modifiers; + BOOL visible; + } items[] = { + {fmtConfig.boldLabel, @selector(toggleBold), @"b", NSEventModifierFlagCommand, fmtConfig.bold}, + {fmtConfig.italicLabel, @selector(toggleItalic), @"i", NSEventModifierFlagCommand, fmtConfig.italic}, + {fmtConfig.underlineLabel, @selector(toggleUnderline), @"u", NSEventModifierFlagCommand, fmtConfig.underline}, + {fmtConfig.strikethroughLabel, @selector(toggleStrikethrough), @"", 0, fmtConfig.strikethrough}, + {fmtConfig.spoilerLabel, @selector(toggleSpoiler), @"", 0, fmtConfig.spoiler}, + {fmtConfig.linkLabel, @selector(showLinkPrompt), @"", 0, fmtConfig.link}, + }; + + for (NSUInteger i = 0; i < sizeof(items) / sizeof(items[0]); i++) { + if (!items[i].visible) { + continue; + } + NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:items[i].title + action:items[i].action + keyEquivalent:items[i].key]; + if (items[i].modifiers) { + item.keyEquivalentModifierMask = items[i].modifiers; + } + item.target = self; + [formatSubmenu addItem:item]; + } + + NSMenuItem *formatItem = [[NSMenuItem alloc] initWithTitle:menuConfig.formatLabel action:nil keyEquivalent:@""]; + formatItem.submenu = formatSubmenu; + [menu addItem:formatItem]; + } + + return menu; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+Internal.h b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+Internal.h new file mode 100644 index 000000000000..a8d35308136c --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput+Internal.h @@ -0,0 +1,64 @@ +#pragma once + +#import "ENRMInputEventEmitter.h" +#import "ENRMInputStyledRange.h" +#import "ENRMInputTypingAttributesController.h" +#import "EnrichedMarkdownTextInput.h" + +NS_ASSUME_NONNULL_BEGIN + +// The owner must keep these strings alive for the duration of the call (the +// view holds them in strong ivars). +typedef struct { + BOOL format; + __unsafe_unretained NSString *_Nullable formatLabel; + BOOL copyAsMarkdown; + __unsafe_unretained NSString *_Nullable copyAsMarkdownLabel; +} ENRMInputSelectionMenuConfig; + +typedef struct { + BOOL bold; + __unsafe_unretained NSString *_Nullable boldLabel; + BOOL italic; + __unsafe_unretained NSString *_Nullable italicLabel; + BOOL underline; + __unsafe_unretained NSString *_Nullable underlineLabel; + BOOL strikethrough; + __unsafe_unretained NSString *_Nullable strikethroughLabel; + BOOL spoiler; + __unsafe_unretained NSString *_Nullable spoilerLabel; + BOOL link; + __unsafe_unretained NSString *_Nullable linkLabel; +} ENRMFormatMenuConfig; + +@interface EnrichedMarkdownTextInput (Internal) + +@property (nonatomic, readonly) ENRMInputEventEmitter *inputEventEmitter; +@property (nonatomic, readonly) ENRMInputTypingAttributesController *typingController; + +- (void)toggleBold; +- (void)toggleItalic; +- (void)toggleUnderline; +- (void)toggleStrikethrough; +- (void)toggleSpoiler; +- (void)toggleInlineStyle:(ENRMInputStyleType)type; +- (void)toggleHeading:(NSInteger)level; +- (void)toggleUnorderedList; +- (void)toggleOrderedList; +- (void)indentList; +- (void)outdentList; +- (BOOL)handleBackspaceAtDocumentStart; +- (void)showLinkPrompt; + +- (NSArray *)contextMenuItemTexts; +- (NSArray *)contextMenuItemIcons; +- (ENRMInputSelectionMenuConfig)inputSelectionMenuConfig; +- (ENRMFormatMenuConfig)formatMenuConfig; + +#if TARGET_OS_OSX +- (NSMenu *)enrichedMenuForEvent:(NSEvent *)event defaultMenu:(NSMenu *)menu textView:(NSTextView *)textView; +#endif + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.h b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.h new file mode 100644 index 000000000000..231d841f677f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.h @@ -0,0 +1,23 @@ +#import "ENRMUIKit.h" +#import + +#ifndef EnrichedMarkdownTextInput_h +#define EnrichedMarkdownTextInput_h + +@class ENRMEditSession; + +NS_ASSUME_NONNULL_BEGIN + +@interface EnrichedMarkdownTextInput : RCTViewComponentView +@property (nonatomic, readonly) ENRMEditSession *editSession; +- (CGSize)measureSize:(CGFloat)maxWidth; +- (nullable NSString *)markdownForSelectedRange; +- (void)copyToClipboard; +- (void)pasteMarkdown:(NSString *)markdown; +- (void)replaceSelectedTextWith:(NSString *)text formattingRanges:(NSArray *)ranges; +- (void)scheduleRelayoutIfNeeded; +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.mm b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.mm new file mode 100644 index 000000000000..afcc22146a68 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/EnrichedMarkdownTextInput.mm @@ -0,0 +1,2169 @@ +#import "EnrichedMarkdownTextInput.h" +#import "ContextMenuUtils.h" +#import "ENRMAutoLinkDetector.h" +#import "ENRMBlockEditCoordinator.h" +#import "ENRMBlockHandler.h" +#import "ENRMBlockStore.h" +#import "ENRMClipboardCoordinator.h" +#import "ENRMDetectorPipeline.h" +#import "ENRMEditPipeline.h" +#import "ENRMEditSession.h" +#import "ENRMFormattingRange.h" +#import "ENRMFormattingStore.h" +#import "ENRMInputEventEmitter.h" +#import "ENRMInputFormatter.h" +#import "ENRMInputLayoutManager.h" +#import "ENRMInputLinkPrompt.h" +#import "ENRMInputListMarkerDrawer.h" +#import "ENRMInputParser.h" +#import "ENRMInputTextView.h" +#import "ENRMInputTypingAttributesController.h" +#import "ENRMLinkCoordinator.h" +#import "ENRMLinkRegexConfig.h" +#import "ENRMMarkdownShortcutMatcher.h" +#import "ENRMMentionCoordinator.h" +#import "ENRMStyleHandler.h" +#import "ENRMStyleMergingConfig.h" +#import "ENRMUIKit.h" +#import "ENRMViewFreeMeasurement.h" +#import "EnrichedMarkdownTextInput+Internal.h" +#import "InputStylePropsUtils.h" +#import "ParagraphStyleUtils.h" +#import "PasteboardUtils.h" +#import "SelectionColorUtils.h" +#import "StyleConfig.h" +#import +#import +#if TARGET_OS_OSX +#import +#endif + +#import +#import +#import +#import + +#import "EnrichedMarkdownTextInputShadowNode.h" +#import "HeightUpdateUtils.h" +#import "RCTFabricComponentsPlugins.h" +#import + +using namespace facebook::react; + +#if !TARGET_OS_OSX +@interface EnrichedMarkdownTextInput () +#else +@interface EnrichedMarkdownTextInput () +#endif +- (void)setupTextView; +- (void)applyFormatting; +- (void)applyFormattingScopedToEditAtLocation:(NSUInteger)editLocation insertedLength:(NSUInteger)insertedLength; +- (void)applyFormattingScopedFromParagraphAtLocation:(NSUInteger)editLocation; +- (void)toggleInlineStyle:(ENRMInputStyleType)styleType; +- (void)resetBaseTypingAttributes; +@end + +static const NSTimeInterval kENRMAtomicSnapPollInterval = 0.1; + +@implementation EnrichedMarkdownTextInput { + ENRMPlatformTextView *_textView; + ENRMInputLayoutManager *_layoutManager; + EnrichedMarkdownTextInputShadowNode::ConcreteState::Shared _state; + int _heightUpdateCounter; + ENRMInputFormatter *_formatter; + ENRMInputFormatterStyle *_formatterStyle; + ENRMFormattingStore *_formattingStore; + ENRMBlockStore *_blockStore; + ENRMInputTypingAttributesController *_typingController; + ENRMInputEventEmitter *_inputEventEmitter; + ENRMEditSession *_editSession; + + ENRMPlaceholderLabel *_placeholderLabel; + NSString *_placeholderText; + + NSUInteger _lastTextLength; + NSRange _lastSelectedRange; + NSRange _preEditSelectedRange; + BOOL _atomicSnapScheduled; + + // Block type/level of the line being edited, captured before a text change so + // a Return that continues a list (or an autocorrect/paste that replaces the + // line) can restore the right block on the resulting line(s). + ENRMInputBlockType _preEditBlockType; + NSInteger _preEditBlockLevel; + BOOL _preEditParagraphWasEmpty; + // Whether the replaced range contained a line break, captured before the edit + // applies (the deleted characters are gone afterwards). Drives the full-vs- + // scoped reformat decision in handleTextChanged. + BOOL _preEditReplacedNewline; + +#if TARGET_OS_OSX + NSScrollView *_scrollView; +#endif + + NSArray *_contextMenuItemTexts; + NSArray *_contextMenuItemIcons; + ENRMAutoLinkDetector *_autoLinkDetector; + ENRMDetectorPipeline *_detectorPipeline; + ENRMEditPipeline *_editPipeline; + ENRMBlockEditCoordinator *_blockCoordinator; + ENRMMentionCoordinator *_mentionCoordinator; + ENRMLinkCoordinator *_linkCoordinator; + ENRMClipboardCoordinator *_clipboardCoordinator; + + ENRMMarkdownShortcutsConfig _markdownShortcutsConfig; + ENRMWritingDirectionMode _writingDirectionMode; + NSWritingDirection _resolvedLayoutDirection; + + ENRMInputSelectionMenuConfig _inputSelectionMenuConfig; + ENRMFormatMenuConfig _formatMenuConfig; + + // Strong owners for the strings the two config structs above reference via + // `__unsafe_unretained` pointers. + NSString *_inputSelectionMenuFormatLabel; + NSString *_inputSelectionMenuCopyAsMarkdownLabel; + NSString *_formatMenuBoldLabel; + NSString *_formatMenuItalicLabel; + NSString *_formatMenuUnderlineLabel; + NSString *_formatMenuStrikethroughLabel; + NSString *_formatMenuSpoilerLabel; + NSString *_formatMenuLinkLabel; +} + +@synthesize editSession = _editSession; + +#pragma mark - Fabric lifecycle + ++ (ComponentDescriptorProvider)componentDescriptorProvider +{ + return concreteComponentDescriptorProvider(); +} + ++ (BOOL)shouldBeRecycled +{ + return NO; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + static const auto defaultProps = std::make_shared(); + _props = defaultProps; + + self.backgroundColor = [RCTUIColor clearColor]; + _heightUpdateCounter = 0; + _formatter = [[ENRMInputFormatter alloc] init]; + _formatterStyle = [[ENRMInputFormatterStyle alloc] init]; + _formattingStore = [[ENRMFormattingStore alloc] init]; + _blockStore = [[ENRMBlockStore alloc] init]; + _lastTextLength = 0; + _lastSelectedRange = NSMakeRange(0, 0); + _mentionCoordinator = [[ENRMMentionCoordinator alloc] initWithFormattingStore:_formattingStore]; + + _writingDirectionMode = ENRMWritingDirectionModeFirstStrong; + _resolvedLayoutDirection = + [[RCTI18nUtil sharedInstance] isRTL] ? NSWritingDirectionRightToLeft : NSWritingDirectionLeftToRight; + _inputSelectionMenuConfig = (ENRMInputSelectionMenuConfig){.format = YES, .copyAsMarkdown = YES}; + _formatMenuConfig = (ENRMFormatMenuConfig){ + .bold = YES, .italic = YES, .underline = YES, .strikethrough = YES, .spoiler = YES, .link = YES}; + + [self setupTextView]; + _editSession = [[ENRMEditSession alloc] initWithTextView:_textView]; + _typingController = [[ENRMInputTypingAttributesController alloc] initWithTextView:_textView + formatterStyle:_formatterStyle + dataSource:self + editSession:_editSession]; + _inputEventEmitter = [[ENRMInputEventEmitter alloc] initWithDataSource:self]; + + [self setupDetectorPipeline]; + + _editPipeline = [[ENRMEditPipeline alloc] initWithFormattingStore:_formattingStore + blockStore:_blockStore + formatter:_formatter + detectorPipeline:_detectorPipeline + host:self]; + _blockCoordinator = [[ENRMBlockEditCoordinator alloc] initWithBlockStore:_blockStore]; + _linkCoordinator = [[ENRMLinkCoordinator alloc] initWithFormattingStore:_formattingStore + autoLinkDetector:_autoLinkDetector]; + _clipboardCoordinator = [[ENRMClipboardCoordinator alloc] initWithFormattingStore:_formattingStore + blockStore:_blockStore + transientRangeProvider:_detectorPipeline + formatter:_formatter]; + } + return self; +} + +- (void)setupDetectorPipeline +{ + _autoLinkDetector = [[ENRMAutoLinkDetector alloc] initWithTextStorage:_textView.textStorage + formattingStore:_formattingStore + style:_formatterStyle]; + + __weak EnrichedMarkdownTextInput *weakSelf = self; + _autoLinkDetector.onLinkDetected = ^(NSString *text, NSString *url, NSRange range) { + EnrichedMarkdownTextInput *strongSelf = weakSelf; + if (strongSelf == nil) { + return; + } + [strongSelf->_inputEventEmitter emitOnLinkDetectedWithText:text url:url range:range]; + }; + + _detectorPipeline = [[ENRMDetectorPipeline alloc] init]; + [_detectorPipeline addDetector:_autoLinkDetector]; +} + +- (void)setupTextView +{ +#if !TARGET_OS_OSX + _layoutManager = [[ENRMInputLayoutManager alloc] init]; + _layoutManager.usesFontLeading = ENRMLayoutManagerUsesFontLeading; + NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(0, CGFLOAT_MAX)]; + textContainer.widthTracksTextView = YES; + [_layoutManager addTextContainer:textContainer]; + + NSTextStorage *textStorage = [[NSTextStorage alloc] init]; + [textStorage addLayoutManager:_layoutManager]; + + ENRMInputTextView *inputTextView = [[ENRMInputTextView alloc] initWithFrame:CGRectZero textContainer:textContainer]; +#else + ENRMInputTextView *inputTextView = [[ENRMInputTextView alloc] initWithFrame:CGRectZero]; + _layoutManager = [[ENRMInputLayoutManager alloc] init]; + _layoutManager.usesFontLeading = ENRMLayoutManagerUsesFontLeading; + [inputTextView.textContainer replaceLayoutManager:_layoutManager]; +#endif + inputTextView.markdownTextInput = self; + _textView = inputTextView; + ENRMConfigureMarkdownTextInputTextView(_textView); +#if !TARGET_OS_OSX + _textView.adjustsFontForContentSizeCategory = YES; + _textView.delegate = self; +#else + _textView.textInputDelegate = self; +#endif + +#if !TARGET_OS_OSX + self.contentView = _textView; +#else + _textView.selectable = YES; + + _scrollView = [[NSScrollView alloc] initWithFrame:CGRectZero]; + _scrollView.backgroundColor = [RCTUIColor clearColor]; + _scrollView.drawsBackground = NO; + _scrollView.borderType = NSNoBorder; + _scrollView.hasHorizontalRuler = NO; + _scrollView.hasVerticalRuler = NO; + _scrollView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + + _textView.verticallyResizable = YES; + _textView.horizontallyResizable = YES; + _textView.textContainer.containerSize = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX); + _textView.textContainer.widthTracksTextView = YES; + + _scrollView.documentView = _textView; + self.contentView = _scrollView; +#endif + + _placeholderLabel = ENRMCreatePlaceholderLabel(_textView, _formatterStyle.baseFont); +#if !TARGET_OS_OSX + _placeholderLabel.adjustsFontForContentSizeCategory = YES; + _placeholderLabel.accessibilityElementsHidden = YES; + _placeholderLabel.isAccessibilityElement = NO; +#endif + + [self resetBaseTypingAttributes]; +} + +#if !TARGET_OS_OSX +#pragma mark - Accessibility + +// The custom TextKit 1 stack leaves the inner UITextView invisible to VoiceOver, so +// the host vends the content itself as one readable element. +- (BOOL)isAccessibilityElement +{ + return YES; +} + +- (NSString *)accessibilityValue +{ + NSString *text = ENRMGetPlainText(_textView); + if (text.length > 0) { + return text; + } + if (_placeholderLabel.text.length > 0) { + return _placeholderLabel.text; + } + return [super accessibilityValue]; +} + +- (BOOL)accessibilityActivate +{ + ENRMFocusTextView(_textView); + [super accessibilityActivate]; + return YES; +} +#endif + +#pragma mark - State + +- (void)updateState:(const facebook::react::State::Shared &)state + oldState:(const facebook::react::State::Shared &)oldState +{ + _state = std::static_pointer_cast(state); + + if (oldState == nullptr) { + [self requestHeightUpdate]; + } +} + +- (void)requestHeightUpdate +{ + ENRMRequestHeightUpdate(_state, _heightUpdateCounter, self); +} + +/// Yoga-resolved direction inherited from any ancestor `direction` style. +/// In FirstStrong mode this feeds the neutral-paragraph fallback, so a change +/// requires re-resolving per-paragraph directions over the current text. +- (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics + oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics +{ + [super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics]; + + NSWritingDirection resolved = _resolvedLayoutDirection; + if (layoutMetrics.layoutDirection == LayoutDirection::RightToLeft) { + resolved = NSWritingDirectionRightToLeft; + } else if (layoutMetrics.layoutDirection == LayoutDirection::LeftToRight) { + resolved = NSWritingDirectionLeftToRight; + } + + if (resolved != _resolvedLayoutDirection) { + _resolvedLayoutDirection = resolved; + if (_writingDirectionMode == ENRMWritingDirectionModeFirstStrong && _textView.textStorage.length > 0) { + [self applyFormatting]; + } + } +} + +#pragma mark - Measurement + +- (CGSize)measureSize:(CGFloat)maxWidth +{ + NSMutableAttributedString *measuredText = + [[NSMutableAttributedString alloc] initWithAttributedString:ENRMGetAttributedText(_textView)]; + + // Empty input should still be the height of a single line. + // Use typingAttributes so the measurement matches the actual configured font. + if (measuredText.length == 0) { + [measuredText appendAttributedString:[[NSAttributedString alloc] initWithString:@"I" + attributes:_textView.typingAttributes]]; + } + + // Same TextKit path as the read-only view, with font leading off. The extra + // line fragment after a trailing newline is kept so that blank line counts + // toward the height, as in RN TextInput. + StyleConfig *config = [[StyleConfig alloc] init]; + CGSize size = ENRMMeasureAttributedTextViewFree(measuredText, maxWidth, config, NO, 0, RCTScreenScale(), 0, + NSLineBreakByWordWrapping, NO); + return CGSizeMake(maxWidth, size.height); +} + +#pragma mark - Props + +- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps +{ + const auto &oldViewProps = *std::static_pointer_cast(_props); + const auto &newViewProps = *std::static_pointer_cast(props); + + if (newViewProps.editable != oldViewProps.editable) { + _textView.editable = newViewProps.editable; + } + + // Copied unconditionally: the generated struct only has `operator==` under + // RN_SERIALIZABLE_STATE, and three BOOLs are cheaper than the comparison. + _markdownShortcutsConfig = (ENRMMarkdownShortcutsConfig){ + .heading = newViewProps.markdownShortcuts.heading, + .unorderedList = newViewProps.markdownShortcuts.unorderedList, + .orderedList = newViewProps.markdownShortcuts.orderedList, + }; + +#if !TARGET_OS_OSX + if (newViewProps.scrollEnabled != oldViewProps.scrollEnabled) { + _textView.scrollEnabled = newViewProps.scrollEnabled; + } + + if (newViewProps.autoCapitalize != oldViewProps.autoCapitalize) { + NSString *value = [NSString stringWithUTF8String:newViewProps.autoCapitalize.c_str()]; + _textView.autocapitalizationType = ENRMAutocapitalizationTypeFromString(value); + if ([_textView isFirstResponder]) { + [_textView resignFirstResponder]; + [_textView becomeFirstResponder]; + } + } + + if (newViewProps.multiline != oldViewProps.multiline) { + _textView.textContainer.maximumNumberOfLines = newViewProps.multiline ? 0 : 1; + _textView.textContainer.lineBreakMode = + newViewProps.multiline ? NSLineBreakByWordWrapping : NSLineBreakByTruncatingTail; + } +#endif + + if (newViewProps.placeholder != oldViewProps.placeholder) { + _placeholderText = [NSString stringWithUTF8String:newViewProps.placeholder.c_str()]; + [self updatePlaceholderText]; + } + + if (newViewProps.placeholderTextColor != oldViewProps.placeholderTextColor) { + if (isColorMeaningful(newViewProps.placeholderTextColor)) { + _placeholderLabel.textColor = RCTUIColorFromSharedColor(newViewProps.placeholderTextColor); + [self updatePlaceholderText]; + } + } + + if (newViewProps.cursorColor != oldViewProps.cursorColor) { + if (isColorMeaningful(newViewProps.cursorColor)) { + ENRMSetCursorColor(_textView, RCTUIColorFromSharedColor(newViewProps.cursorColor)); + } + } + + if (newViewProps.selectionColor != oldViewProps.selectionColor) { + ENRMApplySelectionColor(_textView, newViewProps.selectionColor); + } + + _inputEventEmitter.emitMarkdown = newViewProps.isOnChangeMarkdownSet; + + { + auto configFromProp = [](const auto &prop) { + return [[ENRMLinkRegexConfig alloc] initWithPattern:[NSString stringWithUTF8String:prop.pattern.c_str()] + caseInsensitive:prop.caseInsensitive + dotAll:prop.dotAll + isDisabled:prop.isDisabled + isDefault:prop.isDefault]; + }; + ENRMLinkRegexConfig *oldRegexConfig = configFromProp(oldViewProps.linkRegex); + ENRMLinkRegexConfig *newRegexConfig = configFromProp(newViewProps.linkRegex); + if (![newRegexConfig isEqualToConfig:oldRegexConfig]) { + [_autoLinkDetector setRegexConfig:newRegexConfig]; + } + } + + if (ENRMContextMenuItemsChanged(oldViewProps.contextMenuItems, newViewProps.contextMenuItems)) { + _contextMenuItemTexts = ENRMContextMenuTextsFromItems(newViewProps.contextMenuItems); + _contextMenuItemIcons = ENRMContextMenuIconsFromItems(newViewProps.contextMenuItems); + } + + // Coalesce against `initWithUTF8String:` returning nil on malformed UTF-8 — + // UIMenu / UIAction / NSMenuItem titles are _Nonnull and would crash. + _inputSelectionMenuFormatLabel = + [[NSString alloc] initWithUTF8String:newViewProps.selectionMenuConfig.formatLabel.c_str()] ?: @""; + _inputSelectionMenuCopyAsMarkdownLabel = + [[NSString alloc] initWithUTF8String:newViewProps.selectionMenuConfig.copyAsMarkdownLabel.c_str()] ?: @""; + _inputSelectionMenuConfig = (ENRMInputSelectionMenuConfig){ + .format = newViewProps.selectionMenuConfig.format, + .formatLabel = _inputSelectionMenuFormatLabel, + .copyAsMarkdown = newViewProps.selectionMenuConfig.copyAsMarkdown, + .copyAsMarkdownLabel = _inputSelectionMenuCopyAsMarkdownLabel, + }; + + _formatMenuBoldLabel = [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.boldLabel.c_str()] ?: @""; + _formatMenuItalicLabel = + [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.italicLabel.c_str()] ?: @""; + _formatMenuUnderlineLabel = + [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.underlineLabel.c_str()] ?: @""; + _formatMenuStrikethroughLabel = + [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.strikethroughLabel.c_str()] ?: @""; + _formatMenuSpoilerLabel = + [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.spoilerLabel.c_str()] ?: @""; + _formatMenuLinkLabel = [[NSString alloc] initWithUTF8String:newViewProps.formatMenuConfig.linkLabel.c_str()] ?: @""; + _formatMenuConfig = (ENRMFormatMenuConfig){ + .bold = newViewProps.formatMenuConfig.bold, + .boldLabel = _formatMenuBoldLabel, + .italic = newViewProps.formatMenuConfig.italic, + .italicLabel = _formatMenuItalicLabel, + .underline = newViewProps.formatMenuConfig.underline, + .underlineLabel = _formatMenuUnderlineLabel, + .strikethrough = newViewProps.formatMenuConfig.strikethrough, + .strikethroughLabel = _formatMenuStrikethroughLabel, + .spoiler = newViewProps.formatMenuConfig.spoiler, + .spoilerLabel = _formatMenuSpoilerLabel, + .link = newViewProps.formatMenuConfig.link, + .linkLabel = _formatMenuLinkLabel, + }; + + if (newViewProps.mentionIndicators != oldViewProps.mentionIndicators) { + NSMutableArray *indicators = [NSMutableArray array]; + for (const auto &indicator : newViewProps.mentionIndicators) { + NSString *value = [NSString stringWithUTF8String:indicator.c_str()]; + if (value.length > 0) { + [indicators addObject:value]; + } + } + [self dispatchMentionEvents:[_mentionCoordinator setIndicators:indicators]]; + [self dispatchMentionUpdate]; + } + + BOOL styleChanged = applyInputStyleProps(_formatterStyle, newViewProps, oldViewProps); + + BOOL writingDirectionChanged = NO; + if (newViewProps.writingDirection != oldViewProps.writingDirection) { + NSString *value = [[NSString alloc] initWithUTF8String:newViewProps.writingDirection.c_str()]; + _writingDirectionMode = ENRMResolveWritingDirectionMode(value); + writingDirectionChanged = YES; + } + + if (newViewProps.defaultValue != oldViewProps.defaultValue) { + if (!newViewProps.defaultValue.empty() && oldViewProps.defaultValue.empty()) { + NSString *markdown = [NSString stringWithUTF8String:newViewProps.defaultValue.c_str()]; + [self importMarkdown:markdown]; + } + } + + if (styleChanged) { + [self updatePlaceholderText]; + + [self resetBaseTypingAttributes]; + [self applyFormatting]; + [self requestHeightUpdate]; + } else if (writingDirectionChanged && _textView.textStorage.length > 0) { + [self applyFormatting]; + } + + [super updateProps:props oldProps:oldProps]; +} + +#pragma mark - Relayout + +- (void)scheduleRelayoutIfNeeded +{ + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_performRelayout) object:nil]; + [self performSelector:@selector(_performRelayout) withObject:nil afterDelay:0]; +} + +- (void)_performRelayout +{ + if (!_textView) { + return; + } + + NSUInteger textLength = _textView.textStorage.length; + if (textLength == 0) { + return; + } + + NSRange wholeRange = NSMakeRange(0, textLength); + [_textView.layoutManager invalidateLayoutForCharacterRange:wholeRange actualCharacterRange:NULL]; + [_textView.layoutManager ensureLayoutForTextContainer:_textView.textContainer]; + [_textView.layoutManager invalidateDisplayForCharacterRange:wholeRange]; + + CGSize measuredSize = [self measureSize:_textView.frame.size.width]; + CGSize currentSize = _textView.contentSize; + BOOL sizeChanged = + fabs(currentSize.width - measuredSize.width) > 0.5 || fabs(currentSize.height - measuredSize.height) > 0.5; + if (sizeChanged) { + ENRMSetContentSize(_textView, measuredSize); + } +} + +#pragma mark - Window attachment + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + + if (self.window) { + // Don't override the contentView frame set by RCTViewComponentView. + ENRMRefreshTextViewLayout(_textView); + + [self applyFormatting]; + [self updatePlaceholderVisibility]; + [self requestHeightUpdate]; + + const auto &viewProps = *std::static_pointer_cast(_props); + if (viewProps.autoFocus) { + ENRMFocusTextView(_textView); + } + } +} + +#if TARGET_OS_OSX + +#pragma mark - macOS responder chain + +- (BOOL)acceptsFirstResponder +{ + return _textView.acceptsFirstResponder; +} + +- (BOOL)becomeFirstResponder +{ + return [self.window makeFirstResponder:_textView]; +} + +- (BOOL)needsPanelToBecomeKey +{ + return YES; +} + +- (BOOL)mouseDownCanMoveWindow +{ + return NO; +} + +- (void)mouseDown:(NSEvent *)event +{ + [self.window makeFirstResponder:_textView]; + [_textView mouseDown:event]; +} + +#endif + +#if !TARGET_OS_OSX +- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection +{ + [super traitCollectionDidChange:previousTraitCollection]; + + if (previousTraitCollection.preferredContentSizeCategory != self.traitCollection.preferredContentSizeCategory) { + [_formatterStyle invalidateFontCache]; + + [self resetBaseTypingAttributes]; + + [self updatePlaceholderText]; + + [self applyFormatting]; + [self requestHeightUpdate]; + } +} +#endif + +#pragma mark - ENRMEditPipelineHost + +- (NSString *)plainText +{ + return ENRMGetPlainText(_textView); +} + +- (NSTextStorage *)textStorage +{ + return _textView.textStorage; +} + +#pragma mark - Placeholder + +/// Lays the placeholder out like a body paragraph: base font, and the body line +/// height with the same baseline centering the formatter applies to typed text. +- (void)updatePlaceholderText +{ + NSMutableDictionary *attrs = [@{ + NSFontAttributeName : _formatterStyle.baseFont, + NSForegroundColorAttributeName : _placeholderLabel.textColor, + } mutableCopy]; + if (_formatterStyle.baseLineHeight > 0) { + attrs[NSParagraphStyleAttributeName] = ENRMInputParagraphStyleWithLineHeight(_formatterStyle, nil); + } + NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_placeholderText ?: @"" + attributes:attrs]; + NSRange fullRange = NSMakeRange(0, text.length); + CGFloat baselineOffset = calculateBaselineOffset(text, fullRange); + if (baselineOffset > 0) { + [text addAttribute:NSBaselineOffsetAttributeName value:@(baselineOffset) range:fullRange]; + } + ENRMSetPlaceholderAttributedText(_placeholderLabel, text); +} + +- (void)updatePlaceholderVisibility +{ + // Hide the placeholder once there's any content OR any block has been started + // (e.g. an empty bullet/heading line with only a zero-length anchor): the block + // marker or indent would otherwise overlap the placeholder text. + BOOL hasText = ENRMGetPlainText(_textView).length > 0; + BOOL hasBlock = _blockStore.allRanges.count > 0; + _placeholderLabel.hidden = hasText || hasBlock; +} + +#pragma mark - Markdown import + +- (void)importMarkdown:(NSString *)markdown +{ + ENRMInputParser *parser = [[ENRMInputParser alloc] init]; + ENRMParseResult *parsed = [parser parseToPlainTextAndRanges:markdown]; + + [_editSession enterPhase:ENRMEditPhaseImporting]; + + [_editSession enterPhase:ENRMEditPhaseFormatting]; + // UITextView stamps typingAttributes (including list headIndent from the + // previous cursor) onto all text set via .text. Reset before import so + // setValue does not indent non-list lines with the old list depth. + [self resetBaseTypingAttributes]; + ENRMSetPlainText(_textView, parsed.plainText); + [_editSession enterPhase:ENRMEditPhaseImporting]; + + [_formattingStore setRanges:parsed.formattingRanges]; + [_blockStore setRanges:parsed.blockRanges]; + _lastTextLength = parsed.plainText.length; + _lastSelectedRange = _textView.selectedRange; + + [_editSession exitPhase]; + [self applyFormatting]; + [self updatePlaceholderVisibility]; + + if (parsed.plainText.length == 0) { + [self resetBaseTypingAttributes]; + } +} + +- (void)replaceTextInRange:(NSRange)selection + withText:(NSString *)text + formattingRanges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges +{ + NSUInteger editLocation = selection.location; + + [_editSession enterPhase:ENRMEditPhaseFormatting]; + ENRMReplaceTextInRange(_textView, text, selection); + [_editSession exitPhase]; + + NSString *plainText = [self adjustStoresForEditAtLocation:editLocation + deletedLength:selection.length + insertedLength:text.length]; + + for (ENRMFormattingRange *range in ranges) { + NSRange shifted = NSMakeRange(range.range.location + editLocation, range.range.length); + [_formattingStore addRange:[ENRMFormattingRange rangeWithType:range.type range:shifted url:range.url]]; + } + + for (ENRMBlockRange *block in blockRanges) { + NSRange shifted = NSMakeRange(block.range.location + editLocation, block.range.length); + [_blockStore setBlockType:block.type level:block.level forParagraphRange:shifted inText:plainText]; + } + + _lastTextLength = plainText.length; + _lastSelectedRange = _textView.selectedRange; + + [self applyFormatting]; + + [_detectorPipeline processTextChange:plainText modificationRange:NSMakeRange(editLocation, text.length)]; + + [self updatePlaceholderVisibility]; + [_inputEventEmitter emitOnChangeText]; + [_inputEventEmitter emitOnChangeSelection]; + [_inputEventEmitter emitFormattingChanged]; + [self requestHeightUpdate]; + [self scheduleRelayoutIfNeeded]; +} + +- (void)replaceTextInRange:(NSRange)selection + withText:(NSString *)text + formattingRanges:(NSArray *)ranges +{ + [self replaceTextInRange:selection withText:text formattingRanges:ranges blockRanges:@[]]; +} + +- (void)replaceSelectedTextWith:(NSString *)text formattingRanges:(NSArray *)ranges +{ + [self replaceTextInRange:_textView.selectedRange withText:text formattingRanges:ranges]; +} + +/// Insertion is literal: the string's characters land at the cursor exactly as +/// given. Markdown parsing consumes leading and trailing newlines as block +/// structure, so they are split off before the parse and re-attached verbatim; +/// without this, inserting "\n- item\n" mid-paragraph would merge the list line +/// with the surrounding text. Callers decide separation by including (or +/// omitting) newlines in the string. +- (void)pasteMarkdown:(NSString *)markdown +{ + NSUInteger lead = 0; + while (lead < markdown.length && [markdown characterAtIndex:lead] == '\n') { + lead++; + } + NSUInteger trail = 0; + while (lead + trail < markdown.length && [markdown characterAtIndex:markdown.length - 1 - trail] == '\n') { + trail++; + } + NSString *core = [markdown substringWithRange:NSMakeRange(lead, markdown.length - lead - trail)]; + + ENRMInputParser *parser = [[ENRMInputParser alloc] init]; + ENRMParseResult *parsed = [parser parseToPlainTextAndRanges:core]; + + if (lead == 0 && trail == 0) { + [self replaceTextInRange:_textView.selectedRange + withText:parsed.plainText + formattingRanges:parsed.formattingRanges + blockRanges:parsed.blockRanges]; + return; + } + + NSString *prefix = [@"" stringByPaddingToLength:lead withString:@"\n" startingAtIndex:0]; + NSString *suffix = [@"" stringByPaddingToLength:trail withString:@"\n" startingAtIndex:0]; + NSString *plainText = [NSString stringWithFormat:@"%@%@%@", prefix, parsed.plainText, suffix]; + + NSMutableArray *formattingRanges = + [NSMutableArray arrayWithCapacity:parsed.formattingRanges.count]; + for (ENRMFormattingRange *range in parsed.formattingRanges) { + NSRange shifted = NSMakeRange(range.range.location + lead, range.range.length); + [formattingRanges addObject:[ENRMFormattingRange rangeWithType:range.type range:shifted url:range.url]]; + } + NSMutableArray *blockRanges = [NSMutableArray arrayWithCapacity:parsed.blockRanges.count]; + for (ENRMBlockRange *block in parsed.blockRanges) { + NSRange shifted = NSMakeRange(block.range.location + lead, block.range.length); + [blockRanges addObject:[ENRMBlockRange rangeWithType:block.type range:shifted level:block.level]]; + } + [self replaceTextInRange:_textView.selectedRange + withText:plainText + formattingRanges:formattingRanges + blockRanges:blockRanges]; +} + +#pragma mark - Formatting + +- (void)resetBaseTypingAttributes +{ + NSMutableDictionary *attrs = [@{ + NSFontAttributeName : _formatterStyle.baseFont, + NSForegroundColorAttributeName : _formatterStyle.baseTextColor, + } mutableCopy]; + if (_formatterStyle.baseLineHeight > 0) { + attrs[NSParagraphStyleAttributeName] = ENRMInputParagraphStyleWithLineHeight(_formatterStyle, nil); + } + ENRMSetDefaultTypingAttributes(_textView, attrs); +} + +- (void)applyFormatting +{ + [self applyFormattingScopedToRange:NSMakeRange(0, ENRMGetPlainText(_textView).length)]; +} + +/// Per-keystroke variant: re-applies inline and block attributes only on the +/// line(s) touched by the edit, mirroring Android's applyFormattingScopedToEdit. +- (void)applyFormattingScopedToEditAtLocation:(NSUInteger)editLocation insertedLength:(NSUInteger)insertedLength +{ + NSString *plainText = ENRMGetPlainText(_textView); + NSUInteger textLength = plainText.length; + if (textLength == 0) { + [self applyFormatting]; + return; + } + + NSUInteger rawStart = MIN(editLocation, textLength); + NSUInteger rawEnd = MIN(editLocation + insertedLength, textLength); + rawEnd = MAX(rawEnd, rawStart); + NSRange scope = [plainText lineRangeForRange:NSMakeRange(rawStart, rawEnd - rawStart)]; + [self applyFormattingScopedToRange:scope]; +} + +/// Newline variant: a newline can only restructure the paragraph it lands in and +/// blocks below it, never content above. Scoping from the edit's paragraph start +/// to the end of the text leaves paragraphs above untouched (issue #739). A +/// backspace-merge is covered because editLocation lands at the merge point, +/// whose paragraph range extends back over the joined previous line. +- (void)applyFormattingScopedFromParagraphAtLocation:(NSUInteger)editLocation +{ + NSString *plainText = ENRMGetPlainText(_textView); + NSUInteger textLength = plainText.length; + if (textLength == 0) { + [self applyFormatting]; + return; + } + + NSUInteger location = MIN(editLocation, textLength); + NSRange paragraph = [plainText paragraphRangeForRange:NSMakeRange(location, 0)]; + NSRange scope = NSMakeRange(paragraph.location, textLength - paragraph.location); + [self applyFormattingScopedToRange:scope]; +} + +- (void)applyFormattingScopedToRange:(NSRange)scope +{ + if (_editSession.shouldSuppressFormatting) { + return; + } + if (_editSession.isComposing) { + return; + } + [_editSession enterPhase:ENRMEditPhaseFormatting]; + + NSRange savedSelection = _textView.selectedRange; + + [_formatter applyFormattingRanges:_formattingStore.allRanges + toTextView:_textView + style:_formatterStyle + scopedToRange:scope]; + [_formatter applyBlockRanges:_blockStore.allRanges toTextView:_textView style:_formatterStyle scopedToRange:scope]; + [_detectorPipeline refreshAllStyling]; + [self applyWritingDirection]; + + NSUInteger textLen = ENRMGetPlainText(_textView).length; + if (savedSelection.location + savedSelection.length <= textLen) { + _textView.selectedRange = savedSelection; + } + + [_editSession exitPhase]; +} + +- (void)applyWritingDirection +{ + NSTextStorage *textStorage = _textView.textStorage; + if (textStorage.length == 0) { + return; + } + [textStorage beginEditing]; + ENRMApplyWritingDirectionMode(textStorage, _writingDirectionMode, _resolvedLayoutDirection); + [textStorage endEditing]; +} + +#pragma mark - Commands + +- (void)focus +{ + ENRMFocusTextView(_textView); +} + +- (void)blur +{ + ENRMBlurTextView(_textView); +} + +- (void)setValue:(NSString *)markdown +{ + [self importMarkdown:markdown]; + _lastSelectedRange = _textView.selectedRange; + [_inputEventEmitter emitOnChangeText]; + [_inputEventEmitter emitOnChangeSelection]; + [_inputEventEmitter emitOnChangeState]; + [self requestHeightUpdate]; +} + +- (void)setSelection:(NSInteger)start end:(NSInteger)end +{ + NSInteger textLen = (NSInteger)ENRMGetPlainText(_textView).length; + NSInteger clampedStart = MIN(MAX(start, 0), textLen); + NSInteger clampedEnd = MIN(MAX(end, clampedStart), textLen); + _textView.selectedRange = NSMakeRange((NSUInteger)clampedStart, (NSUInteger)(clampedEnd - clampedStart)); + [_inputEventEmitter emitOnChangeSelection]; + [_inputEventEmitter emitOnChangeState]; +} + +- (void)toggleBold +{ + [self toggleInlineStyle:ENRMInputStyleTypeStrong]; +} + +- (void)toggleItalic +{ + [self toggleInlineStyle:ENRMInputStyleTypeEmphasis]; +} + +- (void)toggleUnderline +{ + [self toggleInlineStyle:ENRMInputStyleTypeUnderline]; +} + +- (void)toggleStrikethrough +{ + [self toggleInlineStyle:ENRMInputStyleTypeStrikethrough]; +} + +- (void)toggleSpoiler +{ + [self toggleInlineStyle:ENRMInputStyleTypeSpoiler]; +} + +- (void)toggleInlineStyle:(ENRMInputStyleType)styleType +{ + id handler = [_formatter handlerForStyleType:styleType]; + if (!handler) { + return; + } + ENRMStyleMergingConfig *mergingConfig = handler.mergingConfig; + + NSRange selection = _textView.selectedRange; + + if ([_formattingStore isToggleBlocked:styleType + atPosition:selection.location + blockingStyles:mergingConfig.blockingStyles]) { + return; + } + + BOOL wasActive = [_formattingStore toggleStyle:styleType + inRange:selection + conflictingStyles:mergingConfig.conflictingStyles]; + + [_typingController togglePendingStyle:styleType wasActive:wasActive hasSelection:(selection.length > 0)]; + + [self applyFormatting]; + [_typingController syncWithPendingStyles]; + [_inputEventEmitter emitFormattingChanged]; +} + +- (void)toggleHeading:(NSInteger)level +{ + if (level < 1 || level > 6) { + return; + } + [self toggleBlockType:ENRMBlockTypeForHeadingLevel(level) level:level]; +} + +- (void)toggleBlockType:(ENRMInputBlockType)type level:(NSInteger)level +{ + NSString *text = ENRMGetPlainText(_textView); + BOOL alreadyActive = [_blockCoordinator toggleBlockType:type + level:level + selectionRange:_textView.selectedRange + inText:text]; + + if (alreadyActive) { + // Strip the stored block paragraph style directly: an empty item's line has no + // stamped block-marker attribute (zero-length ranges are never stamped), so the + // applyFormatting reset below — which is keyed off that marker — cannot reach it. + NSRange paragraphRange = [text paragraphRangeForRange:_textView.selectedRange]; + NSTextStorage *storage = _textView.textStorage; + NSRange clamped = NSIntersectionRange(paragraphRange, NSMakeRange(0, storage.length)); + if (clamped.length > 0) { + [storage beginEditing]; + [storage removeAttribute:NSParagraphStyleAttributeName range:clamped]; + [storage endEditing]; + } + } + + [self applyFormatting]; + [_typingController syncWithCursorBlock]; + [self updatePlaceholderVisibility]; + if (alreadyActive) { + [_typingController clearListParagraphStyle]; + } + [self updateEmptyBulletMarker]; + [_inputEventEmitter emitFormattingChanged]; +} + +- (void)toggleUnorderedList +{ + [self toggleBlockType:ENRMInputBlockTypeUnorderedListItem level:0]; +} + +- (void)toggleOrderedList +{ + [self toggleBlockType:ENRMInputBlockTypeOrderedListItem level:0]; +} + +- (void)indentList +{ + [self changeListDepthBy:1]; +} + +- (void)outdentList +{ + [self changeListDepthBy:-1]; +} + +- (void)changeListDepthBy:(NSInteger)delta +{ + NSString *text = ENRMGetPlainText(_textView); + ENRMDepthChangeResult result = [_blockCoordinator changeDepthBy:delta + cursorPosition:_textView.selectedRange.location + selectionRange:_textView.selectedRange + inText:text]; + if (result == ENRMDepthChangeResultNoOp) { + return; + } + [self applyFormatting]; + [_typingController syncWithCursorBlock]; + [self updateEmptyBulletMarker]; + [_inputEventEmitter emitFormattingChanged]; +} + +- (nullable ENRMBlockRange *)listBlockForCursorParagraph +{ + return [self listBlockForParagraphAtPosition:_textView.selectedRange.location]; +} + +- (nullable ENRMBlockRange *)listBlockForParagraphAtPosition:(NSUInteger)position +{ + return [_blockCoordinator listBlockAtPosition:position inText:_textView.textStorage.string]; +} + +- (nullable ENRMBlockRange *)blockForParagraphAtPosition:(NSUInteger)position +{ + return [_blockCoordinator blockAtPosition:position inText:_textView.textStorage.string]; +} + +- (BOOL)listStateOfType:(ENRMInputBlockType)type forCursorParagraphDepth:(nullable NSInteger *)outDepth +{ + return [_blockCoordinator listStateOfType:type + atPosition:_textView.selectedRange.location + inText:_textView.textStorage.string + depth:outDepth]; +} + +/// Records the block kind/level of the line being edited before the change, so a +/// Return that continues a list can recover the previous item's depth and an +/// in-line replacement (autocorrect/paste) that wipes the line can heal it. +- (void)capturePreEditBlockForRange:(NSRange)range +{ + ENRMBlockRange *block = [self blockForParagraphAtPosition:range.location]; + _preEditBlockType = block != nil ? block.type : ENRMInputBlockTypeParagraph; + _preEditBlockLevel = block != nil ? block.level : 0; +} + +/// Whether `range` of the current (pre-edit) text contains a line break. Scans +/// only the replaced run, mirroring Android's editTouchedNewline. +- (BOOL)replacedRangeTouchesNewline:(NSRange)range +{ + NSString *text = _textView.textStorage.string; + if (range.length == 0 || range.location >= text.length) { + return NO; + } + NSRange clamped = NSMakeRange(range.location, MIN(range.length, text.length - range.location)); + return [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet] options:0 range:clamped].location != + NSNotFound; +} + +/// Whether the caret's paragraph had no glyph content at the start of the edit +/// (an empty line). Used to decide whether Return continues or exits the list. +- (BOOL)preEditParagraphWasEmpty:(NSRange)range +{ + NSString *text = _textView.textStorage.string; + if (text.length == 0) { + return YES; + } + NSRange paragraph = [text paragraphRangeForRange:range]; + if (paragraph.length == 0) { + return YES; + } + return [[text substringWithRange:paragraph] isEqualToString:@"\n"]; +} + +/// Intercepts Tab (indent) and Backspace at a bullet item's start (outdent, then +/// un-list at depth 0). Returns YES when handled, suppressing the default edit. +/// Keyed off the caret's own paragraph (NSMaxRange(range)), not range.location — +/// a backspace at a line start targets the previous line's newline, and using the +/// caret's line lets the next Backspace after un-listing fall through to a merge. +- (BOOL)handleListKeyForReplacementRange:(NSRange)range replacementText:(NSString *)text +{ + NSUInteger caret = NSMaxRange(range); + NSInteger depth; + if (![self listStateForParagraphAtPosition:caret depth:&depth]) { + return NO; + } + + // Tab indents the current item. + if ([text isEqualToString:@"\t"]) { + [self indentList]; + return YES; + } + + // Backspace at the very start of the caret's own item: outdent, or remove the + // marker entirely once at depth 0 (de-indenting the line to a plain paragraph). + if (text.length == 0 && range.length == 1) { + NSString *plainText = ENRMGetPlainText(_textView); + NSRange paragraphRange = [plainText paragraphRangeForRange:NSMakeRange(caret, 0)]; + BOOL atItemStart = caret == paragraphRange.location; + if (atItemStart) { + if (depth > 0) { + [self outdentList]; + } else { + ENRMBlockRange *listBlock = [self listBlockForParagraphAtPosition:caret]; + [self toggleBlockType:listBlock != nil ? listBlock.type : ENRMInputBlockTypeUnorderedListItem level:0]; + } + return YES; + } + } + + return NO; +} + +/// Backspace at the document start (caret at 0) never fires the text-change +/// delegate — nothing precedes the caret — so the first line's bullet has to be +/// outdented/removed here. Returns YES when handled. +- (BOOL)handleBackspaceAtDocumentStart +{ + NSRange selection = _textView.selectedRange; + if (selection.location != 0 || selection.length != 0) { + return NO; + } + ENRMBlockRange *listBlock = [self listBlockForCursorParagraph]; + if (listBlock == nil) { + return NO; + } + if (listBlock.level > 0) { + [self outdentList]; + } else { + [self toggleBlockType:listBlock.type level:0]; + } + return YES; +} + +- (BOOL)listStateForParagraphAtPosition:(NSUInteger)position depth:(NSInteger *)outDepth +{ + ENRMBlockRange *block = [_blockCoordinator listBlockAtPosition:position inText:_textView.textStorage.string]; + if (block != nil) { + if (outDepth) { + *outDepth = block.level; + } + return YES; + } + return NO; +} + +/// Drives the layout manager's empty-line bullet: an empty bullet line has no +/// character to anchor the marker to, so the manager is told its location/depth +/// explicitly; cleared when the caret isn't on an empty bullet line. Runs on +/// every selection-change fire, so it early-returns when there is nothing to +/// draw or clear and only touches storage when the paragraph style differs, +/// avoiding layout churn that jitters the edit menu. +- (void)updateEmptyBulletMarker +{ + NSString *text = ENRMGetPlainText(_textView); + NSRange selection = _textView.selectedRange; + BOOL show = NO; + NSUInteger location = 0; + NSInteger depth = 0; + + BOOL ordered = NO; + NSInteger ordinal = 1; + ENRMBlockRange *cursorListBlock = selection.length == 0 ? [self listBlockForCursorParagraph] : nil; + + ENRMInputListMarkerDrawer *listDrawer = _layoutManager.listMarkerDrawer; + BOOL wasShown = listDrawer.emptyBulletDepth >= 0; + if (cursorListBlock == nil && !wasShown) { + return; + } + + if (cursorListBlock != nil) { + NSInteger cursorDepth = cursorListBlock.level; + ordered = cursorListBlock.type == ENRMInputBlockTypeOrderedListItem; + ordinal = cursorListBlock.ordinal; + NSRange paragraphRange = text.length == 0 ? NSMakeRange(0, 0) : [text paragraphRangeForRange:selection]; + NSString *paragraphText = text.length == 0 ? @"" : [text substringWithRange:paragraphRange]; + BOOL empty = paragraphText.length == 0 || [paragraphText isEqualToString:@"\n"]; + if (empty) { + show = YES; + location = paragraphRange.location; + depth = cursorDepth; + + // A mid-document empty bullet line has no paragraph style and lays out + // flush left; stamp the list style so caret and marker indent immediately. + // (A trailing empty line uses the extra line fragment instead.) + if (paragraphRange.length > 0) { + CGFloat indent = (depth + 1) * kENRMListIndentPerDepth; + NSTextStorage *storage = _textView.textStorage; + NSParagraphStyle *existing = [storage attribute:NSParagraphStyleAttributeName + atIndex:paragraphRange.location + effectiveRange:NULL]; + if (existing == nil || existing.firstLineHeadIndent != indent || existing.headIndent != indent || + existing.paragraphSpacingBefore != _formatterStyle.listItemSpacing) { + NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; + paragraph.firstLineHeadIndent = indent; + paragraph.headIndent = indent; + paragraph.paragraphSpacingBefore = _formatterStyle.listItemSpacing; + [storage beginEditing]; + [storage addAttribute:NSParagraphStyleAttributeName value:paragraph range:paragraphRange]; + [storage endEditing]; + } + } + } + } + + if (!show && !wasShown) { + return; + } + + listDrawer.emptyBulletDepth = show ? depth : -1; + listDrawer.emptyBulletOrdered = ordered; + listDrawer.emptyBulletOrdinal = ordinal; + listDrawer.emptyBulletLocation = location; + listDrawer.emptyBulletFont = _formatterStyle.baseFont; + listDrawer.emptyBulletColor = _formatterStyle.baseTextColor; + listDrawer.emptyBulletRTL = [self emptyListLineIsRTL]; + listDrawer.listItemSpacing = _formatterStyle.listItemSpacing; + + BOOL isTrailing = show && text.length > 0 && location >= text.length; + + // Ensure the extra line fragment is laid out so we can read + // extraLineFragmentTextContainer / extraLineFragmentUsedRect. The + // empty-editor case (length 0) has no glyphs at all; the trailing-line case + // (location >= length) has glyphs on preceding lines but the extra line + // fragment lives beyond them and isn't covered by ensureLayoutForCharRange:. + if (show && (text.length == 0 || location >= text.length)) { + [_layoutManager ensureLayoutForTextContainer:_textView.textContainer]; + } + +#if !TARGET_OS_OSX + if (isTrailing && _layoutManager.extraLineFragmentTextContainer != nil) { + [listDrawer showTrailingBulletInTextView:_textView + textContainer:_layoutManager.extraLineFragmentTextContainer + usedRect:_layoutManager.extraLineFragmentUsedRect]; + } else { + [listDrawer hideTrailingBullet]; + } +#endif + + ENRMSetNeedsDisplay(_textView); + + // The empty-editor bullet would otherwise overlap the placeholder. + [self updatePlaceholderVisibility]; +} + +/// Writing direction the empty list line resolves to, for mirroring its marker. +/// An empty line has no strong character, so Auto and FirstStrong fall back the +/// same way the formatter's direction pass would. +- (BOOL)emptyListLineIsRTL +{ + switch (_writingDirectionMode) { + case ENRMWritingDirectionModeLTR: + return NO; + case ENRMWritingDirectionModeRTL: + return YES; + case ENRMWritingDirectionModeFirstStrong: + return _resolvedLayoutDirection == NSWritingDirectionRightToLeft; + case ENRMWritingDirectionModeAuto: + default: + return ENRMParagraphIsRTL(nil); + } +} + +- (NSInteger)headingLevelForCursorParagraph +{ + return [_blockCoordinator headingLevelAtPosition:_textView.selectedRange.location + inText:_textView.textStorage.string]; +} + +- (NSString *)adjustStoresForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength +{ + return [_editPipeline adjustStoresForEditAtLocation:editLocation + deletedLength:deletedLength + insertedLength:insertedLength]; +} + +- (void)setLink:(NSString *)url +{ + NSRange selection = _textView.selectedRange; + if (![_linkCoordinator setLinkURL:url forSelection:selection]) { + return; + } + [self applyFormatting]; + [_inputEventEmitter emitFormattingChanged]; +} + +- (void)insertLink:(NSString *)text url:(NSString *)url +{ + NSString *displayText = text.length > 0 ? text : url; + NSRange linkRange = NSMakeRange(0, displayText.length); + ENRMFormattingRange *range = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink + range:linkRange + url:[_linkCoordinator sanitizeURL:url]]; + [self replaceSelectedTextWith:displayText formattingRanges:@[ range ]]; +} + +- (void)insertText:(NSString *)text +{ + if (text.length == 0) { + return; + } + [self pasteMarkdown:text]; +} + +- (void)startMention:(NSString *)indicator +{ + if (indicator.length == 0 || ![_mentionCoordinator containsIndicator:indicator]) { + return; + } + + [self replaceSelectedTextWith:indicator formattingRanges:@[]]; + [self dispatchMentionUpdate]; +} + +- (void)insertMention:(NSString *)displayText url:(NSString *)url +{ + if (displayText.length == 0 || !_mentionCoordinator.isActive || + _mentionCoordinator.activeRange.location == NSNotFound) { + return; + } + + NSString *plainText = ENRMGetPlainText(_textView); + NSRange activeRange = _mentionCoordinator.activeRange; + NSUInteger rangeEnd = NSMaxRange(activeRange); + if (rangeEnd > plainText.length) { + return; + } + BOOL nextCharIsWhitespace = rangeEnd < plainText.length && [[NSCharacterSet whitespaceAndNewlineCharacterSet] + characterIsMember:[plainText + characterAtIndex:rangeEnd]]; + NSString *replacement = nextCharIsWhitespace ? displayText : [displayText stringByAppendingString:@" "]; + ENRMFormattingRange *linkRange = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink + range:NSMakeRange(0, displayText.length) + url:[_linkCoordinator sanitizeURL:url]]; + NSString *indicator = _mentionCoordinator.activeIndicator; + + [self dispatchMentionEvents:[_mentionCoordinator clearWithIndicatorOverride:indicator]]; + [self replaceTextInRange:activeRange withText:replacement formattingRanges:@[ linkRange ]]; + _textView.selectedRange = NSMakeRange(activeRange.location + replacement.length, 0); + [_inputEventEmitter emitOnChangeSelection]; +} + +- (void)removeLink +{ + if (![_linkCoordinator removeLinkForSelection:_textView.selectedRange]) { + return; + } + [self applyFormatting]; + [_inputEventEmitter emitFormattingChanged]; +} + +- (void)showLinkPrompt +{ + ENRMFormattingRange *activeLink = [_linkCoordinator linkForSelection:_textView.selectedRange]; + NSString *existingURL = activeLink != nil ? activeLink.url : nil; + + __weak EnrichedMarkdownTextInput *weakSelf = self; + ENRMShowLinkPrompt(self, existingURL, ^(NSString *url) { [weakSelf setLink:url]; }); +} + +/// Serializes plain text with inline + block formatting, resolving each block's +/// markdown line prefix through its registered handler. With no block handlers +/// registered the prefix provider is never consulted productively and output +/// equals the inline-only serialization. +- (NSString *)serializeText:(NSString *)text + ranges:(NSArray *)ranges + blockRanges:(NSArray *)blockRanges +{ + return [_clipboardCoordinator serializeText:text ranges:ranges blockRanges:blockRanges]; +} + +- (nullable NSString *)markdownForSelectedRange +{ + return [_clipboardCoordinator serializeSelectedRange:_textView.selectedRange inText:ENRMGetPlainText(_textView)]; +} + +- (void)copyToClipboard +{ + NSString *plainText = ENRMGetPlainText(_textView); + if (plainText.length == 0) { + return; + } + NSString *markdown = [_clipboardCoordinator serializeFullDocument:plainText]; + NSMutableDictionary *items = [NSMutableDictionary dictionary]; + items[kUTIPlainText] = plainText; + if (markdown.length > 0) { + items[kENRMMarkdownPasteboardType] = markdown; + } + copyItemsToPasteboard(items); +} + +- (void)requestMarkdown:(NSInteger)requestId +{ + [_inputEventEmitter requestMarkdown:requestId]; +} + +- (CGRect)computeCaretRect +{ + CGRect caretRect = CGRectZero; +#if !TARGET_OS_OSX + UITextRange *selectedRange = _textView.selectedTextRange; + if (selectedRange != nil) { + caretRect = [_textView caretRectForPosition:selectedRange.start]; + } +#else + NSRange selection = _textView.selectedRange; + if (selection.location != NSNotFound) { + NSRange glyphRange = [_textView.layoutManager glyphRangeForCharacterRange:NSMakeRange(selection.location, 0) + actualCharacterRange:NULL]; + caretRect = [_textView.layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:_textView.textContainer]; + caretRect.origin.x += _textView.textContainerInset.left; + caretRect.origin.y += _textView.textContainerInset.top; + } +#endif + return caretRect; +} + +- (void)requestCaretRect:(NSInteger)requestId +{ + [_inputEventEmitter requestCaretRect:requestId]; +} + +- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args +{ + RCTEnrichedMarkdownTextInputHandleCommand(self, commandName, args); +} + +#pragma mark - ENRMInputEventEmitterDataSource + +- (std::shared_ptr)fabricEventEmitter +{ + if (_eventEmitter == nullptr || _editSession.shouldSuppressEvents) { + return nullptr; + } + return std::static_pointer_cast(_eventEmitter); +} + +- (NSRange)selectedRange +{ + return _textView.selectedRange; +} + +- (BOOL)isStyleActive:(ENRMInputStyleType)type inRange:(NSRange)range +{ + return [_formattingStore isStyleActive:type inRange:range]; +} + +- (BOOL)isEffectiveStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position +{ + return [_typingController isEffectiveStyleActive:type atPosition:position]; +} + +- (nullable ENRMFormattingRange *)linkForSelection:(NSRange)selection +{ + return [_linkCoordinator linkForSelection:selection]; +} + +#pragma mark - ENRMInputTypingAttributesDataSource + +- (BOOL)isStyleAdjacentBefore:(ENRMInputStyleType)type position:(NSUInteger)position +{ + return [_formattingStore isStyleAdjacentBefore:type position:position]; +} + +- (BOOL)isStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position +{ + return [_formattingStore isStyleActive:type atPosition:position]; +} + +- (NSString *)currentMarkdown +{ + return [self serializeText:ENRMGetPlainText(_textView) + ranges:[self allRangesIncludingTransient] + blockRanges:_blockStore.allRanges]; +} + +- (NSArray *)allRangesIncludingTransient +{ + return [_clipboardCoordinator allRangesIncludingTransient]; +} + +- (void)updateActiveMention +{ + [self dispatchMentionUpdate]; +} + +- (void)clearActiveMention:(nullable NSString *)indicatorOverride +{ + [self dispatchMentionEvents:[_mentionCoordinator clearWithIndicatorOverride:indicatorOverride]]; +} + +- (void)dispatchMentionUpdate +{ + NSString *plainText = ENRMGetPlainText(_textView); + [self dispatchMentionEvents:[_mentionCoordinator updateWithText:plainText selectedRange:_textView.selectedRange]]; +} + +- (void)dispatchMentionEvents:(NSArray *)events +{ + for (ENRMMentionEvent *event in events) { + switch (event.type) { + case ENRMMentionEventStart: + [_inputEventEmitter emitOnStartMention:event.indicator]; + break; + case ENRMMentionEventChange: + [_inputEventEmitter emitOnChangeMentionWithIndicator:event.indicator text:event.text]; + break; + case ENRMMentionEventEnd: + [_inputEventEmitter emitOnEndMention:event.indicator]; + break; + } + } +} + +/// Handles backspace or delete on a link's text, or deleting a selection that +/// starts in a link. Without this, UIKit removes only those characters and +/// leaves a partial link still pointing at the old URL; with it, the whole link +/// is deleted. Returns YES when it did so, and the caller rejects UIKit's edit. +- (BOOL)deleteLinkForReplacementRange:(NSRange)range replacementText:(NSString *)text +{ + if (text.length > 0) { + return NO; + } + + // linkForSelection: would match a caret at a link's start, so backspace at + // the start of the text would delete a link that follows it. + ENRMFormattingRange *linkRange = range.length > 0 ? [_linkCoordinator linkForSelection:range] + : [_linkCoordinator linkRangeForDeletionAtPosition:range.location]; + if (linkRange == nil) { + return NO; + } + + [self replaceTextInRange:linkRange.range withText:@"" formattingRanges:@[]]; + [self clearActiveMention:nil]; + return YES; +} + +- (NSArray *)contextMenuItemTexts +{ + return _contextMenuItemTexts ?: @[]; +} + +- (NSArray *)contextMenuItemIcons +{ + return _contextMenuItemIcons ?: @[]; +} + +- (ENRMInputSelectionMenuConfig)inputSelectionMenuConfig +{ + return _inputSelectionMenuConfig; +} + +- (ENRMFormatMenuConfig)formatMenuConfig +{ + return _formatMenuConfig; +} + +- (ENRMInputEventEmitter *)inputEventEmitter +{ + return _inputEventEmitter; +} + +- (ENRMInputTypingAttributesController *)typingController +{ + return _typingController; +} + +#pragma mark - Text edit tracking + +/// Markdown shortcuts: when the user types a space after `#`…`######`, +/// `-`/`*`/`+` or `1.`/`1)` at the start of a plain paragraph, drop the prefix +/// and make the paragraph that block. Runs after the stores are adjusted for the +/// edit and before scoped formatting. Returns YES when it converted, in which +/// case the replace path has already reformatted and emitted. +- (BOOL)applyMarkdownShortcutForEditAtLocation:(NSUInteger)editLocation + deletedLength:(NSUInteger)deletedLength + insertedLength:(NSUInteger)insertedLength +{ + // A typing affordance, not a paste/import path: pure insertions only, which + // is also how block continuation gates itself. + if (!ENRMMarkdownShortcutsEnabled(_markdownShortcutsConfig) || deletedLength != 0 || insertedLength == 0) { + return NO; + } + + NSString *text = ENRMGetPlainText(_textView); + if (editLocation >= text.length) { + return NO; + } + NSUInteger insertedEnd = MIN(editLocation + insertedLength, text.length); + + // The trigger is the first space inside the inserted run — a single + // keystroke in the common case, a whole token when an automation inserts + // several characters at once. A line break ends the search so the converted + // line is always the one the insertion started on. + NSCharacterSet *newlines = [NSCharacterSet newlineCharacterSet]; + NSUInteger spaceIndex = NSNotFound; + for (NSUInteger i = editLocation; i < insertedEnd; i++) { + unichar c = [text characterAtIndex:i]; + if (c == ' ') { + spaceIndex = i; + break; + } + if ([newlines characterIsMember:c]) { + return NO; + } + } + if (spaceIndex == NSNotFound) { + return NO; + } + + NSUInteger lineStart = [text paragraphRangeForRange:NSMakeRange(spaceIndex, 0)].location; + if (spaceIndex == lineStart || [_blockCoordinator blockAtPosition:lineStart inText:text] != nil) { + return NO; + } + + NSString *prefix = [text substringWithRange:NSMakeRange(lineStart, spaceIndex - lineStart)]; + ENRMInputBlockType type = ENRMInputBlockTypeParagraph; + NSInteger level = 0; + if (![ENRMMarkdownShortcutMatcher matchPrefix:prefix config:_markdownShortcutsConfig outType:&type outLevel:&level]) { + return NO; + } + + NSRange prefixRange = NSMakeRange(lineStart, spaceIndex + 1 - lineStart); + NSRange caretBefore = _textView.selectedRange; + + // A zero-length range at the line start: the store expands it to the whole + // paragraph, and on an emptied line it persists as the block's anchor. + ENRMBlockRange *block = [ENRMBlockRange rangeWithType:type range:NSMakeRange(0, 0) level:level]; + [self replaceTextInRange:prefixRange withText:@"" formattingRanges:@[] blockRanges:@[ block ]]; + + if (caretBefore.location >= NSMaxRange(prefixRange)) { + NSUInteger caret = caretBefore.location - prefixRange.length; + _textView.selectedRange = NSMakeRange(MIN(caret, ENRMGetPlainText(_textView).length), 0); + } + _lastSelectedRange = _textView.selectedRange; + + [_typingController syncWithCursorBlock]; + [self updateEmptyBulletMarker]; + return YES; +} + +- (void)handleTextChanged +{ + if (_editSession.isComposing) { + return; + } + + NSUInteger newLength = ENRMGetPlainText(_textView).length; + NSRange selection = _textView.selectedRange; + + NSRange preEditSelection = _preEditSelectedRange; + NSUInteger editLocation = preEditSelection.location; + NSUInteger deletedLength = 0; + NSUInteger insertedLength = 0; + + if (newLength >= _lastTextLength) { + NSUInteger netInserted = newLength - _lastTextLength; + deletedLength = preEditSelection.length; + insertedLength = deletedLength + netInserted; + } else { + NSUInteger netDeleted = _lastTextLength - newLength; + if (preEditSelection.length > 0) { + deletedLength = preEditSelection.length; + insertedLength = deletedLength > netDeleted ? deletedLength - netDeleted : 0; + } else { + deletedLength = netDeleted; + insertedLength = 0; + if (selection.location < editLocation) { + editLocation = selection.location; + } + } + } + + ENRMEditContext *context = [[ENRMEditContext alloc] initWithEditLocation:editLocation + deletedLength:deletedLength + insertedLength:insertedLength + preEditReplacedNewline:_preEditReplacedNewline + preEditBlockType:_preEditBlockType + preEditBlockLevel:_preEditBlockLevel + preEditParagraphWasEmpty:_preEditParagraphWasEmpty + pendingStyles:_typingController.pendingStyles + pendingStyleRemovals:_typingController.pendingStyleRemovals]; + + BOOL touchedNewline = [_editPipeline processTextChangeWithContext:context]; + + // Consumed: clear pre-edit state so stale values can't leak to the next edit. + _preEditBlockType = ENRMInputBlockTypeParagraph; + _preEditBlockLevel = 0; + _preEditParagraphWasEmpty = NO; + _preEditReplacedNewline = NO; + + _lastTextLength = newLength; + + // A typed markdown prefix turns the paragraph into a block; the replace path + // reformats and emits on its own, so the rest of this pass is redundant. + if ([self applyMarkdownShortcutForEditAtLocation:editLocation + deletedLength:deletedLength + insertedLength:insertedLength]) { + return; + } + +#if !TARGET_OS_OSX + if (newLength == 0) { + if ([self headingLevelForCursorParagraph] > 0 || [self listBlockForCursorParagraph] != nil) { + [_typingController syncWithCursorBlock]; + } else { + [self resetBaseTypingAttributes]; + } + } +#endif + + if (touchedNewline) { + [self applyFormattingScopedFromParagraphAtLocation:editLocation]; + } else { + [self applyFormattingScopedToEditAtLocation:editLocation insertedLength:insertedLength]; + } + + if (_textView.selectedRange.length == 0) { + [_typingController syncWithCursorBlock]; + } + + if ([self listBlockForCursorParagraph] != nil) { + [_typingController syncWithCursorBlock]; + } else if (_textView.typingAttributes[NSParagraphStyleAttributeName] != nil) { + [_typingController clearListParagraphStyle]; + } + + [_editPipeline detectLinksAtLocation:editLocation insertedLength:insertedLength]; + + [self updatePlaceholderVisibility]; + [_inputEventEmitter emitOnChangeText]; + [_inputEventEmitter emitOnChangeSelection]; + [_inputEventEmitter emitFormattingChanged]; + [self updateActiveMention]; + [_inputEventEmitter emitCaretRectChangeIfNeeded]; + [self requestHeightUpdate]; + [self scheduleRelayoutIfNeeded]; + [self updateEmptyBulletMarker]; +} + +#pragma mark - Text view delegate + +#if !TARGET_OS_OSX + +- (void)stripLinkTypingAttributes +{ + NSMutableDictionary *attrs = [_textView.typingAttributes mutableCopy]; + BOOL changed = NO; + + UIColor *linkColor = _formatterStyle.linkColor; + UIColor *currentColor = attrs[NSForegroundColorAttributeName]; + if (currentColor != nil && linkColor != nil && [currentColor isEqual:linkColor]) { + attrs[NSForegroundColorAttributeName] = _formatterStyle.baseTextColor; + changed = YES; + } + + if (attrs[NSUnderlineStyleAttributeName] != nil) { + [attrs removeObjectForKey:NSUnderlineStyleAttributeName]; + changed = YES; + } + + if (attrs[NSLinkAttributeName] != nil) { + [attrs removeObjectForKey:NSLinkAttributeName]; + changed = YES; + } + + if (changed) { + _textView.typingAttributes = attrs; + } +} + +- (void)manageSelectionBasedChanges +{ + [self stripLinkTypingAttributes]; + + if (_textView.selectedRange.length == 0 && _editSession.phase == ENRMEditPhaseIdle) { + NSString *text = ENRMGetPlainText(_textView); + if (text.length > 0) { + NSRange paragraphRange = [text paragraphRangeForRange:_textView.selectedRange]; + NSString *paragraphText = [text substringWithRange:paragraphRange]; + BOOL isEmpty = paragraphText.length == 0 || [paragraphText isEqualToString:@"\n"]; + if (isEmpty) { + if ([self headingLevelForCursorParagraph] > 0 || [self listBlockForCursorParagraph] != nil) { + [_typingController syncWithCursorBlock]; + } else { + NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; + attrs[NSFontAttributeName] = _formatterStyle.baseFont; + attrs[NSForegroundColorAttributeName] = _formatterStyle.baseTextColor; + _textView.typingAttributes = attrs; + } + } + } + } +} + +- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text +{ + [_inputEventEmitter emitOnKeyPress:text]; + if ([self deleteLinkForReplacementRange:range replacementText:text]) { + return NO; + } + if ([self handleListKeyForReplacementRange:range replacementText:text]) { + return NO; + } + _preEditSelectedRange = _lastSelectedRange; + [self capturePreEditBlockForRange:range]; + _preEditParagraphWasEmpty = [self preEditParagraphWasEmpty:range]; + _preEditReplacedNewline = [self replacedRangeTouchesNewline:range]; + [_editSession enterPhase:ENRMEditPhaseProcessing]; + [self stripLinkTypingAttributes]; + return YES; +} + +- (void)textViewDidChange:(UITextView *)textView +{ + if (_editSession.shouldSuppressFormatting) { + return; + } + [self handleTextChanged]; + [_editSession exitPhase]; + [_editSession recordTextChange]; + _lastSelectedRange = textView.selectedRange; +} + +- (void)textViewDidBeginEditing:(UITextView *)textView +{ + [_inputEventEmitter emitOnFocus]; +} + +- (void)textViewDidEndEditing:(UITextView *)textView +{ + [self clearActiveMention:nil]; + [_inputEventEmitter emitOnBlur]; +} + +/// Atomic-link snap clamped to the current text length, so a stale link range +/// past the text end can't drive an unbounded snap/clamp loop. +- (NSRange)clampedAtomicSelectionForSelection:(NSRange)selection +{ + NSRange adjusted = [_formattingStore selectionAdjustedForAtomicLinks:selection]; + NSUInteger textLength = _textView.textStorage.length; + if (adjusted.location > textLength) { + return NSMakeRange(textLength, 0); + } + if (NSMaxRange(adjusted) > textLength) { + adjusted.length = textLength - adjusted.location; + } + return adjusted; +} + +/// YES while a UIKit selection gesture (handle drag, long-press loupe) is +/// mid-flight; snapping selectedRange then fights the gesture and flickers the +/// edit menu, so callers defer the snap until it settles. +- (BOOL)selectionGestureIsActive +{ + for (UIGestureRecognizer *recognizer in _textView.gestureRecognizers) { + if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) { + return YES; + } + } + return NO; +} + +/// Re-applies the atomic-link snap once the selection gesture ends, polling the +/// main queue because UIKit may not re-fire the selection delegate at touch-up. +- (void)schedulePostGestureAtomicSnap +{ + if (_atomicSnapScheduled) { + return; + } + _atomicSnapScheduled = YES; + __weak __typeof(self) weakSelf = self; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kENRMAtomicSnapPollInterval * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + __typeof(self) strongSelf = weakSelf; + if (strongSelf == nil) { + return; + } + strongSelf->_atomicSnapScheduled = NO; + if (strongSelf->_editSession.shouldSuppressSelectionSideEffects || + strongSelf->_editSession.isComposing) { + return; + } + if ([strongSelf selectionGestureIsActive]) { + [strongSelf schedulePostGestureAtomicSnap]; + return; + } + NSRange selection = strongSelf->_textView.selectedRange; + NSRange adjusted = [strongSelf clampedAtomicSelectionForSelection:selection]; + if (!NSEqualRanges(adjusted, selection)) { + strongSelf->_textView.selectedRange = adjusted; + } + }); +} + +- (void)textViewDidChangeSelection:(UITextView *)textView +{ + NSRange newSelection = textView.selectedRange; + if (!_editSession.shouldSuppressSelectionSideEffects && !_editSession.isComposing) { + if ([self selectionGestureIsActive]) { + [self schedulePostGestureAtomicSnap]; + } else { + NSRange adjusted = [self clampedAtomicSelectionForSelection:newSelection]; + if (!NSEqualRanges(adjusted, newSelection)) { + _textView.selectedRange = adjusted; + return; + } + } + } + NSRange previousSelection = _lastSelectedRange; + _lastSelectedRange = newSelection; + + if (_editSession.shouldSuppressSelectionSideEffects) { + return; + } + + if (_editSession.isComposing) { + return; + } + + BOOL selectionMoved = + newSelection.location != previousSelection.location || newSelection.length != previousSelection.length; + + if (selectionMoved) { + [_typingController resetForSelectionChange]; + } + + [self manageSelectionBasedChanges]; + + [_inputEventEmitter emitOnChangeSelection]; + [self updateActiveMention]; + [_inputEventEmitter emitOnChangeState]; + [_inputEventEmitter emitCaretRectChangeIfNeeded]; + [self updateEmptyBulletMarker]; +} + +#else + +#pragma mark - RCTBackedTextInputDelegate (macOS) + +- (BOOL)textInputShouldBeginEditing +{ + return YES; +} + +- (void)textInputDidBeginEditing +{ + [_inputEventEmitter emitOnFocus]; +} + +- (BOOL)textInputShouldEndEditing +{ + return YES; +} + +- (void)textInputDidEndEditing +{ + [self clearActiveMention:nil]; + [_inputEventEmitter emitOnBlur]; +} + +- (BOOL)textInputShouldReturn +{ + return NO; +} + +- (void)textInputDidReturn +{ +} + +- (BOOL)textInputShouldSubmitOnReturn +{ + return NO; +} + +- (nullable NSString *)textInputShouldChangeText:(NSString *)text inRange:(NSRange)range +{ + [_inputEventEmitter emitOnKeyPress:text]; + if ([self deleteLinkForReplacementRange:range replacementText:text]) { + return nil; + } + _preEditSelectedRange = _lastSelectedRange; + // Capture the same pre-edit block state the iOS path does — otherwise these + // ivars carry stale values from a previous edit into reconcileBlockContinuation. + [self capturePreEditBlockForRange:range]; + _preEditParagraphWasEmpty = [self preEditParagraphWasEmpty:range]; + _preEditReplacedNewline = [self replacedRangeTouchesNewline:range]; + [_editSession enterPhase:ENRMEditPhaseProcessing]; + return text; +} + +- (void)textInputDidChange +{ + if (_editSession.shouldSuppressFormatting) { + [_editSession exitPhase]; + return; + } + [self handleTextChanged]; + [_editSession exitPhase]; + [_editSession recordTextChange]; + _lastSelectedRange = _textView.selectedRange; +} + +- (void)textInputDidChangeSelection +{ + NSRange newSelection = _textView.selectedRange; + if (!_editSession.shouldSuppressSelectionSideEffects && !_editSession.isComposing) { + NSRange adjusted = [_formattingStore selectionAdjustedForAtomicLinks:newSelection]; + if (!NSEqualRanges(adjusted, newSelection)) { + _textView.selectedRange = adjusted; + return; + } + } + NSRange previousSelection = _lastSelectedRange; + _lastSelectedRange = newSelection; + + if (_editSession.shouldSuppressSelectionSideEffects) { + return; + } + + if (_editSession.isComposing) { + return; + } + + BOOL selectionMoved = + newSelection.location != previousSelection.location || newSelection.length != previousSelection.length; + + if (selectionMoved) { + [_typingController resetForSelectionChange]; + } + + [_inputEventEmitter emitOnChangeSelection]; + [self updateActiveMention]; + [_inputEventEmitter emitOnChangeState]; + [_inputEventEmitter emitCaretRectChangeIfNeeded]; +} + +// @required stubs for RCTBackedTextInputDelegate — RCTUITextView's internal adapter +// calls these via textInputDelegate; omitting any causes silent failures or crashes. + +- (BOOL)textInputShouldHandleDeleteBackward:(id)sender +{ + return YES; +} + +- (BOOL)textInputShouldHandleDeleteForward:(id)sender +{ + return YES; +} + +- (BOOL)textInputShouldHandleKeyEvent:(NSEvent *)event +{ + return YES; +} + +- (BOOL)hasKeyDownEventOrKeyUpEvent:(NSString *)key +{ + return NO; +} + +- (NSDragOperation)textInputDraggingEntered:(id)draggingInfo +{ + return NSDragOperationNone; +} + +- (void)textInputDraggingExited:(id)draggingInfo +{ +} + +- (BOOL)textInputShouldHandleDragOperation:(id)draggingInfo +{ + return YES; +} + +- (void)textInputDidCancel +{ +} + +- (BOOL)textInputShouldHandlePaste:(id)sender +{ + return YES; +} + +- (void)automaticSpellingCorrectionDidChange:(BOOL)enabled +{ +} + +- (void)continuousSpellCheckingDidChange:(BOOL)enabled +{ +} + +- (void)grammarCheckingDidChange:(BOOL)enabled +{ +} + +- (void)submitOnKeyDownIfNeeded:(NSEvent *)event +{ +} + +#endif + +@end + +Class EnrichedMarkdownTextInputCls(void) +{ + return EnrichedMarkdownTextInput.class; +} diff --git a/packages/react-native-enriched-markdown/ios/input/InputStylePropsUtils.h b/packages/react-native-enriched-markdown/ios/input/InputStylePropsUtils.h new file mode 100644 index 000000000000..18a6ba45d20b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/InputStylePropsUtils.h @@ -0,0 +1,201 @@ +#pragma once + +#import "ENRMInputFormatter.h" +#import "ENRMInputFormatterStyle.h" +#import "ENRMUIKit.h" +#import "FontUtils.h" +#import "ParagraphStyleUtils.h" +#import + +#if !TARGET_OS_OSX +static inline UITextAutocapitalizationType ENRMAutocapitalizationTypeFromString(NSString *value) +{ + if ([value isEqualToString:@"none"]) + return UITextAutocapitalizationTypeNone; + if ([value isEqualToString:@"words"]) + return UITextAutocapitalizationTypeWords; + if ([value isEqualToString:@"characters"]) + return UITextAutocapitalizationTypeAllCharacters; + return UITextAutocapitalizationTypeSentences; +} +#endif + +static inline NSMutableParagraphStyle * +ENRMInputParagraphStyleWithLineHeight(ENRMInputFormatterStyle *style, NSParagraphStyle *_Nullable existingParagraph) +{ + NSMutableParagraphStyle *paragraph = + existingParagraph ? [existingParagraph mutableCopy] : [[NSMutableParagraphStyle alloc] init]; + ENRMApplyLineHeightToParagraphStyle(paragraph, style.baseLineHeight); + return paragraph; +} + +/// Headings h1..h6 share an identical struct shape (fontSize / fontWeight / +/// color) but are distinct codegen types, hence the template. +template +static BOOL applyHeadingLevelProps(ENRMInputFormatterStyle *style, NSInteger level, const HeadingProps &newHeading, + const HeadingProps &oldHeading) +{ + BOOL changed = NO; + + if (newHeading.fontSize != oldHeading.fontSize) { + [style setHeadingFontSize:newHeading.fontSize forLevel:level]; + changed = YES; + } + + if (newHeading.fontWeight != oldHeading.fontWeight) { + NSString *weight = + newHeading.fontWeight.empty() ? nil : [NSString stringWithUTF8String:newHeading.fontWeight.c_str()]; + [style setHeadingFontWeight:weight forLevel:level]; + changed = YES; + } + + if (newHeading.color != oldHeading.color) { + RCTUIColor *color = isColorMeaningful(newHeading.color) ? RCTUIColorFromSharedColor(newHeading.color) : nil; + [style setHeadingColor:color forLevel:level]; + changed = YES; + } + + return changed; +} + +template +BOOL applyInputStyleProps(ENRMInputFormatterStyle *style, const InputProps &newProps, const InputProps &oldProps) +{ + BOOL changed = NO; + + if (newProps.fontSize != oldProps.fontSize) { + CGFloat fontSize = newProps.fontSize > 0 ? newProps.fontSize : 16.0; + style.baseFont = [style.baseFont fontWithSize:fontSize]; + changed = YES; + } + + if (newProps.fontWeight != oldProps.fontWeight) { + CGFloat fontSize = style.baseFont.pointSize; + if (!newProps.fontWeight.empty()) { + NSString *weightString = [NSString stringWithUTF8String:newProps.fontWeight.c_str()]; + UIFontWeight weight = ENRMFontWeightFromString(weightString); + style.baseFont = [UIFont systemFontOfSize:fontSize weight:weight]; + } else { + style.baseFont = [UIFont systemFontOfSize:fontSize]; + } + changed = YES; + } + + if (newProps.fontFamily != oldProps.fontFamily) { + if (!newProps.fontFamily.empty()) { + NSString *familyName = [NSString stringWithUTF8String:newProps.fontFamily.c_str()]; + UIFont *customFont = [UIFont fontWithName:familyName size:style.baseFont.pointSize]; + if (customFont) { + style.baseFont = customFont; + } + } else { + style.baseFont = [UIFont systemFontOfSize:style.baseFont.pointSize]; + } + changed = YES; + } + + if (newProps.color != oldProps.color) { + if (isColorMeaningful(newProps.color)) { + style.baseTextColor = RCTUIColorFromSharedColor(newProps.color); + } else { + style.baseTextColor = [RCTUIColor labelColor]; + } + changed = YES; + } + + if (newProps.lineHeight != oldProps.lineHeight) { + style.baseLineHeight = newProps.lineHeight > 0 ? newProps.lineHeight : 0; + changed = YES; + } + + if (newProps.markdownStyle.strong.color != oldProps.markdownStyle.strong.color) { + if (isColorMeaningful(newProps.markdownStyle.strong.color)) { + style.boldColor = RCTUIColorFromSharedColor(newProps.markdownStyle.strong.color); + } else { + style.boldColor = nil; + } + changed = YES; + } + + if (newProps.markdownStyle.em.color != oldProps.markdownStyle.em.color) { + if (isColorMeaningful(newProps.markdownStyle.em.color)) { + style.italicColor = RCTUIColorFromSharedColor(newProps.markdownStyle.em.color); + } else { + style.italicColor = nil; + } + changed = YES; + } + + if (newProps.markdownStyle.link.color != oldProps.markdownStyle.link.color) { + style.linkColor = RCTUIColorFromSharedColor(newProps.markdownStyle.link.color); + changed = YES; + } + + if (newProps.markdownStyle.link.underline != oldProps.markdownStyle.link.underline) { + style.linkUnderline = newProps.markdownStyle.link.underline; + changed = YES; + } + + if (newProps.markdownStyle.link.backgroundColor != oldProps.markdownStyle.link.backgroundColor) { + RCTUIColor *backgroundColor = RCTUIColorFromSharedColor(newProps.markdownStyle.link.backgroundColor); + style.linkBackgroundColor = CGColorGetAlpha(backgroundColor.CGColor) > 0 ? backgroundColor : nil; + changed = YES; + } + + { + BOOL linkVariantsChanged = newProps.markdownStyle.linkVariants.size() != oldProps.markdownStyle.linkVariants.size(); + if (!linkVariantsChanged) { + for (size_t i = 0; i < newProps.markdownStyle.linkVariants.size(); i++) { + const auto &newVariant = newProps.markdownStyle.linkVariants[i]; + const auto &oldVariant = oldProps.markdownStyle.linkVariants[i]; + if (newVariant.pattern != oldVariant.pattern || newVariant.color != oldVariant.color || + newVariant.underline != oldVariant.underline || newVariant.backgroundColor != oldVariant.backgroundColor) { + linkVariantsChanged = YES; + break; + } + } + } + + if (linkVariantsChanged) { + NSMutableArray *variants = [NSMutableArray array]; + for (const auto &entry : newProps.markdownStyle.linkVariants) { + ENRMInputLinkVariantStyle *variant = [[ENRMInputLinkVariantStyle alloc] init]; + variant.pattern = [[NSString alloc] initWithUTF8String:entry.pattern.c_str()]; + variant.color = RCTUIColorFromSharedColor(entry.color); + variant.underline = entry.underline; + RCTUIColor *backgroundColor = RCTUIColorFromSharedColor(entry.backgroundColor); + variant.backgroundColor = CGColorGetAlpha(backgroundColor.CGColor) > 0 ? backgroundColor : nil; + variant.regex = [NSRegularExpression regularExpressionWithPattern:variant.pattern options:0 error:nil]; + if (variant.regex != nil) { + [variants addObject:variant]; + } + } + style.linkVariants = variants; + changed = YES; + } + } + + if (newProps.markdownStyle.spoiler.color != oldProps.markdownStyle.spoiler.color) { + style.spoilerColor = RCTUIColorFromSharedColor(newProps.markdownStyle.spoiler.color); + changed = YES; + } + + if (newProps.markdownStyle.spoiler.backgroundColor != oldProps.markdownStyle.spoiler.backgroundColor) { + style.spoilerBackgroundColor = RCTUIColorFromSharedColor(newProps.markdownStyle.spoiler.backgroundColor); + changed = YES; + } + + if (newProps.markdownStyle.list.itemSpacing != oldProps.markdownStyle.list.itemSpacing) { + style.listItemSpacing = newProps.markdownStyle.list.itemSpacing; + changed = YES; + } + + changed |= applyHeadingLevelProps(style, 1, newProps.markdownStyle.h1, oldProps.markdownStyle.h1); + changed |= applyHeadingLevelProps(style, 2, newProps.markdownStyle.h2, oldProps.markdownStyle.h2); + changed |= applyHeadingLevelProps(style, 3, newProps.markdownStyle.h3, oldProps.markdownStyle.h3); + changed |= applyHeadingLevelProps(style, 4, newProps.markdownStyle.h4, oldProps.markdownStyle.h4); + changed |= applyHeadingLevelProps(style, 5, newProps.markdownStyle.h5, oldProps.markdownStyle.h5); + changed |= applyHeadingLevelProps(style, 6, newProps.markdownStyle.h6, oldProps.markdownStyle.h6); + + return changed; +} diff --git a/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputComponentDescriptor.h b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputComponentDescriptor.h new file mode 100644 index 000000000000..7d1d6e617d01 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputComponentDescriptor.h @@ -0,0 +1,19 @@ +#pragma once +#include "EnrichedMarkdownTextInputShadowNode.h" +#include +#include + +namespace facebook::react { + +class EnrichedMarkdownTextInputComponentDescriptor final + : public ConcreteComponentDescriptor { +public: + using ConcreteComponentDescriptor::ConcreteComponentDescriptor; + + void adopt(ShadowNode &shadowNode) const override { + react_native_assert(dynamic_cast(&shadowNode)); + ConcreteComponentDescriptor::adopt(shadowNode); + } +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.h b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.h new file mode 100644 index 000000000000..1488126f99c0 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.h @@ -0,0 +1,40 @@ +#pragma once +#include "EnrichedMarkdownTextInputState.h" +#include +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char EnrichedMarkdownTextInputComponentName[]; + +class EnrichedMarkdownTextInputShadowNode + : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + EnrichedMarkdownTextInputShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, + ShadowNodeTraits traits); + + EnrichedMarkdownTextInputShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + + static ShadowNodeTraits BaseTraits() + { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + +private: + int localHeightRecalculationCounter_{0}; + id setupMockInputView_(CGFloat width) const; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.mm b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.mm new file mode 100644 index 000000000000..bf1992c2fd84 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputShadowNode.mm @@ -0,0 +1,84 @@ +#import "EnrichedMarkdownTextInputShadowNode.h" +#import "ENRMEditSession.h" +#import "EnrichedMarkdownTextInput.h" +#import +#import + +namespace facebook::react { + +extern const char EnrichedMarkdownTextInputComponentName[] = "EnrichedMarkdownTextInput"; + +EnrichedMarkdownTextInputShadowNode::EnrichedMarkdownTextInputShadowNode(const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, + ShadowNodeTraits traits) + : ConcreteViewShadowNode(fragment, family, traits) +{ +} + +EnrichedMarkdownTextInputShadowNode::EnrichedMarkdownTextInputShadowNode(const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment) +{ + dirtyLayoutIfNeeded(); +} + +void EnrichedMarkdownTextInputShadowNode::dirtyLayoutIfNeeded() +{ + const auto state = this->getStateData(); + const int receivedCounter = state.getHeightRecalculationCounter(); + + if (receivedCounter > localHeightRecalculationCounter_) { + localHeightRecalculationCounter_ = receivedCounter; + YGNodeMarkDirty(&yogaNode_); + } +} + +id EnrichedMarkdownTextInputShadowNode::setupMockInputView_(CGFloat width) const +{ + EnrichedMarkdownTextInput *mockView = + [[EnrichedMarkdownTextInput alloc] initWithFrame:CGRectMake(20000, 20000, width, 1000)]; + + [mockView.editSession enterPhase:ENRMEditPhaseImporting]; + + const auto props = this->getProps(); + [mockView updateProps:props oldProps:nullptr]; + + return mockView; +} + +Size EnrichedMarkdownTextInputShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const +{ + CGFloat maxWidth = layoutConstraints.maximumSize.width; + + RCTInternalGenericWeakWrapper *weakWrapper = + (RCTInternalGenericWeakWrapper *)unwrapManagedObject(getStateData().getComponentViewRef()); + EnrichedMarkdownTextInput *view = weakWrapper ? (EnrichedMarkdownTextInput *)weakWrapper.object : nil; + + __block CGSize size; + + void (^measureBlock)(void) = ^{ + if (view) { + size = [view measureSize:maxWidth]; + } else { + EnrichedMarkdownTextInput *mockView = setupMockInputView_(maxWidth); + size = [mockView measureSize:maxWidth]; + } + }; + + if ([NSThread isMainThread]) { + measureBlock(); + } else { + dispatch_sync(dispatch_get_main_queue(), measureBlock); + } + + Float clampedWidth = std::max((Float)size.width, layoutConstraints.minimumSize.width); + clampedWidth = std::min(clampedWidth, layoutConstraints.maximumSize.width); + Float clampedHeight = std::max((Float)size.height, layoutConstraints.minimumSize.height); + if (std::isfinite(layoutConstraints.maximumSize.height)) { + clampedHeight = std::min(clampedHeight, layoutConstraints.maximumSize.height); + } + return {clampedWidth, clampedHeight}; +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputState.h b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputState.h new file mode 100644 index 000000000000..2b517afd23d4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/internals/EnrichedMarkdownTextInputState.h @@ -0,0 +1,23 @@ +#pragma once +#include + +namespace facebook::react { + +class EnrichedMarkdownTextInputState { +public: + EnrichedMarkdownTextInputState() = default; + EnrichedMarkdownTextInputState(int counter, std::shared_ptr ref) : counter_(counter), viewRef_(ref) {} + + int getHeightRecalculationCounter() const { + return counter_; + } + std::shared_ptr getComponentViewRef() const { + return viewRef_; + } + +private: + int counter_{0}; + std::shared_ptr viewRef_{nullptr}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMBlockHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBlockHandler.h new file mode 100644 index 000000000000..1a6e81b77e63 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBlockHandler.h @@ -0,0 +1,46 @@ +#pragma once + +#import "ENRMBlockRange.h" +#import "ENRMInputFormatter.h" + +NS_ASSUME_NONNULL_BEGIN + +/// A block handler owns how its ENRMInputBlockType styles its paragraph and how +/// it serializes to a markdown line prefix. Mirrors ENRMStyleHandler for the +/// inline pipeline. Parser recognition is NOT handler-driven: it lives in +/// ENRMInputParser's kSupportedBlocks central map, exactly as kSupportedSpans +/// does for inline styles — a new block type adds one entry there plus one +/// handler here. These signatures are designed to cover headings AND list items. +@protocol ENRMBlockHandler + +@property (nonatomic, readonly) ENRMInputBlockType blockType; + +/// Contribute paragraph-level attributes for a block of this type. Called once +/// per block range during formatting. A heading raises the font size; a list +/// item sets head/tail indents and a marker. May be a no-op. +/// +/// @param paragraphStyle Mutable paragraph style to adjust (indents, spacing). +/// @param attributes Mutable character attributes to add (e.g. font) over +/// the block range; NSParagraphStyleAttributeName is +/// applied by the formatter from `paragraphStyle`. +/// @param blockRange The block being styled (carries type, range, level). +/// @param style Resolved formatter style (base font, colors). +- (void)applyAttributesToParagraphStyle:(NSMutableParagraphStyle *)paragraphStyle + attributes:(NSMutableDictionary *)attributes + blockRange:(ENRMBlockRange *)blockRange + style:(ENRMInputFormatterStyle *)style; + +/// Markdown prefix prepended to each line of the block during serialization, +/// e.g. @"# " for an H1 or @"- " for a bullet. Returns @"" when the block needs +/// no prefix. Owning the marker here replaces a central serializer switch. +- (NSString *)markdownLinePrefixForBlockRange:(ENRMBlockRange *)blockRange; + +@optional + +/// Whether Return continues the block onto the next line (a list item) rather +/// than ending it (a heading). Defaults to NO when unimplemented. +@property (nonatomic, readonly) BOOL continuesOnNewline; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.h new file mode 100644 index 000000000000..d3793c4183d6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMBoldStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.mm new file mode 100644 index 000000000000..e5373948d82b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMBoldStyleHandler.mm @@ -0,0 +1,30 @@ +#import "ENRMBoldStyleHandler.h" + +@implementation ENRMBoldStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeStrong; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return UIFontDescriptorTraitBold; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + if (style.boldColor) { + [storage addAttribute:NSForegroundColorAttributeName value:style.boldColor range:range]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.h new file mode 100644 index 000000000000..5015b5190b4d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.h @@ -0,0 +1,15 @@ +#pragma once + +#import "ENRMBlockHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Block handler for ATX headings (H1-H6). A single instance serves all six +/// levels: it dispatches on ENRMBlockRange.level for both styling (font size via +/// the formatter style's per-level config) and serialization (`#`*level prefix). +/// The formatter registers the same instance under all six heading block-type +/// keys. +@interface ENRMHeadingBlockHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.mm new file mode 100644 index 000000000000..7c5ca5989de2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMHeadingBlockHandler.mm @@ -0,0 +1,41 @@ +#import "ENRMHeadingBlockHandler.h" +#import "ParagraphStyleUtils.h" + +@implementation ENRMHeadingBlockHandler + +- (ENRMInputBlockType)blockType +{ + return ENRMInputBlockTypeHeading1; +} + +- (void)applyAttributesToParagraphStyle:(NSMutableParagraphStyle *)paragraphStyle + attributes:(NSMutableDictionary *)attributes + blockRange:(ENRMBlockRange *)blockRange + style:(ENRMInputFormatterStyle *)style +{ + NSInteger level = blockRange.level; + if (level < 1 || level > 6) { + return; + } + + attributes[NSFontAttributeName] = [style headingFontForLevel:level]; + + RCTUIColor *headingColor = [style headingColorForLevel:level]; + if (headingColor) { + attributes[NSForegroundColorAttributeName] = headingColor; + } + + ENRMApplyLineHeightToParagraphStyle(paragraphStyle, [style derivedLineHeightForHeadingLevel:level]); +} + +- (NSString *)markdownLinePrefixForBlockRange:(ENRMBlockRange *)blockRange +{ + NSInteger level = blockRange.level; + if (level < 1 || level > 6) { + return @""; + } + NSString *hashes = [@"" stringByPaddingToLength:level withString:@"#" startingAtIndex:0]; + return [hashes stringByAppendingString:@" "]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.h new file mode 100644 index 000000000000..41707ebd3a98 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMItalicStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.mm new file mode 100644 index 000000000000..23169acb0b0f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMItalicStyleHandler.mm @@ -0,0 +1,30 @@ +#import "ENRMItalicStyleHandler.h" + +@implementation ENRMItalicStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeEmphasis; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return UIFontDescriptorTraitItalic; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + if (style.italicColor) { + [storage addAttribute:NSForegroundColorAttributeName value:style.italicColor range:range]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.h new file mode 100644 index 000000000000..535053092189 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMLinkStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.mm new file mode 100644 index 000000000000..f0f678af51a9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMLinkStyleHandler.mm @@ -0,0 +1,52 @@ +#import "ENRMLinkStyleHandler.h" + +static ENRMInputLinkVariantStyle *ENRMResolveInputLinkVariant(ENRMInputFormatterStyle *style, NSString *url) +{ + NSRange urlRange = NSMakeRange(0, url.length); + for (ENRMInputLinkVariantStyle *variant in style.linkVariants) { + if ([variant.regex firstMatchInString:url options:0 range:urlRange] != nil) { + return variant; + } + } + return nil; +} + +@implementation ENRMLinkStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeLink; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return 0; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + ENRMInputLinkVariantStyle *variant = ENRMResolveInputLinkVariant(style, formattingRange.url); + RCTUIColor *linkColor = variant.color ?: style.linkColor; + BOOL linkUnderline = variant ? variant.underline : style.linkUnderline; + RCTUIColor *backgroundColor = variant ? variant.backgroundColor : style.linkBackgroundColor; + + if (linkColor != nil) { + [storage addAttribute:NSForegroundColorAttributeName value:linkColor range:range]; + } + if (linkUnderline) { + [storage addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; + } + if (backgroundColor != nil) { + [storage addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:range]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.h new file mode 100644 index 000000000000..daf7d2ea43ac --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.h @@ -0,0 +1,14 @@ +#pragma once + +#import "ENRMBlockHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Block handler for ordered list items. Reserves the same head-indent column as +/// the bullet handler (the layout manager draws the number into it) and +/// serializes to an `N. ` line prefix indented three spaces per nesting level. +/// Depth rides in ENRMBlockRange.level, the number in ENRMBlockRange.ordinal. +@interface ENRMOrderedListBlockHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.mm new file mode 100644 index 000000000000..fd3eac2cb009 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMOrderedListBlockHandler.mm @@ -0,0 +1,48 @@ +#import "ENRMOrderedListBlockHandler.h" +#import "ENRMInputBlockType.h" + +@implementation ENRMOrderedListBlockHandler + +- (ENRMInputBlockType)blockType +{ + return ENRMInputBlockTypeOrderedListItem; +} + +- (BOOL)continuesOnNewline +{ + return YES; +} + +- (void)applyAttributesToParagraphStyle:(NSMutableParagraphStyle *)paragraphStyle + attributes:(NSMutableDictionary *)attributes + blockRange:(ENRMBlockRange *)blockRange + style:(ENRMInputFormatterStyle *)style +{ + NSInteger depth = blockRange.level; + if (depth < 0) { + depth = 0; + } else if (depth > kENRMMaxListDepth) { + depth = kENRMMaxListDepth; + } + + // Same indent column as the bullet handler so mixed lists align; wrapped + // lines hang under the text, not under the number. + CGFloat indent = (depth + 1) * kENRMListIndentPerDepth; + paragraphStyle.firstLineHeadIndent = indent; + paragraphStyle.headIndent = indent; + paragraphStyle.paragraphSpacingBefore = style.listItemSpacing; +} + +- (NSString *)markdownLinePrefixForBlockRange:(ENRMBlockRange *)blockRange +{ + NSInteger depth = blockRange.level; + if (depth < 0) { + depth = 0; + } else if (depth > kENRMMaxListDepth) { + depth = kENRMMaxListDepth; + } + NSString *indent = [@"" stringByPaddingToLength:depth * 3 withString:@" " startingAtIndex:0]; + return [indent stringByAppendingFormat:@"%ld. ", (long)blockRange.ordinal]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.h new file mode 100644 index 000000000000..29baefccbd0d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMSpoilerStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.mm new file mode 100644 index 000000000000..c2a71bab3325 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMSpoilerStyleHandler.mm @@ -0,0 +1,33 @@ +#import "ENRMSpoilerStyleHandler.h" + +@implementation ENRMSpoilerStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeSpoiler; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return 0; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + if (style.spoilerColor) { + [storage addAttribute:NSForegroundColorAttributeName value:style.spoilerColor range:range]; + } + if (style.spoilerBackgroundColor) { + [storage addAttribute:NSBackgroundColorAttributeName value:style.spoilerBackgroundColor range:range]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.h new file mode 100644 index 000000000000..c5c79cacafd8 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMStrikethroughStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.mm new file mode 100644 index 000000000000..f4850f3eaf3c --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStrikethroughStyleHandler.mm @@ -0,0 +1,28 @@ +#import "ENRMStrikethroughStyleHandler.h" + +@implementation ENRMStrikethroughStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeStrikethrough; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return 0; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + [storage addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleHandler.h new file mode 100644 index 000000000000..36462113d7ab --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleHandler.h @@ -0,0 +1,26 @@ +#pragma once + +#import "ENRMFormattingRange.h" +#import "ENRMInputFormatter.h" +#import "ENRMStyleMergingConfig.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol ENRMStyleHandler + +@property (nonatomic, readonly) ENRMInputStyleType styleType; +@property (nonatomic, readonly) ENRMStyleMergingConfig *mergingConfig; + +/// Collect font traits that this style contributes (e.g. bold, italic). +/// Return 0 if the style does not affect the font. +- (UIFontDescriptorSymbolicTraits)fontTraits; + +/// Apply non-font attributes (color, underline, etc.) to the given range. +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.h new file mode 100644 index 000000000000..f671c5e1a2d7 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.h @@ -0,0 +1,26 @@ +#pragma once + +#import "ENRMInputStyledRange.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Declarative rules for style coexistence. + * + * conflictingStyles — mutually exclusive: when this style is applied, + * conflicting styles are removed from the same range. + * blockingStyles — when any blocking style is active at the cursor/range, + * this style cannot be toggled on. + */ +@interface ENRMStyleMergingConfig : NSObject + +@property (nonatomic, strong) NSSet *conflictingStyles; +@property (nonatomic, strong) NSSet *blockingStyles; + ++ (instancetype)configWithConflicting:(NSSet *)conflicting blocking:(NSSet *)blocking; ++ (instancetype)emptyConfig; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.mm new file mode 100644 index 000000000000..81aa68e49dec --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMStyleMergingConfig.mm @@ -0,0 +1,21 @@ +#import "ENRMStyleMergingConfig.h" + +@implementation ENRMStyleMergingConfig + ++ (instancetype)configWithConflicting:(NSSet *)conflicting blocking:(NSSet *)blocking +{ + ENRMStyleMergingConfig *config = [[ENRMStyleMergingConfig alloc] init]; + config.conflictingStyles = conflicting; + config.blockingStyles = blocking; + return config; +} + ++ (instancetype)emptyConfig +{ + static ENRMStyleMergingConfig *shared; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ shared = [self configWithConflicting:[NSSet set] blocking:[NSSet set]]; }); + return shared; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.h new file mode 100644 index 000000000000..14152fada918 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.h @@ -0,0 +1,10 @@ +#pragma once + +#import "ENRMStyleHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMUnderlineStyleHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.mm new file mode 100644 index 000000000000..f7296bbc53ad --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnderlineStyleHandler.mm @@ -0,0 +1,28 @@ +#import "ENRMUnderlineStyleHandler.h" + +@implementation ENRMUnderlineStyleHandler + +- (ENRMInputStyleType)styleType +{ + return ENRMInputStyleTypeUnderline; +} + +- (ENRMStyleMergingConfig *)mergingConfig +{ + return [ENRMStyleMergingConfig emptyConfig]; +} + +- (UIFontDescriptorSymbolicTraits)fontTraits +{ + return 0; +} + +- (void)applyNonFontAttributesToTextStorage:(NSTextStorage *)storage + range:(NSRange)range + formattingRange:(ENRMFormattingRange *)formattingRange + style:(ENRMInputFormatterStyle *)style +{ + [storage addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.h b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.h new file mode 100644 index 000000000000..021a8495abff --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.h @@ -0,0 +1,15 @@ +#pragma once + +#import "ENRMBlockHandler.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Block handler for unordered (bullet) list items. Reserves the head-indent +/// column for the marker via the paragraph style (the layout manager draws the +/// glyph into it) and serializes to a `- ` line prefix indented three spaces per +/// nesting level. Nesting depth is carried in ENRMBlockRange.level. Continues on +/// Return (a new item at the same depth) unlike single-line heading blocks. +@interface ENRMUnorderedListBlockHandler : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.mm b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.mm new file mode 100644 index 000000000000..73639e2d6378 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/input/styles/ENRMUnorderedListBlockHandler.mm @@ -0,0 +1,51 @@ +#import "ENRMUnorderedListBlockHandler.h" +#import "ENRMInputBlockType.h" + +@implementation ENRMUnorderedListBlockHandler + +- (ENRMInputBlockType)blockType +{ + return ENRMInputBlockTypeUnorderedListItem; +} + +- (BOOL)continuesOnNewline +{ + return YES; +} + +- (void)applyAttributesToParagraphStyle:(NSMutableParagraphStyle *)paragraphStyle + attributes:(NSMutableDictionary *)attributes + blockRange:(ENRMBlockRange *)blockRange + style:(ENRMInputFormatterStyle *)style +{ + NSInteger depth = blockRange.level; + if (depth < 0) { + depth = 0; + } else if (depth > kENRMMaxListDepth) { + depth = kENRMMaxListDepth; + } + + // Reserve a marker column per nesting level. Both the first (marker) line and + // wrapped continuation lines align to the same text inset so wrapped text + // hangs under the text, not under the bullet. + CGFloat indent = (depth + 1) * kENRMListIndentPerDepth; + paragraphStyle.firstLineHeadIndent = indent; + paragraphStyle.headIndent = indent; + paragraphStyle.paragraphSpacingBefore = style.listItemSpacing; +} + +- (NSString *)markdownLinePrefixForBlockRange:(ENRMBlockRange *)blockRange +{ + NSInteger depth = blockRange.level; + if (depth < 0) { + depth = 0; + } else if (depth > kENRMMaxListDepth) { + depth = kENRMMaxListDepth; + } + // Three spaces of indent per nesting level (wide enough that ordered markers + // nest under bullets and vice versa), then the bullet marker. + NSString *indent = [@"" stringByPaddingToLength:depth * 3 withString:@" " startingAtIndex:0]; + return [indent stringByAppendingString:@"- "]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/internals/ENRMViewFreeMeasurement.h b/packages/react-native-enriched-markdown/ios/internals/ENRMViewFreeMeasurement.h new file mode 100644 index 000000000000..885353f4e1f2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/ENRMViewFreeMeasurement.h @@ -0,0 +1,376 @@ +#pragma once + +#import "ENRMBlockquoteContainerView.h" +#import "ENRMCodeBlockContainerView.h" +#import "ENRMFeatureFlags.h" +#import "ENRMLinkRegexProps.h" +#import "ENRMMarkdownParser.h" +#import "ENRMTextRenderer.h" +#import "ENRMTextViewSetup.h" +#import "ImageRequestHeaderUtils.h" +#import "LinkPillContentUtils.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RenderedMarkdownSegment.h" +#import "SegmentRenderer.h" +#import "StreamingMarkdownFilter.h" +#import "StylePropsUtils.h" +#import "TableContainerView.h" +#include +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathContainerView.h" +#endif +#if ENRICHED_MARKDOWN_VIDEO +#import "ENRMVideoContainerView.h" +#endif + +/** + * View-free markdown measurement (issue #550). + * + * The previous measurement path built throwaway component views on the main + * thread via `dispatch_sync` — a deadlock when `measureContent` runs under + * RN's locked commit fallback while a main-thread committer (Reanimated) is + * blocked on the same mutex, and a serialization bottleneck (streaming jank) + * even when it doesn't deadlock. + * + * These pipelines measure on the calling thread with no view and no + * main-thread dependency, mirroring RN core's `RCTTextLayoutManager` (which + * measures every `` this way in production) and this library's own + * Android `MeasurementStore`: + * + * - `ENRMMeasureMarkdownViewFree` (EnrichedMarkdownText): parse (md4c) → + * `ENRMRenderASTNodes` (the SAME renderer the visible view uses, so + * measured layout ≡ rendered layout) → a fresh per-call + * NSTextStorage/NSLayoutManager/NSTextContainer stack → shared finalize. + * - `ENRMMeasureSegmentedMarkdownViewFree` (EnrichedMarkdown): the iOS + * counterpart of Android's `MeasurementStore.measureAndCacheSplit` — split + * the AST into segments via the same `ENRMRenderSegmentsFromAST` the view + * uses, then walk them exactly like the view's + * `computeSegmentLayoutForWidth:`: text via the TextKit stack, tables via + * `+[TableContainerView measureHeightForTableNode:…]`, math via + * `+[ENRMMathContainerView measureHeightForLatex:…]`, with the same + * margin arithmetic. + * + * TextKit objects are thread-CONFINED, not main-thread-only: safe off main as + * long as one thread owns a given stack (Apple-sanctioned; the + * Texture/AsyncDisplayKit pattern). Allocating the stack per call — exactly + * what `RCTTextLayoutManager` does — makes confinement trivially true. + * `boundingRectWithSize:` (tables, math fallback) is documented thread-safe. + * + * Ambient-state rules for this path: + * - Font scale comes in as a parameter (from `LayoutContext::fontSizeMultiplier`), + * never from `RCTFontSizeMultiplier()` (UIKit read). + * - Pixel rounding uses `LayoutContext::pointScaleFactor`, never + * `RCTScreenScale()` (dispatch_syncs to main on first use). + * - The resolved layout direction comes from `LayoutConstraints::layoutDirection`, + * never from `RCTI18nUtil`. + * - The geometry config must match the visible view's + * (`ENRMConfigureMarkdownTextView`): zero insets, `lineFragmentPadding = 0`, + * `allowsNonContiguousLayout = NO`. The view's custom `TextViewLayoutManager` + * subclass only draws backgrounds and does not affect geometry. + * - Each entry point drains its own `@autoreleasepool`. The calling JS/layout + * thread has no runloop draining pools, and a full measure autoreleases + * thousands of objects (AST, attributed string, TextKit stack, fonts) — the + * old main-thread path silently leaned on the main runloop's per-cycle + * drain, and without a local pool sustained re-measurement accumulates + * until jetsam kills the app. + * + * RaTeX concurrency (math segments and lazily-measured inline math + * attachments now parse on the calling thread, possibly concurrently with the + * render thread): verified safe against RaTeX sources. The Swift engine is + * stateless per call, font registration is NSLock-guarded and idempotent + * (RaTeXFontLoader), the FFI's last-error slot is thread_local, the Rust + * core's only statics are immutable OnceLock/LazyLock tables, and renderer + * font caches are per-call locals. + */ + +template static inline ENRMMd4cFlags *ENRMMd4cFlagsFromProps(const Md4cFlagsT &props) +{ + ENRMMd4cFlags *flags = [ENRMMd4cFlags defaultFlags]; + flags.underline = props.underline; + flags.superscript = props.superscript; + flags.subscript = props.subscript; + flags.latexMath = props.latexMath; + flags.highlight = props.highlight; + flags.hardSoftBreaks = props.hardSoftBreaks; + flags.preserveBlankLines = props.preserveBlankLines; + flags.admonitions = props.admonitions; + return flags; +} + +/** + * Builds a StyleConfig from props alone, replicating the mock-view recipe + * field for field: a fresh config receives the props' style diffed against a + * default-constructed style struct (the mock view's `updateProps + * oldProps:nullptr` applied the same diff against default props), then the + * font scale, max multiplier, and image request headers. + */ +template +static inline StyleConfig *ENRMStyleConfigFromProps(const PropsT &typedProps, CGFloat fontScale) +{ + StyleConfig *config = [[StyleConfig alloc] init]; + using StyleT = std::remove_cv_t>; + static const StyleT kDefaultStyle{}; + applyMarkdownStyleToConfig(config, typedProps.markdownStyle, kDefaultStyle); + [config setFontScaleMultiplier:fontScale]; + [config setMaxFontSizeMultiplier:typedProps.maxFontSizeMultiplier]; + [config setImageRequestHeaders:ENRMImageRequestHeadersFromProps(typedProps.imageRequestHeaders)]; + [config setLinkPillContent:ENRMLinkPillContentFromProps(typedProps.linkPillContent)]; + return config; +} + +/** + * Lays out an already-rendered attributed string in a fresh, call-confined + * TextKit stack and finalizes with the shared algorithm + * (`ENRMFinalizeMeasuredTextSize`). Returns CGSizeZero for empty text — the + * same result the view path produces, and a guard against TextKit's + * empty-string layout freeze (see RCTTextLayoutManager). + * + * Uses the same `usesFontLeading` as the views that draw the text; see + * ENRMLayoutManagerUsesFontLeading. + */ +static inline CGSize ENRMMeasureAttributedTextViewFree(NSAttributedString *text, CGFloat maxWidth, StyleConfig *config, + BOOL allowTrailingMargin, CGFloat lastElementMarginBottom, + CGFloat pointScaleFactor, NSInteger numberOfLines, + NSLineBreakMode lineBreakMode, BOOL subtractExtraLineFragment) +{ + if (text.length == 0) { + return CGSizeZero; + } + + NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)]; + textContainer.lineFragmentPadding = 0; + if (numberOfLines > 0) { + textContainer.maximumNumberOfLines = numberOfLines; + textContainer.lineBreakMode = lineBreakMode; + } + NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; + layoutManager.allowsNonContiguousLayout = NO; + layoutManager.usesFontLeading = ENRMLayoutManagerUsesFontLeading; + [layoutManager addTextContainer:textContainer]; + NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:text]; + [textStorage addLayoutManager:layoutManager]; + + [layoutManager ensureLayoutForTextContainer:textContainer]; + ENRMTextLayoutResult layout; + layout.usedRect = [layoutManager usedRectForTextContainer:textContainer]; + layout.extraLineFragmentRect = layoutManager.extraLineFragmentRect; + + return ENRMFinalizeMeasuredTextSize(layout, layoutManager, text, maxWidth, config, allowTrailingMargin, + lastElementMarginBottom, subtractExtraLineFragment, pointScaleFactor); +} + +/** + * Measures EnrichedMarkdownText content from props alone, on the calling + * thread. The line-break strategy and writing-direction mode are resolved + * from the props exactly as `updateProps:` resolves them. Falls back to + * (maxWidth × system-16 line height) for empty markdown, parse failures, and + * empty render output — the same fallback `measureSize:` produced. + */ +template +static inline CGSize ENRMMeasureMarkdownViewFree(const PropsT &typedProps, CGFloat maxWidth, CGFloat fontScale, + CGFloat pointScaleFactor, NSWritingDirection resolvedLayoutDirection) +{ + @autoreleasepool { + CGSize fallback = CGSizeMake(maxWidth, UIFontLineHeight([UIFont systemFontOfSize:16.0])); + if (typedProps.markdown.empty()) { + return fallback; + } + + NSString *markdown = [[NSString alloc] initWithUTF8String:typedProps.markdown.c_str()]; + StyleConfig *config = ENRMStyleConfigFromProps(typedProps, fontScale); + + ENRMMd4cFlags *flags = ENRMMd4cFlagsFromProps(typedProps.md4cFlags); + ENRMMarkdownParser *parser = [[ENRMMarkdownParser alloc] init]; + MarkdownASTNode *ast = [parser parseMarkdown:markdown + flags:flags + isGFM:typedProps.isGFM + linkRegex:ENRMLinkRegexConfigFromProps(typedProps.linkRecognition.text) + inlineCodeLinkRegex:ENRMLinkRegexConfigFromProps(typedProps.linkRecognition.inlineCode)]; + if (!ast) { + return fallback; + } + + NSLineBreakStrategy lineBreakStrategy = + ENRMResolveLineBreakStrategy([[NSString alloc] initWithUTF8String:typedProps.lineBreakStrategyIOS.c_str()]); + ENRMRenderResult *result = + ENRMRenderASTNodes(ast.children, config, typedProps.allowTrailingMargin, typedProps.allowFontScaling, + typedProps.maxFontSizeMultiplier, lineBreakStrategy); + NSMutableAttributedString *text = result.attributedText; + if (text.length == 0) { + return fallback; + } + + ENRMWritingDirectionMode writingDirectionMode = + ENRMResolveWritingDirectionMode([[NSString alloc] initWithUTF8String:typedProps.writingDirection.c_str()]); + ENRMApplyWritingDirectionMode(text, writingDirectionMode, resolvedLayoutDirection); + + NSInteger numberOfLines = (NSInteger)typedProps.numberOfLines; + NSLineBreakMode lineBreakMode = + ENRMResolveEllipsizeLineBreakMode([[NSString alloc] initWithUTF8String:typedProps.ellipsizeMode.c_str()]); + CGSize size = ENRMMeasureAttributedTextViewFree(text, maxWidth, config, typedProps.allowTrailingMargin, + result.lastElementMarginBottom, pointScaleFactor, numberOfLines, + lineBreakMode, YES); + if (size.height == 0) { + return fallback; + } + return size; + } +} + +/** + * Measures segmented EnrichedMarkdown content from props alone, on the + * calling thread, replicating the view path end to end: the streaming table + * filter (`ENRMRenderableMarkdownForStreaming` with the props' + * streamingConfig.tableMode), the segment split and per-segment rendering + * (`ENRMRenderSegmentsFromAST` + per-text-segment writing direction — the + * same calls `renderMarkdownContent:` makes), then the walk from + * `computeSegmentLayoutForWidth:`: text segments include their trailing + * margin unless last (`!isLast || allowTrailingMargin`), table and math + * segments add their config marginTop before and marginBottom after under the + * same condition, tables report full width. Finishes with `measureSize:`'s + * pixel rounding (width capped at maxWidth) and its + * (maxWidth × system-16 line height) fallback for empty/failed content. + */ +template +static inline CGSize ENRMMeasureSegmentedMarkdownViewFree(const PropsT &typedProps, CGFloat maxWidth, CGFloat fontScale, + CGFloat pointScaleFactor, + NSWritingDirection resolvedLayoutDirection) +{ + @autoreleasepool { + CGSize fallback = CGSizeMake(maxWidth, UIFontLineHeight([UIFont systemFontOfSize:16.0])); + if (typedProps.markdown.empty()) { + return fallback; + } + + NSString *markdown = [[NSString alloc] initWithUTF8String:typedProps.markdown.c_str()]; + + if (typedProps.streamingAnimation) { + NSString *tableModeStr = [[NSString alloc] initWithUTF8String:typedProps.streamingConfig.tableMode.c_str()]; + ENRMTableStreamingMode tableStreamingMode = + [tableModeStr isEqualToString:@"hidden"] ? ENRMTableStreamingModeHidden : ENRMTableStreamingModeProgressive; + NSString *codeBlockModeStr = + [[NSString alloc] initWithUTF8String:typedProps.streamingConfig.codeBlockMode.c_str()]; + ENRMCodeBlockStreamingMode codeBlockStreamingMode = [codeBlockModeStr isEqualToString:@"hidden"] + ? ENRMCodeBlockStreamingModeHidden + : ENRMCodeBlockStreamingModeProgressive; + markdown = ENRMRenderableMarkdownForStreaming(markdown, tableStreamingMode, codeBlockStreamingMode, NULL); + if (markdown.length == 0) { + return fallback; + } + } + + StyleConfig *config = ENRMStyleConfigFromProps(typedProps, fontScale); + + ENRMMd4cFlags *flags = ENRMMd4cFlagsFromProps(typedProps.md4cFlags); + ENRMMarkdownParser *parser = [[ENRMMarkdownParser alloc] init]; + MarkdownASTNode *ast = [parser parseMarkdown:markdown + flags:flags + isGFM:typedProps.isGFM + linkRegex:ENRMLinkRegexConfigFromProps(typedProps.linkRecognition.text) + inlineCodeLinkRegex:ENRMLinkRegexConfigFromProps(typedProps.linkRecognition.inlineCode)]; + if (!ast) { + return fallback; + } + + NSLineBreakStrategy lineBreakStrategy = + ENRMResolveLineBreakStrategy([[NSString alloc] initWithUTF8String:typedProps.lineBreakStrategyIOS.c_str()]); + ENRMWritingDirectionMode writingDirectionMode = + ENRMResolveWritingDirectionMode([[NSString alloc] initWithUTF8String:typedProps.writingDirection.c_str()]); + + NSArray *segments = + ENRMRenderSegmentsFromAST(ast, config, typedProps.allowTrailingMargin, typedProps.allowFontScaling, + typedProps.maxFontSizeMultiplier, lineBreakStrategy, /*blockquoteContent*/ NO); + for (ENRMRenderedSegment *segment in segments) { + if (segment.kind == ENRMSegmentKindText && segment.textResult) { + ENRMApplyWritingDirectionMode(segment.textResult.attributedText, writingDirectionMode, resolvedLayoutDirection); + } + } + + if (segments.count == 0) { + return fallback; + } + + CGFloat yOffset = 0.0; + CGFloat maxContentWidth = 0.0; + const NSUInteger lastIndex = segments.count - 1; + + for (NSUInteger i = 0; i < segments.count; i++) { + ENRMRenderedSegment *segment = segments[i]; + const BOOL isLast = (i == lastIndex); + const BOOL shouldAddBottomMargin = (!isLast || typedProps.allowTrailingMargin); + + if (segment.kind == ENRMSegmentKindText && segment.textResult) { + CGSize textSize = ENRMMeasureAttributedTextViewFree( + segment.textResult.attributedText, maxWidth, config, shouldAddBottomMargin, + segment.textResult.lastElementMarginBottom, pointScaleFactor, 0, NSLineBreakByWordWrapping, YES); + yOffset += textSize.height; + maxContentWidth = MAX(maxContentWidth, textSize.width); + } else if (segment.kind == ENRMSegmentKindTable && segment.tableSegment) { + yOffset += config.tableMarginTop; + yOffset += [TableContainerView measureHeightForTableNode:segment.tableSegment.tableNode + config:config + allowFontScaling:typedProps.allowFontScaling + maxFontSizeMultiplier:typedProps.maxFontSizeMultiplier + writingDirectionMode:writingDirectionMode + resolvedLayoutDirection:resolvedLayoutDirection]; + maxContentWidth = maxWidth; + if (shouldAddBottomMargin) { + yOffset += config.tableMarginBottom; + } + } else if (segment.kind == ENRMSegmentKindCodeBlock && segment.codeBlockSegment) { + yOffset += config.codeBlockMarginTop; + yOffset += [ENRMCodeBlockContainerView measureHeightForCodeBlockNode:segment.codeBlockSegment.codeBlockNode + config:config]; + maxContentWidth = maxWidth; + if (shouldAddBottomMargin) { + yOffset += config.codeBlockMarginBottom; + } + } else if (segment.kind == ENRMSegmentKindBlockquote && segment.blockquoteSegment) { + yOffset += config.blockquoteMarginTop; + yOffset += [ENRMBlockquoteContainerView measureHeightForBlockquoteNode:segment.blockquoteSegment.blockquoteNode + config:config + maxWidth:maxWidth + pointScaleFactor:pointScaleFactor + allowFontScaling:typedProps.allowFontScaling + lineBreakStrategy:lineBreakStrategy]; + maxContentWidth = maxWidth; + if (shouldAddBottomMargin) { + yOffset += config.blockquoteMarginBottom; + } + } +#if ENRICHED_MARKDOWN_MATH + else if (segment.kind == ENRMSegmentKindMath && segment.mathSegment) { + yOffset += config.mathMarginTop; + yOffset += [ENRMMathContainerView measureHeightForLatex:segment.mathSegment.latex + config:config + maxWidth:maxWidth]; + maxContentWidth = maxWidth; + if (shouldAddBottomMargin) { + yOffset += config.mathMarginBottom; + } + } +#endif +#if ENRICHED_MARKDOWN_VIDEO + else if (segment.kind == ENRMSegmentKindVideo && segment.videoSegment) { + yOffset += config.videoMarginTop; + yOffset += [ENRMVideoContainerView measureHeightForVideoNode:segment.videoSegment.videoNode + config:config + maxWidth:maxWidth]; + maxContentWidth = maxWidth; + if (shouldAddBottomMargin) { + yOffset += config.videoMarginBottom; + } + } +#endif + } + + if (yOffset == 0) { + return fallback; + } + + CGFloat measuredWidth = MIN(ceil(maxContentWidth * pointScaleFactor) / pointScaleFactor, maxWidth); + CGFloat measuredHeight = ceil(yOffset * pointScaleFactor) / pointScaleFactor; + return CGSizeMake(measuredWidth, measuredHeight); + } +} diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownComponentDescriptor.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownComponentDescriptor.h new file mode 100644 index 000000000000..f6707cb88a76 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownComponentDescriptor.h @@ -0,0 +1,18 @@ +#pragma once +#include "EnrichedMarkdownShadowNode.h" +#include +#include + +namespace facebook::react { + +class EnrichedMarkdownComponentDescriptor final : public ConcreteComponentDescriptor { +public: + using ConcreteComponentDescriptor::ConcreteComponentDescriptor; + + void adopt(ShadowNode &shadowNode) const override { + react_native_assert(dynamic_cast(&shadowNode)); + ConcreteComponentDescriptor::adopt(shadowNode); + } +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.h new file mode 100644 index 000000000000..8189d964eadc --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.h @@ -0,0 +1,41 @@ +#pragma once +#include "MeasurementCache.h" +#include +#include +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char EnrichedMarkdownComponentName[]; + +class EnrichedMarkdownShadowNode : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + EnrichedMarkdownShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, + ShadowNodeTraits traits); + + EnrichedMarkdownShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + + static ShadowNodeTraits BaseTraits() + { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + +private: + int localHeightRecalculationCounter_{0}; + mutable int lastExactMeasurementCounter_{0}; + mutable CGSize lastExactMeasurementSize_{0, 0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.mm b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.mm new file mode 100644 index 000000000000..056225f54a2a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownShadowNode.mm @@ -0,0 +1,69 @@ +#import "EnrichedMarkdownShadowNode.h" +#import "ENRMViewFreeMeasurement.h" +#import "EnrichedMarkdown.h" +#import "ShadowMeasurementUtils.h" +#import + +namespace facebook::react { + +extern const char EnrichedMarkdownComponentName[] = "EnrichedMarkdown"; + +EnrichedMarkdownShadowNode::EnrichedMarkdownShadowNode(const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits) + : ConcreteViewShadowNode(fragment, family, traits) +{ +} + +EnrichedMarkdownShadowNode::EnrichedMarkdownShadowNode(const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment), + localHeightRecalculationCounter_( + static_cast(sourceShadowNode).localHeightRecalculationCounter_), + lastExactMeasurementCounter_( + static_cast(sourceShadowNode).lastExactMeasurementCounter_), + lastExactMeasurementSize_( + static_cast(sourceShadowNode).lastExactMeasurementSize_) +{ + const auto &oldProps = *std::static_pointer_cast(sourceShadowNode.getProps()); + const auto &newProps = *std::static_pointer_cast(this->getProps()); + + if (newProps.streamingAnimation && ENRMPropsNeedExactStreamingMeasurement(oldProps, newProps)) { + lastExactMeasurementCounter_ = -1; + } + + dirtyLayoutIfNeeded(); +} + +void EnrichedMarkdownShadowNode::dirtyLayoutIfNeeded() +{ + const auto state = this->getStateData(); + const int receivedCounter = state.getHeightRecalculationCounter(); + + if (receivedCounter > localHeightRecalculationCounter_) { + localHeightRecalculationCounter_ = receivedCounter; + YGNodeMarkDirty(&yogaNode_); + } +} + +Size EnrichedMarkdownShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const +{ + const auto propsHandle = std::static_pointer_cast(this->getProps()); + const auto &typedProps = *propsHandle; + const int receivedCounter = getStateData().getHeightRecalculationCounter(); + const EnrichedMarkdownProps *props = propsHandle.get(); + CGFloat pointScaleFactor = layoutContext.pointScaleFactor; + NSWritingDirection resolvedLayoutDirection = layoutConstraints.layoutDirection == LayoutDirection::RightToLeft + ? NSWritingDirectionRightToLeft + : NSWritingDirectionLeftToRight; + + return ENRMMeasureMarkdownContent( + typedProps, getStateData().getComponentViewRef(), receivedCounter, lastExactMeasurementCounter_, + lastExactMeasurementSize_, MarkdownFlavor::GitHub, layoutContext, layoutConstraints, + ^(EnrichedMarkdown *view, CGFloat maxWidth, CGFloat fontScale) { + return ENRMMeasureSegmentedMarkdownViewFree(*props, maxWidth, fontScale, pointScaleFactor, + resolvedLayoutDirection); + }); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownState.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownState.h new file mode 100644 index 000000000000..3391751fd6b5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownState.h @@ -0,0 +1,23 @@ +#pragma once +#include + +namespace facebook::react { + +class EnrichedMarkdownState { +public: + EnrichedMarkdownState() = default; + EnrichedMarkdownState(int counter, std::shared_ptr ref) : counter_(counter), viewRef_(ref) {} + + int getHeightRecalculationCounter() const { + return counter_; + } + std::shared_ptr getComponentViewRef() const { + return viewRef_; + } + +private: + int counter_{0}; + std::shared_ptr viewRef_{nullptr}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextComponentDescriptor.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextComponentDescriptor.h new file mode 100644 index 000000000000..9b210913294b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextComponentDescriptor.h @@ -0,0 +1,19 @@ +#pragma once +#include "EnrichedMarkdownTextShadowNode.h" +#include +#include + +namespace facebook::react { + +class EnrichedMarkdownTextComponentDescriptor final + : public ConcreteComponentDescriptor { +public: + using ConcreteComponentDescriptor::ConcreteComponentDescriptor; + + void adopt(ShadowNode &shadowNode) const override { + react_native_assert(dynamic_cast(&shadowNode)); + ConcreteComponentDescriptor::adopt(shadowNode); + } +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.h new file mode 100644 index 000000000000..6a25a6918fd3 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.h @@ -0,0 +1,43 @@ +#pragma once +#include "MeasurementCache.h" +#include +#include +#include +#include +#include + +namespace facebook::react { + +JSI_EXPORT extern const char EnrichedMarkdownTextComponentName[]; + +/// ShadowNode implementing measureContent for automatic height calculation. +class EnrichedMarkdownTextShadowNode + : public ConcreteViewShadowNode { +public: + using ConcreteViewShadowNode::ConcreteViewShadowNode; + + EnrichedMarkdownTextShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, + ShadowNodeTraits traits); + + EnrichedMarkdownTextShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); + + void dirtyLayoutIfNeeded(); + + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; + + static ShadowNodeTraits BaseTraits() + { + auto traits = ConcreteViewShadowNode::BaseTraits(); + traits.set(ShadowNodeTraits::Trait::LeafYogaNode); + traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); + return traits; + } + +private: + int localHeightRecalculationCounter_{0}; + mutable int lastExactMeasurementCounter_{0}; + mutable CGSize lastExactMeasurementSize_{0, 0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.mm b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.mm new file mode 100644 index 000000000000..7ae934ac2632 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextShadowNode.mm @@ -0,0 +1,69 @@ +#import "EnrichedMarkdownTextShadowNode.h" +#import "ENRMViewFreeMeasurement.h" +#import "EnrichedMarkdownText.h" +#import "ShadowMeasurementUtils.h" +#import + +namespace facebook::react { + +extern const char EnrichedMarkdownTextComponentName[] = "EnrichedMarkdownText"; + +EnrichedMarkdownTextShadowNode::EnrichedMarkdownTextShadowNode(const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, + ShadowNodeTraits traits) + : ConcreteViewShadowNode(fragment, family, traits) +{ +} + +EnrichedMarkdownTextShadowNode::EnrichedMarkdownTextShadowNode(const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) + : ConcreteViewShadowNode(sourceShadowNode, fragment), + localHeightRecalculationCounter_( + static_cast(sourceShadowNode).localHeightRecalculationCounter_), + lastExactMeasurementCounter_( + static_cast(sourceShadowNode).lastExactMeasurementCounter_), + lastExactMeasurementSize_( + static_cast(sourceShadowNode).lastExactMeasurementSize_) +{ + const auto &oldProps = *std::static_pointer_cast(sourceShadowNode.getProps()); + const auto &newProps = *std::static_pointer_cast(this->getProps()); + + if (newProps.streamingAnimation && ENRMPropsNeedExactStreamingMeasurement(oldProps, newProps)) { + lastExactMeasurementCounter_ = -1; + } + + dirtyLayoutIfNeeded(); +} + +void EnrichedMarkdownTextShadowNode::dirtyLayoutIfNeeded() +{ + const auto state = this->getStateData(); + const int receivedCounter = state.getHeightRecalculationCounter(); + + if (receivedCounter > localHeightRecalculationCounter_) { + localHeightRecalculationCounter_ = receivedCounter; + YGNodeMarkDirty(&yogaNode_); + } +} + +Size EnrichedMarkdownTextShadowNode::measureContent(const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const +{ + const auto propsHandle = std::static_pointer_cast(this->getProps()); + const auto &typedProps = *propsHandle; + const int receivedCounter = getStateData().getHeightRecalculationCounter(); + const EnrichedMarkdownTextProps *props = propsHandle.get(); + CGFloat pointScaleFactor = layoutContext.pointScaleFactor; + NSWritingDirection resolvedLayoutDirection = layoutConstraints.layoutDirection == LayoutDirection::RightToLeft + ? NSWritingDirectionRightToLeft + : NSWritingDirectionLeftToRight; + + return ENRMMeasureMarkdownContent( + typedProps, getStateData().getComponentViewRef(), receivedCounter, lastExactMeasurementCounter_, + lastExactMeasurementSize_, MarkdownFlavor::CommonMark, layoutContext, layoutConstraints, + ^(EnrichedMarkdownText *view, CGFloat maxWidth, CGFloat fontScale) { + return ENRMMeasureMarkdownViewFree(*props, maxWidth, fontScale, pointScaleFactor, resolvedLayoutDirection); + }); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextState.h b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextState.h new file mode 100644 index 000000000000..d01734ed3d35 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/EnrichedMarkdownTextState.h @@ -0,0 +1,24 @@ +#pragma once +#include + +namespace facebook::react { + +/// Counter triggers layout recalculation, viewRef allows shadow node to access view for measurement. +class EnrichedMarkdownTextState { +public: + EnrichedMarkdownTextState() = default; + EnrichedMarkdownTextState(int counter, std::shared_ptr ref) : counter_(counter), viewRef_(ref) {} + + int getHeightRecalculationCounter() const { + return counter_; + } + std::shared_ptr getComponentViewRef() const { + return viewRef_; + } + +private: + int counter_{0}; + std::shared_ptr viewRef_{nullptr}; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/MeasurementCache.h b/packages/react-native-enriched-markdown/ios/internals/MeasurementCache.h new file mode 100644 index 000000000000..5fdaee34451f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/MeasurementCache.h @@ -0,0 +1,303 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +struct HashUtils { + + static inline size_t combine(size_t h, size_t v) + { + return h ^ (v + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2)); + } + + template static inline void hash_one(size_t &seed, const T &v) + { + seed = combine(seed, std::hash{}(v)); + } +}; + +enum class MarkdownFlavor : uint8_t { + CommonMark = 0, + GitHub = 1, +}; + +struct MeasurementCacheKey { + std::string markdown; + CGFloat maxWidth; + bool allowTrailingMargin; + bool allowFontScaling; + double maxFontSizeMultiplier; + bool md4cFlagsUnderline; + bool md4cFlagsSuperscript; + bool md4cFlagsSubscript; + bool md4cFlagsHighlight; + bool md4cFlagsLatexMath; + bool md4cFlagsHardSoftBreaks; + bool md4cFlagsPreserveBlankLines; + bool md4cFlagsAdmonitions; + size_t styleFingerprint; + size_t linkPillContentFingerprint; + CGFloat fontScale; + MarkdownFlavor flavor; + std::string lineBreakStrategyIOS; + std::string writingDirection; + int numberOfLines; + std::string ellipsizeMode; + std::string linkRegexKey; + std::string inlineCodeLinkRegexKey; + + bool operator==(const MeasurementCacheKey &other) const + { + return std::tie(markdown, maxWidth, allowTrailingMargin, allowFontScaling, maxFontSizeMultiplier, + md4cFlagsUnderline, md4cFlagsSuperscript, md4cFlagsSubscript, md4cFlagsHighlight, + md4cFlagsLatexMath, md4cFlagsHardSoftBreaks, md4cFlagsPreserveBlankLines, md4cFlagsAdmonitions, + styleFingerprint, linkPillContentFingerprint, fontScale, flavor, lineBreakStrategyIOS, + writingDirection, numberOfLines, ellipsizeMode, linkRegexKey, inlineCodeLinkRegexKey) == + std::tie(other.markdown, other.maxWidth, other.allowTrailingMargin, other.allowFontScaling, + other.maxFontSizeMultiplier, other.md4cFlagsUnderline, other.md4cFlagsSuperscript, + other.md4cFlagsSubscript, other.md4cFlagsHighlight, other.md4cFlagsLatexMath, + other.md4cFlagsHardSoftBreaks, other.md4cFlagsPreserveBlankLines, other.md4cFlagsAdmonitions, + other.styleFingerprint, other.linkPillContentFingerprint, other.fontScale, other.flavor, + other.lineBreakStrategyIOS, other.writingDirection, other.numberOfLines, other.ellipsizeMode, + other.linkRegexKey, other.inlineCodeLinkRegexKey); + } +}; + +struct MeasurementCacheKeyHash { + size_t operator()(const MeasurementCacheKey &key) const + { + size_t h = 0; + HashUtils::hash_one(h, key.markdown); + HashUtils::hash_one(h, key.maxWidth); + HashUtils::hash_one(h, key.allowTrailingMargin); + HashUtils::hash_one(h, key.allowFontScaling); + HashUtils::hash_one(h, key.maxFontSizeMultiplier); + HashUtils::hash_one(h, key.md4cFlagsUnderline); + HashUtils::hash_one(h, key.md4cFlagsSuperscript); + HashUtils::hash_one(h, key.md4cFlagsSubscript); + HashUtils::hash_one(h, key.md4cFlagsHighlight); + HashUtils::hash_one(h, key.md4cFlagsLatexMath); + HashUtils::hash_one(h, key.md4cFlagsHardSoftBreaks); + HashUtils::hash_one(h, key.md4cFlagsPreserveBlankLines); + HashUtils::hash_one(h, key.md4cFlagsAdmonitions); + HashUtils::hash_one(h, key.styleFingerprint); + HashUtils::hash_one(h, key.linkPillContentFingerprint); + HashUtils::hash_one(h, key.fontScale); + HashUtils::hash_one(h, static_cast(key.flavor)); + HashUtils::hash_one(h, key.lineBreakStrategyIOS); + HashUtils::hash_one(h, key.writingDirection); + HashUtils::hash_one(h, key.numberOfLines); + HashUtils::hash_one(h, key.ellipsizeMode); + HashUtils::hash_one(h, key.linkRegexKey); + HashUtils::hash_one(h, key.inlineCodeLinkRegexKey); + return h; + } +}; + +struct CachedSize { + CGFloat width; + CGFloat height; +}; + +template inline size_t computeStyleFingerprint(const StyleStruct &s) +{ + size_t h = 0; + auto hashFields = [&](auto... args) { (HashUtils::hash_one(h, args), ...); }; + + auto hashTextLayout = [&](const auto &item) { + hashFields(item.fontFamily, item.fontSize, item.fontWeight, item.marginTop, item.marginBottom, item.lineHeight); + }; + + // Block Elements + hashTextLayout(s.paragraph); + hashFields(s.paragraph.textAlign); + hashTextLayout(s.h1); + hashFields(s.h1.textAlign); + hashTextLayout(s.h2); + hashFields(s.h2.textAlign); + hashTextLayout(s.h3); + hashFields(s.h3.textAlign); + hashTextLayout(s.h4); + hashFields(s.h4.textAlign); + hashTextLayout(s.h5); + hashFields(s.h5.textAlign); + hashTextLayout(s.h6); + hashFields(s.h6.textAlign); + + hashTextLayout(s.blockquote); + hashFields(s.blockquote.borderWidth, s.blockquote.gapWidth, s.blockquote.padding, s.blockquote.borderRadius); + + hashTextLayout(s.list); + hashFields(s.list.bulletSize, s.list.markerMinWidth, s.list.markerFontWeight, s.list.gapWidth, s.list.marginLeft, + s.list.itemSpacing); + + // Code & Inlines + hashFields(s.codeBlock.fontFamily, s.codeBlock.fontSize, s.codeBlock.fontWeight, s.codeBlock.marginTop, + s.codeBlock.marginBottom, s.codeBlock.lineHeight, s.codeBlock.padding, s.codeBlock.borderRadius, + s.codeBlock.borderWidth); + hashFields(s.code.fontFamily, s.code.fontSize, s.code.fontScale); + hashFields(s.link.fontFamily, s.strong.fontFamily, s.strong.fontWeight, s.em.fontFamily, s.em.fontStyle); + // Variants change link metrics: a font family, or a pill box around the label. + for (const auto &variant : s.linkVariants) { + hashFields(variant.pattern, variant.fontFamily, variant.pill.enabled, variant.pill.label, variant.pill.iconUri, + variant.pill.paddingHorizontal, variant.pill.paddingVertical, variant.pill.lineHeight, + variant.pill.borderWidth, variant.pill.maxWidth); + } + hashFields(s.highlight.backgroundColor, s.highlight.color); + + // Visual/Spacing Elements + hashFields(s.image.height, s.image.maxHeight, s.image.aspectRatio, s.image.marginTop, s.image.marginBottom); + hashFields(s.video.marginTop, s.video.marginBottom, s.video.borderRadius, s.video.aspectRatio, + s.video.backgroundColor); + hashFields(s.inlineImage.size); + hashFields(s.thematicBreak.height, s.thematicBreak.marginTop, s.thematicBreak.marginBottom); + + // Complex Components + hashTextLayout(s.table); + hashFields(s.table.headerFontFamily, s.table.cellPaddingHorizontal, s.table.cellPaddingVertical, s.table.borderWidth, + s.table.borderRadius, s.table.horizontalOverflow); + hashFields(s.math.fontSize, s.math.padding, s.math.marginTop, s.math.marginBottom, s.math.textAlign); + hashFields(s.taskList.checkboxSize, s.taskList.checkboxBorderRadius); + + return h; +} + +// Pill labels and icons (the `linkPillContent` prop) change link widths. +template inline size_t computeLinkPillContentFingerprint(const ContentVector &content) +{ + size_t h = 0; + for (const auto &entry : content) { + HashUtils::hash_one(h, entry.url); + HashUtils::hash_one(h, entry.label); + HashUtils::hash_one(h, entry.iconUri); + } + return h; +} + +template inline std::string buildLinkRecognitionCacheKey(const RegexProps &props) +{ + std::string key; + key += props.caseInsensitive ? '1' : '0'; + key += props.dotAll ? '1' : '0'; + key += props.isDisabled ? '1' : '0'; + key += props.isDefault ? '1' : '0'; + return key + props.pattern; +} + +template +inline MeasurementCacheKey buildMeasurementCacheKey(const PropsType &props, CGFloat maxWidth, CGFloat fontScale, + MarkdownFlavor flavor) +{ + return MeasurementCacheKey{ + .markdown = props.markdown, + .maxWidth = maxWidth, + .allowTrailingMargin = props.allowTrailingMargin, + .allowFontScaling = props.allowFontScaling, + .maxFontSizeMultiplier = props.maxFontSizeMultiplier, + .md4cFlagsUnderline = props.md4cFlags.underline, + .md4cFlagsSuperscript = props.md4cFlags.superscript, + .md4cFlagsSubscript = props.md4cFlags.subscript, + .md4cFlagsHighlight = props.md4cFlags.highlight, + .md4cFlagsLatexMath = props.md4cFlags.latexMath, + .md4cFlagsHardSoftBreaks = props.md4cFlags.hardSoftBreaks, + .md4cFlagsPreserveBlankLines = props.md4cFlags.preserveBlankLines, + .md4cFlagsAdmonitions = props.md4cFlags.admonitions, + .styleFingerprint = computeStyleFingerprint(props.markdownStyle), + .linkPillContentFingerprint = computeLinkPillContentFingerprint(props.linkPillContent), + .fontScale = fontScale, + .flavor = flavor, + .lineBreakStrategyIOS = props.lineBreakStrategyIOS, + .writingDirection = props.writingDirection, + .numberOfLines = props.numberOfLines, + .ellipsizeMode = props.ellipsizeMode, + .linkRegexKey = buildLinkRecognitionCacheKey(props.linkRecognition.text), + .inlineCodeLinkRegexKey = buildLinkRecognitionCacheKey(props.linkRecognition.inlineCode), + }; +} + +/** + * Thread-safe global measurement cache using an LRU (Least Recently Used) strategy. + * This ensures O(1) lookups while automatically discarding the oldest entries. + */ +class MeasurementCache { +public: + struct CacheEntry { + MeasurementCacheKey key; + CachedSize size; + }; + + static MeasurementCache &shared() + { + static MeasurementCache instance; + return instance; + } + + bool get(const MeasurementCacheKey &key, CachedSize &outSize) + { + std::lock_guard lock(mutex_); + + auto it = map_.find(key); + if (it == map_.end()) { + return false; + } + + list_.splice(list_.begin(), list_, it->second); + + outSize = it->second->size; + return true; + } + + void set(const MeasurementCacheKey &key, CachedSize size) + { + std::lock_guard lock(mutex_); + + auto it = map_.find(key); + if (it != map_.end()) { + it->second->size = size; + list_.splice(list_.begin(), list_, it->second); + return; + } + + list_.push_front({key, size}); + map_[key] = list_.begin(); + + if (map_.size() > kMaxEntries) { + auto &lastEntry = list_.back(); + map_.erase(lastEntry.key); + list_.pop_back(); + } + } + + void removeMatchingMarkdown(const std::string &markdown) + { + std::lock_guard lock(mutex_); + + for (auto it = list_.begin(); it != list_.end();) { + if (it->key.markdown == markdown) { + map_.erase(it->key); + it = list_.erase(it); + } else { + ++it; + } + } + } + +private: + MeasurementCache() = default; + + static constexpr size_t kMaxEntries = 512; + mutable std::mutex mutex_; + + std::list list_; + std::unordered_map::iterator, MeasurementCacheKeyHash> map_; +}; + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/internals/ShadowMeasurementUtils.h b/packages/react-native-enriched-markdown/ios/internals/ShadowMeasurementUtils.h new file mode 100644 index 000000000000..9904ae55fa14 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/internals/ShadowMeasurementUtils.h @@ -0,0 +1,142 @@ +#pragma once + +#include "MeasurementCache.h" +#import +#import +#include +#include +#include +#include +#include + +namespace facebook::react { + +// Threading contract (issue #550): measureContent may run on any thread while +// RN holds commit locks that main-thread committers (e.g. Reanimated) also +// acquire — with `preventShadowTreeCommitExhaustion`, the JS thread re-runs +// layout under `revisionMutexRecursive_` after 3 failed optimistic commits. +// Any dispatch_sync to main from this path can therefore deadlock: JS waits +// for main, main waits for the mutex JS holds (watchdog kill 0x8BADF00D). +// Nothing in the measurement path may wait on the main thread. +// EnrichedMarkdownText and EnrichedMarkdown both measure view-free +// (ENRMViewFreeMeasurement.h) and comply fully. The one known remaining +// violation is the text input's own measureContent +// (EnrichedMarkdownTextInputShadowNode.mm), which measures live editable +// UITextView state and needs its own strategy. + +/** + * Font scale (Dynamic Type multiplier) for measurement, without touching the + * main thread. + * + * Reads `LayoutContext::fontSizeMultiplier` instead of calling + * `RCTFontSizeMultiplier()` (a UIKit read that previously forced a + * dispatch_sync to main on every measure — a deadlock window under the locked + * commit fallback, see the contract above). RN maintains the multiplier for + * us: `RCTFabricSurface::_updateLayoutContext` sets it on main from + * `RCTFontSizeMultiplier()` and re-runs `constraintLayout` whenever + * `UIContentSizeCategoryDidChangeNotification` fires, so every Dynamic Type + * change re-measures with the fresh value. This is the same source + * `ParagraphShadowNode` uses for core text. A measure racing a Dynamic Type + * change at worst caches under the outgoing scale, which is never read again + * once the re-layout lands. + */ +static inline CGFloat ENRMFontScaleForMeasurement(bool allowFontScaling, const LayoutContext &layoutContext) +{ + return allowFontScaling ? layoutContext.fontSizeMultiplier : 1.0; +} + +static inline Size ENRMClampMeasuredSize(CGSize size, const LayoutConstraints &layoutConstraints) +{ + Float clampedWidth = std::max((Float)size.width, layoutConstraints.minimumSize.width); + clampedWidth = std::min(clampedWidth, layoutConstraints.maximumSize.width); + Float clampedHeight = std::max((Float)size.height, layoutConstraints.minimumSize.height); + if (std::isfinite(layoutConstraints.maximumSize.height)) { + clampedHeight = std::min(clampedHeight, layoutConstraints.maximumSize.height); + } + return {clampedWidth, clampedHeight}; +} + +template +static inline bool ENRMPropsNeedExactStreamingMeasurement(const PropsT &oldProps, const PropsT &newProps) +{ + return oldProps.streamingAnimation != newProps.streamingAnimation || + oldProps.allowFontScaling != newProps.allowFontScaling || + oldProps.maxFontSizeMultiplier != newProps.maxFontSizeMultiplier || + oldProps.allowTrailingMargin != newProps.allowTrailingMargin || + oldProps.md4cFlags.underline != newProps.md4cFlags.underline || + oldProps.md4cFlags.superscript != newProps.md4cFlags.superscript || + oldProps.md4cFlags.subscript != newProps.md4cFlags.subscript || + oldProps.md4cFlags.latexMath != newProps.md4cFlags.latexMath || + oldProps.md4cFlags.highlight != newProps.md4cFlags.highlight || + oldProps.md4cFlags.hardSoftBreaks != newProps.md4cFlags.hardSoftBreaks || + oldProps.md4cFlags.preserveBlankLines != newProps.md4cFlags.preserveBlankLines || + oldProps.isGFM != newProps.isGFM || oldProps.md4cFlags.admonitions != newProps.md4cFlags.admonitions || + computeStyleFingerprint(oldProps.markdownStyle) != computeStyleFingerprint(newProps.markdownStyle); +} + +/** + * Shared measureContent implementation for the markdown component views. + * + * Owns the thread-safe layers — the streaming fast path (lock-free + * `ENRMAtomicSize` mailbox published by `updateLayoutMetrics:`), the + * LRU measurement cache, and the `layoutContext`-sourced font scale — then + * delegates cache misses to `measureUncached`, through which both components + * plug their view-free pipeline (`ENRMMeasureMarkdownViewFree` / + * `ENRMMeasureSegmentedMarkdownViewFree`); the resolved view is still handed + * to the block for strategies that can use it. `fontScale` handed to the + * block is the real multiplier even when streaming skips the cache — + * rendering must always use it. + */ +template +static inline Size +ENRMMeasureMarkdownContent(const PropsT &typedProps, const std::shared_ptr &componentViewRef, int receivedCounter, + int &lastExactMeasurementCounter, CGSize &lastExactMeasurementSize, MarkdownFlavor flavor, + const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints, + CGSize (^measureUncached)(ViewT *view, CGFloat maxWidth, CGFloat fontScale)) +{ + CGFloat maxWidth = layoutConstraints.maximumSize.width; + + RCTInternalGenericWeakWrapper *weakWrapper = (RCTInternalGenericWeakWrapper *)unwrapManagedObject(componentViewRef); + ViewT *view = weakWrapper ? (ViewT *)weakWrapper.object : nil; + + // Streaming fast path. Yoga re-measures several times per pass; the first call + // bumps lastExactMeasurementCounter, the rest land here. Return the freshly + // measured size, not the view's mailbox — mid-pass the frame isn't committed, + // so the mailbox is a generation stale and would freeze the height. + if (typedProps.streamingAnimation && view && receivedCounter <= lastExactMeasurementCounter) { + if (lastExactMeasurementSize.width > 0 && lastExactMeasurementSize.height > 0) { + return ENRMClampMeasuredSize(lastExactMeasurementSize, layoutConstraints); + } + CGSize currentSize = [view lastCommittedLayoutSize]; + if (currentSize.width > 0 && currentSize.height > 0) { + return ENRMClampMeasuredSize(currentSize, layoutConstraints); + } + } + + const bool shouldUseMeasurementCache = !typedProps.streamingAnimation; + CGFloat fontScale = ENRMFontScaleForMeasurement(typedProps.allowFontScaling, layoutContext); + + if (shouldUseMeasurementCache && !typedProps.markdown.empty()) { + auto cacheKey = buildMeasurementCacheKey(typedProps, maxWidth, fontScale, flavor); + CachedSize cached; + if (MeasurementCache::shared().get(cacheKey, cached)) { + return ENRMClampMeasuredSize(CGSizeMake(cached.width, cached.height), layoutConstraints); + } + } + + CGSize size = measureUncached(view, maxWidth, fontScale); + + if (shouldUseMeasurementCache && !typedProps.markdown.empty()) { + auto cacheKey = buildMeasurementCacheKey(typedProps, maxWidth, fontScale, flavor); + MeasurementCache::shared().set(cacheKey, {size.width, size.height}); + } + + if (typedProps.streamingAnimation) { + lastExactMeasurementCounter = receivedCounter; + lastExactMeasurementSize = size; + } + + return ENRMClampMeasuredSize(size, layoutConstraints); +} + +} // namespace facebook::react diff --git a/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.h b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.h new file mode 100644 index 000000000000..dd3bd3237706 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.h @@ -0,0 +1,27 @@ +#pragma once +#import + +#import "ENRMLatexErrorReporting.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Returns YES when the error was delivered to a live event emitter, NO when it +/// must be queued and flushed once an emitter is attached. +typedef BOOL (^ENRMLatexErrorEmit)(NSString *source, NSString *message, BOOL displayMode); + +/// Shared LaTeX-error plumbing for both host views. Owns the dedup set and the +/// pending queue and wires reporters; the only per-view difference - casting +/// `_eventEmitter` to the concrete type - stays in the `emit` block each view +/// supplies. +@interface ENRMLatexErrorCoordinator : NSObject + +- (instancetype)initWithEmit:(ENRMLatexErrorEmit)emit NS_DESIGNATED_INITIALIZER; +- (instancetype)init NS_UNAVAILABLE; + +- (void)wireReporters:(NSArray> *)reporters; +- (void)reportSource:(NSString *)source message:(NSString *)message displayMode:(BOOL)displayMode; +- (void)flushPending; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.mm b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.mm new file mode 100644 index 000000000000..ce6e3c25422f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorCoordinator.mm @@ -0,0 +1,75 @@ +#import "ENRMLatexErrorCoordinator.h" + +@interface ENRMPendingLatexError : NSObject +@property (nonatomic, copy, readonly) NSString *source; +@property (nonatomic, copy, readonly) NSString *message; +@property (nonatomic, readonly) BOOL displayMode; +@end + +@implementation ENRMPendingLatexError +- (instancetype)initWithSource:(NSString *)source message:(NSString *)message displayMode:(BOOL)displayMode +{ + if (self = [super init]) { + _source = [source copy]; + _message = [message copy]; + _displayMode = displayMode; + } + return self; +} +@end + +@implementation ENRMLatexErrorCoordinator { + ENRMLatexErrorEmit _emit; + NSMutableSet *_reportedErrors; + NSMutableArray *_pendingErrors; +} + +- (instancetype)initWithEmit:(ENRMLatexErrorEmit)emit +{ + if (self = [super init]) { + _emit = [emit copy]; + _reportedErrors = [NSMutableSet set]; + _pendingErrors = [NSMutableArray array]; + } + return self; +} + +- (void)wireReporters:(NSArray> *)reporters +{ + if (reporters.count == 0) + return; + __weak __typeof(self) weakSelf = self; + ENRMLatexErrorHandler handler = ^(NSString *source, NSString *message, BOOL displayMode) { + [weakSelf reportSource:source message:message displayMode:displayMode]; + }; + for (id reporter in reporters) { + reporter.onLatexError = handler; + [reporter reportLatexErrorIfNeeded]; + } +} + +- (void)reportSource:(NSString *)source message:(NSString *)message displayMode:(BOOL)displayMode +{ + NSString *key = [NSString stringWithFormat:@"%@ %@", displayMode ? @"B" : @"I", source]; + if ([_reportedErrors containsObject:key]) + return; + [_reportedErrors addObject:key]; + if (!_emit(source, message, displayMode)) { + [_pendingErrors addObject:[[ENRMPendingLatexError alloc] initWithSource:source + message:message + displayMode:displayMode]]; + } +} + +- (void)flushPending +{ + if (_pendingErrors.count == 0) + return; + NSArray *pending = [_pendingErrors copy]; + [_pendingErrors removeAllObjects]; + for (ENRMPendingLatexError *e in pending) { + _emit(e.source, e.message, e.displayMode); + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorReporting.h b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorReporting.h new file mode 100644 index 000000000000..c5fe9cbc7569 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/math/ENRMLatexErrorReporting.h @@ -0,0 +1,13 @@ +#pragma once +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^ENRMLatexErrorHandler)(NSString *source, NSString *message, BOOL displayMode); + +@protocol ENRMLatexErrorReporting +@property (nonatomic, copy, nullable) ENRMLatexErrorHandler onLatexError; +- (void)reportLatexErrorIfNeeded; +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/math/ENRMRaTeXBridge.swift b/packages/react-native-enriched-markdown/ios/math/ENRMRaTeXBridge.swift new file mode 100644 index 000000000000..29181be237f6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/math/ENRMRaTeXBridge.swift @@ -0,0 +1,73 @@ +import Foundation +import CoreGraphics +import CoreText +// RaTeX's core Swift sources (RaTeXEngine/RaTeXRenderer/RaTeXFontLoader/DisplayList) are +// vendored into this pod's own module (ios/vendor), so there is no external RaTeX module +// to import; they resolve as same-module symbols. The vendored files import the RaTeXFFI +// binary module from the XCFramework themselves. + +#if canImport(UIKit) +import UIKit +#elseif canImport(AppKit) +import AppKit +private typealias UIColor = NSColor +#endif + +@objc(ENRMRaTeXRenderResult) +public final class ENRMRaTeXRenderResult: NSObject { + private let renderer: RaTeXRenderer + + @objc public let width: CGFloat + @objc public let ascent: CGFloat + @objc public let descent: CGFloat + @objc public var totalHeight: CGFloat { ascent + descent } + + init(renderer: RaTeXRenderer) { + self.renderer = renderer + self.width = renderer.width + self.ascent = renderer.height + self.descent = renderer.depth + super.init() + } + + @objc public func draw(in context: CGContext) { + renderer.draw(in: context) + } +} + +@objc(ENRMRaTeXBridge) +public final class ENRMRaTeXBridge: NSObject { + + @objc public static func ensureFontsLoaded() { + RaTeXFontLoader.ensureLoaded() + } + + @objc public static func parse( + _ latex: String, + displayMode: Bool, + fontSize: CGFloat, + color: UIColor + ) -> ENRMRaTeXRenderResult? { + parse(latex, displayMode: displayMode, fontSize: fontSize, color: color, error: nil) + } + + @objc(parse:displayMode:fontSize:color:error:) + public static func parse( + _ latex: String, + displayMode: Bool, + fontSize: CGFloat, + color: UIColor, + error: NSErrorPointer + ) -> ENRMRaTeXRenderResult? { + RaTeXFontLoader.ensureLoaded() + do { + let displayList = try RaTeXEngine.shared.parse(latex, displayMode: displayMode, color: color) + let renderer = RaTeXRenderer(displayList: displayList, fontSize: fontSize) + return ENRMRaTeXRenderResult(renderer: renderer) + } catch let parseError { + NSLog("[RaTeX] Failed to parse LaTeX: %@", parseError.localizedDescription) + error?.pointee = parseError as NSError + return nil + } + } +} diff --git a/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.h b/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.h new file mode 100644 index 000000000000..6ca21812ef85 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.h @@ -0,0 +1,33 @@ +#import "MarkdownASTNode.h" +#import + +@interface ENRMMd4cFlags : NSObject + +@property (nonatomic, assign) BOOL underline; +@property (nonatomic, assign) BOOL latexMath; +@property (nonatomic, assign) BOOL superscript; +@property (nonatomic, assign) BOOL subscript; +@property (nonatomic, assign) BOOL highlight; +@property (nonatomic, assign) BOOL hardSoftBreaks; +@property (nonatomic, assign) BOOL preserveBlankLines; +@property (nonatomic, assign) BOOL admonitions; + ++ (instancetype)defaultFlags; + +@end + +@class ENRMLinkRegexConfig; + +@interface ENRMMarkdownParser : NSObject + +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown; +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown flags:(ENRMMd4cFlags *)flags; +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown flags:(ENRMMd4cFlags *)flags isGFM:(BOOL)isGFM; +// Recognition runs before returning the AST to renderers and measurement. +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown + flags:(ENRMMd4cFlags *)flags + isGFM:(BOOL)isGFM + linkRegex:(ENRMLinkRegexConfig *)linkRegex + inlineCodeLinkRegex:(ENRMLinkRegexConfig *)inlineCodeLinkRegex; + +@end diff --git a/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.mm b/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.mm new file mode 100644 index 000000000000..e8de7419fe00 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/ENRMMarkdownParser.mm @@ -0,0 +1,73 @@ +#import "ENRMMarkdownParser.h" +#import "ENRMLinkRegexConfig.h" +#import "MarkdownASTNode.h" + +extern MarkdownASTNode *parseMarkdownWithCppParser(NSString *markdown, ENRMMd4cFlags *flags, BOOL isGFM); +extern MarkdownASTNode *parseMarkdownWithCppParser(NSString *markdown, ENRMMd4cFlags *flags, BOOL isGFM, + ENRMLinkRegexConfig *textRegex, ENRMLinkRegexConfig *codeRegex); + +@implementation ENRMMd4cFlags + +- (instancetype)init +{ + if (self = [super init]) { + _underline = NO; + _latexMath = YES; + _superscript = NO; + _subscript = NO; + _highlight = NO; + _hardSoftBreaks = NO; + _preserveBlankLines = NO; + _admonitions = YES; + } + return self; +} + ++ (instancetype)defaultFlags +{ + return [[ENRMMd4cFlags alloc] init]; +} + +- (id)copyWithZone:(NSZone *)zone +{ + ENRMMd4cFlags *copy = [[ENRMMd4cFlags allocWithZone:zone] init]; + copy.underline = self.underline; + copy.latexMath = self.latexMath; + copy.superscript = self.superscript; + copy.subscript = self.subscript; + copy.highlight = self.highlight; + copy.hardSoftBreaks = self.hardSoftBreaks; + copy.preserveBlankLines = self.preserveBlankLines; + copy.admonitions = self.admonitions; + return copy; +} + +@end + +@implementation ENRMMarkdownParser + +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown +{ + return [self parseMarkdown:markdown flags:[ENRMMd4cFlags defaultFlags]]; +} + +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown flags:(ENRMMd4cFlags *)flags +{ + return [self parseMarkdown:markdown flags:flags isGFM:YES]; +} + +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown flags:(ENRMMd4cFlags *)flags isGFM:(BOOL)isGFM +{ + return parseMarkdownWithCppParser(markdown, flags, isGFM); +} + +- (MarkdownASTNode *)parseMarkdown:(NSString *)markdown + flags:(ENRMMd4cFlags *)flags + isGFM:(BOOL)isGFM + linkRegex:(ENRMLinkRegexConfig *)linkRegex + inlineCodeLinkRegex:(ENRMLinkRegexConfig *)inlineCodeLinkRegex +{ + return parseMarkdownWithCppParser(markdown, flags, isGFM, linkRegex, inlineCodeLinkRegex); +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/parser/ENRMTextLinkAttributes.h b/packages/react-native-enriched-markdown/ios/parser/ENRMTextLinkAttributes.h new file mode 100644 index 000000000000..9d36943d00d9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/ENRMTextLinkAttributes.h @@ -0,0 +1,7 @@ +#pragma once + +#import + +// Rendering metadata only. Copy reconstruction retains the source semantics. +static NSString *const ENRMRecognizedLinkAttributeName = @"ENRMRecognizedLink"; +static NSString *const ENRMRecognizedLinkOriginalUnderlineAttributeName = @"ENRMRecognizedLinkOriginalUnderline"; diff --git a/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.h b/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.h new file mode 100644 index 000000000000..63d33e5f92d9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.h @@ -0,0 +1,55 @@ +#import + +typedef NS_ENUM(NSInteger, MarkdownNodeType) { + MarkdownNodeTypeDocument, + MarkdownNodeTypeParagraph, + MarkdownNodeTypeText, + MarkdownNodeTypeLink, + MarkdownNodeTypeHeading, + MarkdownNodeTypeLineBreak, + MarkdownNodeTypeStrong, + MarkdownNodeTypeEmphasis, + MarkdownNodeTypeStrikethrough, + MarkdownNodeTypeUnderline, + MarkdownNodeTypeCode, + MarkdownNodeTypeImage, + MarkdownNodeTypeBlockquote, + MarkdownNodeTypeUnorderedList, + MarkdownNodeTypeOrderedList, + MarkdownNodeTypeListItem, + MarkdownNodeTypeCodeBlock, + MarkdownNodeTypeThematicBreak, + MarkdownNodeTypeTable, + MarkdownNodeTypeTableHead, + MarkdownNodeTypeTableBody, + MarkdownNodeTypeTableRow, + MarkdownNodeTypeTableHeaderCell, + MarkdownNodeTypeTableCell, + MarkdownNodeTypeLatexMathInline, + MarkdownNodeTypeLatexMathDisplay, + MarkdownNodeTypeSpoiler, + MarkdownNodeTypeSuperscript, + MarkdownNodeTypeSubscript, + MarkdownNodeTypeHighlight, + MarkdownNodeTypeSoftBreak, + MarkdownNodeTypeBlankLine, + MarkdownNodeTypeAdmonition, + MarkdownNodeTypeVideo +}; + +@interface MarkdownASTNode : NSObject + +@property (nonatomic, assign) MarkdownNodeType type; +@property (nonatomic, strong) NSString *content; +@property (nonatomic, strong) NSMutableDictionary *attributes; +@property (nonatomic, strong) NSMutableArray *children; + +- (instancetype)initWithType:(MarkdownNodeType)type; +- (void)addChild:(MarkdownASTNode *)child; +- (void)setAttribute:(NSString *)key value:(NSString *)value; + +@end + +/// A node type that md4c emits as a standalone block stacked vertically, +/// as opposed to an inline span. +BOOL ENRMIsTopLevelBlockType(MarkdownNodeType type); diff --git a/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.m b/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.m new file mode 100644 index 000000000000..b6fbe7b2bfa2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/MarkdownASTNode.m @@ -0,0 +1,52 @@ +#import "MarkdownASTNode.h" + +@implementation MarkdownASTNode + +- (instancetype)initWithType:(MarkdownNodeType)type +{ + if (self = [super init]) { + _type = type; + _content = nil; + _attributes = [[NSMutableDictionary alloc] init]; + _children = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addChild:(MarkdownASTNode *)child +{ + [_children addObject:child]; +} + +- (void)setAttribute:(NSString *)key value:(NSString *)value +{ + _attributes[key] = value; +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"MarkdownASTNode(type=%ld, content=%@, children=%lu)", (long)_type, _content, + (unsigned long)_children.count]; +} + +@end + +BOOL ENRMIsTopLevelBlockType(MarkdownNodeType type) +{ + switch (type) { + case MarkdownNodeTypeParagraph: + case MarkdownNodeTypeHeading: + case MarkdownNodeTypeCodeBlock: + case MarkdownNodeTypeBlockquote: + case MarkdownNodeTypeAdmonition: + case MarkdownNodeTypeTable: + case MarkdownNodeTypeUnorderedList: + case MarkdownNodeTypeOrderedList: + case MarkdownNodeTypeThematicBreak: + case MarkdownNodeTypeBlankLine: + case MarkdownNodeTypeLatexMathDisplay: + return YES; + default: + return NO; + } +} diff --git a/packages/react-native-enriched-markdown/ios/parser/MarkdownParserBridge.mm b/packages/react-native-enriched-markdown/ios/parser/MarkdownParserBridge.mm new file mode 100644 index 000000000000..b65bf830fb03 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/parser/MarkdownParserBridge.mm @@ -0,0 +1,235 @@ +#import "ENRMLinkRegexConfig.h" +#import "ENRMMarkdownParser.h" +#include "MD4CParser.hpp" +#import "MarkdownASTNode.h" +#include "MarkdownASTNode.hpp" +#include "TextLinkRecognizer.hpp" +#import + +// Convert C++ AST node to Objective-C AST node +static MarkdownASTNode *convertCppASTToObjC(std::shared_ptr cppNode) +{ + if (!cppNode) { + return [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeDocument]; + } + + // Convert C++ NodeType enum to Objective-C MarkdownNodeType + MarkdownNodeType objcType; + switch (cppNode->type) { + case Markdown::NodeType::Document: + objcType = MarkdownNodeTypeDocument; + break; + case Markdown::NodeType::Paragraph: + objcType = MarkdownNodeTypeParagraph; + break; + case Markdown::NodeType::Text: + objcType = MarkdownNodeTypeText; + break; + case Markdown::NodeType::Link: + objcType = MarkdownNodeTypeLink; + break; + case Markdown::NodeType::Heading: + objcType = MarkdownNodeTypeHeading; + break; + case Markdown::NodeType::LineBreak: + objcType = MarkdownNodeTypeLineBreak; + break; + case Markdown::NodeType::Strong: + objcType = MarkdownNodeTypeStrong; + break; + case Markdown::NodeType::Emphasis: + objcType = MarkdownNodeTypeEmphasis; + break; + case Markdown::NodeType::Strikethrough: + objcType = MarkdownNodeTypeStrikethrough; + break; + case Markdown::NodeType::Underline: + objcType = MarkdownNodeTypeUnderline; + break; + case Markdown::NodeType::Code: + objcType = MarkdownNodeTypeCode; + break; + case Markdown::NodeType::Image: + objcType = MarkdownNodeTypeImage; + break; + case Markdown::NodeType::Blockquote: + objcType = MarkdownNodeTypeBlockquote; + break; + case Markdown::NodeType::UnorderedList: + objcType = MarkdownNodeTypeUnorderedList; + break; + case Markdown::NodeType::OrderedList: + objcType = MarkdownNodeTypeOrderedList; + break; + case Markdown::NodeType::ListItem: + objcType = MarkdownNodeTypeListItem; + break; + case Markdown::NodeType::CodeBlock: + objcType = MarkdownNodeTypeCodeBlock; + break; + case Markdown::NodeType::ThematicBreak: + objcType = MarkdownNodeTypeThematicBreak; + break; + case Markdown::NodeType::Table: + objcType = MarkdownNodeTypeTable; + break; + case Markdown::NodeType::TableHead: + objcType = MarkdownNodeTypeTableHead; + break; + case Markdown::NodeType::TableBody: + objcType = MarkdownNodeTypeTableBody; + break; + case Markdown::NodeType::TableRow: + objcType = MarkdownNodeTypeTableRow; + break; + case Markdown::NodeType::TableHeaderCell: + objcType = MarkdownNodeTypeTableHeaderCell; + break; + case Markdown::NodeType::TableCell: + objcType = MarkdownNodeTypeTableCell; + break; + case Markdown::NodeType::LatexMathInline: + objcType = MarkdownNodeTypeLatexMathInline; + break; + case Markdown::NodeType::LatexMathDisplay: + objcType = MarkdownNodeTypeLatexMathDisplay; + break; + case Markdown::NodeType::Spoiler: + objcType = MarkdownNodeTypeSpoiler; + break; + case Markdown::NodeType::Superscript: + objcType = MarkdownNodeTypeSuperscript; + break; + case Markdown::NodeType::Subscript: + objcType = MarkdownNodeTypeSubscript; + break; + case Markdown::NodeType::Highlight: + objcType = MarkdownNodeTypeHighlight; + break; + case Markdown::NodeType::SoftBreak: + objcType = MarkdownNodeTypeSoftBreak; + break; + case Markdown::NodeType::BlankLine: + objcType = MarkdownNodeTypeBlankLine; + break; + case Markdown::NodeType::Admonition: + objcType = MarkdownNodeTypeAdmonition; + break; + case Markdown::NodeType::Video: + objcType = MarkdownNodeTypeVideo; + break; + } + + MarkdownASTNode *objcNode = [[MarkdownASTNode alloc] initWithType:objcType]; + + // Convert content + if (!cppNode->content.empty()) { + objcNode.content = [NSString stringWithUTF8String:cppNode->content.c_str()]; + } + + // Convert attributes + for (const auto &[key, value] : cppNode->attributes) { + NSString *objcKey = [NSString stringWithUTF8String:key.c_str()]; + NSString *objcValue = [NSString stringWithUTF8String:value.c_str()]; + [objcNode setAttribute:objcKey value:objcValue]; + } + + // Convert children recursively + for (const auto &child : cppNode->children) { + MarkdownASTNode *objcChild = convertCppASTToObjC(child); + [objcNode addChild:objcChild]; + } + + return objcNode; +} + +static NSString *ENRMStringFromUTF8(std::string_view utf8) +{ + return [[NSString alloc] initWithBytes:utf8.data() length:utf8.size() encoding:NSUTF8StringEncoding] ?: @""; +} + +// Host matchers for the core recognizer: NSRanges are UTF-16 units, which is what the core expects. +static Markdown::TextLinkMatchers ENRMTextLinkMatchers(ENRMLinkRegexConfig *textRegex, ENRMLinkRegexConfig *codeRegex) +{ + Markdown::TextLinkMatchers matchers; + NSRegularExpression *text = textRegex.parsedRegex; + if (text) { + matchers.text = [text](const std::vector &runs) { + std::vector> all; + all.reserve(runs.size()); + for (std::string_view run : runs) { + NSString *string = ENRMStringFromUTF8(run); + std::vector ranges; + for (NSTextCheckingResult *match in [text matchesInString:string + options:0 + range:NSMakeRange(0, string.length)]) { + if (match.range.length > 0) + ranges.push_back({match.range.location, NSMaxRange(match.range)}); + } + all.push_back(std::move(ranges)); + } + return all; + }; + } + NSRegularExpression *code = codeRegex.parsedWholeSpanRegex; + if (code) { + matchers.inlineCode = [code](const std::vector &spans) { + std::vector matched; + matched.reserve(spans.size()); + for (std::string_view span : spans) { + NSString *string = ENRMStringFromUTF8(span); + NSRange whole = NSMakeRange(0, string.length); + NSTextCheckingResult *match = [code firstMatchInString:string options:0 range:whole]; + matched.push_back(match != nil && NSEqualRanges(match.range, whole)); + } + return matched; + }; + } + return matchers; +} + +MarkdownASTNode *parseMarkdownWithCppParser(NSString *markdown, ENRMMd4cFlags *flags, BOOL isGFM, + ENRMLinkRegexConfig *textRegex, ENRMLinkRegexConfig *codeRegex); + +MarkdownASTNode *parseMarkdownWithCppParser(NSString *markdown, ENRMMd4cFlags *flags, BOOL isGFM) +{ + return parseMarkdownWithCppParser(markdown, flags, isGFM, nil, nil); +} + +// Parses with the C++ parser, runs text link recognition in the core, and converts to the Objective-C AST. +MarkdownASTNode *parseMarkdownWithCppParser(NSString *markdown, ENRMMd4cFlags *flags, BOOL isGFM, + ENRMLinkRegexConfig *textRegex, ENRMLinkRegexConfig *codeRegex) +{ + if (markdown.length == 0) { + return [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeDocument]; + } + + // Convert NSString to std::string + const char *utf8String = [markdown UTF8String]; + if (!utf8String) { + RCTLogError(@"MarkdownParserBridge: Failed to convert markdown to UTF-8"); + return [[MarkdownASTNode alloc] initWithType:MarkdownNodeTypeDocument]; + } + + std::string cppMarkdown(utf8String); + + // Convert Objective-C flags to C++ flags + Markdown::Md4cFlags cppFlags; + cppFlags.underline = flags.underline; + cppFlags.latexMath = flags.latexMath; + cppFlags.superscript = flags.superscript; + cppFlags.subscript = flags.subscript; + cppFlags.highlight = flags.highlight; + cppFlags.hardSoftBreaks = flags.hardSoftBreaks; + cppFlags.preserveBlankLines = flags.preserveBlankLines; + cppFlags.admonitions = flags.admonitions; + + Markdown::MD4CParser parser; + auto cppAST = parser.parse(cppMarkdown, cppFlags, isGFM); + if (cppAST && (textRegex || codeRegex)) { + Markdown::recognizeTextLinks(*cppAST, ENRMTextLinkMatchers(textRegex, codeRegex)); + } + + // Convert C++ AST to Objective-C AST + return convertCppASTToObjC(cppAST); +} diff --git a/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.h new file mode 100644 index 000000000000..246387ea23fe --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.h @@ -0,0 +1,23 @@ +#import + +@class ENRMBlockquoteTextRenderer; +@class MarkdownASTNode; +@class RenderContext; + +NS_ASSUME_NONNULL_BEGIN + +@interface AttributedRenderer : NSObject +- (instancetype)initWithConfig:(id)config; +// Renders a flat list of sibling nodes into an attributed string: sets the baseline block style, +// walks each node, and trims the trailing block margin. Pass a non-nil block to render the nodes as +// a blockquote's own content (blockquote baseline + the quote's line height applied over the run); +// it draws no box - the ENRMBlockquoteContainerView draws the border/background/padding. See +// ENRMBlockquoteTextRenderer. +- (NSMutableAttributedString *)renderNodes:(NSArray *)nodes + context:(RenderContext *)context + block:(nullable ENRMBlockquoteTextRenderer *)block; +- (CGFloat)getLastElementMarginBottom; +- (void)setAllowTrailingMargin:(BOOL)allow; +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.m new file mode 100644 index 000000000000..737865d74bb2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/AttributedRenderer.m @@ -0,0 +1,229 @@ +#import "AttributedRenderer.h" +#import "BlockquoteBorder.h" +#import "CodeBlockBackground.h" +#import "ENRMBlockquoteTextRenderer.h" +#import "ENRMLinkPillText.h" +#import "LastElementUtils.h" +#import "MarkdownASTNode.h" +#import "NodeRenderer.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation AttributedRenderer { + StyleConfig *_config; + RendererFactory *_rendererFactory; + CGFloat _lastElementMarginBottom; + BOOL _allowTrailingMargin; +} + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super init]; + if (self) { + _config = config; + _rendererFactory = [[RendererFactory alloc] initWithConfig:config]; + _lastElementMarginBottom = 0.0; + _allowTrailingMargin = NO; + } + return self; +} + +/** + * Entry point for rendering a flat list of sibling nodes (e.g. a document's or a block segment's + * children). Sets the baseline block style, runs the recursive traversal, and trims the trailing + * block margin. An optional [block] decorates the pass - it enters a block baseline before the nodes + * render and post-processes the finished string - letting a caller render content as e.g. blockquote + * text without this class knowing anything block-specific. See ENRMBlockquoteTextRenderer. + */ +- (NSMutableAttributedString *)renderNodes:(NSArray *)nodes + context:(RenderContext *)context + block:(ENRMBlockquoteTextRenderer *)block +{ + // 1. Establish the baseline block style. This ensures leaf nodes (like Text) have valid + // attributes if they appear at the top level. A decorator overrides the default paragraph + // baseline (e.g. the blockquote baseline so paragraphs render tight and pick up the quote's + // font/color). + if (block) { + [block pushOnContext:context]; + } else { + [context setBlockStyle:BlockTypeParagraph font:_config.paragraphFont color:_config.paragraphColor headingLevel:0]; + } + + NSMutableAttributedString *output = [[NSMutableAttributedString alloc] init]; + + // 2. Iterate through the sibling nodes. + for (MarkdownASTNode *node in nodes) { + [self renderNodeRecursive:node into:output context:context]; + } + + // 3. Remove trailing paragraph spacing from last block element + // Reset lastElementMarginBottom before processing + _lastElementMarginBottom = 0.0; + [self removeTrailingSpacing:output]; + + // 4. Let the decorator post-process the finished string (e.g. stamp the quote's line height). + [block postProcess:output]; + ENRMLinkPillsAdoptPlaceholderFonts(output); + + // 5. Cleanup global state to prevent side effects in subsequent renders. + [context clearBlockStyle]; + + return output; +} + +/** + * Trims trailing newlines after the last rendered block, with special handling for code blocks. + * + * For non-code-block tail elements: deletes all trailing newlines after the last non-newline + * character and zeroes the last element's paragraph spacing so it doesn't render a margin past + * the content. + * + * For code blocks (`isLastBlockACodeBlock` == YES): keeps the bottom padding spacer in place + * AND preserves a single trailing newline immediately after it (typically the + * codeBlockMarginBottom spacer that CodeBlockRenderer already appended; if none exists, one is + * synthesized here). That extra newline matters because of an iOS layout quirk: + * + * - iOS treats the trailing `\n` of the storage as a paragraph terminator and reports the + * line fragment for the paragraph after it via `extraLineFragmentRect`. + * - `boundingRectForGlyphRange:` excludes that extra line, and the graphics-context clip + * passed to `drawBackgroundForGlyphRange:` is tiled to the laid-out content area (rounded + * up to 128pt boundaries) which also excludes it. + * - If the bottom padding spacer were the trailing `\n`, its 16/19pt line fragment would + * fall into that excluded zone — the background rect would have to be manually extended + * past the clip and the bottom rounded corner would get sliced off at the tile boundary + * (the original visual bug in #354). + * + * By keeping a 1pt-tall tail newline beyond the bottom padding spacer, iOS lays the spacer + * out as a normal interior line fragment included in usedRect/boundingRect and inside the + * drawing tiles, so the corner renders intact and no rect extension is needed. + */ +- (void)removeTrailingSpacing:(NSMutableAttributedString *)output +{ + if (output.length == 0) + return; + + // Find the last non-newline character + NSRange lastContent = [output.string rangeOfCharacterFromSet:[NSCharacterSet.newlineCharacterSet invertedSet] + options:NSBackwardsSearch]; + if (lastContent.location == NSNotFound) + return; + + // 1. Capture the Margin Bottom (Scanning from last content to end) + _lastElementMarginBottom = 0.0; + for (NSUInteger i = lastContent.location; i < output.length;) { + NSRange attrRange; + NSParagraphStyle *style = [output attribute:NSParagraphStyleAttributeName atIndex:i effectiveRange:&attrRange]; + if (style) { + _lastElementMarginBottom = MAX(_lastElementMarginBottom, style.paragraphSpacing); + } + i = NSMaxRange(attrRange); + } + + // 2. Trim trailing characters + NSUInteger logicalEnd = NSMaxRange(lastContent); + BOOL isCodeBlock = isLastBlockACodeBlock(output); + BOOL isPaddedBlockquote = !isCodeBlock && [_config blockquotePadding] > 0 && + [output attribute:BlockquoteDepthAttributeName + atIndex:lastContent.location + effectiveRange:NULL] != nil; + NSRange codeRange = NSMakeRange(0, 0); + if (isCodeBlock) { + [output attribute:CodeBlockAttributeName + atIndex:lastContent.location + longestEffectiveRange:&codeRange + inRange:NSMakeRange(0, output.length)]; + NSUInteger codeEnd = NSMaxRange(codeRange); + if (codeEnd >= output.length) { + [output appendAttributedString:kNewlineAttributedString]; + } + logicalEnd = codeEnd + 1; + } else if (isPaddedBlockquote) { + NSUInteger blockquoteEnd = NSMaxRange(lastContent); + while (blockquoteEnd < output.length && [output attribute:BlockquoteDepthAttributeName + atIndex:blockquoteEnd + effectiveRange:NULL] != nil) { + blockquoteEnd++; + } + if (blockquoteEnd >= output.length) { + [output appendAttributedString:kNewlineAttributedString]; + } + logicalEnd = blockquoteEnd + 1; + } + + if (logicalEnd < output.length) { + [output deleteCharactersInRange:NSMakeRange(logicalEnd, output.length - logicalEnd)]; + } + + if ((isCodeBlock && NSMaxRange(codeRange) < output.length) || isPaddedBlockquote) { + NSUInteger tailIdx = isCodeBlock ? NSMaxRange(codeRange) : logicalEnd - 1; + [output removeAttribute:CodeBlockAttributeName range:NSMakeRange(tailIdx, 1)]; + [output removeAttribute:BlockquoteDepthAttributeName range:NSMakeRange(tailIdx, 1)]; + [output removeAttribute:BlockquoteBackgroundColorAttributeName range:NSMakeRange(tailIdx, 1)]; + NSParagraphStyle *style = [output attribute:NSParagraphStyleAttributeName atIndex:tailIdx effectiveRange:NULL]; + NSMutableParagraphStyle *mutableStyle = style ? [style mutableCopy] : [[NSMutableParagraphStyle alloc] init]; + mutableStyle.paragraphSpacing = 0; + mutableStyle.paragraphSpacingBefore = 0; + mutableStyle.minimumLineHeight = 1; + mutableStyle.maximumLineHeight = 1; + [output addAttribute:NSParagraphStyleAttributeName value:mutableStyle range:NSMakeRange(tailIdx, 1)]; + } + + // 3. Zero out internal spacing for the last element (if not a code block) + if (!isCodeBlock) { + NSRange styleRange; + NSParagraphStyle *style = [output attribute:NSParagraphStyleAttributeName + atIndex:lastContent.location + effectiveRange:&styleRange]; + + if (style) { + NSMutableParagraphStyle *mutableStyle = [style mutableCopy]; + mutableStyle.paragraphSpacing = 0; + mutableStyle.paragraphSpacingBefore = 0; + + if (isLastElementImage(output)) { + mutableStyle.lineSpacing = 0; + } + + NSRange safeRange = NSIntersectionRange(styleRange, NSMakeRange(0, output.length)); + [output addAttribute:NSParagraphStyleAttributeName value:mutableStyle range:safeRange]; + } + } +} + +- (void)setAllowTrailingMargin:(BOOL)allow +{ + _allowTrailingMargin = allow; +} + +- (CGFloat)getLastElementMarginBottom +{ + return _lastElementMarginBottom; +} + +/** + * Orchestrates the recursive traversal of the AST. + * If a specialized renderer exists for a node type, it takes full control. + */ +- (void)renderNodeRecursive:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)out + context:(RenderContext *)context +{ + if (!node) + return; + + id renderer = [_rendererFactory rendererForNodeType:node.type]; + + if (renderer) { + // Specialized renderers (e.g., Strong, Link, Heading) handle their own sub-trees. + [renderer renderNode:node into:out context:context]; + } else { + // Fallback: Default to deep-first traversal for unhandled container nodes. + for (MarkdownASTNode *child in node.children) { + [self renderNodeRecursive:child into:out context:context]; + } + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.h new file mode 100644 index 000000000000..9b7f3c80989e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.h @@ -0,0 +1,33 @@ +#pragma once +#import "NodeRenderer.h" + +@class RendererFactory; +@class StyleConfig; +@class RenderContext; +@class MarkdownASTNode; + +/// Shared base for all node renderers — provides `_rendererFactory` and `_config` +/// as protected ivars and the common designated initializer. +/// `renderNode:into:context:` is a template method: take context snapshot -> +/// `renderNodeContent:into:context:` -> restore snapshot. Subclasses implement +/// `renderNodeContent:into:context:` and, when they mutate scoped context state, +/// override `takeContextSnapshot:` to return `[context snapshotScope]`. +@interface BaseRenderer : NSObject { +@protected + __weak RendererFactory *_rendererFactory; + StyleConfig *_config; +} + +- (instancetype)initWithRendererFactory:(id)rendererFactory config:(id)config; + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context; + +/// Default returns nil. +- (nullable id)takeContextSnapshot:(RenderContext *)context; + +/// Default restores a scope frame when snapshot is non-nil, no-op otherwise. +- (void)restoreContextSnapshot:(nullable id)snapshot context:(RenderContext *)context; + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.m new file mode 100644 index 000000000000..ab2531b3ebee --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BaseRenderer.m @@ -0,0 +1,46 @@ +#import "BaseRenderer.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation BaseRenderer + +- (instancetype)initWithRendererFactory:(id)rendererFactory config:(id)config +{ + if (self = [super init]) { + _rendererFactory = rendererFactory; + _config = (StyleConfig *)config; + } + return self; +} + +- (void)renderNode:(MarkdownASTNode *)node into:(NSMutableAttributedString *)output context:(RenderContext *)context +{ + id snapshot = [self takeContextSnapshot:context]; + @try { + [self renderNodeContent:node into:output context:context]; + } @finally { + [self restoreContextSnapshot:snapshot context:context]; + } +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + [self doesNotRecognizeSelector:_cmd]; +} + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return nil; +} + +- (void)restoreContextSnapshot:(id)snapshot context:(RenderContext *)context +{ + if (snapshot) { + [context restoreScope:snapshot]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.h b/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.h new file mode 100644 index 000000000000..1929e37e087b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.h @@ -0,0 +1,10 @@ +#pragma once +#import "ENRMUIKit.h" +#import + +extern NSString *const ENRMScriptAttributeName; +extern NSString *const ENRMScriptValueSuperscript; +extern NSString *const ENRMScriptValueSubscript; + +void ENRMApplyBaselineShift(NSMutableAttributedString *output, NSRange range, CGFloat fontScale, + CGFloat baselineOffsetScale); diff --git a/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.m b/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.m new file mode 100644 index 000000000000..665d5cd76795 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BaselineShiftTextAttributes.m @@ -0,0 +1,26 @@ +#import "BaselineShiftTextAttributes.h" + +NSString *const ENRMScriptAttributeName = @"ENRMScript"; +NSString *const ENRMScriptValueSuperscript = @"superscript"; +NSString *const ENRMScriptValueSubscript = @"subscript"; + +void ENRMApplyBaselineShift(NSMutableAttributedString *output, NSRange range, CGFloat fontScale, + CGFloat baselineOffsetScale) +{ + [output enumerateAttribute:NSFontAttributeName + inRange:range + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(UIFont *font, NSRange fontRange, BOOL *stop) { + (void)stop; + if (![font isKindOfClass:UIFont.class]) { + return; + } + + UIFont *scaledFont = [UIFont fontWithDescriptor:font.fontDescriptor + size:font.pointSize * fontScale]; + [output addAttribute:NSFontAttributeName value:scaledFont range:fontRange]; + [output addAttribute:NSBaselineOffsetAttributeName + value:@(font.pointSize * baselineOffsetScale) + range:fontRange]; + }]; +} diff --git a/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.h new file mode 100644 index 000000000000..9a5f38c6f0c8 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.h @@ -0,0 +1,4 @@ +#import "BaseRenderer.h" + +@interface BlankLineRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.m new file mode 100644 index 000000000000..2ece69aa400d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BlankLineRenderer.m @@ -0,0 +1,51 @@ +#import "BlankLineRenderer.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "StyleConfig.h" + +#pragma mark - Renderer Implementation + +// Renders a run of consecutive blank lines emitted by the parser when the +// preserveBlankLines flag is enabled. Each blank line in the source is drawn as +// one empty line, so the rendered text keeps the exact line count that was typed +// (e.g. in EnrichedMarkdownTextInput). The empty lines use the paragraph font +// and line height so their vertical rhythm matches the surrounding paragraphs; +// any extra block spacing is left to the caller to configure via markdownStyle. +@implementation BlankLineRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSInteger count = [node.attributes[@"count"] integerValue]; + if (count <= 0) { + return; + } + + [self ensureStartingNewline:output]; + + NSDictionary *attributes = @{NSFontAttributeName : _config.paragraphFont}; + + NSMutableString *blanks = [NSMutableString stringWithCapacity:(NSUInteger)count]; + for (NSInteger i = 0; i < count; i++) { + [blanks appendString:@"\n"]; + } + + NSUInteger start = output.length; + [output appendAttributedString:[[NSAttributedString alloc] initWithString:blanks attributes:attributes]]; + + NSRange range = NSMakeRange(start, output.length - start); + applyLineHeight(output, range, _config.paragraphLineHeight); + applyTextAlignment(output, range, _config.paragraphTextAlign); +} + +#pragma mark - Private Utilities + +- (void)ensureStartingNewline:(NSMutableAttributedString *)output +{ + if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.h new file mode 100644 index 000000000000..ca973374fa4c --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.h @@ -0,0 +1,6 @@ +#import "BaseRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" + +@interface BlockquoteRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.m new file mode 100644 index 000000000000..5f81028d0435 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/BlockquoteRenderer.m @@ -0,0 +1,258 @@ +#import "BlockquoteRenderer.h" +#import "BlockquoteBorder.h" +#import "FontUtils.h" +#import "LastElementUtils.h" +#import "ListItemRenderer.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +static NSString *const kNestedInfoDepthKey = @"depth"; +static NSString *const kNestedInfoRangeKey = @"range"; + +@implementation BlockquoteRenderer + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return [context snapshotScope]; +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:kNewlineAttributedString]; + } + + NSInteger currentDepth = context.blockquoteDepth; + context.blockquoteDepth = currentDepth + 1; + + [context setBlockStyle:BlockTypeBlockquote + font:[_config blockquoteFont] + color:[_config blockquoteColor] + headingLevel:0]; + + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSUInteger end = output.length; + if (end <= start) { + return; + } + + [self applyStylingAndSpacing:output start:start end:end currentDepth:currentDepth context:context]; +} + +#pragma mark - Styling and Spacing + +- (void)applyStylingAndSpacing:(NSMutableAttributedString *)output + start:(NSUInteger)start + end:(NSUInteger)end + currentDepth:(NSInteger)currentDepth + context:(RenderContext *)context +{ + NSUInteger contentStart = start; + if (currentDepth == 0) { + contentStart += applyBlockSpacingBefore(output, start, [_config blockquoteMarginTop]); + } + + // nested quotes pad their own box (matching web CSS padding) + CGFloat padding = [_config blockquotePadding]; + NSUInteger topPadLength = 0; + NSUInteger bottomPadLength = 0; + if (padding > 0) { + NSMutableParagraphStyle *topSpacerStyle = [context spacerStyleWithHeight:padding spacing:0]; + NSAttributedString *topSpacer = [[NSAttributedString alloc] + initWithString:@"\n" + attributes:@{NSParagraphStyleAttributeName : topSpacerStyle, BlockquoteSpacerAttributeName : @YES}]; + [output insertAttributedString:topSpacer atIndex:contentStart]; + topPadLength = 1; + + NSUInteger bottomSpacerLocation = output.length; + [output appendAttributedString:kNewlineAttributedString]; + NSMutableParagraphStyle *bottomSpacerStyle = [context spacerStyleWithHeight:padding spacing:0]; + [output addAttributes:@{NSParagraphStyleAttributeName : bottomSpacerStyle, BlockquoteSpacerAttributeName : @YES} + range:NSMakeRange(bottomSpacerLocation, 1)]; + bottomPadLength = 1; + } + + NSRange blockquoteRange = NSMakeRange(contentStart, (end - start) + topPadLength + bottomPadLength); + NSRange innerRange = NSMakeRange(contentStart + topPadLength, end - start); + CGFloat levelSpacing = [_config blockquoteBorderWidth] + [_config blockquoteGapWidth]; + NSArray *nestedInfo = [self collectNestedBlockquotes:output range:innerRange depth:currentDepth]; + + // Apply base styling (indentation, depth, background, line height) + [self applyBaseBlockquoteStyle:output + boxRange:blockquoteRange + innerRange:innerRange + depth:currentDepth + levelSpacing:levelSpacing + backgroundColor:[_config blockquoteBackgroundColor] + lineHeight:[_config blockquoteLineHeight]]; + + // Re-apply nested blockquote styles to restore their correct indentation + // (applyBaseBlockquoteStyle overwrites nested indents with the parent's indent) + [self reapplyNestedStyles:output nestedInfo:nestedInfo levelSpacing:levelSpacing]; + + if (currentDepth == 0) { + applyBlockSpacingAfter(output, [_config blockquoteMarginBottom]); + } +} + +#pragma mark - Nested Blockquote Handling + +- (NSArray *)collectNestedBlockquotes:(NSMutableAttributedString *)output + range:(NSRange)blockquoteRange + depth:(NSInteger)currentDepth +{ + NSMutableArray *nestedInfo = [NSMutableArray array]; + + [output + enumerateAttribute:BlockquoteDepthAttributeName + inRange:blockquoteRange + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(id value, NSRange range, BOOL *stop) { + NSInteger depth = [value integerValue]; + if (value && depth > currentDepth) { + [nestedInfo + addObject:@{kNestedInfoDepthKey : value, kNestedInfoRangeKey : [NSValue valueWithRange:range]}]; + } + }]; + + return nestedInfo; +} + +- (void)applyBaseBlockquoteStyle:(NSMutableAttributedString *)output + boxRange:(NSRange)boxRange + innerRange:(NSRange)innerRange + depth:(NSInteger)currentDepth + levelSpacing:(CGFloat)levelSpacing + backgroundColor:(RCTUIColor *)backgroundColor + lineHeight:(CGFloat)lineHeight +{ + CGFloat totalIndent = blockquoteIndentForDepth(currentDepth + 1, levelSpacing); + CGFloat padding = [_config blockquotePadding]; + + // Depth and background cover the whole box (incl. padding spacers) so the + // border and background render behind list content and the padding rows. + NSMutableDictionary *depthAttributes = + [NSMutableDictionary dictionaryWithObjectsAndKeys:@(currentDepth), BlockquoteDepthAttributeName, nil]; + if (backgroundColor) { + depthAttributes[BlockquoteBackgroundColorAttributeName] = backgroundColor; + } + [output addAttributes:depthAttributes range:boxRange]; + + // List items bake the blockquote indent into their own paragraph style; only non-list content is stamped here. + [self enumerateNonListRangesIn:output + range:innerRange + usingBlock:^(NSRange nonListRange) { + NSMutableParagraphStyle *paragraphStyle = + getOrCreateParagraphStyle(output, nonListRange.location); + paragraphStyle.firstLineHeadIndent = totalIndent; + paragraphStyle.headIndent = totalIndent; + if (padding > 0) { + paragraphStyle.tailIndent = -padding; + } + [output addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:nonListRange]; + applyLineHeight(output, nonListRange, lineHeight); + applyBaselineOffset(output, nonListRange); + }]; + + if (padding > 0) { + [self applyTailIndent:-padding toListRangesIn:output range:innerRange]; + } +} + +- (void)applyTailIndent:(CGFloat)tailIndent toListRangesIn:(NSMutableAttributedString *)output range:(NSRange)range +{ + [output enumerateAttribute:ListDepthAttribute + inRange:range + options:0 + usingBlock:^(id value, NSRange listRange, BOOL *stop) { + if (!value) { + return; + } + [output enumerateAttribute:NSParagraphStyleAttributeName + inRange:listRange + options:0 + usingBlock:^(NSParagraphStyle *style, NSRange styleRange, BOOL *innerStop) { + NSMutableParagraphStyle *mutableStyle = + style ? [style mutableCopy] : [[NSMutableParagraphStyle alloc] init]; + mutableStyle.tailIndent = tailIndent; + [output addAttribute:NSParagraphStyleAttributeName + value:mutableStyle + range:styleRange]; + }]; + }]; +} + +- (void)reapplyNestedStyles:(NSMutableAttributedString *)output + nestedInfo:(NSArray *)nestedInfo + levelSpacing:(CGFloat)levelSpacing +{ + // Re-apply indentation to nested blockquotes since applyBaseBlockquoteStyle + // overwrote them with the parent's indentation + CGFloat padding = [_config blockquotePadding]; + for (NSDictionary *info in nestedInfo) { + NSRange nestedRange = [info[kNestedInfoRangeKey] rangeValue]; + NSInteger nestedDepth = [info[kNestedInfoDepthKey] integerValue]; + CGFloat indent = blockquoteIndentForDepth(nestedDepth + 1, levelSpacing); + + [output addAttribute:BlockquoteDepthAttributeName value:info[kNestedInfoDepthKey] range:nestedRange]; + + [self enumerateNonListRangesIn:output + range:nestedRange + usingBlock:^(NSRange nonListRange) { + NSMutableParagraphStyle *style = getOrCreateParagraphStyle(output, nonListRange.location); + style.firstLineHeadIndent = indent; + style.headIndent = indent; + style.tailIndent = padding > 0 ? -padding : 0; + [output addAttribute:NSParagraphStyleAttributeName value:style range:nonListRange]; + }]; + } +} + +- (void)enumerateNonListRangesIn:(NSMutableAttributedString *)output + range:(NSRange)range + usingBlock:(void (^)(NSRange nonListRange))block +{ + // List items — and code blocks nested inside them (which carry a list-derived + // indent instead of ListDepthAttribute) — already bake the correct indent in. + NSMutableArray *listRanges = [NSMutableArray array]; + void (^collectRanges)(NSString *) = ^(NSString *attribute) { + [output enumerateAttribute:attribute + inRange:range + options:0 + usingBlock:^(id value, NSRange subRange, BOOL *stop) { + if (value) { + [listRanges addObject:[NSValue valueWithRange:subRange]]; + } + }]; + }; + collectRanges(ListDepthAttribute); + collectRanges(CodeBlockIndentAttributeName); + collectRanges(BlockquoteSpacerAttributeName); + [listRanges sortUsingComparator:^NSComparisonResult(NSValue *a, NSValue *b) { + NSUInteger la = [a rangeValue].location; + NSUInteger lb = [b rangeValue].location; + return la < lb ? NSOrderedAscending : (la > lb ? NSOrderedDescending : NSOrderedSame); + }]; + + NSUInteger pos = range.location; + const NSUInteger end = NSMaxRange(range); + for (NSValue *val in listRanges) { + NSRange listRange = [val rangeValue]; + if (pos < listRange.location) { + block(NSMakeRange(pos, listRange.location - pos)); + } + pos = MAX(pos, NSMaxRange(listRange)); + } + if (pos < end) { + block(NSMakeRange(pos, end - pos)); + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.h new file mode 100644 index 000000000000..74ac77e8e4ee --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.h @@ -0,0 +1,9 @@ +#pragma once +#import "BaseRenderer.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface CodeBlockRenderer : BaseRenderer +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.m new file mode 100644 index 000000000000..ab46bfe3528a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/CodeBlockRenderer.m @@ -0,0 +1,102 @@ +#import "CodeBlockRenderer.h" +#import "CodeBlockBackground.h" +#import "ENRMCodeBlockContent.h" +#import "ENRMCodeBlockHighlighter.h" +#import "LastElementUtils.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation CodeBlockRenderer + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return [context snapshotScope]; +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + // In tight lists md4c emits raw Text siblings without paragraph wrappers, + // so the preceding content may not terminate with a newline. + if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:kNewlineAttributedString]; + } + + [context setBlockStyle:BlockTypeCodeBlock font:[_config codeBlockFont] color:[_config codeBlockColor] headingLevel:0]; + + CGFloat listIndent = context.accumulatedIndent; + CGFloat padding = [_config codeBlockPadding]; + CGFloat marginTop = [_config codeBlockMarginTop]; + CGFloat marginBottom = [_config codeBlockMarginBottom]; + + NSUInteger blockStart = output.length; + blockStart += applyBlockSpacingBefore(output, blockStart, marginTop); + + // Top Padding: Inserted as a spacer character inside the background area + // apply only when positive + if (padding > 0) { + [output appendAttributedString:kNewlineAttributedString]; + NSMutableParagraphStyle *topSpacerStyle = [context spacerStyleWithHeight:padding spacing:0]; + topSpacerStyle.baseWritingDirection = NSWritingDirectionLeftToRight; + [output addAttribute:NSParagraphStyleAttributeName value:topSpacerStyle range:NSMakeRange(blockStart, 1)]; + } + + NSUInteger contentStart = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSUInteger contentEnd = output.length; + if (contentEnd <= contentStart) + return; + + NSRange contentRange = NSMakeRange(contentStart, contentEnd - contentStart); + + ENRMApplyCodeBlockTextAttributes(output, contentRange, _config); + + ENRMApplyHighlightTokens(output, contentRange, ENRMCodeBlockExtractCode(node), ENRMCodeBlockLanguage(node), _config); + + // Horizontal padding is paragraph indentation in this flavor; the shared + // helper already forced the LTR left-aligned base style. + NSMutableParagraphStyle *baseStyle = [getOrCreateParagraphStyle(output, contentStart) mutableCopy]; + baseStyle.firstLineHeadIndent = padding + listIndent; + baseStyle.headIndent = padding + listIndent; + baseStyle.tailIndent = -padding; + [output addAttribute:NSParagraphStyleAttributeName value:baseStyle range:contentRange]; + + // Bottom Padding: Inserted as a spacer character inside the background area + // apply it only when positive + if (padding > 0) { + NSUInteger bottomPaddingStart = output.length; + [output appendAttributedString:kNewlineAttributedString]; + NSMutableParagraphStyle *bottomPaddingStyle = [context spacerStyleWithHeight:padding spacing:0]; + bottomPaddingStyle.baseWritingDirection = NSWritingDirectionLeftToRight; + [output addAttribute:NSParagraphStyleAttributeName + value:bottomPaddingStyle + range:NSMakeRange(bottomPaddingStart, 1)]; + } + + // Define the range for background rendering (includes padding, excludes margins) + NSRange backgroundRange = NSMakeRange(blockStart, output.length - blockStart); + [output addAttribute:CodeBlockAttributeName value:@YES range:backgroundRange]; + if (listIndent > 0) { + [output addAttribute:CodeBlockIndentAttributeName value:@(listIndent) range:backgroundRange]; + } + + // Recovered by a tap for onCodeBlockPress (the AST node is gone after render). + NSString *codeBlockText = ENRMCodeBlockExtractCode(node) ?: @""; + [output addAttribute:@"codeBlockText" value:codeBlockText range:backgroundRange]; + NSString *codeBlockLanguage = ENRMCodeBlockLanguage(node); + if (codeBlockLanguage) { + [output addAttribute:@"codeBlockLanguage" value:codeBlockLanguage range:backgroundRange]; + } + + // External Margin: Applied outside the background range + if (marginBottom > 0) { + applyBlockSpacingAfter(output, marginBottom); + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.h new file mode 100644 index 000000000000..ccc5f8100a64 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.h @@ -0,0 +1,9 @@ +#pragma once +#import "BaseRenderer.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface CodeRenderer : BaseRenderer +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.m new file mode 100644 index 000000000000..8ab099054dc6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/CodeRenderer.m @@ -0,0 +1,69 @@ +#import "CodeRenderer.h" +#import "CodeBackground.h" +#import "ENRMUIKit.h" +#import "FontUtils.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" +#import + +@implementation CodeRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + + BlockStyle *blockStyle = [context getBlockStyle]; + + RCTUIColor *codeColor = _config.codeColor; + + UIFont *blockFont = cachedFontFromBlockStyle(blockStyle, context); + + UIFontDescriptorSymbolicTraits traits = blockFont.fontDescriptor.symbolicTraits; + UIFontWeight weight = (traits & UIFontDescriptorTraitBold) ? UIFontWeightBold : UIFontWeightRegular; + + CGFloat codeFontSize = _config.codeFontSize > 0 ? _config.codeFontSize : blockStyle.fontSize * _config.codeFontScale; + + // Both sizes above are unscaled; apply the same multiplier as the surrounding block font. + CGFloat fontScale = context.allowFontScaling ? RCTFontSizeMultiplierWithMax(context.maxFontSizeMultiplier) : 1.0; + + NSString *codeFontFamily = _config.codeFontFamily; + UIFont *codeFont; + if (codeFontFamily.length > 0) { + NSString *weightStr = (weight == UIFontWeightBold) ? @"bold" : nil; + codeFont = [RCTFont updateFont:nil + withFamily:codeFontFamily + size:@(codeFontSize) + weight:weightStr + style:nil + variant:nil + scaleMultiplier:fontScale]; + } else { + codeFont = [UIFont monospacedSystemFontOfSize:codeFontSize * fontScale weight:weight]; + } + + NSUInteger start = output.length; + + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = [RenderContext rangeForRenderedContent:output start:start]; + if (range.length > 0) { + NSDictionary *existingAttributes = [output attributesAtIndex:start effectiveRange:NULL]; + NSMutableDictionary *codeAttributes = [existingAttributes ?: @{} mutableCopy]; + + codeAttributes[NSFontAttributeName] = codeFont; + if (codeColor) { + codeAttributes[NSForegroundColorAttributeName] = codeColor; + } + codeAttributes[CodeAttributeName] = @YES; + + // Store block line height directly for CodeBackground to use + codeAttributes[@"BlockLineHeight"] = @(UIFontLineHeight(blockFont)); + + [output setAttributes:codeAttributes range:range]; + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.h new file mode 100644 index 000000000000..f371dd571c3f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.h @@ -0,0 +1,25 @@ +#pragma once +#import + +@class RenderContext; +@class StyleConfig; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Renders a GFM blockquote's own prose content - the nodes left after nested quotes, code blocks and + * other block segments have been split out - as blockquote text. + * + * It decorates a generic AttributedRenderer pass rather than owning the render envelope itself: + * -pushOnContext: enters the blockquote baseline block style (+depth) so text picks up the quote's + * font/color and paragraphs render tight (currentBlockType == Blockquote), matching the commonmark + * path; -postProcess: applies the quote's line height once the string is complete. It draws no + * border/background/padding - the ENRMBlockquoteContainerView draws the box. + */ +@interface ENRMBlockquoteTextRenderer : NSObject +- (instancetype)initWithConfig:(StyleConfig *)config; +- (void)pushOnContext:(RenderContext *)context; +- (void)postProcess:(NSMutableAttributedString *)text; +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.m new file mode 100644 index 000000000000..40d4dfc83785 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMBlockquoteTextRenderer.m @@ -0,0 +1,48 @@ +#import "ENRMBlockquoteTextRenderer.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "StyleConfig.h" + +@implementation ENRMBlockquoteTextRenderer { + StyleConfig *_config; +} + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super init]; + if (self) { + _config = config; + } + return self; +} + +- (void)pushOnContext:(RenderContext *)context +{ + // Only set the blockquote baseline block style (tight paragraphs + the quote's font/color). + // Unlike the commonmark inline path we do NOT bump blockquoteDepth: the ENRMBlockquoteContainerView + // already insets its content by the quote's border/gap/padding, so bumping it here would make + // ListItemRenderer add a second blockquoteIndentForDepth on top and over-indent nested lists. + [context setBlockStyle:BlockTypeBlockquote font:_config.blockquoteFont color:_config.blockquoteColor headingLevel:0]; +} + +- (void)postProcess:(NSMutableAttributedString *)text +{ + // Stamp the quote's line height per paragraph. applyLineHeight copies the paragraph style at the + // range start over the whole range, so applying it across the entire run would overwrite every + // paragraph with the first one's style - wiping each list item's firstLineHeadIndent/headIndent + // (the marker draws from a separate attribute, so it would then land on top of un-indented text). + CGFloat lineHeight = [_config blockquoteLineHeight]; + if (text.length == 0 || lineHeight <= 0) { + return; + } + NSString *string = text.string; + NSUInteger location = 0; + while (location < text.length) { + NSRange paragraph = [string paragraphRangeForRange:NSMakeRange(location, 0)]; + applyLineHeight(text, paragraph, lineHeight); + applyBaselineOffset(text, paragraph); + location = NSMaxRange(paragraph); + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.h new file mode 100644 index 000000000000..6ffa0bd3ade9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.h @@ -0,0 +1,9 @@ +#pragma once +#import "BaseRenderer.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMImageRenderer : BaseRenderer +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.m new file mode 100644 index 000000000000..32edfcce882d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMImageRenderer.m @@ -0,0 +1,69 @@ +#import "ENRMImageRenderer.h" +#import "ENRMImageAttachment.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +static const unichar kLineBreak = '\n'; +static const unichar kZeroWidthSpace = 0x200B; + +@implementation ENRMImageRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSString *imageURL = node.attributes[@"url"]; + if (!imageURL || imageURL.length == 0) { + return; + } + + BOOL isInline = [self isInlineImageInOutput:output]; + ENRMImageAttachment *attachment = [ENRMImageAttachment attachmentForURL:imageURL config:_config isInline:isInline]; + + NSUInteger startIndex = output.length; + + NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment]; + [output appendAttributedString:imageString]; + + // Extract alt text from children (![alt text](url) - "alt text" is in children) + NSString *altText = [self extractTextFromNode:node]; + NSRange imageRange = NSMakeRange(startIndex, output.length - startIndex); + [context registerImageRange:imageRange altText:altText url:imageURL]; +} + +- (NSString *)extractTextFromNode:(MarkdownASTNode *)node +{ + if (!node) + return @""; + + NSMutableString *buffer = [NSMutableString string]; + [self _appendChildTextFromNode:node toBuffer:buffer]; + return [buffer stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} + +- (void)_appendChildTextFromNode:(MarkdownASTNode *)node toBuffer:(NSMutableString *)buffer +{ + if (node.content.length > 0) { + [buffer appendString:node.content]; + } else if (node.type == MarkdownNodeTypeSoftBreak || node.type == MarkdownNodeTypeLineBreak) { + [buffer appendString:@" "]; + } + + for (MarkdownASTNode *child in node.children) { + [self _appendChildTextFromNode:child toBuffer:buffer]; + } +} + +- (BOOL)isInlineImageInOutput:(NSAttributedString *)output +{ + if (output.length == 0) { + return NO; + } + + unichar lastChar = [output.string characterAtIndex:output.length - 1]; + return (lastChar != kLineBreak && lastChar != kZeroWidthSpace); +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.h new file mode 100644 index 000000000000..bdfe794b253e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.h @@ -0,0 +1,9 @@ +#pragma once +#import "BaseRenderer.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMMathInlineRenderer : BaseRenderer +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.m new file mode 100644 index 000000000000..5a45362af5f7 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMMathInlineRenderer.m @@ -0,0 +1,65 @@ +#import "ENRMMathInlineRenderer.h" +#import "ENRMMathInlineAttachment.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +#import "ENRMFeatureFlags.h" + +#if ENRICHED_MARKDOWN_MATH + +@implementation ENRMMathInlineRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSString *latex = [self extractLatexFromNode:node]; + if (latex.length == 0) { + return; + } + + NSDictionary *textAttrs = [context getTextAttributes]; + UIFont *currentFont = textAttrs[NSFontAttributeName]; + + ENRMMathInlineAttachment *attachment = [[ENRMMathInlineAttachment alloc] init]; + attachment.latex = latex; + attachment.fontSize = currentFont ? currentFont.pointSize : [_config paragraphFontSize]; + attachment.mathTextColor = [_config inlineMathColor]; + [context.mathReporters addObject:attachment]; + +#if TARGET_OS_OSX + // On macOS, NSLayoutManager uses self.image/self.bounds rather than calling + // imageForBounds:textContainer:characterIndex:, so we pre-render eagerly. + [attachment renderForMacOS]; +#endif + + NSMutableAttributedString *attachmentString = + [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy]; + if (currentFont) { + [attachmentString addAttribute:NSFontAttributeName value:currentFont range:NSMakeRange(0, attachmentString.length)]; + } + [output appendAttributedString:attachmentString]; +} + +- (NSString *)extractLatexFromNode:(MarkdownASTNode *)node +{ + if (node.content.length > 0) { + return node.content; + } + + NSMutableString *buffer = [NSMutableString string]; + for (MarkdownASTNode *child in node.children) { + if (child.content.length > 0) { + [buffer appendString:child.content]; + } else if (child.type == MarkdownNodeTypeSoftBreak || child.type == MarkdownNodeTypeLineBreak) { + [buffer appendString:@" "]; + } + } + return buffer; +} + +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.h new file mode 100644 index 000000000000..71a08284e9f8 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface ENRMSpoilerRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.m new file mode 100644 index 000000000000..61547246f605 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ENRMSpoilerRenderer.m @@ -0,0 +1,34 @@ +#import "ENRMSpoilerRenderer.h" +#import "ENRMSpoilerTapUtils.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" + +@implementation ENRMSpoilerRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + [output addAttribute:SpoilerAttributeName value:@YES range:range]; + + [output enumerateAttribute:NSForegroundColorAttributeName + inRange:range + options:0 + usingBlock:^(id value, NSRange subRange, BOOL *stop) { + if (value) { + [output addAttribute:SpoilerOriginalColorAttributeName value:value range:subRange]; + } + }]; + + [output addAttribute:NSForegroundColorAttributeName value:[RCTUIColor colorWithWhite:0 alpha:0] range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.h new file mode 100644 index 000000000000..81724e422d67 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface EmphasisRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.m new file mode 100644 index 000000000000..f2c699d09ba2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/EmphasisRenderer.m @@ -0,0 +1,100 @@ +#import "EmphasisRenderer.h" +#import "FontUtils.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" +#import + +@implementation EmphasisRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + BlockStyle *blockStyle = [context getBlockStyle]; + RCTUIColor *configEmphasisColor = [_config emphasisColor]; + NSString *emphasisFontFamily = [_config emphasisFontFamily]; + NSString *emphasisFontStyle = [_config emphasisFontStyle]; + BOOL useNormalStyle = [emphasisFontStyle isEqualToString:@"normal"]; + + // Cache the Strong color calculation to efficiently detect nested Strong nodes + RCTUIColor *strongColorToPreserve = [_config strongColor] ? [RenderContext calculateStrongColor:[_config strongColor] + blockColor:blockStyle.color] + : nil; + + [output enumerateAttributesInRange:range + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(NSDictionary *attrs, NSRange subrange, BOOL *stop) { + UIFont *currentFont = + attrs[NSFontAttributeName] ?: cachedFontFromBlockStyle(blockStyle, context); + UIFont *resolvedFont = nil; + + if (emphasisFontFamily.length > 0) { + resolvedFont = [RCTFont updateFont:currentFont + withFamily:emphasisFontFamily + size:nil + weight:nil + style:useNormalStyle ? nil : @"italic" + variant:nil + scaleMultiplier:1.0]; + } else if (currentFont && + !(currentFont.fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic)) { + resolvedFont = [self ensureFontIsItalic:currentFont]; + } + + if (resolvedFont && ![resolvedFont isEqual:currentFont]) { + [output addAttribute:NSFontAttributeName value:resolvedFont range:subrange]; + } + + // 2. Color Optimization: Handle nesting and avoid redundant updates + if (configEmphasisColor) { + RCTUIColor *currentColor = attrs[NSForegroundColorAttributeName]; + BOOL isLink = attrs[NSLinkAttributeName] != nil; + + // Verify if the current color belongs to a Strong parent + BOOL isStrongColor = + strongColorToPreserve && [currentColor isEqual:strongColorToPreserve]; + + // Preserving colors for higher-priority elements (links, strong nodes, etc.) + if (!isLink && !isStrongColor && ![RenderContext shouldPreserveColors:attrs]) { + // Only modify the string if the color is actually different + if (![currentColor isEqual:configEmphasisColor]) { + [output addAttribute:NSForegroundColorAttributeName + value:configEmphasisColor + range:subrange]; + } + } + } + }]; +} + +#pragma mark - Helper Methods + +- (UIFont *)ensureFontIsItalic:(UIFont *)font +{ + if (!font) + return nil; + + UIFontDescriptorSymbolicTraits traits = font.fontDescriptor.symbolicTraits; + if (traits & UIFontDescriptorTraitItalic) + return font; + + // Combine italic with existing traits (e.g., preserving Bold if present) + UIFontDescriptorSymbolicTraits combinedTraits = traits | UIFontDescriptorTraitItalic; + UIFontDescriptor *italicDescriptor = [font.fontDescriptor fontDescriptorWithSymbolicTraits:combinedTraits]; + + // Size 0 in fontWithDescriptor:size: maintains the current point size + return [UIFont fontWithDescriptor:italicDescriptor size:0] ?: font; +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.h new file mode 100644 index 000000000000..981cbdf2b758 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.h @@ -0,0 +1,6 @@ +#import "BaseRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" + +@interface HeadingRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.m new file mode 100644 index 000000000000..b56a930751f5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/HeadingRenderer.m @@ -0,0 +1,103 @@ +#import "HeadingRenderer.h" +#import "ENRMLinkPillText.h" +#import "FontUtils.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "RuntimeKeys.h" +#import "StyleConfig.h" + +// Lightweight struct to hold style data without object overhead +typedef struct { + __unsafe_unretained UIFont *font; + __unsafe_unretained RCTUIColor *color; + CGFloat marginTop; + CGFloat marginBottom; + CGFloat lineHeight; + NSTextAlignment textAlign; +} HeadingStyle; + +static NSString *const kHeadingTypes[] = {nil, @"heading-1", @"heading-2", @"heading-3", + @"heading-4", @"heading-5", @"heading-6"}; + +@implementation HeadingRenderer + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return [context snapshotScope]; +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:kNewlineAttributedString]; + } + + NSInteger level = [node.attributes[@"level"] integerValue]; + if (level < 1 || level > 6) + level = 1; + + HeadingStyle style = [self styleForLevel:level]; + [context setBlockStyle:BlockTypeHeading font:style.font color:style.color headingLevel:level]; + + NSUInteger start = output.length; + NSUInteger contentStart = start; + + // Spacing at the very start of the document requires a spacer character (index 0 check) + if (start == 0) { + NSUInteger offset = applyBlockSpacingBefore(output, 0, style.marginTop); + contentStart += offset; + start += offset; + } + + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + // Register heading for accessibility + NSString *headingText = ENRMStringByExpandingLinkPills([output attributedSubstringFromRange:range]); + [context registerHeadingRange:range level:level text:headingText]; + + // Metadata attribute used for post-processing (e.g., Export to Markdown/HTML) + [output addAttribute:MarkdownTypeAttributeName value:kHeadingTypes[level] range:range]; + + applyLineHeight(output, range, style.lineHeight); + applyBaselineOffset(output, range); + applyTextAlignment(output, range, style.textAlign); + + // Skip marginTop for the first block — already handled by applyBlockSpacingBefore above + if (contentStart != 1) { + NSUInteger inserted = applyParagraphSpacingBefore(output, range, style.marginTop); + start += inserted; + } + applyParagraphSpacingAfter(output, start, style.marginBottom); +} + +#pragma mark - Style Mapping + +- (HeadingStyle)styleForLevel:(NSInteger)level +{ + StyleConfig *c = _config; + switch (level) { + case 1: + return (HeadingStyle){c.h1Font, c.h1Color, c.h1MarginTop, c.h1MarginBottom, c.h1LineHeight, c.h1TextAlign}; + case 2: + return (HeadingStyle){c.h2Font, c.h2Color, c.h2MarginTop, c.h2MarginBottom, c.h2LineHeight, c.h2TextAlign}; + case 3: + return (HeadingStyle){c.h3Font, c.h3Color, c.h3MarginTop, c.h3MarginBottom, c.h3LineHeight, c.h3TextAlign}; + case 4: + return (HeadingStyle){c.h4Font, c.h4Color, c.h4MarginTop, c.h4MarginBottom, c.h4LineHeight, c.h4TextAlign}; + case 5: + return (HeadingStyle){c.h5Font, c.h5Color, c.h5MarginTop, c.h5MarginBottom, c.h5LineHeight, c.h5TextAlign}; + case 6: + return (HeadingStyle){c.h6Font, c.h6Color, c.h6MarginTop, c.h6MarginBottom, c.h6LineHeight, c.h6TextAlign}; + default: + return [self styleForLevel:1]; + } +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.h new file mode 100644 index 000000000000..46cf4ac44d34 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.h @@ -0,0 +1,7 @@ +#pragma once +#import "BaseRenderer.h" + +extern NSString *const HighlightAttributeName; + +@interface HighlightRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.m new file mode 100644 index 000000000000..398d7ddd938d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/HighlightRenderer.m @@ -0,0 +1,33 @@ +#import "HighlightRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +NSString *const HighlightAttributeName = @"EnrichedMarkdownHighlight"; + +@implementation HighlightRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + BlockStyle *blockStyle = [context getBlockStyle]; + RCTUIColor *foregroundColor = [RenderContext calculateHighlightColor:[_config highlightColor] + paragraphColor:[_config paragraphColor] + blockColor:blockStyle.color]; + [output addAttribute:NSForegroundColorAttributeName value:foregroundColor range:range]; + [output addAttribute:NSBackgroundColorAttributeName value:[_config highlightBackgroundColor] range:range]; + [output addAttribute:HighlightAttributeName value:@YES range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.h new file mode 100644 index 000000000000..761a3a7536ff --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.h @@ -0,0 +1,6 @@ +#import "BaseRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" + +@interface LinkRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.m new file mode 100644 index 000000000000..66daf6b218bf --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/LinkRenderer.m @@ -0,0 +1,160 @@ +#import "LinkRenderer.h" +#import "CodeBackground.h" +#import "ENRMLinkPillAttachment.h" +#import "ENRMSpoilerTapUtils.h" +#import "ENRMTextLinkAttributes.h" +#import "FontUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" +#import + +#if !TARGET_OS_OSX +static BOOL ENRMRangeHasAttribute(NSAttributedString *text, NSRange range, NSAttributedStringKey key) +{ + __block BOOL found = NO; + [text enumerateAttribute:key + inRange:range + options:0 + usingBlock:^(id value, NSRange subrange, BOOL *stop) { + if (value) { + found = YES; + *stop = YES; + } + }]; + return found; +} + +/// Replaces the rendered link content with one attachment character and returns its range. +static NSRange ENRMCollapseLinkIntoPill(NSMutableAttributedString *output, NSRange range, NSString *url, + LinkVariantConfig *variant, StyleConfig *config, RenderContext *context) +{ + LinkPillContent *content = [config linkPillContent][url]; + BOOL hasOwnIcon = content.iconUri.length > 0; + // A tint set for the link wins. The variant's tint is for the variant's own icon, not for an + // icon supplied per link (an avatar would become a silhouette). + RCTUIColor *iconTint = content.iconTintColor ?: (hasOwnIcon ? nil : variant.pill.iconTintColor); + NSDictionary *attributes = [output attributesAtIndex:range.location effectiveRange:NULL]; + ENRMLinkPillAttachment *pill = [[ENRMLinkPillAttachment alloc] + initWithOriginalText:[output attributedSubstringFromRange:range] + variant:variant + label:content.label.length > 0 ? content.label : variant.pill.label + iconUri:hasOwnIcon ? content.iconUri : variant.pill.iconUri + iconTintColor:iconTint + font:attributes[NSFontAttributeName] ?: [context getBlockStyle].cachedFont + requestHeaders:[config imageRequestHeaders]]; + pill.lineHeight = [config lineHeightForLinkPill:variant.pill]; + + // The placeholder keeps the block context of the text it replaces. The pill draws its own + // background, underline and label, so inline decoration of that text must not show around it. + NSMutableDictionary *placeholder = [attributes mutableCopy]; + [placeholder removeObjectsForKeys:@[ + NSBackgroundColorAttributeName, NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName, + NSStrikethroughStyleAttributeName, CodeAttributeName + ]]; + placeholder[NSAttachmentAttributeName] = pill; + [output replaceCharactersInRange:range + withAttributedString:[[NSAttributedString alloc] initWithString:@"\uFFFC" attributes:placeholder]]; + return NSMakeRange(range.location, 1); +} +#endif + +@implementation LinkRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + BOOL recognizedLink = [node.attributes[@"recognizedLink"] isEqualToString:@"true"]; + NSUInteger start = output.length; + + // 1. Render children first to establish base attributes + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + // 2. Extract configuration + NSString *url = node.attributes[@"url"] ?: @""; + LinkVariantConfig *variant = [_config effectiveLinkVariantForURL:url]; + + RCTUIColor *linkColor = variant.color ?: [_config linkColor]; + BOOL linkUnderline = variant ? variant.underline : [_config linkUnderline]; + NSString *linkFontFamily = variant.fontFamily.length > 0 ? variant.fontFamily : [_config linkFontFamily]; + RCTUIColor *backgroundColor = variant ? variant.backgroundColor : [_config linkBackgroundColor]; + + NSNumber *underlineStyle = @(linkUnderline ? NSUnderlineStyleSingle : NSUnderlineStyleNone); + + // 3. Apply core link functionality (non-destructive) + [output addAttribute:NSLinkAttributeName value:url range:range]; + + // 4. Optimize visual attributes via enumeration to avoid redundant updates + [output enumerateAttributesInRange:range + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(NSDictionary *attrs, NSRange subrange, BOOL *stop) { + NSMutableDictionary *newAttributes = [NSMutableDictionary dictionary]; + newAttributes[@"linkSourceType"] = + recognizedLink ? (attrs[CodeAttributeName] ? @"inline-code" : @"text") : @"markdown"; + if (recognizedLink) { + newAttributes[ENRMRecognizedLinkAttributeName] = @YES; + newAttributes[ENRMRecognizedLinkOriginalUnderlineAttributeName] = + attrs[NSUnderlineStyleAttributeName] ?: @0; + } + + // Only apply link color if the subrange isn't already colored by the link style + if (linkColor && ![attrs[NSForegroundColorAttributeName] isEqual:linkColor]) { + newAttributes[NSForegroundColorAttributeName] = linkColor; + newAttributes[NSUnderlineColorAttributeName] = linkColor; + } + + // Only update underline style if it differs from the config + if (![attrs[NSUnderlineStyleAttributeName] isEqual:underlineStyle]) { + newAttributes[NSUnderlineStyleAttributeName] = underlineStyle; + } + + if (linkFontFamily.length > 0) { + UIFont *currentFont = attrs[NSFontAttributeName]; + if (currentFont) { + UIFont *linkFont = [RCTFont updateFont:currentFont + withFamily:linkFontFamily + size:nil + weight:nil + style:nil + variant:nil + scaleMultiplier:1.0]; + if (linkFont && ![currentFont isEqual:linkFont]) { + newAttributes[NSFontAttributeName] = linkFont; + } + } + } + + if (newAttributes.count > 0) { + [output addAttributes:newAttributes range:subrange]; + } + }]; + +#if !TARGET_OS_OSX + // A pill is one line and one unit: links holding attachments or a line break stay ordinary links. + // So do links holding a spoiler, whose hidden text the label would show. + BOOL willBePill = + variant.pill != nil && !ENRMRangeHasAttribute(output, range, NSAttachmentAttributeName) && + !ENRMRangeHasAttribute(output, range, SpoilerAttributeName) && + [output.string rangeOfCharacterFromSet:NSCharacterSet.newlineCharacterSet options:0 range:range].location == + NSNotFound; +#else + BOOL willBePill = NO; +#endif + if (backgroundColor && !willBePill) + [output addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:range]; + +#if !TARGET_OS_OSX + if (willBePill) + range = ENRMCollapseLinkIntoPill(output, range, url, variant, _config, context); +#endif + [context registerLinkRange:range url:url]; +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.h new file mode 100644 index 000000000000..6bac6121f012 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.h @@ -0,0 +1,24 @@ +#import "BaseRenderer.h" +#import "RenderContext.h" + +extern NSString *const ListDepthAttribute; +extern NSString *const ListTypeAttribute; +extern NSString *const ListItemNumberAttribute; +extern NSString *const ListItemMarkerStartAttribute; + +extern NSString *const TaskItemAttribute; +extern NSString *const TaskCheckedAttribute; +extern NSString *const TaskIndexAttribute; + +@interface ENRMListMarkerDescriptor : NSObject +@property (nonatomic, assign) BOOL isTask; +@property (nonatomic, assign) BOOL isChecked; +@property (nonatomic, assign) NSInteger taskIndex; +@property (nonatomic, assign) ListType listType; +@property (nonatomic, assign) NSInteger number; +@property (nonatomic, assign) NSInteger depth; +@property (nonatomic, assign) CGFloat indent; +@end + +@interface ListItemRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.m new file mode 100644 index 000000000000..ed80dfad7fc1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ListItemRenderer.m @@ -0,0 +1,279 @@ +#import "ListItemRenderer.h" +#import "BlockquoteBorder.h" +#import "ENRMUIKit.h" +#import "LastElementUtils.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +NSString *const ListDepthAttribute = @"ListDepth"; +NSString *const ListTypeAttribute = @"ListType"; +NSString *const ListItemNumberAttribute = @"ListItemNumber"; +NSString *const ListItemMarkerStartAttribute = @"ListItemMarkerStart"; +NSString *const TaskItemAttribute = @"TaskItem"; +NSString *const TaskCheckedAttribute = @"TaskChecked"; +NSString *const TaskIndexAttribute = @"TaskIndex"; + +@implementation ENRMListMarkerDescriptor +@end + +// NSArray's -hash is its count, so plain one-marker arrays all collide in the +// table that uniques attribute dictionaries, and each list item probes past +// every earlier one. Hashing by the item's own marker keeps rendering linear. +@interface ENRMListMarkerArray : NSArray +@end + +@implementation ENRMListMarkerArray { + NSArray *_markers; +} + +- (instancetype)initWithMarkers:(NSArray *)markers +{ + if (self = [super init]) { + _markers = [markers copy]; + } + return self; +} + +- (NSUInteger)count +{ + return _markers.count; +} + +- (id)objectAtIndex:(NSUInteger)index +{ + return _markers[index]; +} + +- (NSUInteger)hash +{ + return _markers.lastObject.hash; +} + +@end + +@interface ListItemRenderer () +- (void)applyCheckedDecorationsTo:(NSMutableAttributedString *)output + range:(NSRange)range + nestingLevel:(NSInteger)nestingLevel; +@end + +@implementation ListItemRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + if (!context) + return; + + context.listItemNumber++; + const NSInteger currentPosition = context.listItemNumber; + const NSInteger currentDepth = context.listDepth; // 1-based (1 = top level) + + const BOOL isTask = [node.attributes[@"isTask"] isEqualToString:@"true"]; + const BOOL isChecked = isTask && [node.attributes[@"taskChecked"] isEqualToString:@"true"]; + NSInteger taskIndex = -1; + if (isTask) { + taskIndex = context.taskItemCount; + context.taskItemCount++; + } + + // currentDepth - 1 handles the horizontal offset for nested lists + const NSInteger nestingLevel = currentDepth - 1; + const CGFloat baseMarkerWidth = isTask ? [_config effectiveListMarginLeftForTask] + : (context.listType == ListTypeOrdered) ? [_config effectiveListMarginLeftForNumber] + : [_config effectiveListMarginLeftForBullet]; + + const CGFloat blockquoteIndent = + blockquoteIndentForDepth(context.blockquoteDepth, [_config blockquoteBorderWidth] + [_config blockquoteGapWidth]); + + const CGFloat totalIndent = blockquoteIndent + baseMarkerWidth + [_config effectiveListGapWidth] + + (nestingLevel * [_config listStyleMarginLeft]); + + const NSUInteger startLocation = output.length; + + // Manual save/restore — a scope snapshot would also roll back the listItemNumber increment + const CGFloat prevIndent = context.accumulatedIndent; + context.accumulatedIndent = totalIndent; + @try { + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + } @finally { + context.accumulatedIndent = prevIndent; + } + + // Ensure every list item ends with a newline to prevent paragraph merging + if (output.length > startLocation && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:kNewlineAttributedString]; + } + + const NSRange itemRange = NSMakeRange(startLocation, output.length - startLocation); + if (itemRange.length == 0) + return; + + // Informs MarkdownAccessibilityElementBuilder about the specific boundaries of this list item + [context registerListItemRange:itemRange + position:currentPosition + depth:currentDepth + isOrdered:(context.listType == ListTypeOrdered)]; + + const CGFloat lineHeightConfig = [_config listStyleLineHeight]; + + // Boxing metadata for attributed string storage + NSMutableDictionary *metadata = [@{ + ListDepthAttribute : @(nestingLevel), + ListTypeAttribute : @(context.listType), + ListItemNumberAttribute : @(currentPosition) + } mutableCopy]; + + if (isTask) { + metadata[TaskItemAttribute] = @YES; + metadata[TaskCheckedAttribute] = @(isChecked); + metadata[TaskIndexAttribute] = @(taskIndex); + } + + // Preserve styles of nested sub-lists and code blocks by applying the list + // paragraph style only to the surviving gaps between them. + NSMutableArray *skipRanges = [NSMutableArray array]; + [output enumerateAttribute:CodeBlockAttributeName + inRange:itemRange + options:0 + usingBlock:^(id value, NSRange range, BOOL *stop) { + if ([value boolValue]) { + [skipRanges addObject:[NSValue valueWithRange:range]]; + } + }]; + [output enumerateAttribute:ListDepthAttribute + inRange:itemRange + options:0 + usingBlock:^(id depthAttr, NSRange range, BOOL *stop) { + if (depthAttr && [depthAttr integerValue] > nestingLevel) { + [skipRanges addObject:[NSValue valueWithRange:range]]; + } + }]; + [skipRanges sortUsingComparator:^NSComparisonResult(NSValue *a, NSValue *b) { + NSUInteger la = [a rangeValue].location; + NSUInteger lb = [b rangeValue].location; + return la < lb ? NSOrderedAscending : (la > lb ? NSOrderedDescending : NSOrderedSame); + }]; + + void (^applyStyleToRange)(NSRange) = ^(NSRange range) { + if (range.length == 0) + return; + NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; + style.firstLineHeadIndent = totalIndent; + style.headIndent = totalIndent; + const CGFloat lineHeight = ENRMLineHeightWithLinkPills(output, range, lineHeightConfig); + if (lineHeight > 0) { + style.minimumLineHeight = lineHeight; + } + NSMutableDictionary *attributesToApply = [metadata mutableCopy]; + attributesToApply[NSParagraphStyleAttributeName] = style; + [output addAttributes:attributesToApply range:range]; + if (lineHeight > 0) { + applyBaselineOffset(output, range); + } + }; + + NSUInteger pos = itemRange.location; + const NSUInteger itemEnd = NSMaxRange(itemRange); + for (NSValue *val in skipRanges) { + NSRange skip = [val rangeValue]; + if (pos < skip.location) { + applyStyleToRange(NSMakeRange(pos, skip.location - pos)); + } + pos = MAX(pos, NSMaxRange(skip)); + } + if (pos < itemEnd) { + applyStyleToRange(NSMakeRange(pos, itemEnd - pos)); + } + + ENRMListMarkerDescriptor *marker = [[ENRMListMarkerDescriptor alloc] init]; + marker.isTask = isTask; + marker.isChecked = isChecked; + marker.taskIndex = taskIndex; + marker.listType = context.listType; + marker.number = currentPosition; + marker.depth = nestingLevel; + marker.indent = totalIndent; + + // Anchor on the first content character so items that open with a code block + // or nested sublist still get their marker; fall back to startLocation for + // whitespace-only items. + NSUInteger anchorLocation = startLocation; + NSString *string = output.string; + for (NSUInteger i = startLocation; i < itemEnd; i++) { + if ([string characterAtIndex:i] != '\n') { + anchorLocation = i; + break; + } + } + + // Cover the whole grapheme cluster: anchoring on a single UTF-16 code unit + // splits multi-unit graphemes (emoji surrogate pairs, ZWJ sequences) across + // two attribute runs, which drops the glyph and hides the marker for every + // item but the last. + const NSRange anchorRange = [string rangeOfComposedCharacterSequenceAtIndex:anchorLocation]; + + NSArray *existingMarkers = [output attribute:ListItemMarkerStartAttribute atIndex:anchorLocation effectiveRange:NULL]; + NSArray *markers = + [existingMarkers isKindOfClass:[NSArray class]] ? [existingMarkers arrayByAddingObject:marker] : @[ marker ]; + [output addAttribute:ListItemMarkerStartAttribute + value:[[ENRMListMarkerArray alloc] initWithMarkers:markers] + range:anchorRange]; + + if (isTask && isChecked) { + [self applyCheckedDecorationsTo:output range:itemRange nestingLevel:nestingLevel]; + } +} + +- (void)applyCheckedDecorationsTo:(NSMutableAttributedString *)output + range:(NSRange)range + nestingLevel:(NSInteger)nestingLevel +{ + RCTUIColor *checkedColor = [_config taskListCheckedTextColor]; + BOOL shouldStrikethrough = [_config taskListCheckedStrikethrough]; + + if (!checkedColor && !shouldStrikethrough) { + return; + } + + NSMutableDictionary *checkedAttrs = [NSMutableDictionary dictionary]; + + if (checkedColor) { + checkedAttrs[NSForegroundColorAttributeName] = checkedColor; + } + + if (shouldStrikethrough) { + checkedAttrs[NSStrikethroughStyleAttributeName] = @(NSUnderlineStyleSingle); + + RCTUIColor *lineColor = checkedColor ?: [_config listStyleColor]; + if (lineColor) { + checkedAttrs[NSStrikethroughColorAttributeName] = lineColor; + } + } + + [output enumerateAttribute:ListDepthAttribute + inRange:range + options:0 + usingBlock:^(NSNumber *depth, NSRange segmentRange, BOOL *stop) { + BOOL isNestedSubItem = (depth && [depth integerValue] > nestingLevel); + if (isNestedSubItem) { + return; + } + + // Skip code block ranges — preserve CodeBlockRenderer styles. + NSNumber *isCodeBlock = [output attribute:CodeBlockAttributeName + atIndex:segmentRange.location + effectiveRange:nil]; + if ([isCodeBlock boolValue]) { + return; + } + + [output addAttributes:checkedAttrs range:segmentRange]; + }]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.h new file mode 100644 index 000000000000..f32f624178e5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.h @@ -0,0 +1,13 @@ +#import "BaseRenderer.h" + +@class RendererFactory; +@class StyleConfig; +@class RenderContext; + +@interface ListRenderer : BaseRenderer + +- (instancetype)initWithRendererFactory:(RendererFactory *)rendererFactory + config:(StyleConfig *)config + isOrdered:(BOOL)isOrdered; + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.m new file mode 100644 index 000000000000..47283dc99916 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ListRenderer.m @@ -0,0 +1,108 @@ +#import "ListRenderer.h" +#import "BlockquoteRenderer.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +// Inserts the configured vertical gap between consecutive list items (including +// nested ones) by raising paragraphSpacing on the paragraph preceding each item +// start. The first item of the root list gets no spacing above it. +static void applyListItemSpacing(NSMutableAttributedString *output, RenderContext *context, NSUInteger listStart, + CGFloat itemSpacing) +{ + if (itemSpacing <= 0) + return; + + NSMutableIndexSet *itemStarts = [NSMutableIndexSet indexSet]; + for (NSValue *value in context.listItemRanges) { + NSUInteger location = [value rangeValue].location; + if (location >= listStart && location < output.length) { + [itemStarts addIndex:location]; + } + } + if (itemStarts.count < 2) + return; + + NSString *string = output.string; + const NSUInteger firstStart = itemStarts.firstIndex; + [itemStarts enumerateIndexesUsingBlock:^(NSUInteger itemStart, BOOL *stop) { + if (itemStart == firstStart) + return; + NSRange prevParagraph = [string paragraphRangeForRange:NSMakeRange(itemStart - 1, 0)]; + [output enumerateAttribute:NSParagraphStyleAttributeName + inRange:prevParagraph + options:0 + usingBlock:^(NSParagraphStyle *style, NSRange range, BOOL *innerStop) { + if (style.paragraphSpacing >= itemSpacing) + return; + NSMutableParagraphStyle *updated = + style ? [style mutableCopy] : [[NSMutableParagraphStyle alloc] init]; + updated.paragraphSpacing = itemSpacing; + [output addAttribute:NSParagraphStyleAttributeName value:updated range:range]; + }]; + }]; +} + +@implementation ListRenderer { + BOOL _isOrdered; +} + +- (instancetype)initWithRendererFactory:(RendererFactory *)factory config:(StyleConfig *)config isOrdered:(BOOL)ordered +{ + if (self = [super initWithRendererFactory:factory config:config]) { + _isOrdered = ordered; + } + return self; +} + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return [context snapshotScope]; +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + if (!context) + return; + + const NSInteger prevDepth = context.listDepth; + const NSUInteger startLocation = output.length; + + if (prevDepth == 0) { + // Apply top margin for root-level list + applyBlockSpacingBefore(output, startLocation, _config.listStyleMarginTop); + } else if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + // Ensure nested lists start on a new line + [output appendAttributedString:kNewlineAttributedString]; + } + + context.listDepth = prevDepth + 1; + context.listType = _isOrdered ? ListTypeOrdered : ListTypeUnordered; + NSInteger startNumber = 1; + NSString *startAttr = node.attributes[@"start"]; + if (_isOrdered && startAttr != nil) { + startNumber = MAX((NSInteger)0, (NSInteger)startAttr.integerValue); + } + // ListItemRenderer pre-increments, so the counter starts one below the + // first rendered number. + context.listItemNumber = startNumber - 1; + + [context setBlockStyle:_isOrdered ? BlockTypeOrderedList : BlockTypeUnorderedList + font:_config.listStyleFont + color:_config.listStyleColor + headingLevel:0]; + + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + if (prevDepth == 0) { + applyListItemSpacing(output, context, startLocation, [_config listStyleItemSpacing]); + // Apply bottom margin for root-level list + applyBlockSpacingAfter(output, _config.listStyleMarginBottom); + } +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/NodeRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/NodeRenderer.h new file mode 100644 index 000000000000..cf1cd21c903a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/NodeRenderer.h @@ -0,0 +1,8 @@ +#import + +@class MarkdownASTNode; +@class RenderContext; + +@protocol NodeRenderer +- (void)renderNode:(MarkdownASTNode *)node into:(NSMutableAttributedString *)output context:(RenderContext *)context; +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.h new file mode 100644 index 000000000000..b46110772a9d --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.h @@ -0,0 +1,6 @@ +#import "BaseRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" + +@interface ParagraphRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.m new file mode 100644 index 000000000000..413182e34357 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ParagraphRenderer.m @@ -0,0 +1,85 @@ +#import "ParagraphRenderer.h" +#import "FontUtils.h" +#import "MarkdownASTNode.h" +#import "ParagraphStyleUtils.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation ParagraphRenderer + +- (id)takeContextSnapshot:(RenderContext *)context +{ + return [context snapshotScope]; +} + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + // Synthetic wrapper around tight list item inlines (see wrapListItemInlineRuns + // in MD4CParser) — render transparently, the list owns spacing and layout. + if ([node.attributes[@"tight"] boolValue]) { + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + return; + } + + // Only set block style if a parent element (e.g. List, Blockquote) hasn't already established one + BOOL isTopLevel = (context.currentBlockType == BlockTypeNone); + + if (isTopLevel) { + [context setBlockStyle:BlockTypeParagraph font:_config.paragraphFont color:_config.paragraphColor headingLevel:0]; + } + + NSUInteger start = output.length; + // Paragraphs directly inside a blockquote keep their block margins so spacing + // between blocks matches the top-level document (a heading defaults to + // marginTop 0, so the gap before it comes from the preceding paragraph's + // marginBottom). List content stays tight - lists own their item spacing. + BOOL shouldApplyMargin = + (context.currentBlockType == BlockTypeNone || context.currentBlockType == BlockTypeParagraph || + context.currentBlockType == BlockTypeBlockquote); + + // Detect if the paragraph is a wrapper for a standalone image to use image-specific spacing + BOOL isBlockImage = (node.children.count == 1 && ((MarkdownASTNode *)node.children[0]).type == MarkdownNodeTypeImage); + CGFloat marginTop = isBlockImage ? _config.imageMarginTop : _config.paragraphMarginTop; + + NSUInteger contentStart = start; + + // Handle leading margin for the first element in the document (Index 0 check) + if (shouldApplyMargin && start == 0) { + NSUInteger offset = applyBlockSpacingBefore(output, 0, marginTop); + contentStart += offset; + start += offset; + } + + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + if (output.length <= start) + return; + NSRange range = NSMakeRange(start, output.length - start); + + // Avoid standard line height on block images to prevent vertical alignment issues + if (!isBlockImage) { + applyLineHeight(output, range, _config.paragraphLineHeight); + if (!ENRMBlockTypeReappliesBaselineOffset(context.currentBlockType)) { + applyBaselineOffset(output, range); + } + } + + applyTextAlignment(output, range, _config.paragraphTextAlign); + + // Skip marginTop for the first block — already handled by applyBlockSpacingBefore above + if (shouldApplyMargin && contentStart != 1) { + NSUInteger inserted = applyParagraphSpacingBefore(output, range, marginTop); + start += inserted; + } + + CGFloat marginBottom = 0; + if (shouldApplyMargin) { + marginBottom = isBlockImage ? _config.imageMarginBottom : _config.paragraphMarginBottom; + } + + applyParagraphSpacingAfter(output, start, marginBottom); +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/RenderContext.h b/packages/react-native-enriched-markdown/ios/renderer/RenderContext.h new file mode 100644 index 000000000000..ad4a6431a02a --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/RenderContext.h @@ -0,0 +1,141 @@ +#import "ENRMLatexErrorReporting.h" +#import "ENRMUIKit.h" +#import + +typedef NS_ENUM(NSInteger, BlockType) { + BlockTypeNone, + BlockTypeParagraph, + BlockTypeHeading, + BlockTypeBlockquote, + BlockTypeUnorderedList, + BlockTypeOrderedList, + BlockTypeCodeBlock +}; + +/// YES when the enclosing block re-stamps its own line height over paragraph content and applies the +/// matching baseline offset itself, so a paragraph nested inside it must not apply its own (the outer +/// block's line height wins, and applyBaselineOffset skips ranges that already carry an offset). +/// TODO: loose list items have the same shape (ParagraphRenderer runs, then the list re-stamps its +/// line height); add BlockTypeUnorderedList/BlockTypeOrderedList here once lists own their offset too. +static inline BOOL ENRMBlockTypeReappliesBaselineOffset(BlockType type) +{ + return type == BlockTypeBlockquote; +} + +typedef NS_ENUM(NSInteger, ListType) { ListTypeUnordered, ListTypeOrdered }; + +@interface BlockStyle : NSObject +@property (nonatomic, assign) CGFloat fontSize; +@property (nonatomic, strong) NSString *fontFamily; +@property (nonatomic, strong) NSString *fontWeight; +@property (nonatomic, strong) RCTUIColor *color; +@property (nonatomic, strong) UIFont *cachedFont; +@property (nonatomic, strong) NSDictionary *cachedTextAttributes; +@end + +@interface RenderContext : NSObject +@property (nonatomic, strong) NSMutableArray *linkRanges; +@property (nonatomic, strong) NSMutableArray *linkURLs; +@property (nonatomic, strong) NSMutableArray *headingRanges; +@property (nonatomic, strong) NSMutableArray *headingLevels; +@property (nonatomic, strong) NSMutableArray *imageRanges; +@property (nonatomic, strong) NSMutableArray *imageAltTexts; +@property (nonatomic, strong) NSMutableArray *imageURLs; +@property (nonatomic, strong) NSMutableArray *listItemRanges; +@property (nonatomic, strong) NSMutableArray *listItemPositions; // Position in parent list (1, 2, 3...) +@property (nonatomic, strong) NSMutableArray *listItemDepths; // Nesting depth (1 = top level, 2+ = nested) +@property (nonatomic, strong) NSMutableArray *listItemOrdered; // YES = ordered, NO = unordered (bullet) +@property (nonatomic, assign) BlockType currentBlockType; +@property (nonatomic, strong) BlockStyle *currentBlockStyle; +@property (nonatomic, assign) NSInteger currentHeadingLevel; +@property (nonatomic, assign) NSInteger blockquoteDepth; +@property (nonatomic, assign) NSInteger listDepth; +@property (nonatomic, assign) ListType listType; +@property (nonatomic, assign) NSInteger listItemNumber; +@property (nonatomic, assign) CGFloat accumulatedIndent; +@property (nonatomic, assign) BOOL allowFontScaling; +@property (nonatomic, assign) CGFloat maxFontSizeMultiplier; +@property (nonatomic, assign) NSInteger taskItemCount; +@property (nonatomic, strong) NSMutableArray> *mathReporters; + +- (instancetype)init; +- (void)reset; + +- (UIFont *)cachedFontForSize:(CGFloat)fontSize family:(NSString *)fontFamily weight:(NSString *)fontWeight; +- (NSMutableParagraphStyle *)spacerStyleWithHeight:(CGFloat)height spacing:(CGFloat)spacing; +- (NSMutableParagraphStyle *)blockSpacerStyleWithMargin:(CGFloat)margin; +- (void)registerLinkRange:(NSRange)range url:(NSString *)url; + +- (void)applyLinkAttributesToString:(NSMutableAttributedString *)attributedString; +- (void)applyImageAttributesToString:(NSMutableAttributedString *)attributedString; +- (void)registerHeadingRange:(NSRange)range level:(NSInteger)level text:(NSString *)text; +- (void)registerImageRange:(NSRange)range altText:(NSString *)altText url:(NSString *)url; +- (void)registerListItemRange:(NSRange)range + position:(NSInteger)position + depth:(NSInteger)depth + isOrdered:(BOOL)isOrdered; +- (void)setBlockStyle:(BlockType)type + fontSize:(CGFloat)fontSize + fontFamily:(NSString *)fontFamily + fontWeight:(NSString *)fontWeight + color:(RCTUIColor *)color; +- (void)setBlockStyle:(BlockType)type + fontSize:(CGFloat)fontSize + fontFamily:(NSString *)fontFamily + fontWeight:(NSString *)fontWeight + color:(RCTUIColor *)color + headingLevel:(NSInteger)headingLevel; +- (void)setBlockStyle:(BlockType)type + font:(UIFont *)font + color:(RCTUIColor *)color + headingLevel:(NSInteger)headingLevel; +- (BlockStyle *)getBlockStyle; +- (NSDictionary *)getTextAttributes; +- (void)clearBlockStyle; + +/** + * Captures/restores the scoped context state: block style, block type, heading level, + * blockquote/list depths, list type, list item counter and accumulated indent. + * Accumulators (range registries, taskItemCount) are excluded on purpose — they + * must survive restores. + */ +- (id)snapshotScope; +- (void)restoreScope:(id)snapshot; + +/** + * Checks if colors should be preserved based on existing attributes. + * Returns YES if the text is inside a link or inline code, which means + * we should preserve their colors instead of applying new colors. + */ ++ (BOOL)shouldPreserveColors:(NSDictionary *)existingAttributes; + +/** + * Calculates the color that strong would use based on the configured strong color and block style. + * Uses strongColor if explicitly set (different from block color), otherwise uses block color. + */ ++ (RCTUIColor *)calculateStrongColor:(RCTUIColor *)configStrongColor blockColor:(RCTUIColor *)blockColor; + +/** + * Resolves highlight foreground color: uses block color when config matches paragraph default. + */ ++ (RCTUIColor *)calculateHighlightColor:(RCTUIColor *)configHighlightColor + paragraphColor:(RCTUIColor *)paragraphColor + blockColor:(RCTUIColor *)blockColor; + +/** + * Calculates the range for content rendered between start and current output length. + * Returns a range with length 0 if no content was rendered. + */ ++ (NSRange)rangeForRenderedContent:(NSMutableAttributedString *)output start:(NSUInteger)start; + +/** + * Applies font and color attributes conditionally, only updating if they've changed. + * Returns YES if any attributes were updated, NO otherwise. + */ ++ (BOOL)applyFontAndColorAttributes:(NSMutableAttributedString *)output + range:(NSRange)range + font:(UIFont *)font + color:(RCTUIColor *)color + existingAttributes:(NSDictionary *)existingAttributes + shouldPreserveColors:(BOOL)shouldPreserveColors; +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/RenderContext.m b/packages/react-native-enriched-markdown/ios/renderer/RenderContext.m new file mode 100644 index 000000000000..b226867087c6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/RenderContext.m @@ -0,0 +1,395 @@ +#import "RenderContext.h" +#import "CodeBackground.h" +#import "FontUtils.h" +#import + +@implementation BlockStyle +@end + +static NSArray *ENRMScopedKeyPaths(void) +{ + static NSArray *keyPaths; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + keyPaths = @[ + @"currentBlockType", + @"currentHeadingLevel", + @"currentBlockStyle.fontSize", + @"currentBlockStyle.fontFamily", + @"currentBlockStyle.fontWeight", + @"currentBlockStyle.color", + @"currentBlockStyle.cachedFont", + @"currentBlockStyle.cachedTextAttributes", + @"blockquoteDepth", + @"listDepth", + @"listType", + @"listItemNumber", + @"accumulatedIndent", + ]; + }); + return keyPaths; +} + +@implementation RenderContext { + NSMutableDictionary *_fontCache; + NSParagraphStyle *_baseSpacerTemplate; + NSParagraphStyle *_baseBlockSpacerTemplate; +} + +- (instancetype)init +{ + if (self = [super init]) { + _linkRanges = [NSMutableArray array]; + _linkURLs = [NSMutableArray array]; + _headingRanges = [NSMutableArray array]; + _headingLevels = [NSMutableArray array]; + _imageRanges = [NSMutableArray array]; + _imageAltTexts = [NSMutableArray array]; + _imageURLs = [NSMutableArray array]; + _listItemRanges = [NSMutableArray array]; + _listItemPositions = [NSMutableArray array]; + _listItemDepths = [NSMutableArray array]; + _listItemOrdered = [NSMutableArray array]; + _mathReporters = [NSMutableArray array]; + _fontCache = [NSMutableDictionary dictionary]; + _currentBlockStyle = [[BlockStyle alloc] init]; + _allowFontScaling = YES; + _maxFontSizeMultiplier = 0; + + NSMutableParagraphStyle *spacerTemplate = [[NSMutableParagraphStyle alloc] init]; + _baseSpacerTemplate = [spacerTemplate copy]; + + NSMutableParagraphStyle *blockSpacerTemplate = [[NSMutableParagraphStyle alloc] init]; + blockSpacerTemplate.minimumLineHeight = 1; + blockSpacerTemplate.maximumLineHeight = 1; + _baseBlockSpacerTemplate = [blockSpacerTemplate copy]; + + [self reset]; + } + return self; +} + +#pragma mark - Font Cache + +- (UIFont *)cachedFontForSize:(CGFloat)fontSize family:(NSString *)fontFamily weight:(NSString *)fontWeight +{ + CGFloat effectiveMultiplier = _allowFontScaling ? RCTFontSizeMultiplierWithMax(_maxFontSizeMultiplier) : 1.0; + + NSString *weightKey = (fontWeight.length > 0) ? fontWeight : @""; + NSString *key = + [NSString stringWithFormat:@"%.1f|%@|%@|%.2f", fontSize, fontFamily ?: @"", weightKey, effectiveMultiplier]; + + UIFont *cached = _fontCache[key]; + if (cached) { + return cached; + } + + NSString *effectiveWeight = (fontWeight.length > 0) ? fontWeight : nil; + + UIFont *font = [RCTFont updateFont:nil + withFamily:fontFamily + size:@(fontSize) + weight:effectiveWeight + style:nil + variant:nil + scaleMultiplier:effectiveMultiplier]; + + if (font) { + _fontCache[key] = font; + } + return font; +} + +#pragma mark - Paragraph Style Factory + +- (NSMutableParagraphStyle *)spacerStyleWithHeight:(CGFloat)height spacing:(CGFloat)spacing +{ + NSMutableParagraphStyle *style = [_baseSpacerTemplate mutableCopy]; + style.minimumLineHeight = height; + style.maximumLineHeight = height; + style.paragraphSpacing = spacing; + return style; +} + +- (NSMutableParagraphStyle *)blockSpacerStyleWithMargin:(CGFloat)margin +{ + NSMutableParagraphStyle *style = [_baseBlockSpacerTemplate mutableCopy]; + style.paragraphSpacing = margin; + return style; +} + +#pragma mark - Link Registry + +- (void)registerLinkRange:(NSRange)range url:(NSString *)url +{ + if (range.length == 0) + return; + [self.linkRanges addObject:[NSValue valueWithRange:range]]; + [self.linkURLs addObject:url ?: @""]; +} + +- (void)applyLinkAttributesToString:(NSMutableAttributedString *)attributedString +{ + NSUInteger length = attributedString.length; + for (NSUInteger i = 0; i < self.linkRanges.count; i++) { + NSRange range = [self.linkRanges[i] rangeValue]; + if (NSMaxRange(range) > length) + continue; + [attributedString addAttribute:@"linkURL" value:self.linkURLs[i] range:range]; + } +} + +- (void)applyImageAttributesToString:(NSMutableAttributedString *)attributedString +{ + NSUInteger length = attributedString.length; + for (NSUInteger i = 0; i < self.imageRanges.count; i++) { + NSRange range = [self.imageRanges[i] rangeValue]; + if (NSMaxRange(range) > length) + continue; + [attributedString addAttribute:@"imageURL" value:self.imageURLs[i] range:range]; + [attributedString addAttribute:@"imageAltText" value:self.imageAltTexts[i] range:range]; + } +} + +- (void)registerHeadingRange:(NSRange)range level:(NSInteger)level text:(NSString *)text +{ + if (range.length == 0) + return; + [self.headingRanges addObject:[NSValue valueWithRange:range]]; + [self.headingLevels addObject:@(level)]; +} + +- (void)registerImageRange:(NSRange)range altText:(NSString *)altText url:(NSString *)url +{ + if (range.length == 0) + return; + [self.imageRanges addObject:[NSValue valueWithRange:range]]; + [self.imageAltTexts addObject:altText ?: @""]; + [self.imageURLs addObject:url ?: @""]; +} + +#pragma mark - Registration Helpers + +- (void)registerListItemRange:(NSRange)range + position:(NSInteger)position + depth:(NSInteger)depth + isOrdered:(BOOL)isOrdered +{ + if (![self isValidRange:range]) + return; + + [self.listItemRanges addObject:[NSValue valueWithRange:range]]; + [self.listItemPositions addObject:@(position)]; + [self.listItemDepths addObject:@(depth)]; + [self.listItemOrdered addObject:@(isOrdered)]; +} + +#pragma mark - Private + +- (BOOL)isValidRange:(NSRange)range +{ + return range.length > 0 && range.location != NSNotFound; +} + +#pragma mark - Block Style Management + +/** + * Updates the shared BlockStyle object with new traits. + * This avoids allocating a new object for every block node in the AST. + */ +- (void)setBlockStyle:(BlockType)type + fontSize:(CGFloat)fontSize + fontFamily:(NSString *)fontFamily + fontWeight:(NSString *)fontWeight + color:(RCTUIColor *)color + headingLevel:(NSInteger)headingLevel +{ + _currentBlockType = type; + _currentHeadingLevel = headingLevel; + + _currentBlockStyle.fontSize = fontSize; + _currentBlockStyle.fontFamily = fontFamily ?: @""; + _currentBlockStyle.fontWeight = fontWeight ?: @"normal"; + _currentBlockStyle.color = color ?: [RCTUIColor blackColor]; +} + +- (void)setBlockStyle:(BlockType)type + fontSize:(CGFloat)fontSize + fontFamily:(NSString *)fontFamily + fontWeight:(NSString *)fontWeight + color:(RCTUIColor *)color +{ + [self setBlockStyle:type fontSize:fontSize fontFamily:fontFamily fontWeight:fontWeight color:color headingLevel:0]; +} + +- (void)setBlockStyle:(BlockType)type font:(UIFont *)font color:(RCTUIColor *)color headingLevel:(NSInteger)headingLevel +{ + _currentBlockType = type; + _currentHeadingLevel = headingLevel; + + RCTUIColor *finalColor = color ?: [RCTUIColor blackColor]; + _currentBlockStyle.cachedFont = font; + _currentBlockStyle.color = finalColor; + + // Pre-create text attributes dictionary if we have both font and color + if (font) { + _currentBlockStyle.cachedTextAttributes = + @{NSFontAttributeName : font, NSForegroundColorAttributeName : finalColor}; + } +} + +- (BlockStyle *)getBlockStyle +{ + return _currentBlockStyle; +} + +- (NSDictionary *)getTextAttributes +{ + BlockStyle *style = _currentBlockStyle; + + // Return pre-cached attributes if available + if (style.cachedTextAttributes) { + return style.cachedTextAttributes; + } + + // Fall back to creating attributes from font cache + UIFont *font = style.cachedFont; + if (!font) { + font = [self cachedFontForSize:style.fontSize family:style.fontFamily weight:style.fontWeight]; + } + RCTUIColor *color = style.color ?: [RCTUIColor blackColor]; + + // Cache for future calls within same block + style.cachedTextAttributes = @{NSFontAttributeName : font, NSForegroundColorAttributeName : color}; + return style.cachedTextAttributes; +} + +- (void)clearBlockStyle +{ + _currentBlockType = BlockTypeNone; + _currentHeadingLevel = 0; + _currentBlockStyle.cachedFont = nil; + _currentBlockStyle.cachedTextAttributes = nil; +} + +- (id)snapshotScope +{ + NSArray *keyPaths = ENRMScopedKeyPaths(); + NSMutableDictionary *snapshot = [NSMutableDictionary dictionaryWithCapacity:keyPaths.count]; + for (NSString *keyPath in keyPaths) { + snapshot[keyPath] = [self valueForKeyPath:keyPath] ?: [NSNull null]; + } + return snapshot; +} + +- (void)restoreScope:(id)snapshot +{ + NSDictionary *frame = snapshot; + for (NSString *keyPath in ENRMScopedKeyPaths()) { + id value = frame[keyPath]; + [self setValue:(value == [NSNull null] ? nil : value) forKeyPath:keyPath]; + } +} + +#pragma mark - Reset + +- (void)reset +{ + [_linkRanges removeAllObjects]; + [_linkURLs removeAllObjects]; + [_headingRanges removeAllObjects]; + [_headingLevels removeAllObjects]; + [_imageRanges removeAllObjects]; + [_imageAltTexts removeAllObjects]; + [_imageURLs removeAllObjects]; + [_listItemRanges removeAllObjects]; + [_listItemPositions removeAllObjects]; + [_listItemDepths removeAllObjects]; + [_listItemOrdered removeAllObjects]; + [_mathReporters removeAllObjects]; + [self clearBlockStyle]; + + _blockquoteDepth = 0; + _listDepth = 0; + _listType = ListTypeUnordered; + _listItemNumber = 0; + _accumulatedIndent = 0; + _taskItemCount = 0; + + // Revert shared style object to baseline defaults + _currentBlockStyle.fontSize = 0; + _currentBlockStyle.fontFamily = @""; + _currentBlockStyle.fontWeight = @""; + _currentBlockStyle.color = [RCTUIColor blackColor]; +} + +#pragma mark - Static Utilities + +/** + * Determines if specific inline attributes should protect the current color. + */ ++ (BOOL)shouldPreserveColors:(NSDictionary *)attrs +{ + return (attrs[NSLinkAttributeName] != nil || attrs[CodeAttributeName] != nil); +} + +// TODO: Unify calculateStrongColor and calculateHighlightColor into a single helper that +// resolves inline foreground color from (configColor, inheritanceBaseline, blockColor). + +/** + * Calculates whether a strong color should override the block color. + */ ++ (RCTUIColor *)calculateStrongColor:(RCTUIColor *)configStrongColor blockColor:(RCTUIColor *)blockColor +{ + if (!configStrongColor || [configStrongColor isEqual:blockColor]) { + return blockColor; + } + return configStrongColor; +} + ++ (RCTUIColor *)calculateHighlightColor:(RCTUIColor *)configHighlightColor + paragraphColor:(RCTUIColor *)paragraphColor + blockColor:(RCTUIColor *)blockColor +{ + if ([configHighlightColor isEqual:paragraphColor]) { + return blockColor; + } + return configHighlightColor; +} + +/** + * Safely calculates a range based on a start point and the current output length. + */ ++ (NSRange)rangeForRenderedContent:(NSMutableAttributedString *)output start:(NSUInteger)start +{ + if (output.length < start) + return NSMakeRange(start, 0); + return NSMakeRange(start, output.length - start); +} + +/** + * Surgically applies attributes only if they differ from current values. + * This minimizes "dirtying" the AttributedString, which improves layout performance. + */ ++ (void)applyFontAndColorAttributes:(NSMutableAttributedString *)output + range:(NSRange)range + font:(UIFont *)font + color:(RCTUIColor *)color + existingAttributes:(NSDictionary *)attrs + shouldPreserveColors:(BOOL)shouldPreserve +{ + if (range.length == 0) + return; + + // Font Update: Only if it exists and is different + if (font && ![font isEqual:attrs[NSFontAttributeName]]) { + [output addAttribute:NSFontAttributeName value:font range:range]; + } + + // Color Update: Only if not a link/code and different from existing + if (color && !shouldPreserve && ![color isEqual:attrs[NSForegroundColorAttributeName]]) { + [output addAttribute:NSForegroundColorAttributeName value:color range:range]; + } +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.h b/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.h new file mode 100644 index 000000000000..ac291a866ca2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.h @@ -0,0 +1,12 @@ +#import "MarkdownASTNode.h" +#import "NodeRenderer.h" + +@class RenderContext; + +@interface RendererFactory : NSObject +- (instancetype)initWithConfig:(id)config; +- (id)rendererForNodeType:(MarkdownNodeType)type; +- (void)renderChildrenOfNode:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context; +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.m b/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.m new file mode 100644 index 000000000000..a5554197d915 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/RendererFactory.m @@ -0,0 +1,167 @@ +#import "RendererFactory.h" +#import "BlankLineRenderer.h" +#import "BlockquoteRenderer.h" +#import "CodeBlockRenderer.h" +#import "CodeRenderer.h" +#import "ENRMImageRenderer.h" +#import "EmphasisRenderer.h" + +#import "ENRMFeatureFlags.h" + +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathInlineRenderer.h" +#endif +#import "ENRMSpoilerRenderer.h" +#import "HeadingRenderer.h" +#import "HighlightRenderer.h" +#import "LinkRenderer.h" +#import "ListItemRenderer.h" +#import "ListRenderer.h" +#import "MarkdownASTNode.h" +#import "ParagraphRenderer.h" +#import "RenderContext.h" +#import "StrikethroughRenderer.h" +#import "StrongRenderer.h" +#import "StyleConfig.h" +#import "SubscriptRenderer.h" +#import "SuperscriptRenderer.h" +#import "TextRenderer.h" +#import "ThematicBreakRenderer.h" +#import "UnderlineRenderer.h" + +@implementation RendererFactory { + StyleConfig *_config; + NSMutableDictionary> *_cache; +} + +/** + * Initializes the factory with a shared style configuration. + * Uses a mutable dictionary to cache renderer instances as they are needed. + */ +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super init]; + if (self) { + _config = config; + _cache = [NSMutableDictionary new]; + } + return self; +} + +/** + * Returns a shared renderer instance for a specific node type. + * Implements lazy initialization to avoid allocating unused renderers. + */ +- (id)rendererForNodeType:(MarkdownNodeType)type +{ + id cached = _cache[@(type)]; + if (cached) { + return cached; + } + + id renderer = [self createRendererForType:type]; + if (renderer) { + _cache[@(type)] = renderer; + } + return renderer; +} + +/** + * Internal factory method to instantiate specialized renderers. + */ +- (id)createRendererForType:(MarkdownNodeType)type +{ + switch (type) { + case MarkdownNodeTypeText: + return [TextRenderer new]; + case MarkdownNodeTypeStrong: + return [[StrongRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeEmphasis: + return [[EmphasisRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeStrikethrough: + return [[StrikethroughRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeUnderline: + return [[UnderlineRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeSuperscript: + return [[SuperscriptRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeSubscript: + return [[SubscriptRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeHighlight: + return [[HighlightRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeParagraph: + return [[ParagraphRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeLink: + return [[LinkRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeHeading: + return [[HeadingRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeCode: + return [[CodeRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeImage: + return [[ENRMImageRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeBlockquote: + // A list-nested admonition falls back to the inline blockquote renderer + // (no themed header); top-level admonitions use the segment container path. + case MarkdownNodeTypeAdmonition: + return [[BlockquoteRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeListItem: + return [[ListItemRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeUnorderedList: + return [[ListRenderer alloc] initWithRendererFactory:self config:_config isOrdered:NO]; + case MarkdownNodeTypeOrderedList: + return [[ListRenderer alloc] initWithRendererFactory:self config:_config isOrdered:YES]; + case MarkdownNodeTypeCodeBlock: + return [[CodeBlockRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeThematicBreak: + return [[ThematicBreakRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeBlankLine: + return [[BlankLineRenderer alloc] initWithRendererFactory:self config:_config]; +#if ENRICHED_MARKDOWN_MATH + case MarkdownNodeTypeLatexMathInline: + return [[ENRMMathInlineRenderer alloc] initWithRendererFactory:self config:_config]; + case MarkdownNodeTypeLatexMathDisplay: + // Display math INSIDE a paragraph (mid-paragraph / softbreak-adjacent + // `$$…$$`) previously fell through to the nil-renderer child dump — + // the body leaked as plain text with its delimiters silently dropped. + // Typeset it as an inline attachment instead; block-level display math + // is unaffected (SegmentRenderer intercepts root-level display nodes + // before this factory is consulted). + return [[ENRMMathInlineRenderer alloc] initWithRendererFactory:self config:_config]; +#endif + case MarkdownNodeTypeSpoiler: + return [[ENRMSpoilerRenderer alloc] initWithRendererFactory:self config:_config]; + default: + return nil; + } +} + +/** + * Helper method for container renderers to process their children. + * Leverages the factory to find the appropriate renderer for each child node. + */ +- (void)renderChildrenOfNode:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + for (MarkdownASTNode *child in node.children) { + if (child.type == MarkdownNodeTypeLineBreak) { + NSAttributedString *lineBreak = [[NSAttributedString alloc] initWithString:@"\u2028" + attributes:[context getTextAttributes]]; + [output appendAttributedString:lineBreak]; + continue; + } + if (child.type == MarkdownNodeTypeSoftBreak) { + NSAttributedString *softBreak = [[NSAttributedString alloc] initWithString:@" " + attributes:[context getTextAttributes]]; + [output appendAttributedString:softBreak]; + continue; + } + id renderer = [self rendererForNodeType:child.type]; + if (renderer) { + [renderer renderNode:child into:output context:context]; + } else if (child.children.count > 0) { + [self renderChildrenOfNode:child into:output context:context]; + } + } +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.h new file mode 100644 index 000000000000..8354b2bca2a2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface StrikethroughRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.m new file mode 100644 index 000000000000..15991a2a2dd6 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/StrikethroughRenderer.m @@ -0,0 +1,30 @@ +#import "StrikethroughRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation StrikethroughRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + // Apply strikethrough style + [output addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; + + // Apply strikethrough line color (not text color) + RCTUIColor *strikethroughColor = [_config strikethroughColor]; + [output addAttribute:NSStrikethroughColorAttributeName value:strikethroughColor range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.h new file mode 100644 index 000000000000..ca377c93166f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface StrongRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.m new file mode 100644 index 000000000000..15a76af85380 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/StrongRenderer.m @@ -0,0 +1,88 @@ +#import "StrongRenderer.h" +#import "FontUtils.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" +#import + +@implementation StrongRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + BlockStyle *blockStyle = [context getBlockStyle]; + RCTUIColor *configStrongColor = [_config strongColor]; + RCTUIColor *calculatedColor = + configStrongColor ? [RenderContext calculateStrongColor:configStrongColor blockColor:blockStyle.color] : nil; + NSString *strongFontFamily = [_config strongFontFamily]; + NSString *strongFontWeight = [_config strongFontWeight]; + BOOL useNormalWeight = [strongFontWeight isEqualToString:@"normal"]; + + [output enumerateAttributesInRange:range + options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(NSDictionary *attrs, NSRange subrange, BOOL *stop) { + // 1. Resolve Font + UIFont *currentFont = + attrs[NSFontAttributeName] ?: cachedFontFromBlockStyle(blockStyle, context); + + UIFont *resolvedFont = currentFont; + + if (strongFontFamily.length > 0) { + NSString *weight = useNormalWeight ? nil : @"bold"; + resolvedFont = [RCTFont updateFont:currentFont + withFamily:strongFontFamily + size:nil + weight:weight + style:nil + variant:nil + scaleMultiplier:1.0]; + } else if (!([currentFont.fontDescriptor symbolicTraits] & UIFontDescriptorTraitBold)) { + resolvedFont = [self ensureFontIsBold:currentFont]; + } + + if (resolvedFont && ![resolvedFont isEqual:currentFont]) { + [output addAttribute:NSFontAttributeName value:resolvedFont range:subrange]; + } + + // 2. Resolve Color + // Only apply if we have a color and the current segment doesn't explicitly forbid overrides + if (calculatedColor && ![RenderContext shouldPreserveColors:attrs]) { + // Optimization: Check if this color is already set to avoid redundant attribute changes + if (![attrs[NSForegroundColorAttributeName] isEqual:calculatedColor]) { + [output addAttribute:NSForegroundColorAttributeName + value:calculatedColor + range:subrange]; + } + } + }]; +} + +#pragma mark - Helper Methods + +- (UIFont *)ensureFontIsBold:(UIFont *)font +{ + if (!font) + return nil; + + UIFontDescriptor *descriptor = font.fontDescriptor; + UIFontDescriptorSymbolicTraits traits = descriptor.symbolicTraits; + + // Create new descriptor combining current traits with Bold + UIFontDescriptor *boldDescriptor = [descriptor fontDescriptorWithSymbolicTraits:(traits | UIFontDescriptorTraitBold)]; + + // Fallback to original font if bold version is unavailable + return boldDescriptor ? [UIFont fontWithDescriptor:boldDescriptor size:0] : font; +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.h new file mode 100644 index 000000000000..694590407ab1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface SubscriptRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.m new file mode 100644 index 000000000000..af72ec4940eb --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/SubscriptRenderer.m @@ -0,0 +1,25 @@ +#import "SubscriptRenderer.h" +#import "BaselineShiftTextAttributes.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation SubscriptRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + [output addAttribute:ENRMScriptAttributeName value:ENRMScriptValueSubscript range:range]; + ENRMApplyBaselineShift(output, range, _config.subscriptFontScale, -_config.subscriptBaselineOffsetScale); +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.h new file mode 100644 index 000000000000..d205fc17357b --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.h @@ -0,0 +1,5 @@ +#pragma once +#import "BaseRenderer.h" + +@interface SuperscriptRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.m new file mode 100644 index 000000000000..23d6293d7e15 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/SuperscriptRenderer.m @@ -0,0 +1,25 @@ +#import "SuperscriptRenderer.h" +#import "BaselineShiftTextAttributes.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation SuperscriptRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + [output addAttribute:ENRMScriptAttributeName value:ENRMScriptValueSuperscript range:range]; + ENRMApplyBaselineShift(output, range, _config.superscriptFontScale, _config.superscriptBaselineOffsetScale); +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.h new file mode 100644 index 000000000000..c4e3e924dce0 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.h @@ -0,0 +1,6 @@ +#import "BaseRenderer.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" + +@interface TextRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.m new file mode 100644 index 000000000000..cbd3cc725b24 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/TextRenderer.m @@ -0,0 +1,18 @@ +#import "TextRenderer.h" +#import "RenderContext.h" + +@implementation TextRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + if (!node.content) + return; + + NSAttributedString *text = [[NSAttributedString alloc] initWithString:node.content + attributes:[context getTextAttributes]]; + [output appendAttributedString:text]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.h new file mode 100644 index 000000000000..2ae80c7213a1 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.h @@ -0,0 +1,4 @@ +#import "BaseRenderer.h" + +@interface ThematicBreakRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.m new file mode 100644 index 000000000000..efaa0b364b31 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/ThematicBreakRenderer.m @@ -0,0 +1,42 @@ +#import "ThematicBreakRenderer.h" +#import "MarkdownASTNode.h" +#import "StyleConfig.h" +#import "ThematicBreakAttachment.h" + +#pragma mark - Renderer Implementation + +@implementation ThematicBreakRenderer + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + [self ensureStartingNewline:output]; + + ThematicBreakAttachment *attachment = [[ThematicBreakAttachment alloc] init]; + attachment.lineColor = _config.thematicBreakColor ?: [RCTUIColor separatorColor]; + attachment.lineHeight = _config.thematicBreakHeight > 0 ? _config.thematicBreakHeight : 1.0; + attachment.marginTop = _config.thematicBreakMarginTop; + attachment.marginBottom = _config.thematicBreakMarginBottom; + + NSDictionary *attributes = @{ + NSAttachmentAttributeName : attachment, + NSParagraphStyleAttributeName : [NSParagraphStyle defaultParagraphStyle] + }; + + NSAttributedString *breakString = [[NSAttributedString alloc] initWithString:@"\uFFFC" attributes:attributes]; + + [output appendAttributedString:breakString]; + [output appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]]; +} + +#pragma mark - Private Utilities + +- (void)ensureStartingNewline:(NSMutableAttributedString *)output +{ + if (output.length > 0 && ![output.string hasSuffix:@"\n"]) { + [output appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]]; + } +} + +@end \ No newline at end of file diff --git a/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.h b/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.h new file mode 100644 index 000000000000..a7a94ad8117e --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.h @@ -0,0 +1,4 @@ +#import "BaseRenderer.h" + +@interface UnderlineRenderer : BaseRenderer +@end diff --git a/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.m b/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.m new file mode 100644 index 000000000000..6a4c202510c0 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/renderer/UnderlineRenderer.m @@ -0,0 +1,41 @@ +#import "UnderlineRenderer.h" +#import "ENRMTextLinkAttributes.h" +#import "MarkdownASTNode.h" +#import "RenderContext.h" +#import "RendererFactory.h" +#import "StyleConfig.h" + +@implementation UnderlineRenderer + +#pragma mark - Rendering + +- (void)renderNodeContent:(MarkdownASTNode *)node + into:(NSMutableAttributedString *)output + context:(RenderContext *)context +{ + NSUInteger start = output.length; + [_rendererFactory renderChildrenOfNode:node into:output context:context]; + + NSRange range = NSMakeRange(start, output.length - start); + if (range.length == 0) + return; + + [output addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range]; + // Recognized links inside this span were styled before it closed; record the underline for them too. + [output enumerateAttribute:ENRMRecognizedLinkAttributeName + inRange:range + options:0 + usingBlock:^(id value, NSRange linkRange, BOOL *stop) { + if ([value boolValue]) { + [output addAttribute:ENRMRecognizedLinkOriginalUnderlineAttributeName + value:@(NSUnderlineStyleSingle) + range:linkRange]; + } + }]; + + RCTUIColor *underlineColor = [_config underlineColor]; + + [output addAttribute:NSUnderlineColorAttributeName value:underlineColor range:range]; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.h b/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.h new file mode 100644 index 000000000000..0604cd702bd4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.h @@ -0,0 +1,31 @@ +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +#ifdef __cplusplus +extern "C" { +#endif + +// GitHub admonition/alert header assets shared with Android and web. +// +// The `d` path strings live in ENRMAdmonitionIcons.m and are taken verbatim from +// @primer/octicons (16x16 viewBox); they MUST stay byte-identical across: +// - iOS: this file +// - Android: android/.../segments/AdmonitionIcons.kt +// - Web: src/web/renderers/admonitionIcons.ts +extern const CGFloat ENRMAdmonitionIconViewBox; + +// CGPath for the octicon of the given admonition type ("note", "tip", +// "important", "warning", "caution"), in the 16x16 icon space. NULL for unknown +// types. The returned path is cached and owned by the module; do not release. +CGPathRef _Nullable ENRMAdmonitionIconPath(NSString *type); + +// Capitalized header title for the type (e.g. "note" -> "Note"). +NSString *ENRMAdmonitionTitle(NSString *type); + +#ifdef __cplusplus +} +#endif + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.m b/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.m new file mode 100644 index 000000000000..65c817358f1c --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMAdmonitionIcons.m @@ -0,0 +1,93 @@ +#import "ENRMAdmonitionIcons.h" +#import "ENRMSVGPath.h" + +const CGFloat ENRMAdmonitionIconViewBox = 16.0; + +// note=info, tip=light-bulb, important=report, warning=alert, caution=stop. +// Keep byte-identical with AdmonitionIcons.kt / admonitionIcons.ts (the web file +// is the source of truth). Parity is enforced by +// __tests__/admonition-icons-parity.test.ts (jest, run in CI), which reads all +// three files and fails on any drift. That guard only works while all three +// copies live under packages/react-native-enriched-markdown/**; moving a copy +// out of this package requires re-homing the guard (or adding a native-side +// check) so the copies can't silently diverge. +static NSDictionary *ENRMAdmonitionIconPathData(void) +{ + static NSDictionary *data; + static dispatch_once_t once; + dispatch_once(&once, ^{ + data = @{ + @"note" : + @"M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.5 " + @"7.75A.75.75 0 0 1 7.25 7h1a.75.75 0 0 1 .75.75v2.75h.25a.75.75 0 0 1 0 1.5h-2a.75.75 0 0 1 " + @"0-1.5h.25v-2h-.25a.75.75 0 0 1-.75-.75ZM8 6a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z", + @"tip" : + @"M8 1.5c-2.363 0-4 1.69-4 3.75 0 .984.424 1.625.984 2.304l.214.253c.223.264.47.556.673.848.284." + @"411.537.896.621 1.49a.75.75 0 0 1-1.484.211c-.04-.282-.163-.547-.37-.847a8.456 8.456 0 0 " + @"0-.542-.68c-.084-.1-.173-.205-.268-.32C3.201 7.75 2.5 6.766 2.5 5.25 2.5 2.31 4.863 0 8 0s5.5 2.31 " + @"5.5 5.25c0 1.516-.701 2.5-1.328 3.259-.095.115-.184.22-.268.319-.207.245-.383.453-.541.681-.208.3-." + @"33.565-.37.847a.751.751 0 0 1-1.485-.212c.084-.593.337-1.078.621-1.489.203-.292.45-.584.673-.848." + @"075-.088.147-.173.213-.253.561-.679.985-1.32.985-2.304 0-2.06-1.637-3.75-4-3.75ZM5.75 12h4.5a.75.75 " + @"0 0 1 0 1.5h-4.5a.75.75 0 0 1 0-1.5ZM6 15.25a.75.75 0 0 1 .75-.75h2.5a.75.75 0 0 1 0 1.5h-2.5a.75.75 " + @"0 0 1-.75-.75Z", + @"important" : + @"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v9.5A1.75 1.75 0 0 1 14.25 " + @"13H8.06l-2.573 2.573A1.458 1.458 0 0 1 3 14.543V13H1.75A1.75 1.75 0 0 1 0 11.25Zm1.75-.25a.25." + @"25 0 0 0-.25.25v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 " + @".53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25Zm7 2.25v2.5a.75.75 0 0 1-1.5 " + @"0v-2.5a.75.75 0 0 1 1.5 0ZM9 9a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z", + @"warning" : + @"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 " + @"1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a." + @"25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 " + @"0 1 1 0 0 1 2 0Z", + @"caution" : + @"M4.47.22A.749.749 0 0 1 5 0h6c.199 0 .389.079.53.22l4.25 4.25c.141.14.22.331.22.53v6a.749.749 0 " + @"0 1-.22.53l-4.25 4.25A.749.749 0 0 1 11 16H5a.749.749 0 0 1-.53-.22L.22 11.53A.749.749 0 0 1 0 " + @"11V5c0-.199.079-.389.22-.53Zm.84 1.28L1.5 5.31v5.38l3.81 3.81h5.38l3.81-3.81V5.31L10.69 1.5ZM8 " + @"4a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 4Zm0 8a1 1 0 1 1 0-2 1 1 0 0 1 0 " + @"2Z", + }; + }); + return data; +} + +static NSDictionary *ENRMAdmonitionIconPaths(void) +{ + static NSDictionary *paths; + static dispatch_once_t once; + dispatch_once(&once, ^{ + NSDictionary *data = ENRMAdmonitionIconPathData(); + NSMutableDictionary *parsed = [NSMutableDictionary dictionaryWithCapacity:data.count]; + for (NSString *key in data) { + CGPathRef path = ENRMCreateCGPathFromSVGPath(data[key]); + if (path) { + parsed[key] = (__bridge_transfer id)path; + } + } + paths = parsed; + }); + return paths; +} + +CGPathRef ENRMAdmonitionIconPath(NSString *type) +{ + return (__bridge CGPathRef)ENRMAdmonitionIconPaths()[type]; +} + +NSString *ENRMAdmonitionTitle(NSString *type) +{ + static NSDictionary *titles; + static dispatch_once_t once; + dispatch_once(&once, ^{ + titles = @{ + @"note" : @"Note", + @"tip" : @"Tip", + @"important" : @"Important", + @"warning" : @"Warning", + @"caution" : @"Caution", + }; + }); + NSString *title = titles[type]; + return title ?: type.capitalizedString; +} diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.h new file mode 100644 index 000000000000..85b0c54f3865 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.h @@ -0,0 +1,91 @@ +#pragma once + +#import "ENRMCodeBlockContainerView.h" +#import "ENRMContainerNodeView.h" +#import "StyleConfig.h" + +@class MarkdownASTNode; +@class ENRMAccessibilityLabels; + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^ENRMBlockquoteLinkBlock)(NSString *url); + +/** + * A GFM blockquote rendered as a recursive container (issue #608): it splits its + * own AST children into segments and lays them out through the shared + * ENRMContainerNodeView machinery, so a nested quote becomes another + * ENRMBlockquoteContainerView, a fenced code block becomes an + * ENRMCodeBlockContainerView, and prose collapses into a single inner text view. + * Nesting depth is automatic: each level is its own view, inset further by its + * padding, so drawRect: only ever renders one accent bar plus the background for + * this single level. This mirrors Android's BlockquoteContainerView. + * + * The content inset is applied via contentInsets (left = borderWidth + gapWidth + * + padding, other edges = padding), reusing the geometry the commonmark + * BlockquoteBorder draws for the in-text (list-nested) path, which stays + * untouched. The base measure/layout already honor contentInsets. + * + * Streaming is static inside a quote (no pending fence, no animation); a content + * change re-signs the whole subtree so the outer reconciler still reuses the + * quote view. + */ +@interface ENRMBlockquoteContainerView : ENRMContainerNodeView + +- (instancetype)initWithConfig:(StyleConfig *)config; + +// Splits the node's children into segments and applies them to this container. +- (void)applyBlockquoteNode:(MarkdownASTNode *)node; + +// Laid-out height of this quote at the given outer width (the width the parent +// lays it out at, before this view's own inset). +- (CGFloat)measureHeight:(CGFloat)maxWidth; + +// View-free height for the shadow-node measurement pass: the same height an +// instance's measureHeight: reports for the node, without building a view. It +// sums the child segments at the reduced inner width and adds the vertical +// inset, recursing into itself for nested quotes. pointScaleFactor is the layout +// context's scale (the visible instance path uses RCTScreenScale), threaded so +// the per-text-segment pixel rounding matches the laid-out height. ++ (CGFloat)measureHeightForBlockquoteNode:(MarkdownASTNode *)node + config:(StyleConfig *)config + maxWidth:(CGFloat)maxWidth + pointScaleFactor:(CGFloat)pointScaleFactor + allowFontScaling:(BOOL)allowFontScaling + lineBreakStrategy:(NSLineBreakStrategy)lineBreakStrategy; + +// Consumer text props threaded into the quote's inner content so it honors them +// the same way the root document path does, instead of assuming defaults. Set by +// the host (root view or parent quote) at creation; propagated to nested quotes. +@property (nonatomic, assign) BOOL allowFontScaling; +@property (nonatomic, assign) NSLineBreakStrategy lineBreakStrategy; + +// YES when this quote is nested directly inside another quote. A nested quote +// carries no vertical margin (only the outermost quote does, applied by the root +// host), matching the commonmark path which applies blockquote margins only at +// depth 0. Set by the parent quote's child registry. +@property (nonatomic, assign) BOOL nested; + +// Bridged up to the JS onLinkPress/onLinkLongPress events; propagated to nested +// quotes so links at any depth fire. +@property (nonatomic, copy, nullable) void (^onLinkPress)(NSString *url, NSString *sourceType); +@property (nonatomic, copy, nullable) ENRMBlockquoteLinkBlock onLinkLongPress; +@property (nonatomic, copy, nullable) void (^onImagePress)(NSString *url, NSString *altText); + +@property (nonatomic, copy, nullable) ENRMCodeBlockCopyBlock onCopyPress; +@property (nonatomic, copy, nullable) ENRMCodeBlockPressBlock onCodeBlockPress; + +// Shared, runtime-mutable block props (context-menu gate, code-block tap gate, +// copy labels) read live at use-time. Set to the root's shared instance at +// creation and handed unchanged to this quote's children, so a child added after +// a toggle is born current with no per-toggle push. See ENRMDynamicBlockProps. +@property (nonatomic, strong) ENRMDynamicBlockProps *dynamicProps; + +// Resolved VoiceOver strings (list, quote, table and math announcements). Set by +// the host at creation and pushed to this quote's children, recursing into +// nested quotes, so they are labelled the same way top-level segments are. +@property (nonatomic, strong, nullable) ENRMAccessibilityLabels *accessibilityLabels; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.mm b/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.mm new file mode 100644 index 000000000000..96c7a7079181 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMBlockquoteContainerView.mm @@ -0,0 +1,606 @@ +#import "ENRMBlockquoteContainerView.h" +#import "ENRMAdmonitionIcons.h" +#import "ENRMCodeBlockContainerView.h" +#import "ENRMFeatureFlags.h" +#import "ENRMLinkContextMenus.h" +#import "ENRMSegmentHeightMeasurer.h" +#import "ENRMTableIOSGridView.h" +#import "ENRMTextInteractionUtils.h" +#import "ENRMTextRenderer.h" +#import "EnrichedMarkdownInternalText.h" +#import "LinkTapUtils.h" +#import "MarkdownASTNode.h" +#import "MarkdownASTSerializer.h" +#import "PasteboardUtils.h" +#import "SegmentRenderer.h" +#import "TableContainerView.h" +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathContainerView.h" +#endif +#if ENRICHED_MARKDOWN_VIDEO +#import "ENRMVideoContainerView.h" +#endif +#if TARGET_OS_OSX +#import "ENRMMenuAction.h" +#endif + +// Inner content is rendered with trailing margins disabled; the quote's own +// vertical inset provides the bottom gap, and per-segment margins between children +// still apply (allowTrailingMargin only gates the last child's bottom margin). The +// consumer's allowFontScaling / lineBreakStrategy are threaded through so the +// quote's content honors them the same way the root document path does. +static NSArray *ENRMRenderBlockquoteChildren(MarkdownASTNode *node, StyleConfig *config, + BOOL allowFontScaling, + NSLineBreakStrategy lineBreakStrategy) +{ + return ENRMRenderSegmentsFromAST(node, config, /*allowTrailingMargin*/ NO, allowFontScaling, + config.maxFontSizeMultiplier, lineBreakStrategy, /*blockquoteContent*/ YES); +} + +// The admonition type ("note"/"tip"/…) for a node, or nil for a plain quote. +static NSString *ENRMAdmonitionTypeForNode(MarkdownASTNode *node) +{ + if (node.type != MarkdownNodeTypeAdmonition) { + return nil; + } + NSString *type = node.attributes[@"admonitionType"]; + return type.length > 0 ? type : @"note"; +} + +static CGFloat ENRMAdmonitionIconSize(StyleConfig *config) +{ + return ceil(config.blockquoteFontSize); +} + +// Bold variant of the blockquote font for the header title, respecting the +// configured family where the platform supports trait derivation. +static UIFont *ENRMAdmonitionTitleFont(StyleConfig *config) +{ + UIFont *base = config.blockquoteFont; +#if !TARGET_OS_OSX + UIFontDescriptor *descriptor = [base.fontDescriptor + fontDescriptorWithSymbolicTraits:(base.fontDescriptor.symbolicTraits | UIFontDescriptorTraitBold)]; + UIFont *bold = descriptor ? [UIFont fontWithDescriptor:descriptor size:base.pointSize] : nil; + return bold ?: [UIFont boldSystemFontOfSize:base.pointSize]; +#else + NSFontDescriptor *descriptor = [base.fontDescriptor fontDescriptorWithSymbolicTraits:NSFontDescriptorTraitBold]; + NSFont *bold = descriptor ? [NSFont fontWithDescriptor:descriptor size:base.pointSize] : nil; + return bold ?: [NSFont boldSystemFontOfSize:base.pointSize]; +#endif +} + +// Height of the header band (icon + title row); body sits a gap below it. +static CGFloat ENRMAdmonitionHeaderContentHeight(StyleConfig *config) +{ + return ceil(MAX(ENRMAdmonitionIconSize(config), config.blockquoteFontSize * 1.35)); +} + +static CGFloat ENRMAdmonitionHeaderToBodyGap(StyleConfig *config) +{ + return round(config.blockquoteFontSize * 0.4); +} + +// Vertical space reserved above the body for the header (0 for a plain quote). +static CGFloat ENRMAdmonitionHeaderReservedHeight(StyleConfig *config, BOOL isAdmonition) +{ + if (!isAdmonition) { + return 0; + } + return ENRMAdmonitionHeaderContentHeight(config) + ENRMAdmonitionHeaderToBodyGap(config); +} + +static UIEdgeInsets ENRMBlockquoteContentInsetsForNode(StyleConfig *config, BOOL isAdmonition) +{ + CGFloat padding = config.blockquotePadding; + CGFloat left = ceil(config.blockquoteBorderWidth + config.blockquoteGapWidth + padding); + CGFloat top = ceil(padding + ENRMAdmonitionHeaderReservedHeight(config, isAdmonition)); + CGFloat vertical = ceil(padding); + CGFloat right = ceil(padding); + return UIEdgeInsetsMake(top, left, vertical, right); +} + +static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config) +{ + return ENRMBlockquoteContentInsetsForNode(config, NO); +} + +@interface ENRMBlockquoteContainerView () +#if !TARGET_OS_OSX + +#endif +// nil for a plain blockquote; the admonition type string otherwise. +@property (nonatomic, copy, nullable) NSString *admonitionType; +@property (nonatomic, copy) NSString *cachedMarkdown; +@property (nonatomic, copy) NSString *cachedPlainText; +@end + +#if !TARGET_OS_OSX +@interface ENRMBlockquoteContainerView () +@end +#endif + +@implementation ENRMBlockquoteContainerView + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super initWithFrame:CGRectZero]; + if (self) { + self.config = config; + self.contentInsets = ENRMBlockquoteContentInsets(config); + self.allowTrailingMargin = NO; + // Preserved prior defaults until the host overrides them at creation. + _allowFontScaling = YES; + _lineBreakStrategy = NSLineBreakStrategyNone; + _dynamicProps = [[ENRMDynamicBlockProps alloc] init]; + _cachedMarkdown = @""; + _cachedPlainText = @""; +#if !TARGET_OS_OSX + self.contentMode = UIViewContentModeRedraw; + UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self]; + [self addInteraction:contextMenu]; +#endif + self.segmentViewRegistry = [self buildChildRegistry]; + } + return self; +} + +- (void)applyBlockquoteNode:(MarkdownASTNode *)node +{ + self.admonitionType = ENRMAdmonitionTypeForNode(node); + self.contentInsets = ENRMBlockquoteContentInsetsForNode(self.config, self.admonitionType != nil); + self.cachedMarkdown = markdownFromBlockquoteNode(node); + self.cachedPlainText = plainTextFromASTNode(node); + NSArray *rendered = + ENRMRenderBlockquoteChildren(node, self.config, self.allowFontScaling, self.lineBreakStrategy); + [self applySegments:rendered reset:NO]; +#if !TARGET_OS_OSX + [self setNeedsDisplay]; +#else + self.needsDisplay = YES; +#endif +} + +- (void)setAccessibilityLabels:(ENRMAccessibilityLabels *)accessibilityLabels +{ + if (_accessibilityLabels == accessibilityLabels) { + return; + } + _accessibilityLabels = accessibilityLabels; + // Children created before this point (or before a labels prop change) still + // hold the previous labels; nested quotes forward them to their own children. + for (RCTUIView *child in self.subviews) { + if ([child isKindOfClass:[EnrichedMarkdownInternalText class]]) { + ((EnrichedMarkdownInternalText *)child).accessibilityLabels = accessibilityLabels; + } else if ([child isKindOfClass:[TableContainerView class]]) { + ((TableContainerView *)child).accessibilityLabels = accessibilityLabels; + } else if ([child isKindOfClass:[ENRMBlockquoteContainerView class]]) { + ((ENRMBlockquoteContainerView *)child).accessibilityLabels = accessibilityLabels; + } +#if ENRICHED_MARKDOWN_MATH + else if ([child isKindOfClass:[ENRMMathContainerView class]]) { + ((ENRMMathContainerView *)child).accessibilityLabels = accessibilityLabels; + } +#endif + } +} + +// Child registry for this quote's own content. It reuses static creators for +// every kind and, for a nested Blockquote, creates another +// ENRMBlockquoteContainerView (the recursion). Streaming is static: no +// animation, no pending-fence sync. +- (ENRMSegmentViewRegistry *)buildChildRegistry +{ + StyleConfig *config = self.config; + __weak ENRMBlockquoteContainerView *weakSelf = self; + NSMutableArray *handlers = [NSMutableArray array]; + + [handlers + addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindText + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[EnrichedMarkdownInternalText class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + ENRMBlockquoteContainerView *strongSelf = weakSelf; + EnrichedMarkdownInternalText *view = [[EnrichedMarkdownInternalText alloc] initWithConfig:config]; + view.lastElementMarginBottom = segment.textResult.lastElementMarginBottom; + view.accessibilityInfo = segment.textResult.accessibilityInfo; + view.accessibilityLabels = strongSelf.accessibilityLabels; + [view applyAttributedText:segment.textResult.attributedText context:segment.textResult.context]; + if (strongSelf) { + [strongSelf attachLinkTapToTextView:view]; + } + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + EnrichedMarkdownInternalText *textView = (EnrichedMarkdownInternalText *)view; + textView.lastElementMarginBottom = segment.textResult.lastElementMarginBottom; + textView.accessibilityInfo = segment.textResult.accessibilityInfo; + [textView applyAttributedText:segment.textResult.attributedText + context:segment.textResult.context]; + }]]; + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindTable + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[TableContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + TableContainerView *view = [[TableContainerView alloc] initWithConfig:config]; + ENRMBlockquoteContainerView *strongSelf = weakSelf; + if (strongSelf) { + view.dynamicProps = strongSelf.dynamicProps; + view.accessibilityLabels = strongSelf.accessibilityLabels; + view.onLinkPress = ^(NSString *url, NSString *sourceType) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onLinkPress && url) + s.onLinkPress(url, sourceType); + }; + view.onLinkLongPress = ^(NSString *url) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onLinkLongPress && url) + s.onLinkLongPress(url); + }; + view.onImagePress = ^(NSString *url, NSString *altText) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onImagePress && url) + s.onImagePress(url, altText); + }; + } + [view applyTableNode:segment.tableSegment.tableNode]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(TableContainerView *)view applyTableNode:segment.tableSegment.tableNode]; + }]]; + + [handlers + addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindCodeBlock + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMCodeBlockContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + ENRMCodeBlockContainerView *view = [[ENRMCodeBlockContainerView alloc] initWithConfig:config]; + ENRMBlockquoteContainerView *strongSelf = weakSelf; + view.dynamicProps = strongSelf.dynamicProps; + view.onCopyPress = ^(NSString *code, NSString *language) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onCopyPress) + s.onCopyPress(code, language); + }; + view.onCodeBlockPress = ^(NSString *code, NSString *language) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onCodeBlockPress) + s.onCodeBlockPress(code, language); + }; + [view applyCodeBlockNode:segment.codeBlockSegment.codeBlockNode]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMCodeBlockContainerView *)view applyCodeBlockNode:segment.codeBlockSegment.codeBlockNode]; + }]]; + + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindBlockquote + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMBlockquoteContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + ENRMBlockquoteContainerView *view = + [[ENRMBlockquoteContainerView alloc] initWithConfig:config]; + view.nested = YES; + ENRMBlockquoteContainerView *strongSelf = weakSelf; + if (strongSelf) { + view.allowFontScaling = strongSelf.allowFontScaling; + view.lineBreakStrategy = strongSelf.lineBreakStrategy; + view.dynamicProps = strongSelf.dynamicProps; + view.accessibilityLabels = strongSelf.accessibilityLabels; + view.onCopyPress = strongSelf.onCopyPress; + view.onCodeBlockPress = strongSelf.onCodeBlockPress; + view.onImagePress = ^(NSString *url, NSString *altText) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onImagePress && url) + s.onImagePress(url, altText); + }; + view.onLinkPress = ^(NSString *url, NSString *sourceType) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onLinkPress && url) + s.onLinkPress(url, sourceType); + }; + view.onLinkLongPress = ^(NSString *url) { + ENRMBlockquoteContainerView *s = weakSelf; + if (s.onLinkLongPress && url) + s.onLinkLongPress(url); + }; + } + [view applyBlockquoteNode:segment.blockquoteSegment.blockquoteNode]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMBlockquoteContainerView *)view + applyBlockquoteNode:segment.blockquoteSegment.blockquoteNode]; + }]]; + +#if ENRICHED_MARKDOWN_MATH +#if !TARGET_OS_OSX + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindMath + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMMathContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + ENRMMathContainerView *view = [[ENRMMathContainerView alloc] initWithConfig:config]; + ENRMBlockquoteContainerView *strongSelf = weakSelf; + view.dynamicProps = strongSelf.dynamicProps; + view.accessibilityLabels = strongSelf.accessibilityLabels; + [view applyLatex:segment.mathSegment.latex]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMMathContainerView *)view applyLatex:segment.mathSegment.latex]; + }]]; +#endif +#endif + +#if ENRICHED_MARKDOWN_VIDEO + __weak ENRMBlockquoteContainerView *weakBQ = self; + [handlers addObject:[ENRMSegmentViewHandler handlerWithKind:ENRMSegmentKindVideo + matchesView:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [view isKindOfClass:[ENRMVideoContainerView class]]; + } + createView:^RCTUIView *(ENRMRenderedSegment *segment) { + ENRMVideoContainerView *view = [[ENRMVideoContainerView alloc] initWithConfig:config]; + ENRMBlockquoteContainerView *bq = weakBQ; + if (bq) { + view.dynamicProps = bq.dynamicProps; + } + [view applyVideoNode:segment.videoSegment.videoNode]; + return view; + } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { + [(ENRMVideoContainerView *)view applyVideoNode:segment.videoSegment.videoNode]; + }]]; +#endif + + return [[ENRMSegmentViewRegistry alloc] initWithHandlers:handlers]; +} + +- (void)attachLinkTapToTextView:(EnrichedMarkdownInternalText *)view +{ + ENRMTapRecognizer *tap = [[ENRMTapRecognizer alloc] initWithTarget:self action:@selector(handleTextTap:)]; + [view.textView addGestureRecognizer:tap]; +#if !TARGET_OS_OSX + view.textView.delegate = self; +#endif +} + +- (void)handleTextTap:(ENRMTapRecognizer *)recognizer +{ + ENRMPlatformTextView *textView = (ENRMPlatformTextView *)recognizer.view; + __weak ENRMBlockquoteContainerView *weakSelf = self; + if (ENRMHandleTapOnTextView(textView, recognizer, ^(NSString *url, NSString *sourceType) { + ENRMBlockquoteContainerView *strongSelf = weakSelf; + if (strongSelf.onLinkPress && url) + strongSelf.onLinkPress(url, sourceType); + })) { + return; + } + + if (self.onImagePress) { + NSDictionary *image = imageAtTapLocation(textView, recognizer); + if (image) + self.onImagePress(image[@"url"], image[@"altText"]); + } +} + +- (CGFloat)measureHeight:(CGFloat)maxWidth +{ + return [self computeContentHeightForWidth:MAX(maxWidth - self.contentInsets.left - self.contentInsets.right, 0)]; +} + ++ (CGFloat)measureHeightForBlockquoteNode:(MarkdownASTNode *)node + config:(StyleConfig *)config + maxWidth:(CGFloat)maxWidth + pointScaleFactor:(CGFloat)pointScaleFactor + allowFontScaling:(BOOL)allowFontScaling + lineBreakStrategy:(NSLineBreakStrategy)lineBreakStrategy +{ + UIEdgeInsets insets = ENRMBlockquoteContentInsetsForNode(config, ENRMAdmonitionTypeForNode(node) != nil); + CGFloat innerWidth = MAX(maxWidth - insets.left - insets.right, 1); + + NSArray *rendered = + ENRMRenderBlockquoteChildren(node, config, allowFontScaling, lineBreakStrategy); + CGFloat childrenHeight = ENRMMeasureSegmentsHeightViewFree( + rendered, config, innerWidth, /*allowTrailingMargin*/ NO, pointScaleFactor, ENRMWritingDirectionModeFirstStrong, + NSWritingDirectionNatural, allowFontScaling, lineBreakStrategy); + + return childrenHeight + insets.top + insets.bottom; +} + +- (void)drawRect:(CGRect)rect +{ + StyleConfig *config = self.config; + CGFloat borderWidth = config.blockquoteBorderWidth; + CGFloat radius = config.blockquoteBorderRadius; + CGRect bounds = self.bounds; + + // The rounded (or plain) box outline, shared by the background fill and the accent + // bar's clip so the bar's left corners follow the border radius. +#if !TARGET_OS_OSX + UIBezierPath *boxPath = radius > 0 ? [UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:radius] + : [UIBezierPath bezierPathWithRect:bounds]; +#else + NSBezierPath *boxPath = radius > 0 ? [NSBezierPath bezierPathWithRoundedRect:bounds xRadius:radius yRadius:radius] + : [NSBezierPath bezierPathWithRect:bounds]; +#endif + + // Admonitions theme the box with their per-type color; a plain quote keeps the + // base blockquote colors. + NSString *admonitionType = self.admonitionType; + RCTUIColor *backgroundColor = + admonitionType ? [config admonitionBackgroundColorForType:admonitionType] : config.blockquoteBackgroundColor; + if (backgroundColor && backgroundColor != [RCTUIColor clearColor]) { + [backgroundColor setFill]; + [boxPath fill]; + } + + if (borderWidth > 0) { + RCTUIColor *borderColor = + admonitionType ? [config admonitionColorForType:admonitionType] : config.blockquoteBorderColor; + if (borderColor) { + CGRect barRect = CGRectMake(0, 0, borderWidth, bounds.size.height); + [borderColor setFill]; +#if !TARGET_OS_OSX + CGContextRef ctx = UIGraphicsGetCurrentContext(); + CGContextSaveGState(ctx); + [boxPath addClip]; + [[UIBezierPath bezierPathWithRect:barRect] fill]; + CGContextRestoreGState(ctx); +#else + [NSGraphicsContext saveGraphicsState]; + [boxPath addClip]; + [[NSBezierPath bezierPathWithRect:barRect] fill]; + [NSGraphicsContext restoreGraphicsState]; +#endif + } + } + + if (admonitionType) { + [self drawAdmonitionHeaderForType:admonitionType config:config]; + } +} + +// Draws the admonition header (tinted octicon + capitalized title) in the band +// reserved at the top by the enlarged content inset. The view is flipped on +// macOS, so the y-down icon path and text draw identically on both platforms. +- (void)drawAdmonitionHeaderForType:(NSString *)type config:(StyleConfig *)config +{ + RCTUIColor *tint = [config admonitionColorForType:type]; + CGFloat padding = config.blockquotePadding; + CGFloat leftInset = ceil(config.blockquoteBorderWidth + config.blockquoteGapWidth + padding); + CGFloat iconSize = ENRMAdmonitionIconSize(config); + CGFloat headerHeight = ENRMAdmonitionHeaderContentHeight(config); + CGFloat headerTop = ceil(padding); + CGFloat titleX = leftInset; + + CGPathRef iconPath = ENRMAdmonitionIconPath(type); + if (iconPath) { +#if !TARGET_OS_OSX + CGContextRef ctx = UIGraphicsGetCurrentContext(); +#else + CGContextRef ctx = [[NSGraphicsContext currentContext] CGContext]; +#endif + if (ctx) { + CGFloat scale = iconSize / ENRMAdmonitionIconViewBox; + CGFloat iconY = headerTop + (headerHeight - iconSize) / 2.0; + CGContextSaveGState(ctx); + CGContextTranslateCTM(ctx, leftInset, iconY); + CGContextScaleCTM(ctx, scale, scale); + CGContextAddPath(ctx, iconPath); + [tint setFill]; + CGContextFillPath(ctx); + CGContextRestoreGState(ctx); + } + titleX = leftInset + iconSize + round(iconSize * 0.4); + } + + NSString *title = ENRMAdmonitionTitle(type); + UIFont *titleFont = ENRMAdmonitionTitleFont(config); + NSDictionary *attributes = + @{NSFontAttributeName : titleFont, NSForegroundColorAttributeName : tint}; + NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:title attributes:attributes]; + CGSize titleSize = [attributed size]; + CGFloat titleY = headerTop + (headerHeight - titleSize.height) / 2.0; + [attributed drawAtPoint:CGPointMake(titleX, titleY)]; +} + +#pragma mark - Context menu + +- (void)copyMarkdownToPasteboard +{ + if (_cachedMarkdown.length > 0) { + copyStringToPasteboard(_cachedMarkdown); + } +} + +- (void)copyPlainTextToPasteboard +{ + if (_cachedPlainText.length > 0) { + NSMutableDictionary *items = [NSMutableDictionary dictionary]; + items[kUTIPlainText] = _cachedPlainText; + if (_cachedMarkdown.length > 0) { + items[kUTIMarkdown] = _cachedMarkdown; + } + copyItemsToPasteboard(items); + } +} + +#if !TARGET_OS_OSX +- (UITextItemMenuConfiguration *)textView:(UITextView *)textView + menuConfigurationForTextItem:(UITextItem *)textItem + defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0)) +{ + return ENRMLinkMenuConfigurationForTextItem(textView, textItem, defaultMenu, self.dynamicProps.linkContextMenus, + self.dynamicProps.enableLinkPreview, self.onLinkLongPress); +} + +- (ENRMLinkContextMenus *)linkContextMenusForTextView:(UITextView *)textView +{ + return self.dynamicProps.linkContextMenus; +} + +- (UIContextMenuConfiguration *)contextMenuInteraction:(UIContextMenuInteraction *)interaction + configurationForMenuAtLocation:(CGPoint)location +{ + // Let the leaf interaction present a configured link menu, including nested tables. + UIView *hit = [interaction.view hitTest:location withEvent:nil]; + while (hit && hit != interaction.view) { + CGPoint point = [interaction.view convertPoint:location toView:hit]; + NSString *url = nil; + if ([hit isKindOfClass:[UITextView class]]) + url = linkURLAtPoint((UITextView *)hit, point); + else if ([hit isKindOfClass:[ENRMTableIOSGridView class]]) + url = [(ENRMTableIOSGridView *)hit linkAtPoint:point].url; + if ([self.dynamicProps.linkContextMenus hasMenuForURL:url]) + return nil; + hit = hit.superview; + } + if (!self.dynamicProps.enableBlockContextMenu) { + return nil; + } + return [UIContextMenuConfiguration + configurationWithIdentifier:nil + previewProvider:nil + actionProvider:^UIMenu *(NSArray *suggestedActions) { + UIAction *copyPlainText = + [UIAction actionWithTitle:self.dynamicProps.menuCopyLabel + image:[RCTUIImage systemImageNamed:@"doc.on.doc"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyPlainTextToPasteboard]; }]; + + UIAction *copyMarkdown = + [UIAction actionWithTitle:self.dynamicProps.menuCopyAsMarkdownLabel + image:[RCTUIImage systemImageNamed:@"doc.text"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyMarkdownToPasteboard]; }]; + + return [UIMenu menuWithTitle:@"" children:@[ copyPlainText, copyMarkdown ]]; + }]; +} +#endif // !TARGET_OS_OSX + +#if TARGET_OS_OSX +- (BOOL)isFlipped +{ + return YES; +} + +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + if (!self.dynamicProps.enableBlockContextMenu) { + return [super menuForEvent:event]; + } + NSMenu *menu = [[NSMenu alloc] initWithTitle:@""]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyLabel, ^{ [self copyPlainTextToPasteboard]; })]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyAsMarkdownLabel, ^{ [self copyMarkdownToPasteboard]; })]; + return menu; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.h new file mode 100644 index 000000000000..e17d3dfb98e7 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.h @@ -0,0 +1,46 @@ +#pragma once +#import "ENRMDynamicBlockProps.h" +#import "ENRMUIKit.h" +#import "StyleConfig.h" + +@class MarkdownASTNode; + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^ENRMCodeBlockCopyBlock)(NSString *code, NSString *language); +typedef void (^ENRMCodeBlockPressBlock)(NSString *code, NSString *language); + +@interface ENRMCodeBlockContainerView : RCTUIView + +- (instancetype)initWithConfig:(StyleConfig *)config; + +- (void)applyCodeBlockNode:(MarkdownASTNode *)node; + +- (CGFloat)measureHeight:(CGFloat)maxWidth; + +// View-free height for the shadow-node measurement pass: the same height an +// instance's measureHeight: reports for the node, without building a view. ++ (CGFloat)measureHeightForCodeBlockNode:(MarkdownASTNode *)node config:(StyleConfig *)config; + +@property (nonatomic, strong) StyleConfig *config; + +// True until the closing fence arrives: highlighting is deferred and copying is +// disabled, while the header stays visible. +@property (nonatomic, assign) BOOL pending; + +// Shared, runtime-mutable block props (context-menu gate, tap gate, copy labels) +// read live at use-time. Set to the root's shared instance at creation so a code +// block added after a toggle is born current. See ENRMDynamicBlockProps. +@property (nonatomic, strong) ENRMDynamicBlockProps *dynamicProps; + +// Fired when the code is copied (header button, context-menu Copy, or the +// VoiceOver copy action); set by the host to bridge up to the JS onCopyPress +// event. Not fired for "Copy as Markdown". +@property (nonatomic, copy, nullable) ENRMCodeBlockCopyBlock onCopyPress; + +// Bridges a whole-block tap (not the copy button) up to the JS onCodeBlockPress event. +@property (nonatomic, copy, nullable) ENRMCodeBlockPressBlock onCodeBlockPress; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.m b/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.m new file mode 100644 index 000000000000..53029a745c9f --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMCodeBlockContainerView.m @@ -0,0 +1,667 @@ +#import "ENRMCodeBlockContainerView.h" +#import "ENRMCodeBlockContent.h" +#import "ENRMCodeBlockHighlighter.h" +#import "ENRMHorizontalScrollView.h" +#import "MarkdownASTNode.h" +#import "PasteboardUtils.h" +#if TARGET_OS_OSX +#import "ENRMMenuAction.h" +#endif + +// Block segment view for fenced code blocks (see SegmentRenderer.m): +// a fixed header bar (language name, copy button) above a horizontally +// scrolling, non-wrapping code pane. The container's drawRect: draws +// background, border, label, and divider; only the copy button and the +// scroll view are subviews. Syntax coloring comes from the +// ENRMCodeBlockHighlighter seam and falls back to plain text. The box +// visuals must stay in sync with the commonmark flavor's CodeBlockBackground. +// +// measureHeight: must stay in sync with the drawn content: it uses the +// unconstrained bounding rect of the same attributed string and the same +// header metrics, so the reported height matches the drawn height. Since +// lines never wrap, the height is independent of the available width. + +static const CGFloat kENRMHeaderLabelScale = 0.85; +// The copy glyph reads cleaner a touch smaller than the language label and at a +// regular (not medium) weight; sized independently so the two never couple. +static const CGFloat kENRMHeaderIconScale = 0.72; +static const CGFloat kENRMHeaderSecondaryAlpha = 0.6; +static const CGFloat kENRMHeaderDividerAlpha = 0.2; + +// Height geometry and code-run construction shared by the instance layout path +// and the view-free measureHeightForCodeBlockNode:, so the two cannot drift. + +static CGFloat ENRMCodeBlockContentInset(StyleConfig *config) +{ + return [config codeBlockPadding] + [config codeBlockBorderWidth]; +} + +#if !TARGET_OS_OSX +static UIFont *ENRMCodeBlockHeaderFont(StyleConfig *config) +{ + return [UIFont systemFontOfSize:[config codeBlockFont].pointSize * kENRMHeaderLabelScale weight:UIFontWeightMedium]; +} + +static CGFloat ENRMCodeBlockHeaderLabelLineHeight(UIFont *headerFont) +{ + return ceil(UIFontLineHeight(headerFont)); +} +#else +static NSFont *ENRMCodeBlockHeaderFont(StyleConfig *config) +{ + return [NSFont systemFontOfSize:[config codeBlockFont].pointSize * kENRMHeaderLabelScale weight:NSFontWeightMedium]; +} + +static CGFloat ENRMCodeBlockHeaderLabelLineHeight(NSFont *headerFont) +{ + return ceil(UIFontLineHeight(headerFont)); +} +#endif + +static NSAttributedString *ENRMCodeBlockPlainAttributedCode(NSString *code, StyleConfig *config) +{ + if (code.length == 0) { + return [[NSAttributedString alloc] initWithString:@""]; + } + NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:code]; + ENRMApplyCodeBlockTextAttributes(attributed, NSMakeRange(0, attributed.length), config); + return attributed; +} + +// Per-line height applied to the code text (see ENRMApplyCodeBlockTextAttributes): +// when a code block line height is configured every line fragment is exactly that +// tall; otherwise the font's natural line height is used. +static CGFloat ENRMCodeBlockPerLineHeight(StyleConfig *config) +{ + CGFloat lineHeight = [config codeBlockLineHeight]; + return lineHeight > 0 ? lineHeight : ceil(UIFontLineHeight([config codeBlockFont])); +} + +// Analytic code height: lines never wrap and each fragment is a fixed height, so +// the laid-out height is simply lineCount * perLineHeight. No text layout needed, +// which is what boundingRectWithSize used to do on the whole block. +static CGFloat ENRMCodeBlockCodeHeight(NSString *code, StyleConfig *config) +{ + if (code.length == 0) { + return 0; + } + __block NSUInteger lineCount = 0; + [code enumerateSubstringsInRange:NSMakeRange(0, code.length) + options:NSStringEnumerationByLines | NSStringEnumerationSubstringNotRequired + usingBlock:^(NSString *_Nullable substring, NSRange substringRange, NSRange enclosingRange, + BOOL *stop) { lineCount++; }]; + if (lineCount == 0) { + lineCount = 1; + } + return ceil(lineCount * ENRMCodeBlockPerLineHeight(config)); +} + +// Used only to pick the scroll indicator style for the code pane, so the +// indicator stays visible on dark code block backgrounds without affecting +// any other scroll view. +static BOOL ENRMColorIsDark(RCTUIColor *color) +{ + if (!color) { + return NO; + } + CGFloat r = 0, g = 0, b = 0, a = 0; +#if !TARGET_OS_OSX + if (![color getRed:&r green:&g blue:&b alpha:&a]) { + CGFloat white = 0; + if (![color getWhite:&white alpha:&a]) { + return NO; + } + r = g = b = white; + } +#else + NSColor *rgb = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + if (!rgb) { + return NO; + } + [rgb getRed:&r green:&g blue:&b alpha:&a]; +#endif + return (0.299 * r + 0.587 * g + 0.114 * b) < 0.5; +} + +// Scrollable code pane content. Draws the attributed code unwrapped at a +// fixed origin; the hosting ENRMCodeBlockContainerView draws everything else. +// +// The TextKit stack (storage/layout manager/container) is built and laid out +// once, when attributedCode is set, then cached: drawRect: only paints the +// already-computed glyphs, so scrolling and redraws never re-lay-out. This is +// the same rendering path drawAtPoint used internally, so output is identical, +// but the layout is no longer thrown away on every draw. The container is +// unbounded (lines never wrap) with zero line-fragment padding and font leading +// disabled, matching the NSStringDrawing origin the block used before. +@interface ENRMCodeBlockContentView : RCTUIView +@property (nonatomic, strong, nullable) NSAttributedString *attributedCode; +@property (nonatomic, assign) CGPoint textOrigin; +// Laid-out content width, for the horizontal scroll extent. Free once the +// cached stack exists; no separate measurement pass. +@property (nonatomic, readonly) CGFloat usedWidth; +#if TARGET_OS_OSX +@property (nonatomic, copy, nullable) NSMenu * (^menuProvider)(void); +#endif +@end + +@implementation ENRMCodeBlockContentView { + NSTextStorage *_textStorage; + NSLayoutManager *_layoutManager; + NSTextContainer *_textContainer; +} + +#if TARGET_OS_OSX +- (BOOL)isFlipped +{ + return YES; +} + +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + return self.menuProvider ? self.menuProvider() : [super menuForEvent:event]; +} +#endif + +- (void)setAttributedCode:(nullable NSAttributedString *)attributedCode +{ + _attributedCode = attributedCode; + if (attributedCode.length == 0) { + _textStorage = nil; + _layoutManager = nil; + _textContainer = nil; + return; + } + _textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedCode]; + _layoutManager = [[NSLayoutManager alloc] init]; + _layoutManager.usesFontLeading = ENRMLayoutManagerUsesFontLeading; + _textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)]; + _textContainer.lineFragmentPadding = 0; + _textContainer.maximumNumberOfLines = 0; + [_layoutManager addTextContainer:_textContainer]; + [_textStorage addLayoutManager:_layoutManager]; + [_layoutManager ensureLayoutForTextContainer:_textContainer]; +} + +- (CGFloat)usedWidth +{ + if (!_layoutManager) { + return 0; + } + return ceil([_layoutManager usedRectForTextContainer:_textContainer].size.width); +} + +- (void)drawRect:(CGRect)rect +{ + if (!_layoutManager) { + return; + } + // Only paint the glyphs intersecting the dirty rect; tall blocks skip their + // off-screen lines. The rect is in view space, the layout in container space. + CGRect boundingRect = CGRectOffset(rect, -self.textOrigin.x, -self.textOrigin.y); + NSRange glyphRange = [_layoutManager glyphRangeForBoundingRect:boundingRect inTextContainer:_textContainer]; + [_layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:self.textOrigin]; +} + +@end + +#if !TARGET_OS_OSX +@interface ENRMCodeBlockContainerView () +@end +#endif + +@implementation ENRMCodeBlockContainerView { + NSAttributedString *_attributedCode; + NSString *_cachedCode; + NSString *_cachedLanguage; + NSString *_displayLanguage; + NSString *_fenceChar; + ENRMHorizontalScrollView *_scrollView; + ENRMCodeBlockContentView *_codeContentView; + CGSize _codeSize; + CGFloat _headerLabelLineHeight; + NSAttributedString *_languageLabel; + CGSize _languageLabelSize; +#if !TARGET_OS_OSX + UIFont *_headerFont; + UIButton *_copyButton; + UITapGestureRecognizer *_tapRecognizer; +#else + NSFont *_headerFont; + NSButton *_copyButton; +#endif +} + +- (void)setPending:(BOOL)pending +{ + if (_pending == pending) { + return; + } + _pending = pending; + // Header stays visible while streaming; only copying is held back. + _copyButton.enabled = !pending; + // The reconciler can reuse an unchanged block without re-applying the node, so + // re-derive here to pick up highlighting once the block closes. + [self rebuildAttributedCode]; +#if !TARGET_OS_OSX + [self setNeedsLayout]; + [self setNeedsDisplay]; + [_codeContentView setNeedsDisplay]; +#else + self.needsLayout = YES; + [self setNeedsDisplay:YES]; + [_codeContentView setNeedsDisplay:YES]; +#endif +} + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super initWithFrame:CGRectZero]; + if (self) { + _config = config; + _cachedCode = @""; + _fenceChar = @"`"; + _dynamicProps = [[ENRMDynamicBlockProps alloc] init]; + _headerFont = ENRMCodeBlockHeaderFont(config); + _headerLabelLineHeight = ENRMCodeBlockHeaderLabelLineHeight(_headerFont); + self.backgroundColor = [RCTUIColor clearColor]; + [self setupScrollView]; + +#if !TARGET_OS_OSX + self.contentMode = UIViewContentModeRedraw; + self.isAccessibilityElement = YES; + + UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self]; + [self addInteraction:contextMenu]; + + _copyButton = [UIButton buttonWithType:UIButtonTypeSystem]; + UIImageSymbolConfiguration *symbolConfig = + [UIImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale + weight:UIImageSymbolWeightRegular]; + [_copyButton setImage:[UIImage systemImageNamed:@"doc.on.doc" withConfiguration:symbolConfig] + forState:UIControlStateNormal]; + _copyButton.tintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha]; + [_copyButton addTarget:self action:@selector(copyCodeToPasteboard) forControlEvents:UIControlEventTouchUpInside]; + [self addSubview:_copyButton]; + + _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCodeBlockTap:)]; + _tapRecognizer.delegate = self; + [self addGestureRecognizer:_tapRecognizer]; +#else + NSImageSymbolConfiguration *symbolConfig = + [NSImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale + weight:NSFontWeightRegular]; + NSImage *copyImage = [[NSImage imageWithSystemSymbolName:@"doc.on.doc" + accessibilityDescription:nil] imageWithSymbolConfiguration:symbolConfig]; + _copyButton = [NSButton buttonWithImage:copyImage target:self action:@selector(copyCodeToPasteboard)]; + _copyButton.bordered = NO; + _copyButton.contentTintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha]; + [self addSubview:_copyButton]; +#endif + } + return self; +} + +- (void)setupScrollView +{ + _scrollView = [[ENRMHorizontalScrollView alloc] init]; + _scrollView.showsVerticalScrollIndicator = NO; + _scrollView.showsHorizontalScrollIndicator = YES; + _codeContentView = [[ENRMCodeBlockContentView alloc] initWithFrame:CGRectZero]; + BOOL darkBackground = ENRMColorIsDark([_config codeBlockBackgroundColor]); +#if !TARGET_OS_OSX + _scrollView.alwaysBounceHorizontal = NO; + _scrollView.backgroundColor = [UIColor clearColor]; + _scrollView.isAccessibilityElement = NO; + _scrollView.accessibilityElementsHidden = YES; + _scrollView.indicatorStyle = darkBackground ? UIScrollViewIndicatorStyleWhite : UIScrollViewIndicatorStyleDefault; + _codeContentView.backgroundColor = [UIColor clearColor]; + _codeContentView.contentMode = UIViewContentModeRedraw; + [_scrollView addSubview:_codeContentView]; + [_codeContentView addInteraction:[[UIContextMenuInteraction alloc] initWithDelegate:self]]; +#else + ((NSScrollView *)_scrollView).drawsBackground = NO; + ((NSScrollView *)_scrollView).scrollerKnobStyle = + darkBackground ? NSScrollerKnobStyleLight : NSScrollerKnobStyleDefault; + __weak ENRMCodeBlockContainerView *weakSelf = self; + NSMenu * (^menuProvider)(void) = ^{ return [weakSelf buildContextMenu]; }; + _codeContentView.menuProvider = menuProvider; + [(NSScrollView *)_scrollView setDocumentView:_codeContentView]; +#endif + [self addSubview:_scrollView]; +} + +- (void)layoutScrollArea +{ + CGFloat borderW = ceil([_config codeBlockBorderWidth]); + CGFloat headerH = [self headerHeight]; + CGFloat inset = [self contentInset]; + CGRect frame = CGRectMake(borderW, headerH, MAX(self.bounds.size.width - borderW * 2, 0), + MAX(self.bounds.size.height - headerH - borderW, 0)); + _scrollView.frame = frame; + + CGFloat horizontalPad = MAX(inset - borderW, 0); + CGFloat contentWidth = MAX(_codeSize.width + horizontalPad * 2, frame.size.width); + _codeContentView.textOrigin = CGPointMake(horizontalPad, inset); + _codeContentView.frame = CGRectMake(0, 0, contentWidth, frame.size.height); +#if !TARGET_OS_OSX + _scrollView.contentSize = CGSizeMake(contentWidth, frame.size.height); + _scrollView.scrollEnabled = contentWidth > frame.size.width; +#endif +} + +// The code pane starts after the content inset and one header-label line. +- (CGFloat)headerHeight +{ + return [self contentInset] + _headerLabelLineHeight; +} + +- (CGFloat)headerCenterY +{ + // The divider sits halfway into the code pane's top inset. + return ([self headerHeight] + [self contentInset] / 2) / 2; +} + +- (void)layoutHeaderButton +{ + CGFloat headerH = [self headerHeight]; + CGFloat iconWidth = _copyButton.intrinsicContentSize.width; + if (iconWidth <= 0 || iconWidth > headerH) { + iconWidth = headerH; + } + CGFloat iconSlack = (headerH - iconWidth) / 2; + CGFloat buttonLeft = MAX(self.bounds.size.width - [self contentInset] - headerH + iconSlack, 0); + CGFloat buttonTop = MAX([self headerCenterY] - headerH / 2, 0); + _copyButton.frame = CGRectMake(buttonLeft, buttonTop, headerH, headerH); +} + +#if !TARGET_OS_OSX +- (void)layoutSubviews +{ + [super layoutSubviews]; + [self layoutHeaderButton]; + [self layoutScrollArea]; +} +#else +- (void)layout +{ + [super layout]; + [self layoutHeaderButton]; + [self layoutScrollArea]; +} +#endif + +#if TARGET_OS_OSX +- (BOOL)isFlipped +{ + return YES; +} + +- (void)setFrameSize:(NSSize)newSize +{ + [super setFrameSize:newSize]; + [self setNeedsDisplay:YES]; +} +#endif + +// Highlighting is deferred while pending, applied once the block closes. +- (void)rebuildAttributedCode +{ + NSAttributedString *plainCode = [self plainAttributedCode]; + NSAttributedString *highlighted = + _pending ? nil : ENRMHighlightedAttributedCode(plainCode, _cachedCode, _cachedLanguage, _config); + _attributedCode = highlighted ?: plainCode; + // Setting attributedCode builds and lays out the cached TextKit stack once; + // width then reads out of that layout, and height stays analytic. + _codeContentView.attributedCode = _attributedCode; + _codeSize = CGSizeMake(_codeContentView.usedWidth, ENRMCodeBlockCodeHeight(_cachedCode, _config)); +} + +- (void)applyCodeBlockNode:(MarkdownASTNode *)node +{ + _cachedCode = ENRMCodeBlockExtractCode(node); + _fenceChar = ENRMCodeBlockFenceChar(node); + + NSString *newLanguage = ENRMCodeBlockLanguage(node); + BOOL languageChanged = newLanguage != _cachedLanguage && ![newLanguage isEqualToString:_cachedLanguage]; + if (languageChanged) { + _cachedLanguage = newLanguage; + _displayLanguage = ENRMCodeBlockDisplayLanguageName(newLanguage); + [self rebuildLanguageLabel]; + } + + [self rebuildAttributedCode]; + + // iOS VoiceOver reads the copy label live via accessibilityCustomActions and the + // button is hidden behind the container's single a11y element, so its own label + // is consumed only on macOS; refresh it there on each content update. +#if TARGET_OS_OSX + _copyButton.accessibilityLabel = self.dynamicProps.menuCopyLabel; +#endif + +#if !TARGET_OS_OSX + [self setNeedsLayout]; + [self setNeedsDisplay]; + [_codeContentView setNeedsDisplay]; +#else + self.needsLayout = YES; + [self setNeedsDisplay:YES]; + [_codeContentView setNeedsDisplay:YES]; +#endif +} + +- (void)rebuildLanguageLabel +{ + if (_displayLanguage.length == 0) { + _languageLabel = nil; + _languageLabelSize = CGSizeZero; + return; + } + NSMutableDictionary *labelAttributes = [NSMutableDictionary dictionary]; + labelAttributes[NSFontAttributeName] = _headerFont; + RCTUIColor *labelColor = [[_config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha]; + if (labelColor) { + labelAttributes[NSForegroundColorAttributeName] = labelColor; + } + _languageLabel = [[NSAttributedString alloc] initWithString:_displayLanguage attributes:labelAttributes]; + _languageLabelSize = _languageLabel.size; +} + +- (NSAttributedString *)plainAttributedCode +{ + return ENRMCodeBlockPlainAttributedCode(_cachedCode, _config); +} + +- (CGFloat)contentInset +{ + return ENRMCodeBlockContentInset(_config); +} + +- (CGFloat)measureHeight:(CGFloat)maxWidth +{ + CGFloat inset = [self contentInset]; + return _codeSize.height + inset * 2 + [self headerHeight]; +} + ++ (CGFloat)measureHeightForCodeBlockNode:(MarkdownASTNode *)node config:(StyleConfig *)config +{ + CGFloat inset = ENRMCodeBlockContentInset(config); + CGFloat headerH = inset + ENRMCodeBlockHeaderLabelLineHeight(ENRMCodeBlockHeaderFont(config)); + CGFloat codeHeight = ENRMCodeBlockCodeHeight(ENRMCodeBlockExtractCode(node), config); + return codeHeight + inset * 2 + headerH; +} + +- (void)drawRect:(CGRect)rect +{ + CGFloat borderWidth = [_config codeBlockBorderWidth]; + CGFloat radius = [_config codeBlockBorderRadius]; + CGRect borderRect = CGRectInset(self.bounds, borderWidth / 2, borderWidth / 2); + +#if !TARGET_OS_OSX + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:borderRect cornerRadius:radius]; +#else + NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:borderRect xRadius:radius yRadius:radius]; +#endif + + RCTUIColor *backgroundColor = [_config codeBlockBackgroundColor]; + if (backgroundColor) { + [backgroundColor setFill]; + [path fill]; + } + if (borderWidth > 0) { + RCTUIColor *borderColor = [_config codeBlockBorderColor]; + if (borderColor) { + path.lineWidth = borderWidth; + [borderColor setStroke]; + [path stroke]; + } + } + + CGFloat inset = [self contentInset]; + CGFloat headerH = [self headerHeight]; + + // Divider between the header and the code, centered in the gap the code + // text's top inset creates, so it adds no height of its own. + RCTUIColor *dividerColor = [[_config codeBlockColor] colorWithAlphaComponent:kENRMHeaderDividerAlpha]; + if (dividerColor) { + CGRect dividerRect = CGRectMake(borderWidth, headerH + inset / 2, self.bounds.size.width - borderWidth * 2, 1); + [dividerColor setFill]; +#if !TARGET_OS_OSX + [[UIBezierPath bezierPathWithRect:dividerRect] fill]; +#else + [[NSBezierPath bezierPathWithRect:dividerRect] fill]; +#endif + } + + if (_languageLabel.length > 0) { + [_languageLabel drawAtPoint:CGPointMake(inset, [self headerCenterY] - _languageLabelSize.height / 2)]; + } +} + +- (NSString *)fencedMarkdown +{ + return ENRMCodeBlockFencedMarkdown(_cachedCode, _cachedLanguage, _fenceChar); +} + +- (void)copyCodeToPasteboard +{ + copyStringToPasteboard(_cachedCode); + if (self.onCopyPress) { + self.onCopyPress(_cachedCode ?: @"", _cachedLanguage ?: @""); + } +} + +- (void)copyMarkdownToPasteboard +{ + copyStringToPasteboard([self fencedMarkdown]); +} + +#if !TARGET_OS_OSX +- (void)handleCodeBlockTap:(UITapGestureRecognizer *)recognizer +{ + if (!self.dynamicProps.enableCodeBlockPress || _pending) { + return; + } + if (self.onCodeBlockPress) { + self.onCodeBlockPress(_cachedCode ?: @"", _cachedLanguage ?: @""); + } +} + +- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer +{ + if (gestureRecognizer == _tapRecognizer) { + return self.dynamicProps.enableCodeBlockPress && !_pending; + } + return YES; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch +{ + // Let the copy button handle its own tap. + for (UIView *hit = touch.view; hit != nil; hit = hit.superview) { + if (hit == _copyButton) { + return NO; + } + } + return YES; +} +#endif + +#if !TARGET_OS_OSX +- (UIContextMenuConfiguration *)contextMenuInteraction:(UIContextMenuInteraction *)interaction + configurationForMenuAtLocation:(CGPoint)location +{ + if (!self.dynamicProps.enableBlockContextMenu || _pending) { + return nil; + } + return [UIContextMenuConfiguration + configurationWithIdentifier:nil + previewProvider:nil + actionProvider:^UIMenu *(NSArray *suggestedActions) { + UIAction *copyCode = + [UIAction actionWithTitle:self.dynamicProps.menuCopyLabel + image:[RCTUIImage systemImageNamed:@"doc.on.doc"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyCodeToPasteboard]; }]; + + UIAction *copyMarkdown = + [UIAction actionWithTitle:self.dynamicProps.menuCopyAsMarkdownLabel + image:[RCTUIImage systemImageNamed:@"doc.text"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyMarkdownToPasteboard]; }]; + + return [UIMenu menuWithTitle:@"" children:@[ copyCode, copyMarkdown ]]; + }]; +} +#endif + +#if TARGET_OS_OSX +- (NSMenu *)buildContextMenu +{ + if (!self.dynamicProps.enableBlockContextMenu || _pending) { + return nil; + } + NSMenu *menu = [[NSMenu alloc] initWithTitle:@""]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyLabel, ^{ [self copyCodeToPasteboard]; })]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyAsMarkdownLabel, ^{ [self copyMarkdownToPasteboard]; })]; + return menu; +} + +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + return [self buildContextMenu]; +} +#endif + +- (NSString *)accessibilityLabel +{ + return _cachedCode; +} + +#if !TARGET_OS_OSX +- (UIAccessibilityTraits)accessibilityTraits +{ + return UIAccessibilityTraitStaticText; +} + +// The container is a single accessibility element, which hides the copy +// button subview from VoiceOver; expose the copy action explicitly instead. +- (NSArray *)accessibilityCustomActions +{ + if (_pending || self.dynamicProps.menuCopyLabel.length == 0) { + return @[]; + } + UIAccessibilityCustomAction *copyAction = + [[UIAccessibilityCustomAction alloc] initWithName:self.dynamicProps.menuCopyLabel + target:self + selector:@selector(performCopyAccessibilityAction:)]; + return @[ copyAction ]; +} + +- (BOOL)performCopyAccessibilityAction:(UIAccessibilityCustomAction *)action +{ + [self copyCodeToPasteboard]; + return YES; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.h new file mode 100644 index 000000000000..41e522d05e47 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.h @@ -0,0 +1,52 @@ +#pragma once + +#import "ENRMUIKit.h" +#import "RenderedMarkdownSegment.h" +#import "SegmentViewRegistry.h" +#import "StyleConfig.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Reusable host view for an AST branch node that holds a vertical stack of block + * children (currently every blockquote; the analogue of Android's + * ContainerNodeView). It owns the machinery shared by such hosts: reconciling a + * list of ENRMRenderedSegment into real child views by signature via + * ENRMSegmentReconciler + a per-kind ENRMSegmentViewRegistry the subclass + * supplies, stacking them vertically with per-segment margins, and reporting the + * total height (including its own content insets). + * + * Layout honors contentInsets so a subclass can inset its children (e.g. a + * blockquote's border/gap/padding): children are laid out at width minus the + * horizontal insets, starting at (insets.left, insets.top). Per-kind margins are + * read from the config exactly as the root view's layout applies them. + * + * Streaming inside a container is treated as static: no fade/tail animation and + * no pending-code-fence sync. A content change re-signs the whole subtree, so + * the outer reconciler still reuses the container view by signature. + */ +@interface ENRMContainerNodeView : RCTUIView + +@property (nonatomic, strong) StyleConfig *config; + +// Set by a subclass before applySegments:reset:. The reconcile/layout loop is +// identical across hosts; only the child view construction varies per registry. +@property (nonatomic, strong) ENRMSegmentViewRegistry *segmentViewRegistry; + +// Inset applied to all children. A plain container leaves this zero. +@property (nonatomic, assign) UIEdgeInsets contentInsets; + +// Whether the last child contributes its trailing bottom margin. +@property (nonatomic, assign) BOOL allowTrailingMargin; + +// Reconciles the current child views against renderedSegments, attaching and +// removing subviews as needed. Requests a re-layout. +- (void)applySegments:(NSArray *)renderedSegments reset:(BOOL)reset; + +// Total laid-out height for the current children at contentWidth (inner width, +// i.e. bounds width minus horizontal insets), including the vertical insets. +- (CGFloat)computeContentHeightForWidth:(CGFloat)contentWidth; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.mm b/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.mm new file mode 100644 index 000000000000..448840013e73 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMContainerNodeView.mm @@ -0,0 +1,201 @@ +#import "ENRMContainerNodeView.h" +#import "ENRMBlockquoteContainerView.h" +#import "ENRMCodeBlockContainerView.h" +#import "ENRMFeatureFlags.h" +#import "EnrichedMarkdownInternalText.h" +#import "SegmentReconciler.h" +#import "TableContainerView.h" +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathContainerView.h" +#endif +#if ENRICHED_MARKDOWN_VIDEO +#import "ENRMVideoContainerView.h" +#endif + +@implementation ENRMContainerNodeView { + NSMutableArray *_segmentViews; + NSMutableArray *_segmentSignatures; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + _segmentViews = [NSMutableArray array]; + _segmentSignatures = [NSMutableArray array]; + _contentInsets = UIEdgeInsetsZero; + _allowTrailingMargin = NO; + self.backgroundColor = [RCTUIColor clearColor]; +#if !TARGET_OS_OSX + self.contentMode = UIViewContentModeRedraw; +#endif + } + return self; +} + +#if TARGET_OS_OSX +- (BOOL)isFlipped +{ + return YES; +} +#endif + +- (void)applySegments:(NSArray *)renderedSegments reset:(BOOL)reset +{ + ENRMSegmentViewRegistry *registry = _segmentViewRegistry; + ENRMSegmentReconciliationResult *result = [ENRMSegmentReconciler reconcileCurrentViews:_segmentViews + currentSignatures:_segmentSignatures + renderedSegments:renderedSegments + reset:reset + createView:^RCTUIView *(ENRMRenderedSegment *segment) { return [registry createViewForSegment:segment]; } + updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) { [registry updateView:view withSegment:segment]; } + attachView:^(RCTUIView *view) { [self addSubview:view]; } + removeView:^(RCTUIView *view) { [view removeFromSuperview]; } + matchesKind:^BOOL(RCTUIView *view, ENRMRenderedSegment *segment) { + return [registry view:view matchesSegment:segment]; + }]; + + _segmentViews = result.views; + _segmentSignatures = result.signatures; + +#if !TARGET_OS_OSX + [self setNeedsLayout]; +#else + self.needsLayout = YES; +#endif +} + +- (CGFloat)marginTopForView:(RCTUIView *)view +{ + if ([view isKindOfClass:[TableContainerView class]]) { + return _config.tableMarginTop; + } + if ([view isKindOfClass:[ENRMCodeBlockContainerView class]]) { + return _config.codeBlockMarginTop; + } + if ([view isKindOfClass:[ENRMBlockquoteContainerView class]]) { + // A quote laid out inside another quote is nested and carries no margin; the + // outermost quote's margin is applied by the root host instead. + return ((ENRMBlockquoteContainerView *)view).nested ? 0 : _config.blockquoteMarginTop; + } +#if ENRICHED_MARKDOWN_MATH + if ([view isKindOfClass:[ENRMMathContainerView class]]) { + return _config.mathMarginTop; + } +#endif +#if ENRICHED_MARKDOWN_VIDEO + if ([view isKindOfClass:[ENRMVideoContainerView class]]) { + return _config.videoMarginTop; + } +#endif + return 0; +} + +- (CGFloat)marginBottomForView:(RCTUIView *)view +{ + if ([view isKindOfClass:[TableContainerView class]]) { + return _config.tableMarginBottom; + } + if ([view isKindOfClass:[ENRMCodeBlockContainerView class]]) { + return _config.codeBlockMarginBottom; + } + if ([view isKindOfClass:[ENRMBlockquoteContainerView class]]) { + return ((ENRMBlockquoteContainerView *)view).nested ? 0 : _config.blockquoteMarginBottom; + } +#if ENRICHED_MARKDOWN_MATH + if ([view isKindOfClass:[ENRMMathContainerView class]]) { + return _config.mathMarginBottom; + } +#endif +#if ENRICHED_MARKDOWN_VIDEO + if ([view isKindOfClass:[ENRMVideoContainerView class]]) { + return _config.videoMarginBottom; + } +#endif + return 0; +} + +- (CGFloat)heightForView:(RCTUIView *)view atWidth:(CGFloat)width shouldAddBottomMargin:(BOOL)shouldAddBottomMargin +{ + if ([view isKindOfClass:[EnrichedMarkdownInternalText class]]) { + EnrichedMarkdownInternalText *textView = (EnrichedMarkdownInternalText *)view; + textView.allowTrailingMargin = shouldAddBottomMargin; + return [textView measureSize:width].height; + } + if ([view isKindOfClass:[TableContainerView class]]) { + return [(TableContainerView *)view measureHeight:width]; + } + if ([view isKindOfClass:[ENRMCodeBlockContainerView class]]) { + return [(ENRMCodeBlockContainerView *)view measureHeight:width]; + } + if ([view isKindOfClass:[ENRMBlockquoteContainerView class]]) { + return [(ENRMBlockquoteContainerView *)view measureHeight:width]; + } +#if ENRICHED_MARKDOWN_MATH + if ([view isKindOfClass:[ENRMMathContainerView class]]) { + return [(ENRMMathContainerView *)view measureHeight:width]; + } +#endif +#if ENRICHED_MARKDOWN_VIDEO + if ([view isKindOfClass:[ENRMVideoContainerView class]]) { + return [(ENRMVideoContainerView *)view measureHeight:width]; + } +#endif + return 0; +} + +// Mirrors the root's computeSegmentLayoutForWidth: (text via measureSize:, +// block kinds via measureHeight: plus their config margins), but confined to the +// inner content rect defined by contentInsets so a subclass can pad its children. +- (CGSize)layoutChildrenForOuterWidth:(CGFloat)outerWidth applyFrames:(BOOL)applyFrames +{ + CGFloat contentWidth = MAX(outerWidth - _contentInsets.left - _contentInsets.right, 0); + if (_segmentViews.count == 0 || contentWidth <= 0) { + return CGSizeMake(0, _contentInsets.top + _contentInsets.bottom); + } + + CGFloat yOffset = _contentInsets.top; + const NSUInteger lastIndex = _segmentViews.count - 1; + + for (NSUInteger i = 0; i < _segmentViews.count; i++) { + RCTUIView *view = _segmentViews[i]; + const BOOL isLast = (i == lastIndex); + const BOOL shouldAddBottomMargin = (!isLast || _allowTrailingMargin); + + yOffset += [self marginTopForView:view]; + CGFloat height = [self heightForView:view atWidth:contentWidth shouldAddBottomMargin:shouldAddBottomMargin]; + + if (applyFrames) { + view.frame = CGRectMake(_contentInsets.left, yOffset, contentWidth, height); + } + + yOffset += height; + if (shouldAddBottomMargin) { + yOffset += [self marginBottomForView:view]; + } + } + + yOffset += _contentInsets.bottom; + return CGSizeMake(outerWidth, yOffset); +} + +- (CGFloat)computeContentHeightForWidth:(CGFloat)contentWidth +{ + return [self layoutChildrenForOuterWidth:contentWidth + _contentInsets.left + _contentInsets.right applyFrames:NO] + .height; +} + +#if !TARGET_OS_OSX +- (void)layoutSubviews +{ + [super layoutSubviews]; + [self layoutChildrenForOuterWidth:self.bounds.size.width applyFrames:YES]; +} +#else +- (void)layout +{ + [super layout]; + [self layoutChildrenForOuterWidth:self.bounds.size.width applyFrames:YES]; +} +#endif + +@end diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.h b/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.h new file mode 100644 index 000000000000..abf4ab3f89e3 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.h @@ -0,0 +1,35 @@ +#pragma once +#import "ENRMLinkContextMenus.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Runtime-mutable block props that a prop update can flip WITHOUT recreating the + * segment tree: the block context-menu gate, the code-block tap gate, and the + * copy menu labels. The root owns one instance and mutates it in place; every + * block view down the tree holds the same reference (never a copy) and reads a + * field at use-time (menu-open, tap). So a view created after a toggle - e.g. a + * code block added to a blockquote once onCodeBlockPress is on - is born current + * instead of from a stale snapshot, and no per-toggle push into existing views is + * needed. Mirrors Android's DynamicBlockProps. See issues #768 and #822. + * + * The copy/tap callbacks stay per-view: on iOS they are stable event bridges set + * once at creation, so they never go stale. Only props that actually change at + * runtime and gate no layout/draw belong here; style stays on the immutable + * StyleConfig, where a snapshot can never go stale. + * + * Getters are renamed to avoid the Cocoa `copy` method family, matching + * ENRMCodeBlockContainerView; property names are unchanged so call sites read + * dynamic.copyLabel. + */ +@interface ENRMDynamicBlockProps : NSObject +@property (nonatomic, strong, nullable) ENRMLinkContextMenus *linkContextMenus; +@property (nonatomic, assign) BOOL enableLinkPreview; +@property (nonatomic, assign) BOOL enableBlockContextMenu; +@property (nonatomic, assign) BOOL enableCodeBlockPress; +@property (nonatomic, copy, nullable, getter=menuCopyLabel) NSString *copyLabel; +@property (nonatomic, copy, nullable, getter=menuCopyAsMarkdownLabel) NSString *copyAsMarkdownLabel; +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.m b/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.m new file mode 100644 index 000000000000..e3cac3f5a081 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMDynamicBlockProps.m @@ -0,0 +1,16 @@ +#import "ENRMDynamicBlockProps.h" + +@implementation ENRMDynamicBlockProps + +- (instancetype)init +{ + self = [super init]; + if (self) { + _enableLinkPreview = YES; + _enableBlockContextMenu = YES; + _enableCodeBlockPress = NO; + } + return self; +} + +@end diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.h new file mode 100644 index 000000000000..e6fab59c6508 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.h @@ -0,0 +1,39 @@ +#pragma once +#import "ENRMDynamicBlockProps.h" +#import "ENRMLatexErrorReporting.h" +#import "ENRMUIKit.h" +#import "StyleConfig.h" + +@class ENRMAccessibilityLabels; + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMMathContainerView : RCTUIView + +- (instancetype)initWithConfig:(StyleConfig *)config; + +- (void)applyLatex:(NSString *)latex; + +- (CGFloat)measureHeight:(CGFloat)maxWidth; + +/// View-free math-block height for shadow-node measurement (issue #550): +/// parses the LaTeX through the same RaTeX bridge `applyLatex:` uses and +/// applies the same padding math as `measureHeight:` — including the wrapped +/// source-fallback path when RaTeX cannot parse — without creating any view. +/// Runs on the calling thread. Like every member of this class, only +/// implemented when ENRICHED_MARKDOWN_MATH is on — guard call sites. ++ (CGFloat)measureHeightForLatex:(NSString *)latex config:(StyleConfig *)config maxWidth:(CGFloat)maxWidth; + +@property (nonatomic, strong) StyleConfig *config; +@property (nonatomic, copy, readonly) NSString *cachedLatex; +@property (nonatomic, strong, nullable) ENRMAccessibilityLabels *accessibilityLabels; +@property (nonatomic, copy, nullable) ENRMLatexErrorHandler onLatexError; + +// Shared, runtime-mutable block props (context-menu gate + copy labels) read live +// at menu-open. Set to the root's shared instance at creation. See +// ENRMDynamicBlockProps. +@property (nonatomic, strong) ENRMDynamicBlockProps *dynamicProps; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.m b/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.m new file mode 100644 index 000000000000..3f1829dda9ae --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMMathContainerView.m @@ -0,0 +1,313 @@ +#import "ENRMMathContainerView.h" +#import "ENRMAccessibilityLabels.h" +#import "ENRMFeatureFlags.h" +#import "ENRMHorizontalScrollView.h" +#include + +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathFallback.h" +#import "PasteboardUtils.h" +#if __has_include("ReactNativeEnrichedMarkdown-Swift.h") +#import "ReactNativeEnrichedMarkdown-Swift.h" +#elif __has_include() +#import +#endif +#if TARGET_OS_OSX +#import "ENRMMenuAction.h" +#endif +#endif + +#if ENRICHED_MARKDOWN_MATH + +@interface ENRMRaTeXCanvasView : RCTUIView +@property (nonatomic, strong, nullable) ENRMRaTeXRenderResult *renderResult; +// Visible-source fallback when RaTeX cannot parse the block, drawn wrapped; +// see ENRMMathFallback.h. +@property (nonatomic, strong, nullable) NSAttributedString *fallbackSource; +@end + +@implementation ENRMRaTeXCanvasView + +- (void)drawRect:(CGRect)rect +{ + if (!_renderResult) { + if (_fallbackSource) { + [_fallbackSource drawWithRect:self.bounds options:NSStringDrawingUsesLineFragmentOrigin context:nil]; + } + return; + } + CGContextRef ctx = UIGraphicsGetCurrentContext(); + if (!ctx) + return; + [_renderResult drawIn:ctx]; +} + +- (CGSize)intrinsicContentSize +{ + if (!_renderResult) + return CGSizeZero; + return CGSizeMake(ceil(_renderResult.width), ceil(_renderResult.totalHeight)); +} + +@end + +#if !TARGET_OS_OSX +@interface ENRMMathContainerView () +@property (nonatomic, strong, readonly) ENRMHorizontalScrollView *scrollView; +#else +@interface ENRMMathContainerView () +#endif +@property (nonatomic, strong, readonly) ENRMRaTeXCanvasView *mathView; +@property (nonatomic, copy, readwrite) NSString *cachedLatex; +@end + +@implementation ENRMMathContainerView { + BOOL _parseFailed; + NSString *_parseMessage; +} + +- (void)reportLatexErrorIfNeeded +{ + if (_parseFailed && self.onLatexError) { + self.onLatexError(_cachedLatex, _parseMessage ?: @"", YES); + } +} + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + self = [super initWithFrame:CGRectZero]; + if (self) { + _config = config; + _cachedLatex = @""; + _dynamicProps = [[ENRMDynamicBlockProps alloc] init]; + + _mathView = [[ENRMRaTeXCanvasView alloc] initWithFrame:CGRectZero]; + _mathView.backgroundColor = [RCTUIColor clearColor]; + +#if !TARGET_OS_OSX + _scrollView = [[ENRMHorizontalScrollView alloc] init]; + _scrollView.showsVerticalScrollIndicator = NO; + _scrollView.showsHorizontalScrollIndicator = YES; + _scrollView.alwaysBounceHorizontal = NO; + _scrollView.scrollEnabled = NO; + [self addSubview:_scrollView]; + [_scrollView addSubview:_mathView]; + + self.isAccessibilityElement = YES; + + UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self]; + [self addInteraction:contextMenu]; +#else + [self addSubview:_mathView]; +#endif + } + return self; +} + +- (void)applyLatex:(NSString *)latex +{ + _cachedLatex = [latex copy]; + _parseFailed = NO; + _parseMessage = nil; + + StyleConfig *config = self.config; + + NSError *error = nil; + ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:latex + displayMode:YES + fontSize:config.mathFontSize + color:config.mathColor + error:&error]; + if (!result) { + _parseFailed = YES; + _parseMessage = error.localizedDescription ?: @""; + [self reportLatexErrorIfNeeded]; + } + _mathView.renderResult = result; + _mathView.fallbackSource = result ? nil : ENRMMathFallbackString(latex, @"$$", config.mathFontSize, config.mathColor); + + CGFloat padding = config.mathPadding; + _mathView.frame = CGRectMake(padding, padding, ceil(result.width), ceil(result.totalHeight)); + + self.backgroundColor = config.mathBackgroundColor; + + [_mathView invalidateIntrinsicContentSize]; +#if !TARGET_OS_OSX + [_mathView setNeedsDisplay]; +#else + [_mathView setNeedsDisplay:YES]; +#endif + [self setNeedsLayout]; +} + +#if !TARGET_OS_OSX +- (UIContextMenuConfiguration *)contextMenuInteraction:(UIContextMenuInteraction *)interaction + configurationForMenuAtLocation:(CGPoint)location +{ + if (!self.dynamicProps.enableBlockContextMenu) { + return nil; + } + return [UIContextMenuConfiguration + configurationWithIdentifier:nil + previewProvider:nil + actionProvider:^UIMenu *(NSArray *suggestedActions) { + UIAction *copyPlainText = + [UIAction actionWithTitle:self.dynamicProps.menuCopyLabel + image:[RCTUIImage systemImageNamed:@"doc.on.doc"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyLatexToPasteboard]; }]; + + UIAction *copyMarkdown = + [UIAction actionWithTitle:self.dynamicProps.menuCopyAsMarkdownLabel + image:[RCTUIImage systemImageNamed:@"doc.text"] + identifier:nil + handler:^(__kindof UIAction *action) { [self copyMarkdownToPasteboard]; }]; + + return [UIMenu menuWithTitle:@"" children:@[ copyPlainText, copyMarkdown ]]; + }]; +} +#endif + +#if TARGET_OS_OSX +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + if (!self.dynamicProps.enableBlockContextMenu) { + return nil; + } + NSMenu *menu = [[NSMenu alloc] initWithTitle:@""]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyLabel, ^{ [self copyLatexToPasteboard]; })]; + [menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyAsMarkdownLabel, ^{ [self copyMarkdownToPasteboard]; })]; + return menu; +} +#endif + +- (void)copyLatexToPasteboard +{ + copyStringToPasteboard(_cachedLatex); +} + +- (void)copyMarkdownToPasteboard +{ + copyStringToPasteboard([NSString stringWithFormat:@"$$\n%@\n$$", _cachedLatex]); +} + +- (CGSize)mathViewIntrinsicSize +{ + return _mathView.intrinsicContentSize; +} + +- (CGFloat)measureHeight:(CGFloat)maxWidth +{ + CGFloat padding = self.config.mathPadding; + if (!_mathView.renderResult && _mathView.fallbackSource) { + CGFloat available = MAX(maxWidth - padding * 2, 1); + CGRect bounds = [_mathView.fallbackSource boundingRectWithSize:CGSizeMake(available, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil]; + return ceil(bounds.size.height) + padding * 2; + } + return [self mathViewIntrinsicSize].height + padding * 2; +} + ++ (CGFloat)measureHeightForLatex:(NSString *)latex config:(StyleConfig *)config maxWidth:(CGFloat)maxWidth +{ + CGFloat padding = config.mathPadding; + + ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:latex + displayMode:YES + fontSize:config.mathFontSize + color:config.mathColor]; + if (result) { + return ceil(result.totalHeight) + padding * 2; + } + + NSAttributedString *fallbackSource = ENRMMathFallbackString(latex, @"$$", config.mathFontSize, config.mathColor); + if (!fallbackSource) { + return 0; + } + CGFloat available = MAX(maxWidth - padding * 2, 1); + CGRect bounds = [fallbackSource boundingRectWithSize:CGSizeMake(available, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil]; + return ceil(bounds.size.height) + padding * 2; +} + +- (CGFloat)alignedOriginXForWidth:(CGFloat)formulaWidth inBounds:(CGFloat)boundsWidth padding:(CGFloat)padding +{ + CGFloat available = boundsWidth - padding * 2; + if (formulaWidth >= available) + return padding; + + NSString *align = self.config.mathTextAlign; + if ([align isEqualToString:@"left"]) + return padding; + if ([align isEqualToString:@"right"]) + return padding + available - formulaWidth; + return padding + (available - formulaWidth) / 2.0; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + CGFloat padding = self.config.mathPadding; + + if (!_mathView.renderResult && _mathView.fallbackSource) { + // Fallback source fills the available width and wraps; no horizontal scroll. +#if !TARGET_OS_OSX + _scrollView.frame = self.bounds; + _scrollView.contentSize = self.bounds.size; + _scrollView.contentOffset = CGPointZero; + _scrollView.scrollEnabled = NO; +#endif + _mathView.frame = CGRectMake(padding, padding, MAX(self.bounds.size.width - padding * 2, 1), + MAX(self.bounds.size.height - padding * 2, 1)); +#if !TARGET_OS_OSX + [_mathView setNeedsDisplay]; +#else + [_mathView setNeedsDisplay:YES]; +#endif + return; + } + + CGSize intrinsicSize = [self mathViewIntrinsicSize]; + CGFloat contentWidth = intrinsicSize.width + padding * 2; + CGFloat contentHeight = self.bounds.size.height; + BOOL overflows = contentWidth > self.bounds.size.width; + CGFloat originX = [self alignedOriginXForWidth:intrinsicSize.width inBounds:self.bounds.size.width padding:padding]; + +#if !TARGET_OS_OSX + _scrollView.frame = self.bounds; + _scrollView.contentSize = CGSizeMake(overflows ? contentWidth : self.bounds.size.width, contentHeight); + _scrollView.scrollEnabled = overflows; + _mathView.frame = CGRectMake(originX, padding, intrinsicSize.width, intrinsicSize.height); +#else + _mathView.frame = CGRectMake(originX, padding, intrinsicSize.width, intrinsicSize.height); + [_mathView setNeedsDisplay:YES]; +#endif +} + +#if TARGET_OS_OSX +- (void)layout +{ + [super layout]; + [self layoutSubviews]; +} +#endif + +- (NSString *)accessibilityLabel +{ + return [_accessibilityLabels.mathEquation stringByReplacingOccurrencesOfString:@"{latex}" + withString:_cachedLatex ?: @""]; +} + +#if !TARGET_OS_OSX +- (UIAccessibilityTraits)accessibilityTraits +{ + return UIAccessibilityTraitStaticText; +} +#endif + +@end + +#endif diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.h b/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.h new file mode 100644 index 000000000000..79f768363d87 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.h @@ -0,0 +1,21 @@ +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +#ifdef __cplusplus +extern "C" { +#endif + +// Parse an SVG path `d` string into a CGPath. Supports the M/L/H/V/C/S/Q/T/A/Z +// command set (absolute and relative), which covers the @primer/octicons glyphs +// used for admonition headers. Elliptical arcs are approximated with cubic +// beziers. Returns NULL on empty/invalid input. Caller owns the returned path +// (CGPathRelease). CoreGraphics is used so the same code renders on iOS and macOS. +CGPathRef _Nullable ENRMCreateCGPathFromSVGPath(NSString *pathData) CF_RETURNS_RETAINED; + +#ifdef __cplusplus +} +#endif + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.m b/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.m new file mode 100644 index 000000000000..10a4fb1b0ec9 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMSVGPath.m @@ -0,0 +1,409 @@ +#import "ENRMSVGPath.h" +#import + +// Minimal SVG path `d` parser producing a CGPath. It is intentionally scoped to +// the command set the admonition octicons use (M m L l H h V v C c S s Q q T t +// A a Z z); it is not a general-purpose SVG engine. The parser walks the string +// with a scanner, tracking the current point, the current subpath start, and the +// previous control point (for the smooth S/T shorthands). Elliptical arcs are +// converted to cubic beziers via the endpoint -> center parameterization from +// the SVG implementation notes (appendix F.6). + +typedef struct { + const char *chars; + NSUInteger length; + NSUInteger index; +} ENRMScanner; + +static BOOL ENRMScanIsCommand(char c) +{ + switch (c) { + case 'M': + case 'm': + case 'L': + case 'l': + case 'H': + case 'h': + case 'V': + case 'v': + case 'C': + case 'c': + case 'S': + case 's': + case 'Q': + case 'q': + case 'T': + case 't': + case 'A': + case 'a': + case 'Z': + case 'z': + return YES; + default: + return NO; + } +} + +static void ENRMScanSkipSeparators(ENRMScanner *s) +{ + while (s->index < s->length) { + char c = s->chars[s->index]; + if (c == ' ' || c == ',' || c == '\t' || c == '\n' || c == '\r') { + s->index++; + } else { + break; + } + } +} + +// Reads the next number. SVG allows numbers to run together without separators +// (e.g. "1 1 0 1 1"), and a leading '-' or '.' starts a new number even with no +// separator (e.g. "16 0Zm8-6.5"). Returns NO when no number is available. +static BOOL ENRMScanNumber(ENRMScanner *s, double *out) +{ + ENRMScanSkipSeparators(s); + NSUInteger start = s->index; + BOOL seenDigit = NO; + BOOL seenDot = NO; + BOOL seenExp = NO; + + if (s->index < s->length && (s->chars[s->index] == '+' || s->chars[s->index] == '-')) { + s->index++; + } + while (s->index < s->length) { + char c = s->chars[s->index]; + if (c >= '0' && c <= '9') { + seenDigit = YES; + s->index++; + } else if (c == '.' && !seenDot && !seenExp) { + seenDot = YES; + s->index++; + } else if ((c == 'e' || c == 'E') && seenDigit && !seenExp) { + seenExp = YES; + s->index++; + if (s->index < s->length && (s->chars[s->index] == '+' || s->chars[s->index] == '-')) { + s->index++; + } + } else { + break; + } + } + + if (!seenDigit) { + s->index = start; + return NO; + } + + char buffer[64]; + NSUInteger count = s->index - start; + if (count >= sizeof(buffer)) { + count = sizeof(buffer) - 1; + } + memcpy(buffer, s->chars + start, count); + buffer[count] = '\0'; + *out = atof(buffer); + return YES; +} + +// A single arc segment (<= 90 degrees) approximated as one cubic bezier. +static void ENRMArcSegment(CGMutablePathRef path, double cx, double cy, double rx, double ry, double phi, double t1, + double dt) +{ + double cosPhi = cos(phi); + double sinPhi = sin(phi); + double alpha = (4.0 / 3.0) * tan(dt / 4.0); + + double x1 = cos(t1); + double y1 = sin(t1); + double x2 = cos(t1 + dt); + double y2 = sin(t1 + dt); + + double p1x = cx + rx * cosPhi * x1 - ry * sinPhi * y1; + double p1y = cy + rx * sinPhi * x1 + ry * cosPhi * y1; + double p2x = cx + rx * cosPhi * x2 - ry * sinPhi * y2; + double p2y = cy + rx * sinPhi * x2 + ry * cosPhi * y2; + + double d1x = -rx * cosPhi * y1 - ry * sinPhi * x1; + double d1y = -rx * sinPhi * y1 + ry * cosPhi * x1; + double d2x = -rx * cosPhi * y2 - ry * sinPhi * x2; + double d2y = -rx * sinPhi * y2 + ry * cosPhi * x2; + + CGPathAddCurveToPoint(path, NULL, (CGFloat)(p1x + alpha * d1x), (CGFloat)(p1y + alpha * d1y), + (CGFloat)(p2x - alpha * d2x), (CGFloat)(p2y - alpha * d2y), (CGFloat)p2x, (CGFloat)p2y); +} + +// Endpoint -> center parameterization, then split into <=90 degree bezier arcs. +static void ENRMAppendArc(CGMutablePathRef path, double x0, double y0, double rx, double ry, double xAxisRotationDeg, + BOOL largeArc, BOOL sweep, double x, double y) +{ + if (rx == 0.0 || ry == 0.0) { + CGPathAddLineToPoint(path, NULL, (CGFloat)x, (CGFloat)y); + return; + } + + rx = fabs(rx); + ry = fabs(ry); + double phi = xAxisRotationDeg * M_PI / 180.0; + double cosPhi = cos(phi); + double sinPhi = sin(phi); + + double dx = (x0 - x) / 2.0; + double dy = (y0 - y) / 2.0; + double x1p = cosPhi * dx + sinPhi * dy; + double y1p = -sinPhi * dx + cosPhi * dy; + + // Scale up the radii if they are too small to span the endpoints. + double lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry); + if (lambda > 1.0) { + double scale = sqrt(lambda); + rx *= scale; + ry *= scale; + } + + double num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p; + double den = rx * rx * y1p * y1p + ry * ry * x1p * x1p; + double factor = den == 0.0 ? 0.0 : sqrt(fmax(0.0, num / den)); + if (largeArc == sweep) { + factor = -factor; + } + + double cxp = factor * (rx * y1p / ry); + double cyp = factor * (-ry * x1p / rx); + double cx = cosPhi * cxp - sinPhi * cyp + (x0 + x) / 2.0; + double cy = sinPhi * cxp + cosPhi * cyp + (y0 + y) / 2.0; + + double startAngle = atan2((y1p - cyp) / ry, (x1p - cxp) / rx); + double endAngle = atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx); + double delta = endAngle - startAngle; + + if (!sweep && delta > 0.0) { + delta -= 2.0 * M_PI; + } else if (sweep && delta < 0.0) { + delta += 2.0 * M_PI; + } + + int segments = (int)ceil(fabs(delta) / (M_PI / 2.0)); + if (segments < 1) { + segments = 1; + } + double segDelta = delta / segments; + double angle = startAngle; + for (int i = 0; i < segments; i++) { + ENRMArcSegment(path, cx, cy, rx, ry, phi, angle, segDelta); + angle += segDelta; + } +} + +CGPathRef ENRMCreateCGPathFromSVGPath(NSString *pathData) +{ + if (pathData.length == 0) { + return NULL; + } + + NSData *utf8 = [pathData dataUsingEncoding:NSUTF8StringEncoding]; + ENRMScanner scanner = {.chars = (const char *)utf8.bytes, .length = utf8.length, .index = 0}; + ENRMScanner *s = &scanner; + + CGMutablePathRef path = CGPathCreateMutable(); + double cx = 0, cy = 0; // current point + double sx = 0, sy = 0; // subpath start + double lastCx = 0, lastCy = 0; // last cubic control point (for S/s) + double lastQx = 0, lastQy = 0; // last quadratic control point (for T/t) + char lastCommand = 0; + char command = 0; + + while (s->index < s->length) { + ENRMScanSkipSeparators(s); + if (s->index >= s->length) { + break; + } + + char c = s->chars[s->index]; + if (ENRMScanIsCommand(c)) { + command = c; + s->index++; + } else if (command == 0) { + break; // malformed: data before any command + } else if (command == 'M') { + command = 'L'; // implicit lineto for repeated M coordinate pairs + } else if (command == 'm') { + command = 'l'; + } + + switch (command) { + case 'M': + case 'm': { + double nx, ny; + if (!ENRMScanNumber(s, &nx) || !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 'm') { + nx += cx; + ny += cy; + } + cx = nx; + cy = ny; + sx = cx; + sy = cy; + CGPathMoveToPoint(path, NULL, (CGFloat)cx, (CGFloat)cy); + break; + } + case 'L': + case 'l': { + double nx, ny; + if (!ENRMScanNumber(s, &nx) || !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 'l') { + nx += cx; + ny += cy; + } + cx = nx; + cy = ny; + CGPathAddLineToPoint(path, NULL, (CGFloat)cx, (CGFloat)cy); + break; + } + case 'H': + case 'h': { + double nx; + if (!ENRMScanNumber(s, &nx)) { + goto done; + } + cx = command == 'h' ? cx + nx : nx; + CGPathAddLineToPoint(path, NULL, (CGFloat)cx, (CGFloat)cy); + break; + } + case 'V': + case 'v': { + double ny; + if (!ENRMScanNumber(s, &ny)) { + goto done; + } + cy = command == 'v' ? cy + ny : ny; + CGPathAddLineToPoint(path, NULL, (CGFloat)cx, (CGFloat)cy); + break; + } + case 'C': + case 'c': { + double c1x, c1y, c2x, c2y, nx, ny; + if (!ENRMScanNumber(s, &c1x) || !ENRMScanNumber(s, &c1y) || !ENRMScanNumber(s, &c2x) || + !ENRMScanNumber(s, &c2y) || !ENRMScanNumber(s, &nx) || !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 'c') { + c1x += cx; + c1y += cy; + c2x += cx; + c2y += cy; + nx += cx; + ny += cy; + } + CGPathAddCurveToPoint(path, NULL, (CGFloat)c1x, (CGFloat)c1y, (CGFloat)c2x, (CGFloat)c2y, (CGFloat)nx, + (CGFloat)ny); + lastCx = c2x; + lastCy = c2y; + cx = nx; + cy = ny; + break; + } + case 'S': + case 's': { + double c2x, c2y, nx, ny; + if (!ENRMScanNumber(s, &c2x) || !ENRMScanNumber(s, &c2y) || !ENRMScanNumber(s, &nx) || + !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 's') { + c2x += cx; + c2y += cy; + nx += cx; + ny += cy; + } + double c1x = cx, c1y = cy; + if (lastCommand == 'C' || lastCommand == 'c' || lastCommand == 'S' || lastCommand == 's') { + c1x = 2 * cx - lastCx; + c1y = 2 * cy - lastCy; + } + CGPathAddCurveToPoint(path, NULL, (CGFloat)c1x, (CGFloat)c1y, (CGFloat)c2x, (CGFloat)c2y, (CGFloat)nx, + (CGFloat)ny); + lastCx = c2x; + lastCy = c2y; + cx = nx; + cy = ny; + break; + } + case 'Q': + case 'q': { + double c1x, c1y, nx, ny; + if (!ENRMScanNumber(s, &c1x) || !ENRMScanNumber(s, &c1y) || !ENRMScanNumber(s, &nx) || + !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 'q') { + c1x += cx; + c1y += cy; + nx += cx; + ny += cy; + } + CGPathAddQuadCurveToPoint(path, NULL, (CGFloat)c1x, (CGFloat)c1y, (CGFloat)nx, (CGFloat)ny); + lastQx = c1x; + lastQy = c1y; + cx = nx; + cy = ny; + break; + } + case 'T': + case 't': { + double nx, ny; + if (!ENRMScanNumber(s, &nx) || !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 't') { + nx += cx; + ny += cy; + } + double c1x = cx, c1y = cy; + if (lastCommand == 'Q' || lastCommand == 'q' || lastCommand == 'T' || lastCommand == 't') { + c1x = 2 * cx - lastQx; + c1y = 2 * cy - lastQy; + } + CGPathAddQuadCurveToPoint(path, NULL, (CGFloat)c1x, (CGFloat)c1y, (CGFloat)nx, (CGFloat)ny); + lastQx = c1x; + lastQy = c1y; + cx = nx; + cy = ny; + break; + } + case 'A': + case 'a': { + double rx, ry, rot, laf, sf, nx, ny; + if (!ENRMScanNumber(s, &rx) || !ENRMScanNumber(s, &ry) || !ENRMScanNumber(s, &rot) || + !ENRMScanNumber(s, &laf) || !ENRMScanNumber(s, &sf) || !ENRMScanNumber(s, &nx) || !ENRMScanNumber(s, &ny)) { + goto done; + } + if (command == 'a') { + nx += cx; + ny += cy; + } + ENRMAppendArc(path, cx, cy, rx, ry, rot, laf != 0.0, sf != 0.0, nx, ny); + cx = nx; + cy = ny; + break; + } + case 'Z': + case 'z': { + CGPathCloseSubpath(path); + cx = sx; + cy = sy; + break; + } + default: + goto done; + } + + lastCommand = command; + } + +done: + return path; +} diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.h b/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.h new file mode 100644 index 000000000000..0f26dccfce49 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.h @@ -0,0 +1,33 @@ +#pragma once + +#import "ENRMUIKit.h" +#import "ParagraphStyleUtils.h" +#import "RenderedMarkdownSegment.h" +#import "StyleConfig.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * View-free height summation for a vertical stack of already-rendered + * segments at a fixed content width. This is the iOS counterpart of Android's + * SegmentHeightMeasurer: it single-sources the per-segment height arithmetic so + * the shadow-node measurement pass (ENRMViewFreeMeasurement) and the blockquote + * container's own laid-out/static heights cannot drift. + * + * Each kind is measured with the same helper the visible view uses: text via a + * fresh call-confined TextKit stack (ENRMMeasureAttributedTextViewFree), tables + * via +[TableContainerView measureHeightForTableNode:...], code blocks via + * +[ENRMCodeBlockContainerView measureHeightForCodeBlockNode:...], math via + * +[ENRMMathContainerView measureHeightForLatex:...], and nested blockquotes via + * +[ENRMBlockquoteContainerView measureHeightForBlockquoteNode:...] (recursion). + * Per-kind margins come from the config exactly as computeSegmentLayout applies + * them: marginTop before, marginBottom after unless it is the last segment and + * trailing margins are disabled. + */ +CGFloat ENRMMeasureSegmentsHeightViewFree(NSArray *segments, StyleConfig *config, + CGFloat contentWidth, BOOL allowTrailingMargin, CGFloat pointScaleFactor, + ENRMWritingDirectionMode writingDirectionMode, + NSWritingDirection resolvedLayoutDirection, BOOL allowFontScaling, + NSLineBreakStrategy lineBreakStrategy); + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.mm b/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.mm new file mode 100644 index 000000000000..a8328804a4a5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMSegmentHeightMeasurer.mm @@ -0,0 +1,94 @@ +#import "ENRMSegmentHeightMeasurer.h" +#import "ENRMBlockquoteContainerView.h" +#import "ENRMCodeBlockContainerView.h" +#import "ENRMFeatureFlags.h" +#import "ENRMTextRenderer.h" +#import "ENRMViewFreeMeasurement.h" +#import "TableContainerView.h" +#if ENRICHED_MARKDOWN_MATH +#import "ENRMMathContainerView.h" +#endif +#if ENRICHED_MARKDOWN_VIDEO +#import "ENRMVideoContainerView.h" +#endif + +CGFloat ENRMMeasureSegmentsHeightViewFree(NSArray *segments, StyleConfig *config, + CGFloat contentWidth, BOOL allowTrailingMargin, CGFloat pointScaleFactor, + ENRMWritingDirectionMode writingDirectionMode, + NSWritingDirection resolvedLayoutDirection, BOOL allowFontScaling, + NSLineBreakStrategy lineBreakStrategy) +{ + if (segments.count == 0) { + return 0; + } + + CGFloat totalHeight = 0; + const NSUInteger lastIndex = segments.count - 1; + + for (NSUInteger i = 0; i < segments.count; i++) { + ENRMRenderedSegment *segment = segments[i]; + const BOOL isLast = (i == lastIndex); + const BOOL shouldAddBottomMargin = (!isLast || allowTrailingMargin); + + if (segment.kind == ENRMSegmentKindText && segment.textResult) { + // GFM segments are never line-clamped (numberOfLines is a no-op for GFM). + CGSize textSize = ENRMMeasureAttributedTextViewFree( + segment.textResult.attributedText, contentWidth, config, shouldAddBottomMargin, + segment.textResult.lastElementMarginBottom, pointScaleFactor, 0, NSLineBreakByWordWrapping, YES); + totalHeight += textSize.height; + } else if (segment.kind == ENRMSegmentKindTable && segment.tableSegment) { + totalHeight += config.tableMarginTop; + totalHeight += [TableContainerView measureHeightForTableNode:segment.tableSegment.tableNode + config:config + allowFontScaling:allowFontScaling + maxFontSizeMultiplier:config.maxFontSizeMultiplier + writingDirectionMode:writingDirectionMode + resolvedLayoutDirection:resolvedLayoutDirection]; + if (shouldAddBottomMargin) { + totalHeight += config.tableMarginBottom; + } + } else if (segment.kind == ENRMSegmentKindCodeBlock && segment.codeBlockSegment) { + totalHeight += config.codeBlockMarginTop; + totalHeight += [ENRMCodeBlockContainerView measureHeightForCodeBlockNode:segment.codeBlockSegment.codeBlockNode + config:config]; + if (shouldAddBottomMargin) { + totalHeight += config.codeBlockMarginBottom; + } + } else if (segment.kind == ENRMSegmentKindBlockquote && segment.blockquoteSegment) { + // This helper only ever sums a quote's own children, so any quote here is + // nested and carries no vertical margin (only the outermost quote does, + // added by the root measurement pass); mirrors ENRMBlockquoteContainerView.nested. + totalHeight += + [ENRMBlockquoteContainerView measureHeightForBlockquoteNode:segment.blockquoteSegment.blockquoteNode + config:config + maxWidth:contentWidth + pointScaleFactor:pointScaleFactor + allowFontScaling:allowFontScaling + lineBreakStrategy:lineBreakStrategy]; + } +#if ENRICHED_MARKDOWN_MATH + else if (segment.kind == ENRMSegmentKindMath && segment.mathSegment) { + totalHeight += config.mathMarginTop; + totalHeight += [ENRMMathContainerView measureHeightForLatex:segment.mathSegment.latex + config:config + maxWidth:contentWidth]; + if (shouldAddBottomMargin) { + totalHeight += config.mathMarginBottom; + } + } +#endif +#if ENRICHED_MARKDOWN_VIDEO + else if (segment.kind == ENRMSegmentKindVideo && segment.videoSegment) { + totalHeight += config.videoMarginTop; + totalHeight += [ENRMVideoContainerView measureHeightForVideoNode:segment.videoSegment.videoNode + config:config + maxWidth:contentWidth]; + if (shouldAddBottomMargin) { + totalHeight += config.videoMarginBottom; + } + } +#endif + } + + return totalHeight; +} diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.h new file mode 100644 index 000000000000..698b3d939409 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#if TARGET_OS_OSX + +#import "ENRMUIKit.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMMacOSTableRowData : NSObject +@property (nonatomic, strong) NSArray *cellTexts; +@property (nonatomic, strong) NSColor *backgroundColor; +@end + +/// Flipped NSView that draws the entire table (backgrounds, borders, text) in a +/// single drawRect: pass. Avoids all NSView subview hierarchy and CALayer +/// compositing issues on macOS where child views of layer-backed RCTUIViews +/// frequently fail to composite correctly. +@interface ENRMTableGridView : NSView + +@property (nonatomic, copy, nullable) NSMenu *_Nullable (^menuProvider)(void); + +- (void)updateWithRows:(NSArray *)rows + columnWidths:(NSArray *)columnWidths + rowHeights:(NSArray *)rowHeights + borderColor:(NSColor *)borderColor + borderWidth:(CGFloat)borderWidth + horizontalCellPadding:(CGFloat)horizontalCellPadding + verticalCellPadding:(CGFloat)verticalCellPadding + cornerRadius:(CGFloat)cornerRadius; + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.m b/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.m new file mode 100644 index 000000000000..257b5dc8ecd4 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMTableGridView.m @@ -0,0 +1,98 @@ +#import "ENRMTableGridView.h" +#import "ENRMMenuAction.h" + +#if TARGET_OS_OSX + +@implementation ENRMMacOSTableRowData +@end + +@implementation ENRMTableGridView { + NSArray *_tableRows; + NSArray *_columnWidths; + NSArray *_rowHeights; + NSColor *_borderColor; + CGFloat _borderWidth; + CGFloat _horizontalCellPadding; + CGFloat _verticalCellPadding; + CGFloat _cornerRadius; +} + +- (BOOL)isFlipped +{ + return YES; +} + +- (void)updateWithRows:(NSArray *)rows + columnWidths:(NSArray *)columnWidths + rowHeights:(NSArray *)rowHeights + borderColor:(NSColor *)borderColor + borderWidth:(CGFloat)borderWidth + horizontalCellPadding:(CGFloat)horizontalCellPadding + verticalCellPadding:(CGFloat)verticalCellPadding + cornerRadius:(CGFloat)cornerRadius +{ + _tableRows = rows; + _columnWidths = columnWidths; + _rowHeights = rowHeights; + _borderColor = borderColor; + _borderWidth = borderWidth; + _horizontalCellPadding = horizontalCellPadding; + _verticalCellPadding = verticalCellPadding; + _cornerRadius = cornerRadius; + [self setNeedsDisplay:YES]; +} + +- (NSMenu *)menuForEvent:(NSEvent *)event +{ + return _menuProvider ? _menuProvider() : [super menuForEvent:event]; +} + +- (void)drawRect:(NSRect)dirtyRect +{ + if (!_tableRows.count || !_columnWidths.count || !_rowHeights.count) + return; + + [[NSGraphicsContext currentContext] saveGraphicsState]; + + if (_cornerRadius > 0) { + [[NSBezierPath bezierPathWithRoundedRect:self.bounds xRadius:_cornerRadius yRadius:_cornerRadius] setClip]; + } + + CGFloat yOffset = 0; + for (NSUInteger r = 0; r < _tableRows.count; r++) { + ENRMMacOSTableRowData *rowData = _tableRows[r]; + CGFloat rowHeight = [_rowHeights[r] doubleValue]; + CGFloat xOffset = 0; + + for (NSUInteger c = 0; c < rowData.cellTexts.count; c++) { + CGFloat columnWidth = [_columnWidths[c] doubleValue]; + NSRect cellRect = NSMakeRect(xOffset, yOffset, columnWidth + _borderWidth, rowHeight + _borderWidth); + + [rowData.backgroundColor setFill]; + NSRectFill(cellRect); + + [_borderColor setStroke]; + NSBezierPath *border = [NSBezierPath bezierPathWithRect:cellRect]; + border.lineWidth = _borderWidth; + [border stroke]; + + NSAttributedString *text = rowData.cellTexts[c]; + if (text.length > 0) { + NSRect textRect = NSMakeRect(xOffset + _horizontalCellPadding, yOffset + _verticalCellPadding, + columnWidth - _horizontalCellPadding * 2, rowHeight - _verticalCellPadding * 2); + [text drawWithRect:textRect + options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading + context:nil]; + } + + xOffset += columnWidth; + } + yOffset += rowHeight; + } + + [[NSGraphicsContext currentContext] restoreGraphicsState]; +} + +@end + +#endif // TARGET_OS_OSX diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.h new file mode 100644 index 000000000000..0960bad52576 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#if !TARGET_OS_OSX + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^ENRMTableIOSLinkBlock)(NSString *url); + +typedef NS_ENUM(NSInteger, ENRMTableIOSItemKind) { + ENRMTableIOSItemKindLink, + ENRMTableIOSItemKindImage, +}; + +/// An interactive item found under a point of the grid. +@interface ENRMTableIOSItemHit : NSObject +@property (nonatomic, assign) ENRMTableIOSItemKind kind; +@property (nonatomic, copy) NSString *url; +@property (nonatomic, copy) NSString *sourceType; +/// The link's visible label, or an image's alt text. +@property (nonatomic, copy, nullable) NSString *title; +/// The item's frame in grid coordinates. +@property (nonatomic, assign) CGRect frame; +@end + +@interface ENRMTableIOSRowData : NSObject +@property (nonatomic, strong) NSArray *cellTexts; +@property (nonatomic, strong) UIColor *backgroundColor; +@end + +/// Draws the entire table grid in a single drawRect: pass, avoiding +/// per-cell UITextView allocation and the TextKit layout storms that +/// cause multi-second main-thread hangs on large tables. +@interface ENRMTableIOSGridView : UIView + +@property (nonatomic, copy, nullable) void (^onLinkTap)(NSString *url, NSString *sourceType); +@property (nonatomic, copy, nullable) ENRMTableIOSLinkBlock onLinkLongTap; +@property (nonatomic, copy, nullable) void (^onImageTap)(NSString *url, NSString *altText); +/// Asked when a touch lands on a link: a link with a menu is left to the context-menu +/// interaction, so the long-press recognizer must not take that touch. +@property (nonatomic, copy, nullable) BOOL (^hasLinkContextMenu)(NSString *url); +- (nullable ENRMTableIOSItemHit *)linkAtPoint:(CGPoint)point; + +- (void)updateWithRows:(NSArray *)rows + columnWidths:(NSArray *)columnWidths + rowHeights:(NSArray *)rowHeights + borderColor:(UIColor *)borderColor + borderWidth:(CGFloat)borderWidth + horizontalCellPadding:(CGFloat)horizontalCellPadding + verticalCellPadding:(CGFloat)verticalCellPadding + cornerRadius:(CGFloat)cornerRadius; + +- (void)fadeInRowsFrom:(NSUInteger)startRow duration:(NSTimeInterval)duration; + +@end + +NS_ASSUME_NONNULL_END + +#endif // !TARGET_OS_OSX diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.m b/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.m new file mode 100644 index 000000000000..8b31c8b4b5e2 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMTableIOSGridView.m @@ -0,0 +1,268 @@ +#import "ENRMTableIOSGridView.h" +#import "LinkTapUtils.h" + +#if !TARGET_OS_OSX + +@interface ENRMTableIOSGridView () +@end + +@implementation ENRMTableIOSItemHit +@end + +@implementation ENRMTableIOSRowData +@end + +@implementation ENRMTableIOSGridView { + NSArray *_tableRows; + NSArray *_columnWidths; + NSArray *_rowHeights; + UIColor *_borderColor; + CGFloat _borderWidth; + CGFloat _horizontalCellPadding; + CGFloat _verticalCellPadding; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + self.contentMode = UIViewContentModeRedraw; + self.opaque = NO; + self.accessibilityElementsHidden = YES; + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; + [self addGestureRecognizer:tap]; + + UILongPressGestureRecognizer *longPress = + [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.delegate = self; + [self addGestureRecognizer:longPress]; + } + return self; +} + +#pragma mark - Data + +- (void)updateWithRows:(NSArray *)rows + columnWidths:(NSArray *)columnWidths + rowHeights:(NSArray *)rowHeights + borderColor:(UIColor *)borderColor + borderWidth:(CGFloat)borderWidth + horizontalCellPadding:(CGFloat)horizontalCellPadding + verticalCellPadding:(CGFloat)verticalCellPadding + cornerRadius:(CGFloat)cornerRadius +{ + _tableRows = [rows copy]; + _columnWidths = [columnWidths copy]; + _rowHeights = [rowHeights copy]; + _borderColor = borderColor; + _borderWidth = borderWidth; + _horizontalCellPadding = horizontalCellPadding; + _verticalCellPadding = verticalCellPadding; + [self setNeedsDisplay]; +} + +- (void)fadeInRowsFrom:(NSUInteger)startRow duration:(NSTimeInterval)duration +{ + if (startRow >= _tableRows.count) + return; + + [UIView transitionWithView:self + duration:duration + options:UIViewAnimationOptionTransitionCrossDissolve + animations:^{} + completion:nil]; +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)dirtyRect +{ + if (!_tableRows.count || !_columnWidths.count || !_rowHeights.count) + return; + + CGFloat yOffset = 0; + for (NSUInteger r = 0; r < _tableRows.count; r++) { + ENRMTableIOSRowData *rowData = _tableRows[r]; + CGFloat rowHeight = [_rowHeights[r] doubleValue]; + CGFloat xOffset = 0; + + NSUInteger colCount = MIN(rowData.cellTexts.count, _columnWidths.count); + for (NSUInteger c = 0; c < colCount; c++) { + CGFloat columnWidth = [_columnWidths[c] doubleValue]; + CGRect cellRect = CGRectMake(xOffset, yOffset, columnWidth + _borderWidth, rowHeight + _borderWidth); + + [rowData.backgroundColor setFill]; + UIRectFill(cellRect); + + [_borderColor setStroke]; + UIBezierPath *border = [UIBezierPath bezierPathWithRect:cellRect]; + border.lineWidth = _borderWidth; + [border stroke]; + + NSAttributedString *text = rowData.cellTexts[c]; + if (text.length > 0) { + CGRect textRect = CGRectMake(xOffset + _horizontalCellPadding, yOffset + _verticalCellPadding, + columnWidth - _horizontalCellPadding * 2, rowHeight - _verticalCellPadding * 2); + [text drawWithRect:textRect + options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading + context:nil]; + } + + xOffset += columnWidth; + } + yOffset += rowHeight; + } +} + +#pragma mark - Link hit-testing + +- (BOOL)cellAtPoint:(CGPoint)point + rowOrigin:(out CGFloat *)outRowY + rowHeight:(out CGFloat *)outRowH + colOrigin:(out CGFloat *)outColX + colWidth:(out CGFloat *)outColW + cellText:(out NSAttributedString *__autoreleasing *)outText +{ + CGFloat rowY = 0; + for (NSUInteger r = 0; r < _tableRows.count; r++) { + CGFloat rh = [_rowHeights[r] doubleValue]; + if (point.y >= rowY && point.y < rowY + rh) { + CGFloat colX = 0; + for (NSUInteger c = 0; c < _columnWidths.count; c++) { + CGFloat cw = [_columnWidths[c] doubleValue]; + if (point.x >= colX && point.x < colX + cw) { + ENRMTableIOSRowData *rowData = _tableRows[r]; + if (c >= rowData.cellTexts.count) + return NO; + *outRowY = rowY; + *outRowH = rh; + *outColX = colX; + *outColW = cw; + *outText = rowData.cellTexts[c]; + return YES; + } + colX += cw; + } + return NO; + } + rowY += rh; + } + return NO; +} + +static ENRMTableIOSItemHit *itemInAttributedString(NSAttributedString *text, CGRect textRect, CGPoint point) +{ + if (text.length == 0) + return nil; + + NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:text]; + NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; + NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:textRect.size]; + textContainer.lineFragmentPadding = 0; + [layoutManager addTextContainer:textContainer]; + [textStorage addLayoutManager:layoutManager]; + [layoutManager ensureLayoutForTextContainer:textContainer]; + + CGPoint local = CGPointMake(point.x - textRect.origin.x, point.y - textRect.origin.y); + CGFloat fraction = 0; + NSUInteger glyphIndex = [layoutManager glyphIndexForPoint:local + inTextContainer:textContainer + fractionOfDistanceThroughGlyph:&fraction]; + if (glyphIndex >= layoutManager.numberOfGlyphs) + return nil; + NSUInteger charIndex = [layoutManager characterIndexForGlyphAtIndex:glyphIndex]; + if (charIndex >= text.length) + return nil; + + NSRange itemRange; + NSRange whole = NSMakeRange(0, text.length); + NSString *linkURL = [text attribute:@"linkURL" atIndex:charIndex longestEffectiveRange:&itemRange inRange:whole]; + NSString *imageURL = + linkURL ? nil : [text attribute:@"imageURL" atIndex:charIndex longestEffectiveRange:&itemRange inRange:whole]; + if (!linkURL && !imageURL) + return nil; + + NSRange glyphRange = [layoutManager glyphRangeForCharacterRange:itemRange actualCharacterRange:NULL]; + CGRect frame = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer]; + // Links keep nearest-glyph hits; an image needs the tap inside its bounds. + if (imageURL && !CGRectContainsPoint(frame, local)) + return nil; + + ENRMTableIOSItemHit *hit = [[ENRMTableIOSItemHit alloc] init]; + hit.kind = linkURL ? ENRMTableIOSItemKindLink : ENRMTableIOSItemKindImage; + hit.url = linkURL ?: imageURL; + hit.sourceType = [text attribute:@"linkSourceType" atIndex:charIndex effectiveRange:NULL] ?: @"markdown"; + hit.title = linkURL ? linkTitleAtIndex(text, charIndex) + : [text attribute:@"imageAltText" atIndex:charIndex effectiveRange:NULL]; + hit.frame = CGRectOffset(frame, textRect.origin.x, textRect.origin.y); + return hit; +} + +- (ENRMTableIOSItemHit *)itemAtPoint:(CGPoint)point +{ + CGFloat rowY, rowH, colX, colW; + NSAttributedString *text; + if (![self cellAtPoint:point rowOrigin:&rowY rowHeight:&rowH colOrigin:&colX colWidth:&colW cellText:&text]) + return nil; + + CGRect textRect = CGRectMake(colX + _horizontalCellPadding, rowY + _verticalCellPadding, + colW - _horizontalCellPadding * 2, rowH - _verticalCellPadding * 2); + if (!CGRectContainsPoint(textRect, point)) + return nil; + + return itemInAttributedString(text, textRect, point); +} + +- (ENRMTableIOSItemHit *)linkAtPoint:(CGPoint)point +{ + ENRMTableIOSItemHit *hit = [self itemAtPoint:point]; + return hit.kind == ENRMTableIOSItemKindLink ? hit : nil; +} + +#pragma mark - Gesture handlers + +- (void)handleLinkGesture:(UIGestureRecognizer *)recognizer block:(ENRMTableIOSLinkBlock)block +{ + CGPoint point = [recognizer locationInView:self]; + NSString *url = [self linkAtPoint:point].url; + if (url && block) { + block(url); + } +} + +- (void)handleTap:(UITapGestureRecognizer *)recognizer +{ + if (recognizer.state != UIGestureRecognizerStateEnded) + return; + ENRMTableIOSItemHit *hit = [self itemAtPoint:[recognizer locationInView:self]]; + if (!hit) + return; + if (hit.kind == ENRMTableIOSItemKindLink) { + if (self.onLinkTap) + self.onLinkTap(hit.url, hit.sourceType); + } else if (self.onImageTap) { + self.onImageTap(hit.url, hit.title ?: @""); + } +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch +{ + if (![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) + return YES; + // Reject before recognition so the context-menu interaction can own this touch. + NSString *url = [self linkAtPoint:[touch locationInView:self]].url; + return !(url && self.hasLinkContextMenu && self.hasLinkContextMenu(url)); +} + +- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer +{ + if (recognizer.state == UIGestureRecognizerStateBegan) { + [self handleLinkGesture:recognizer block:self.onLinkLongTap]; + } +} + +@end + +#endif // !TARGET_OS_OSX diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.h b/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.h new file mode 100644 index 000000000000..ce6a2fffb288 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.h @@ -0,0 +1,40 @@ +#pragma once +#import "ENRMFeatureFlags.h" + +#if ENRICHED_MARKDOWN_VIDEO + +#import "ENRMDynamicBlockProps.h" +#import "ENRMUIKit.h" +#import "StyleConfig.h" + +@class MarkdownASTNode; + +NS_ASSUME_NONNULL_BEGIN + +@interface ENRMVideoContainerView : RCTUIView +#if !TARGET_OS_OSX + +#endif + +- (instancetype)initWithConfig:(StyleConfig *)config; + +- (void)applyVideoNode:(MarkdownASTNode *)node; + +- (void)reapplyStyle; + +- (CGFloat)measureHeight:(CGFloat)maxWidth; + ++ (CGFloat)measureHeightForVideoNode:(MarkdownASTNode *)node config:(StyleConfig *)config maxWidth:(CGFloat)maxWidth; + +@property (nonatomic, strong) StyleConfig *config; + +// Shared, runtime-mutable block props (context-menu gate + copy labels) read live +// at menu-open. Set to the root's shared instance at creation. See +// ENRMDynamicBlockProps. +@property (nonatomic, strong) ENRMDynamicBlockProps *dynamicProps; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.m b/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.m new file mode 100644 index 000000000000..d3137e1597d5 --- /dev/null +++ b/packages/react-native-enriched-markdown/ios/segments/ENRMVideoContainerView.m @@ -0,0 +1,421 @@ +#import "ENRMFeatureFlags.h" + +#if ENRICHED_MARKDOWN_VIDEO + +#import "ENRMVideoContainerView.h" +#import "MarkdownASTNode.h" +#import "PasteboardUtils.h" +#import +#if TARGET_OS_OSX +#import "ENRMMenuAction.h" +#endif + +static const CGFloat kDefaultVideoAspectRatio = 16.0 / 9.0; + +static inline CGFloat ENRMVideoAspectRatio(StyleConfig *config) +{ + CGFloat aspectRatio = [config videoAspectRatio]; + return aspectRatio > 0 ? aspectRatio : kDefaultVideoAspectRatio; +} + +#if !TARGET_OS_OSX + +// A thin wrapper VC that hosts AVPlayerViewController as a child with correct +// containment. RNSScreen (react-native-screens) overrides +// shouldAutomaticallyForwardAppearanceMethods, so using our own intermediate VC +// lets us trigger appearance transitions explicitly and guarantees the player +// controls render. +@interface ENRMVideoHostController : UIViewController +@property (nonatomic, strong, readonly) AVPlayerViewController *playerViewController; +- (void)applyCornerRadius:(CGFloat)radius backgroundColor:(UIColor *)color; +@end + +@implementation ENRMVideoHostController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + self.view.backgroundColor = [UIColor clearColor]; + + _playerViewController = [[AVPlayerViewController alloc] init]; + _playerViewController.showsPlaybackControls = YES; + _playerViewController.entersFullScreenWhenPlaybackBegins = NO; + _playerViewController.exitsFullScreenWhenPlaybackEnds = YES; + _playerViewController.view.layer.masksToBounds = YES; + + [self addChildViewController:_playerViewController]; + [self.view addSubview:_playerViewController.view]; + [_playerViewController didMoveToParentViewController:self]; +} + +- (void)applyCornerRadius:(CGFloat)radius backgroundColor:(UIColor *)color +{ + _playerViewController.view.layer.cornerRadius = radius; + _playerViewController.view.backgroundColor = color ?: [UIColor blackColor]; +} + +- (void)viewDidLayoutSubviews +{ + [super viewDidLayoutSubviews]; + _playerViewController.view.frame = self.view.bounds; +} + +@end + +#endif // !TARGET_OS_OSX + +// ===== iOS implementation ===== + +#if !TARGET_OS_OSX + +static RCTUIView *ENRMCreatePlayIconOverlay(void) +{ + CGFloat size = 52; + RCTUIView *circle = [[RCTUIView alloc] initWithFrame:CGRectMake(0, 0, size, size)]; + circle.userInteractionEnabled = NO; + circle.layer.backgroundColor = [RCTUIColor colorWithWhite:0 alpha:0.5].CGColor; + circle.layer.cornerRadius = size / 2.0; + + CGFloat inset = size * 0.3; + CGFloat triLeft = inset + size * 0.04; + CGFloat triTop = inset - size * 0.04; + CGFloat triRight = size - inset + size * 0.04; + CGFloat triMid = size / 2.0; + + UIBezierPath *triangle = [UIBezierPath bezierPath]; + [triangle moveToPoint:CGPointMake(triLeft, triTop)]; + BezierPathAddLine(triangle, CGPointMake(triRight, triMid)); + BezierPathAddLine(triangle, CGPointMake(triLeft, size - triTop)); + [triangle closePath]; + + CAShapeLayer *triLayer = [CAShapeLayer layer]; + triLayer.path = triangle.CGPath; + triLayer.fillColor = [RCTUIColor whiteColor].CGColor; + [circle.layer addSublayer:triLayer]; + + return circle; +} + +@implementation ENRMVideoContainerView { + ENRMVideoHostController *_hostController; + RCTUIView *_playIconOverlay; + NSString *_currentURL; + BOOL _hostInstalled; + BOOL _hasBeenTapped; +} + +- (instancetype)initWithConfig:(StyleConfig *)config +{ + if (self = [super init]) { + _config = config; + _dynamicProps = [[ENRMDynamicBlockProps alloc] init]; + self.userInteractionEnabled = YES; + + _hostController = [[ENRMVideoHostController alloc] init]; + [_hostController loadViewIfNeeded]; + [_hostController applyCornerRadius:[config videoBorderRadius] backgroundColor:[config videoBackgroundColor]]; + [self addSubview:_hostController.view]; + + _playIconOverlay = ENRMCreatePlayIconOverlay(); + _playIconOverlay.userInteractionEnabled = NO; + [self addSubview:_playIconOverlay]; + + UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self]; + [_hostController.view addInteraction:contextMenu]; + } + return self; +} + +#pragma mark - Touch Forwarding + +- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event +{ + if (!self.userInteractionEnabled || self.hidden || self.alpha < 0.01) { + return nil; + } + if ([self pointInside:point withEvent:event]) { + if (!_hasBeenTapped) { + _hasBeenTapped = YES; + _playIconOverlay.hidden = YES; + } + return [_hostController.view hitTest:[self convertPoint:point toView:_hostController.view] withEvent:event]; + } + return nil; +} + +#pragma mark - View Controller Containment + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + if (self.window && !_hostInstalled) { + UIViewController *parentVC = [self enrm_closestViewController]; + if (parentVC) { + [parentVC addChildViewController:_hostController]; + [_hostController beginAppearanceTransition:YES animated:NO]; + [_hostController didMoveToParentViewController:parentVC]; + [_hostController endAppearanceTransition]; + _hostInstalled = YES; + } + } else if (!self.window && _hostInstalled) { + [_hostController beginAppearanceTransition:NO animated:NO]; + [_hostController endAppearanceTransition]; + [_hostController willMoveToParentViewController:nil]; + [_hostController removeFromParentViewController]; + _hostInstalled = NO; + } +} + +- (UIViewController *)enrm_closestViewController +{ + UIResponder *responder = self.nextResponder; + while (responder) { + if ([responder isKindOfClass:[UIViewController class]]) { + return (UIViewController *)responder; + } + responder = responder.nextResponder; + } + return nil; +} + +#pragma mark - Style Updates + +- (void)reapplyStyle +{ + [_hostController applyCornerRadius:[_config videoBorderRadius] backgroundColor:[_config videoBackgroundColor]]; +} + +#pragma mark - Video Loading + +- (void)applyVideoNode:(MarkdownASTNode *)node +{ + NSString *url = [node.attributes objectForKey:@"url"]; + if (!url || [url isEqualToString:_currentURL]) { + return; + } + _currentURL = [url copy]; + _hasBeenTapped = NO; + _playIconOverlay.hidden = NO; + + AVPlayerViewController *playerVC = _hostController.playerViewController; + [playerVC.player pause]; + + NSURL *videoURL = [NSURL URLWithString:url]; + if (!videoURL) { + playerVC.player = nil; + return; + } + + playerVC.player = [AVPlayer playerWithURL:videoURL]; +} + +#pragma mark - Layout & Measurement + +- (void)layoutSubviews +{ + [super layoutSubviews]; + _hostController.view.frame = self.bounds; + _playIconOverlay.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); +} + +- (CGFloat)measureHeight:(CGFloat)maxWidth +{ + return maxWidth / ENRMVideoAspectRatio(_config); +} + ++ (CGFloat)measureHeightForVideoNode:(__unused MarkdownASTNode *)node + config:(StyleConfig *)config + maxWidth:(CGFloat)maxWidth +{ + return maxWidth / ENRMVideoAspectRatio(config); +} + +#pragma mark - Context Menu + +- (void)copyURLToPasteboard +{ + if (_currentURL.length > 0) { + copyStringToPasteboard(_currentURL); + } +} + +- (void)copyMarkdownToPasteboard +{ + if (_currentURL.length > 0) { + NSString *markdown; + if ([_currentURL containsString:@"\""]) { + markdown = [NSString stringWithFormat:@"