From ffcfbd7feb028782f518b942ecdb377c0e8e530c Mon Sep 17 00:00:00 2001
From: wibus-wee <62133302+wibus-wee@users.noreply.github.com>
Date: Fri, 20 Nov 2026 17:01:14 +0800
Subject: [PATCH] perf(components): lazy-load Monaco editor and pdfjs viewer
Monaco (~3.7MB) and pdfjs were statically imported by the session file
viewer, so every app load paid for both even when the user never opened
a code file or a PDF. Follow the existing office-preview convention and
load them on demand.
- SessionMonacoTextViewer -> LazySessionMonacoTextViewer (React.lazy +
Suspense, Spinner fallback) at both call sites in
session-file-content-view and the two in mobile-project-file-browser.
- session-monaco-language-providers kept a top-level monaco import just
for monaco.Uri. The code-collab URI scheme + fileId->provider registry
moved to code-collab-monaco-model-provider.ts, which is monaco-free
(hand-rolled URI build/parse, byte-identical to monaco.Uri output).
The old module re-exports it and keeps monaco only for the language
providers that run inside the editor chunk.
- SessionFilePdfPreview -> lazy() + Suspense, matching the office
renderer pattern. pdf-file-preview's static pdfjs import became
type-only; createLocalPdfRangeTransport dynamically imports the new
pdf-range-transport module.
Electron renderer build emits session-monaco-text-viewer-*.js (3.69MB),
pdf-*.js (495kB) and session-file-pdf-preview-*.js (229kB) as async
chunks; the main entry no longer contains monaco/pdfjs code.
Model: magpie/orchestrator
---
.../files/mobile-project-file-browser.tsx | 6 +-
.../lazy-session-monaco-text-viewer.tsx | 43 ++++
.../sessions/session-file-binary-preview.tsx | 45 +++-
.../sessions/session-file-content-view.tsx | 20 +-
.../sessions/session-monaco-text-viewer.tsx | 6 +-
.../lib/code-collab-monaco-model-provider.ts | 195 ++++++++++++++++++
.../components/src/lib/pdf-file-preview.ts | 46 ++---
.../components/src/lib/pdf-range-transport.ts | 46 +++++
.../lib/session-monaco-editor-controller.ts | 17 +-
.../lib/session-monaco-language-providers.ts | 85 ++------
10 files changed, 376 insertions(+), 133 deletions(-)
create mode 100644 packages/components/src/components/sessions/lazy-session-monaco-text-viewer.tsx
create mode 100644 packages/components/src/lib/code-collab-monaco-model-provider.ts
create mode 100644 packages/components/src/lib/pdf-range-transport.ts
diff --git a/packages/components/src/components/files/mobile-project-file-browser.tsx b/packages/components/src/components/files/mobile-project-file-browser.tsx
index 6270705107..5bac6df4f2 100644
--- a/packages/components/src/components/files/mobile-project-file-browser.tsx
+++ b/packages/components/src/components/files/mobile-project-file-browser.tsx
@@ -38,7 +38,7 @@ import { SessionFileImagePreview } from '@/components/sessions/session-file-imag
import { SessionFileVideoPreview } from '@/components/sessions/session-file-video-preview';
import { MarkdownRenderer } from '@/components/ai-gui/markdown-renderer';
import { MarkdownFileResources } from '@/components/ai-gui/markdown-file-image';
-import { SessionMonacoTextViewer } from '@/components/sessions/session-monaco-text-viewer';
+import { LazySessionMonacoTextViewer } from '@/components/sessions/lazy-session-monaco-text-viewer';
import { SessionShikiTextViewer } from '@/components/sessions/session-shiki-text-viewer';
import { useFileWorkspaceTree } from '@/hooks/use-code-session';
import { isNativeAppShell } from '@/lib/native-platform';
@@ -878,7 +878,7 @@ function MobileTextPreview({
) : showHtml ? (
) : (
-
- ;
+
+const styles = stylex.create({
+ loading: {
+ display: 'flex',
+ height: '100%',
+ minHeight: 0,
+ width: '100%',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+});
+
+const LazyMonacoViewer = lazy(() =>
+ import('./session-monaco-text-viewer').then((module) => ({
+ default: module.SessionMonacoTextViewer,
+ }))
+);
+
+/**
+ * Code-splits the Monaco editor bundle: `session-monaco-text-viewer` and
+ * everything it imports (`monaco-editor` JS/CSS, workers, language
+ * registrations) load only when a text surface actually mounts the
+ * viewer. The fallback paints a centered spinner while the chunk loads.
+ */
+export function LazySessionMonacoTextViewer(props: SessionMonacoTextViewerProps) {
+ return (
+
+
+
+ }
+ >
+
+
+ );
+}
diff --git a/packages/components/src/components/sessions/session-file-binary-preview.tsx b/packages/components/src/components/sessions/session-file-binary-preview.tsx
index 99e48f42f4..c08d2a74e4 100644
--- a/packages/components/src/components/sessions/session-file-binary-preview.tsx
+++ b/packages/components/src/components/sessions/session-file-binary-preview.tsx
@@ -1,6 +1,8 @@
+import * as stylex from '@stylexjs/stylex';
import type { SessionFileErrorActions } from '@/lib/session-file-actions';
-import { memo } from 'react';
+import { lazy, memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
+import { Spinner } from '@lody/ui/spinner';
import { getImageMimeTypeForPath } from '@/lib/image-file-preview';
import { isPdfFilePath } from '@/lib/pdf-file-preview';
import { getOfficePreviewKind } from '@/lib/session-file-office-source';
@@ -8,11 +10,29 @@ import { getVideoMimeTypeForPath } from '@/lib/video-file-preview';
import { SessionFileVideoPreview } from './session-file-video-preview';
import { SessionFileImagePreview } from './session-file-image-preview';
import { SessionFileOfficePreview } from './session-file-office-preview';
-import { SessionFilePdfPreview } from './session-file-pdf-preview';
import { SessionFileNoticeCard } from './session-file-error-state';
import { DocumentSelectionSurface } from './document-selection-surface';
import type { DocumentSelection } from '@/lib/document-selection';
+// `pdfjs-dist` (JS + viewer CSS + worker URL) stays out of the eager
+// file-viewer chunk; it loads only when a PDF preview actually mounts,
+// matching how `SessionFileOfficePreview` lazy-loads its renderers.
+const LazySessionFilePdfPreview = lazy(() =>
+ import('./session-file-pdf-preview').then((module) => ({
+ default: module.SessionFilePdfPreview,
+ }))
+);
+
+const styles = stylex.create({
+ loading: {
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+});
+
interface SessionFileBinaryPreviewProps {
readonly path: string;
readonly bytes?: Uint8Array;
@@ -73,12 +93,21 @@ function BinaryPreviewContent({
if (isPdfFilePath(path) && (url || bytes !== undefined)) {
return (
-
+
+
+ {t('sessions.fileViewer.pdf.loading', 'Loading PDF…')}
+
+ }
+ >
+
+
);
}
diff --git a/packages/components/src/components/sessions/session-file-content-view.tsx b/packages/components/src/components/sessions/session-file-content-view.tsx
index 78a40a5536..ad25e3a622 100644
--- a/packages/components/src/components/sessions/session-file-content-view.tsx
+++ b/packages/components/src/components/sessions/session-file-content-view.tsx
@@ -98,10 +98,8 @@ import { usePostHog } from '@posthog/react';
import { capturePostHogEvent, getAnalyticsFileKind } from '@/lib/posthog-analytics';
import { useCodeCollabLiveText } from '@/hooks/use-code-collab-live-text';
import { useMachineFlockRows } from '@/hooks/use-machine-flock-rows';
-import {
- SessionMonacoTextViewer,
- type SessionMonacoExternalTextUpdate,
-} from './session-monaco-text-viewer';
+import { LazySessionMonacoTextViewer } from './lazy-session-monaco-text-viewer';
+import type { SessionMonacoExternalTextUpdate } from './session-monaco-text-viewer';
import {
useCodeCollabSaveText,
type SessionFileLiveSyncStatus,
@@ -114,7 +112,7 @@ import { useLatestRef } from '@/hooks/use-latest-ref';
import {
buildCodeCollabMonacoUri,
registerCodeCollabMonacoModelProvider,
-} from '@/lib/session-monaco-language-providers';
+} from '@/lib/code-collab-monaco-model-provider';
import {
normalizeSessionMonacoSelectedLines,
type SessionMonacoSelectedLines,
@@ -1499,6 +1497,8 @@ function SessionFileContentViewImpl({
// so Cmd-click / F12 reach the right provider when multiple files are
// open. Unregisters on unmount or when the active fileId / provider
// changes so a stale entry can't intercept a different mount.
+ // The URI is a serialized `code-collab://` string built without
+ // `monaco-editor`; the lazy viewer parses it once its chunk loads.
const lspModelUri = useMemo(
() =>
isLspEnabled && lspFileId ? buildCodeCollabMonacoUri(lspFileId, normalizedPath) : undefined,
@@ -1788,7 +1788,7 @@ function SessionFileContentViewImpl({
/>
) : (
;
+ return ;
}
function LazyTextMonacoViewer(props: SessionTextMonacoViewerProps) {
- return ;
+ return ;
}
type SessionTextMonacoViewerProps = {
@@ -2807,5 +2807,7 @@ type SessionTextMonacoViewerProps = {
readonly externalTextUpdate?: SessionMonacoExternalTextUpdate;
readonly onExternalTextUpdateApplied?: (result: 'applied' | 'no-op') => void;
readonly findRequestSeq?: number;
- readonly modelUri?: import('monaco-editor/esm/vs/editor/editor.api.js').Uri;
+ // Serialized `code-collab://` model URI; kept as a string so this module
+ // never needs the `monaco-editor` import.
+ readonly modelUri?: string;
};
diff --git a/packages/components/src/components/sessions/session-monaco-text-viewer.tsx b/packages/components/src/components/sessions/session-monaco-text-viewer.tsx
index 129b8324fe..e133c360ee 100644
--- a/packages/components/src/components/sessions/session-monaco-text-viewer.tsx
+++ b/packages/components/src/components/sessions/session-monaco-text-viewer.tsx
@@ -101,13 +101,15 @@ export function SessionMonacoTextViewer({
readonly character: number;
}) => void;
readonly onScrollChange?: (state: { readonly scrollTop: number }) => void;
- // Optional Monaco model URI. When provided the viewer creates the
+ // Optional serialized Monaco model URI (e.g. from
+ // `buildCodeCollabMonacoUri`). When provided the viewer creates the
// model under this URI, which lets Monaco's globally-registered
// Code Collab definition/reference providers (see
// `lib/session-monaco-language-providers`) attach via the
// `code-collab://` scheme. Defaults to Monaco's auto-generated
// URI so non-collab callers (story/diff viewer) keep working unchanged.
- readonly modelUri?: monaco.Uri;
+ // Serialized so callers can build it without importing `monaco-editor`.
+ readonly modelUri?: string;
readonly className?: string;
}) {
const containerRef = useRef(null);
diff --git a/packages/components/src/lib/code-collab-monaco-model-provider.ts b/packages/components/src/lib/code-collab-monaco-model-provider.ts
new file mode 100644
index 0000000000..1dfda7801f
--- /dev/null
+++ b/packages/components/src/lib/code-collab-monaco-model-provider.ts
@@ -0,0 +1,195 @@
+import type { SessionFileProvider } from './session-file-provider';
+
+// Code Collab Monaco models use this URI scheme so a single global
+// `registerDefinitionProvider` / `registerReferenceProvider` can pick
+// them out from other Monaco models in the page. The authority carries
+// the fileId; the path carries the workspace path so Monaco can infer
+// extension-specific language behavior for TSX/JSX while LSP lookup still
+// keys only by fileId.
+//
+// This module is deliberately free of `monaco-editor` imports so the file
+// viewer can build model URIs and own provider registrations without
+// pulling the editor bundle into the eager graph. The URI helpers
+// reproduce `monaco.Uri` (vscode-uri) `from`/`parse` serialization for
+// the restricted scheme/authority/path shape used here; the Monaco side
+// parses the string form with `monaco.Uri.parse` once the editor chunk
+// has loaded.
+export const CODE_COLLAB_MONACO_URI_SCHEME = 'code-collab';
+
+// vscode-uri's explicit escape table: these characters get a fixed
+// `%XX` escape instead of `encodeURIComponent` (which would leave
+// `!'()*` literal).
+const URI_ESCAPE_TABLE: Record = {
+ 58: '%3A', // :
+ 47: '%2F', // /
+ 63: '%3F', // ?
+ 35: '%23', // #
+ 91: '%5B', // [
+ 93: '%5D', // ]
+ 64: '%40', // @
+ 33: '%21', // !
+ 36: '%24', // $
+ 38: '%26', // &
+ 39: '%27', // '
+ 40: '%28', // (
+ 41: '%29', // )
+ 42: '%2A', // *
+ 43: '%2B', // +
+ 44: '%2C', // ,
+ 59: '%3B', // ;
+ 61: '%3D', // =
+ 32: '%20', // space
+};
+
+// Percent-encodes URI components the way `monaco.Uri` (vscode-uri)
+// `toString` does. For paths (`encodeURIComponentFast`) unreserved marks
+// pass through, `/` is allowed, and everything else takes the fixed
+// escape from `URI_ESCAPE_TABLE` or `encodeURIComponent`.
+function encodeUriComponentFast(value: string, allowSlash: boolean): string {
+ let result = '';
+ for (const char of value) {
+ const code = char.codePointAt(0) ?? 0;
+ const isUnreserved =
+ (code >= 0x61 && code <= 0x7a) || // a-z
+ (code >= 0x41 && code <= 0x5a) || // A-Z
+ (code >= 0x30 && code <= 0x39) || // 0-9
+ char === '-' ||
+ char === '.' ||
+ char === '_' ||
+ char === '~';
+ if (isUnreserved || (allowSlash && char === '/')) {
+ result += char;
+ } else {
+ result += URI_ESCAPE_TABLE[code] ?? encodeURIComponent(char);
+ }
+ }
+ return result;
+}
+
+// `monaco.Uri.toString` splits the lowercased authority into
+// `userinfo@host:port` at the FIRST `@` (extra `@`s belong to userinfo)
+// and the last `:` of the host portion (port separator). Each segment is
+// encoded with `encodeURIComponentFast`, except the host keeps
+// `:`/`[`/`]` literal (port / IPv6 syntax).
+function encodeUriAuthority(authority: string): string {
+ let rest = authority.toLowerCase();
+ let userinfo = '';
+ const atIndex = rest.indexOf('@');
+ if (atIndex !== -1) {
+ const user = rest.slice(0, atIndex);
+ rest = rest.slice(atIndex + 1);
+ const colonIndex = user.indexOf(':');
+ userinfo =
+ colonIndex === -1
+ ? `${encodeUriComponentFast(user, false)}@`
+ : `${encodeUriComponentFast(user.slice(0, colonIndex), false)}:${encodeUriComponentFast(user.slice(colonIndex + 1), false)}@`;
+ }
+ const colonIndex = rest.lastIndexOf(':');
+ if (colonIndex === -1) {
+ return userinfo + encodeUriComponentFastAuthorityHost(rest);
+ }
+ return (
+ userinfo +
+ encodeUriComponentFastAuthorityHost(rest.slice(0, colonIndex)) +
+ rest.slice(colonIndex)
+ );
+}
+
+// Host portion of the authority: `encodeURIComponentFast` with `:`, `[`
+// and `]` kept literal.
+function encodeUriComponentFastAuthorityHost(host: string): string {
+ let result = '';
+ for (const char of host) {
+ result +=
+ char === ':' || char === '[' || char === ']' ? char : encodeUriComponentFast(char, false);
+ }
+ return result;
+}
+
+/**
+ * Builds the serialized `code-collab:///` model URI,
+ * identical to `monaco.Uri.from({scheme, authority, path}).toString()`
+ * (authority is lowercased like `Uri`'s host normalization). Returns a
+ * string instead of `monaco.Uri` so callers do not need the editor
+ * bundle; the Monaco viewer parses it with `monaco.Uri.parse`, whose
+ * `uri.toString()` reproduces this same string for `getModel` reuse.
+ */
+export function buildCodeCollabMonacoUri(fileId: string, filePath?: string): string {
+ const normalizedPath = filePath?.replace(/\\/g, '/').replace(/^\/+/, '');
+ const path = normalizedPath && normalizedPath.length > 0 ? `/${normalizedPath}` : '/';
+ // `Uri.toString` omits the `//` entirely when the authority is empty.
+ const authority = fileId.length > 0 ? `//${encodeUriAuthority(fileId)}` : '';
+ return `${CODE_COLLAB_MONACO_URI_SCHEME}:${authority}${encodeUriComponentFast(path, true)}`;
+}
+
+/**
+ * Reads the fileId (URI authority) back out of a serialized Code Collab
+ * model URI — the same value `uri.authority` yields after
+ * `monaco.Uri.parse`, i.e. percent-decoded. Returns `undefined` for
+ * other schemes or a missing authority.
+ */
+export function readFileIdFromCodeCollabMonacoUri(modelUri: string): string | undefined {
+ const schemeSeparator = modelUri.indexOf('://');
+ if (
+ schemeSeparator === -1 ||
+ modelUri.slice(0, schemeSeparator) !== CODE_COLLAB_MONACO_URI_SCHEME
+ ) {
+ return undefined;
+ }
+ const rest = modelUri.slice(schemeSeparator + 3);
+ const pathStart = rest.indexOf('/');
+ const authority = pathStart === -1 ? rest : rest.slice(0, pathStart);
+ if (authority.length === 0) return undefined;
+ try {
+ return decodeURIComponent(authority);
+ } catch {
+ // Keep undecodable input verbatim, mirroring monaco's lenient
+ // percent decoder.
+ return authority;
+ }
+}
+
+// Registry mapping fileId → stack of SessionFileProviders. Each
+// `SessionFileContentView` mount pushes its provider; the unmount
+// removes that specific entry. Two concurrent mounts (e.g. diff
+// viewer + editor on the same file) are common, so single-slot
+// storage would let either unmount delete the entry the other still
+// depends on. The stack lets the most-recently-mounted viewer drive
+// the language providers while every mount safely owns one entry's
+// worth of lifecycle.
+const providerRegistry = new Map();
+
+export function registerCodeCollabMonacoModelProvider(
+ fileId: string,
+ provider: SessionFileProvider
+): () => void {
+ let stack = providerRegistry.get(fileId);
+ if (!stack) {
+ stack = [];
+ providerRegistry.set(fileId, stack);
+ }
+ stack.push(provider);
+ return () => {
+ const current = providerRegistry.get(fileId);
+ if (!current) return;
+ // `lastIndexOf` so a re-mount that happens to reuse the same
+ // provider instance still removes its own most-recent entry.
+ const index = current.lastIndexOf(provider);
+ if (index >= 0) {
+ current.splice(index, 1);
+ }
+ if (current.length === 0) {
+ providerRegistry.delete(fileId);
+ }
+ };
+}
+
+/** Latest mounted provider for the fileId carried by `modelUri`. */
+export function findCodeCollabMonacoModelProvider(
+ modelUri: string
+): SessionFileProvider | undefined {
+ const fileId = readFileIdFromCodeCollabMonacoUri(modelUri);
+ if (!fileId) return undefined;
+ const stack = providerRegistry.get(fileId);
+ return stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
+}
diff --git a/packages/components/src/lib/pdf-file-preview.ts b/packages/components/src/lib/pdf-file-preview.ts
index 2de01cd1d6..a42a0511f7 100644
--- a/packages/components/src/lib/pdf-file-preview.ts
+++ b/packages/components/src/lib/pdf-file-preview.ts
@@ -1,4 +1,4 @@
-import { PDFDataRangeTransport } from 'pdfjs-dist/legacy/build/pdf.mjs';
+import type { PDFDataRangeTransport } from 'pdfjs-dist/legacy/build/pdf.mjs';
export const PDF_RANGE_CHUNK_BYTES = 64 * 1024;
@@ -10,7 +10,7 @@ interface PdfRangeTransportOptions {
readonly fetchImpl?: typeof fetch;
}
-interface PdfRangeResult {
+export interface PdfRangeResult {
readonly bytes: Uint8Array;
readonly length: number;
}
@@ -20,41 +20,19 @@ export async function createLocalPdfRangeTransport({
signal,
fetchImpl = fetch,
}: PdfRangeTransportOptions): Promise {
+ // `pdfjs-dist` is loaded lazily: this module stays on the eager file-viewer
+ // path for `isPdfFilePath`, so the transport implementation is imported
+ // only when a PDF preview actually runs. The dynamic import resolves to
+ // an already-loaded module once the preview bundle is up.
+ const { createPdfRangeTransport } = await import('./pdf-range-transport');
const initial = await readPdfRange(fetchImpl, url, 0, PDF_RANGE_CHUNK_BYTES, signal);
- return new LocalPdfRangeTransport(url, initial, fetchImpl, signal);
+ return createPdfRangeTransport(initial, signal, (begin, end, rangeSignal, knownLength) =>
+ readPdfRange(fetchImpl, url, begin, end, rangeSignal, knownLength)
+ );
}
-class LocalPdfRangeTransport extends PDFDataRangeTransport {
- private readonly controller = new AbortController();
-
- constructor(
- private readonly url: string,
- initial: PdfRangeResult,
- private readonly fetchImpl: typeof fetch,
- signal: AbortSignal
- ) {
- super(initial.length, initial.bytes);
- if (signal.aborted) {
- this.abort();
- } else {
- signal.addEventListener('abort', () => this.abort(), { once: true });
- }
- }
-
- override requestDataRange(begin: number, end: number): void {
- void readPdfRange(this.fetchImpl, this.url, begin, end, this.controller.signal, this.length)
- .then(({ bytes }) => this.onDataRange(begin, bytes))
- .catch(() => {
- if (!this.controller.signal.aborted) {
- this.onDataRange(begin, new Uint8Array());
- this.abort();
- }
- });
- }
-
- override abort(): void {
- this.controller.abort();
- }
+export interface PdfRangeReader {
+ (begin: number, end: number, signal: AbortSignal, knownLength?: number): Promise;
}
async function readPdfRange(
diff --git a/packages/components/src/lib/pdf-range-transport.ts b/packages/components/src/lib/pdf-range-transport.ts
new file mode 100644
index 0000000000..0451668169
--- /dev/null
+++ b/packages/components/src/lib/pdf-range-transport.ts
@@ -0,0 +1,46 @@
+import { PDFDataRangeTransport } from 'pdfjs-dist/legacy/build/pdf.mjs';
+import type { PdfRangeReader, PdfRangeResult } from './pdf-file-preview';
+
+// Range transport used by the lazy PDF preview. Lives in its own module so
+// `pdf-file-preview.ts` can keep `isPdfFilePath` on the eager file-viewer
+// path without statically importing `pdfjs-dist`; this module is reached
+// only through the dynamic `import()` in `createLocalPdfRangeTransport`.
+export function createPdfRangeTransport(
+ initial: PdfRangeResult,
+ signal: AbortSignal,
+ readRange: PdfRangeReader
+): PDFDataRangeTransport {
+ return new LocalPdfRangeTransport(initial, signal, readRange);
+}
+
+class LocalPdfRangeTransport extends PDFDataRangeTransport {
+ private readonly controller = new AbortController();
+
+ constructor(
+ initial: PdfRangeResult,
+ signal: AbortSignal,
+ private readonly readRange: PdfRangeReader
+ ) {
+ super(initial.length, initial.bytes);
+ if (signal.aborted) {
+ this.abort();
+ } else {
+ signal.addEventListener('abort', () => this.abort(), { once: true });
+ }
+ }
+
+ override requestDataRange(begin: number, end: number): void {
+ void this.readRange(begin, end, this.controller.signal, this.length)
+ .then(({ bytes }) => this.onDataRange(begin, bytes))
+ .catch(() => {
+ if (!this.controller.signal.aborted) {
+ this.onDataRange(begin, new Uint8Array());
+ this.abort();
+ }
+ });
+ }
+
+ override abort(): void {
+ this.controller.abort();
+ }
+}
diff --git a/packages/components/src/lib/session-monaco-editor-controller.ts b/packages/components/src/lib/session-monaco-editor-controller.ts
index dba1b875d4..8fc1e51aa2 100644
--- a/packages/components/src/lib/session-monaco-editor-controller.ts
+++ b/packages/components/src/lib/session-monaco-editor-controller.ts
@@ -51,7 +51,9 @@ export type SessionMonacoEditorControllerOptions = {
readonly initialTheme: string;
readonly initialReadOnly: boolean;
readonly initialWordWrap: boolean;
- readonly initialModelUri?: monaco.Uri;
+ // Serialized `monaco.Uri` (e.g. `code-collab:///`), kept as a
+ // string so callers can build it without importing the editor bundle.
+ readonly initialModelUri?: string;
readonly callbacks: SessionMonacoEditorCallbacks;
};
@@ -75,17 +77,14 @@ export class SessionMonacoEditorController {
// `createModel` rejects duplicate URIs. If a peer mount already
// built a model for our URI, reuse it — and remember not to
// dispose it during teardown.
- const existingModel = options.initialModelUri
- ? monaco.editor.getModel(options.initialModelUri)
- : null;
+ const modelUri = options.initialModelUri
+ ? monaco.Uri.parse(options.initialModelUri)
+ : undefined;
+ const existingModel = modelUri ? monaco.editor.getModel(modelUri) : null;
this.ownsModel = !existingModel;
this.model =
existingModel ??
- monaco.editor.createModel(
- options.initialText,
- options.initialLanguage,
- options.initialModelUri
- );
+ monaco.editor.createModel(options.initialText, options.initialLanguage, modelUri);
this.editor = monaco.editor.create(options.container, {
model: this.model,
diff --git a/packages/components/src/lib/session-monaco-language-providers.ts b/packages/components/src/lib/session-monaco-language-providers.ts
index 6688bfa589..38410f443c 100644
--- a/packages/components/src/lib/session-monaco-language-providers.ts
+++ b/packages/components/src/lib/session-monaco-language-providers.ts
@@ -1,71 +1,18 @@
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
import { isRecord } from '@lody/shared';
import { parseCodeCollabLspLocations, type CodeCollabLspLocation } from './code-collab-lsp-result';
-import { hasSessionFileLspProvider, type SessionFileProvider } from './session-file-provider';
+import { hasSessionFileLspProvider } from './session-file-provider';
+import {
+ CODE_COLLAB_MONACO_URI_SCHEME,
+ findCodeCollabMonacoModelProvider,
+ readFileIdFromCodeCollabMonacoUri,
+} from './code-collab-monaco-model-provider';
-// Code Collab Monaco models use this URI scheme so a single global
-// `registerDefinitionProvider` / `registerReferenceProvider` can pick
-// them out from other Monaco models in the page. The authority carries
-// the fileId; the path carries the workspace path so Monaco can infer
-// extension-specific language behavior for TSX/JSX while LSP lookup still
-// keys only by fileId.
-export const CODE_COLLAB_MONACO_URI_SCHEME = 'code-collab';
-
-export function buildCodeCollabMonacoUri(fileId: string, filePath?: string): monaco.Uri {
- const normalizedPath = filePath?.replace(/\\/g, '/').replace(/^\/+/, '');
- return monaco.Uri.from({
- scheme: CODE_COLLAB_MONACO_URI_SCHEME,
- authority: fileId,
- path: normalizedPath && normalizedPath.length > 0 ? `/${normalizedPath}` : '/',
- });
-}
-
-export function readFileIdFromCodeCollabMonacoUri(uri: monaco.Uri): string | undefined {
- if (uri.scheme !== CODE_COLLAB_MONACO_URI_SCHEME) return undefined;
- return uri.authority || undefined;
-}
-
-// Registry mapping fileId → stack of SessionFileProviders. Each
-// `SessionFileContentView` mount pushes its provider; the unmount
-// removes that specific entry. Two concurrent mounts (e.g. diff
-// viewer + editor on the same file) are common, so single-slot
-// storage would let either unmount delete the entry the other still
-// depends on. The stack lets the most-recently-mounted viewer drive
-// the language providers while every mount safely owns one entry's
-// worth of lifecycle.
-const providerRegistry = new Map();
-
-export function registerCodeCollabMonacoModelProvider(
- fileId: string,
- provider: SessionFileProvider
-): () => void {
- let stack = providerRegistry.get(fileId);
- if (!stack) {
- stack = [];
- providerRegistry.set(fileId, stack);
- }
- stack.push(provider);
- return () => {
- const current = providerRegistry.get(fileId);
- if (!current) return;
- // `lastIndexOf` so a re-mount that happens to reuse the same
- // provider instance still removes its own most-recent entry.
- const index = current.lastIndexOf(provider);
- if (index >= 0) {
- current.splice(index, 1);
- }
- if (current.length === 0) {
- providerRegistry.delete(fileId);
- }
- };
-}
-
-function findProviderForUri(uri: monaco.Uri): SessionFileProvider | undefined {
- const fileId = readFileIdFromCodeCollabMonacoUri(uri);
- if (!fileId) return undefined;
- const stack = providerRegistry.get(fileId);
- return stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
-}
+export {
+ buildCodeCollabMonacoUri,
+ readFileIdFromCodeCollabMonacoUri,
+ registerCodeCollabMonacoModelProvider,
+} from './code-collab-monaco-model-provider';
// Helper for parsing the host response: walks `locations` only when
// status is `'ready'`. Everything else (`'unsupported'` / malformed)
@@ -112,8 +59,9 @@ export function ensureCodeCollabMonacoLanguageProviders(): void {
{ scheme: CODE_COLLAB_MONACO_URI_SCHEME },
{
async provideDefinition(model, position) {
- const provider = findProviderForUri(model.uri);
- const fileId = readFileIdFromCodeCollabMonacoUri(model.uri);
+ const modelUri = model.uri.toString();
+ const provider = findCodeCollabMonacoModelProvider(modelUri);
+ const fileId = readFileIdFromCodeCollabMonacoUri(modelUri);
if (!hasSessionFileLspProvider(provider) || !fileId) {
return null;
}
@@ -144,8 +92,9 @@ export function ensureCodeCollabMonacoLanguageProviders(): void {
{ scheme: CODE_COLLAB_MONACO_URI_SCHEME },
{
async provideReferences(model, position) {
- const provider = findProviderForUri(model.uri);
- const fileId = readFileIdFromCodeCollabMonacoUri(model.uri);
+ const modelUri = model.uri.toString();
+ const provider = findCodeCollabMonacoModelProvider(modelUri);
+ const fileId = readFileIdFromCodeCollabMonacoUri(modelUri);
if (!hasSessionFileLspProvider(provider) || !fileId) {
return null;
}