// The CodeChat Editor, a word processor for software developers.
Copyright // (C) 2024-2026 Bryan A. Jones. // // This file is part of the CodeChat Editor. The CodeChat Editor is free // software: you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // The CodeChat Editor is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // the CodeChat Editor. If not, see // [http://www.gnu.org/licenses](http://www.gnu.org/licenses). // // `CodeChatEditorFramework.mts` -- the CodeChat Editor Client Framework // ===================================================================== // // This maintains a websocket connection with the CodeChat Editor Server. The // accompanying HTML is a full-screen iframe, allowing the Framework to change // or update the webpage in response to messages received from the websocket, or // to report navigation events as a websocket message when the iframe's location // changes. // // Imports // ------- // // ### Third-party import ReconnectingWebSocket from "./third-party/ReconnectingWebSocket.cjs"; // ### Local import { assert } from "./assert.mjs"; import { consoleLog, MAX_MESSAGE_LENGTH } from "./debug_enabled.mjs"; import { CodeChatForWeb, EditorMessage, EditorMessageContents, getErrorMessage, KeysOfRustEnum, MessageResult, UpdateMessageContents, } from "./shared.mjs"; import { onError, onDomContentLoaded } from "./CodeChatEditor.mjs"; import { showToast as showToastCore, TOAST_NO_TIMEOUT } from "./show_toast.mjs"; import { ResultErrTypes } from "./rust-types/ResultErrTypes.js"; import { CursorPosition } from "./rust-types/CursorPosition.js"; // Websocket // --------- // // This code communicates with the CodeChat Editor Server via its websocket // interface. // // The timeout for a websocket `Response`, in ms. const RESPONSE_TIMEOUT_MS = 15000; // An instance of the websocket communication class. let webSocketComm: WebSocketComm; class WebSocketComm { // The initial websocket ID for a Client. Use a unique ID for each websocket // message sent. wsId = 4; // The websocket used by this class. Really a `ReconnectingWebSocket`, but // that's not a type. ws: WebSocket; // A map of message id to (timer id, resolver) for all pending messages. pendingMessages: Record< number, { // Undefined until `send` transmits the message. timerId?: number; // Settles the promise which `sendMessage` returned. resolve: (result: MessageResult) => void; } > = {}; // Messages held while the websocket reconnects, oldest first. When a // websocket drops unexpectedly, the Server keeps its session's queues for // the reconnecting websocket (see `client_websocket` in // [webserver.rs](../../server/src/webserver.rs)), so these messages still // reach the same session. outbox: EditorMessage[] = []; // True once the Client has asked to close the websocket; see // `closeWebsocket`. closing = false; // Called once `pendingMessages` empties; see `allAnswered`. allAnsweredCallbacks: (() => void)[] = []; // The current filename of the file being edited. This is provided by the // IDE and passed back to it, but not otherwise used by the Framework. currentFilename: string | undefined = undefined; // The version number of the current file. This default value will be // overwritten when the first `Update` is sent. version = 0.0; // Resolves once the `rootIframe` finishes loading the page most recently // assigned by `setRootIframeSrc`. An `Update` waits on this, since it calls // functions which the Client defines in `onDomContentLoaded`. I'd prefer to // use a system-maintained value such as // [readyState](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState). // However, this value only applies to the initial load of the iframe; it // doesn't change when the iframe's `src` attribute is changed. So, track // this manually instead. loaded = Promise.resolve(); // A promise to serialize calls to and from the Client. This is important: a // `CurrentFile` requires the Client to save, then switch to a new web page. // If an `Update` comes in, it should be applied after the `CurrentFile` has // finished executing. promise = Promise.resolve(); constructor(wsUrl: string) { // The `ReconnectingWebSocket` doesn't provide ALL the `WebSocket` // methods. Ignore this, since we can't use `ReconnectingWebSocket` as a // type. /// @ts-expect-error("This is legacy, third-party code.") this.ws = new ReconnectingWebSocket!(wsUrl, undefined, { maxReconnectAttempts: 10, }); this.ws.onopen = () => { consoleLog( `CodeChat Editor Client: websocket to CodeChat Server open.`, ); for (const em of this.outbox.splice(0)) { this.send(em); } // Finish a close requested while the websocket reconnected. if (this.closing) { this.ws.close(); } }; // Provide logging to help track down errors. this.ws.onerror = (event: Event) => { reportError(`CodeChat Editor Client: websocket error.`, event); }; this.ws.onclose = ( // This is a `CustomEvent`, not a `CloseEvent`; see // `ReconnectingWebSocket.cjs:275-293`. _event: Event, ) => { consoleLog("CodeChat Editor Client: websocket closed."); // If this came after a `RequestClose` message, then the Client data // is now saved and it's safe to close the window. See // . if (this.closing) { window.close(); // A browser lets a script close only a window it opened or a // top-level window whose history holds a single page; a VSCode // webview shows this page in an iframe, which can't be closed. // If the window stays open, report that the editor closed. See // [Window.close()](https://developer.mozilla.org/en-US/docs/Web/API/Window/close). if (!window.closed) { showToast( "The CodeChat Editor has closed. You may now close this window.", TOAST_NO_TIMEOUT, ); } } }; // Handle websocket messages. this.ws.onmessage = (event: MessageEvent) => { // Parse the received message, which must be a single element of a // dictionary representing an `EditorMessage`. const jointMessage = JSON.parse(event.data) as EditorMessage; const { id, message } = jointMessage; consoleLog( `CodeChat Editor Client: received data id = ${id}, message = ${formatStruct(message)}`, ); assert(id !== undefined); assert(message !== undefined); // A Rust enum variant with no data (e.g. `RequestClose`) is // serialized as a bare string rather than a single-key object; a // variant with data is serialized as a single-key object. See // `KeysOfRustEnum` for the same convention used by its type. let key: KeysOfRustEnum; let value: unknown; if (typeof message === "string") { key = message as KeysOfRustEnum; value = undefined; } else { const keys = Object.keys(message); assert(keys.length === 1); key = keys[0] as KeysOfRustEnum; value = Object.values(message)[0]; } // Process this message. switch (key) { case "Update": { // Load this data in. const currentUpdate = value as UpdateMessageContents; // The rest of this should run after all other messages have // been processed. this.enqueue(async () => { // Check or update the `currentFilename`. if (this.currentFilename === undefined) { this.currentFilename = currentUpdate.file_path; } else if ( currentUpdate.file_path !== this.currentFilename ) { const msg = `Ignoring update for ${currentUpdate.file_path} because it's not the current file ${this.currentFilename}.`; reportError(msg); this.sendResult(id, { IgnoredUpdate: [ currentUpdate.file_path, this.currentFilename, ], }); return; } const contents = currentUpdate.contents; if (contents !== undefined) { // Check and update the version. If this is a diff, // ensure the diff was made against the version of // the file we have. if ("Diff" in contents.source) { if ( contents.source.Diff.version !== this.version ) { if (currentUpdate.is_re_translation) { // An edit from this Client, still in // flight to the Server, supersedes this // re-translation; the Server re-translates // that edit when it arrives. Reply anyway: // the Server reports an unanswered message // as a timeout error, which the IDE then // shows. consoleLog( `Ignoring out-of-sync re-translation update.`, ); this.sendResult(id); } else { reportError( `Out of sync: Client version ${this.version} !== incoming version ${contents.source.Diff.version}.`, ); this.sendResult(id, { OutOfSync: [ this.version, contents.source.Diff.version, ], }); } return; } } } await this.loaded; if (contents !== undefined) { // If `setContent` throws, the server will send the // full contents after receiving the // `ClientUpdateError`, overwriting `this.version`; // therefore, setting it now is ok and avoids race // conditions produced when setting it after the // `await`. this.version = contents.version; try { await setContent( contents, currentUpdate.is_re_translation, currentUpdate.cursor_position, currentUpdate.scroll_position, ); } catch (err) { reportError(`Unable to update content: ${err}`); this.sendResult(id, { ClientUpdateError: getErrorMessage(err), }); return; } } else { // The `rootIframe` may hold a page other than the // Client, which doesn't define `scrollToLine`. rootIframe!.contentWindow?.CodeChatEditor?.scrollToLine?.( currentUpdate.cursor_position, currentUpdate.scroll_position, ); } this.sendResult(id); }); break; } case "CurrentFile": { // Note that we can ignore `value[1]` (if the file is text // or binary); the server only sends text files here. const currentFile = (value as [string, boolean | null])[0]; const testSuffix = testMode ? // Append the test parameter correctly, depending if // there are already parameters or not. currentFile.indexOf("?") === -1 ? "?test" : "&test" : ""; // Execute this after all other messages have been // processed. this.enqueue(async () => { // If the save fails, there's no recourse; load the new // file anyway. const saveError = await saveClient("loading a new file"); this.setRootIframeSrc(currentFile + testSuffix); this.sendResult(id, saveError); }); break; } case "UpdateToc": { const html = value as string; // Execute this after all other messages have been // processed. this.enqueue(() => { setSidebarToc(html); this.sendResult(id); }); break; } case "Result": { // If the result has the magic ID, then call a debug // routine. if (id === 1e6 && DEBUG_ENABLED) { rootIframe!.contentWindow?.CodeChatEditor?.doDebug(); break; } // Cancel the timer for this message, deliver its result, // and remove it from `pendingMessages`. const resultContents = value as MessageResult; const pendingMessage = this.pendingMessages[id]; if (pendingMessage !== undefined) { const { timerId, resolve } = pendingMessage; clearTimeout(timerId); this.removePending(id); resolve(resultContents); } // Report if this was an error. if ("Err" in resultContents) { reportError( `Error in message ${id}: ${JSON.stringify(resultContents.Err)}.`, resultContents.Err, ); // The Server sends this error when the IDE's text first // fails to translate (see `ide_update` in // [translation.rs](../../server/src/translation.rs)). // Queue this behind any update still being applied: // that update holds older text, so applying it would // otherwise end the read-only state. const err = resultContents.Err; if ( typeof err === "object" && "CannotTranslateSource" in err ) { this.enqueue(() => getClient()?.setReadOnly(true)); } } break; } // Server-requested (graceful) // shutdown. case "RequestClose": { // Prevent further edits when shutting down. getClient()?.setReadOnly(true); this.enqueue(async () => { const saveError = await saveClient("closing"); // Per the shutdown protocol (see `client_websocket` in // [webserver.rs](../../server/src/webserver.rs)), wait // for the Server to answer every message sent before // closing the websocket. `saveClient` waited only for // the save's `Update`; the Server answers some messages // itself but forwards others to the IDE, so an earlier // message, such as an autosave, may still be // unanswered. Reply only then, too: once the IDE has // this reply, it may close the Client before those // answers arrive. await this.allAnswered(); this.sendResult(id, saveError); // After the websocket closes, the resulting event will // close this window. this.closeWebsocket(); }); break; } default: { const msg = `Received unhandled message ${key}(${formatStruct( value, )})`; reportError(msg); this.sendResult(id, { ClientIllegalMessageReceived: `${key}(${formatStruct( value, )})`, }); break; } } }; } // Enqueue a task in response to receiving a message; these tasks will then // execute in order. enqueue = (task: () => void | Promise) => { this.promise = this.promise .then(task) .catch((err) => reportError(`Error handling a message: ${err}`, err), ); }; // Show `url` in the `rootIframe`. Every caller first saves the page this // replaces. setRootIframeSrc = (url: string) => { assert(rootIframe !== undefined); // Is this navigation to an id in the current document? The Server's // `CurrentFile` sends a root-relative URL, so resolve it against this // page. Before the first load, the iframe shows its `srcdoc` and has no // `src` to compare against. const newUrl = new URL(url, window.location.href); if ( rootIframe.hasAttribute("src") && rootIframe.contentWindow !== null ) { const currentUrl = new URL(rootIframe.src); if ( newUrl.origin === currentUrl.origin && newUrl.pathname === currentUrl.pathname && newUrl.search == currentUrl.search ) { // TODO: navigate within the page. This doesn't work if the // relevant section of the document isn't loaded. rootIframe.contentWindow.location.hash = newUrl.hash; return; } } // The `currentFile` is a URL-encoded path, not a filesystem path. So, // we can't use it for `currentFilename`. Instead, signal that the // `currentFilename` should be set on the next `Update` message. this.currentFilename = undefined; // Let the page being replaced navigate away. It stays live until the // new page loads; an `Update` it sent meanwhile would name no file or, // once the new page's first `Update` arrives, the wrong one. So, this // flag also stops it from sending any, and the page becomes read-only // so that the user can't make edits which it would then discard. const client = getClient(); if (client !== undefined) { client.allow_navigation = true; client.setReadOnly(true); } // Set the new src to (re)load content. At startup, the `srcdoc` // attribute shows some welcome text. Remove it so that we can now // assign the `src` attribute. rootIframe.removeAttribute("srcdoc"); rootIframe.src = url; this.loaded = new Promise((resolve) => rootIframe!.addEventListener("load", () => resolve(), { once: true, }), ); }; reportServerTimeout = (messageId: number) => { this.pendingMessages[messageId]?.resolve({ Err: { MessageTimeout: messageId }, }); this.removePending(messageId); reportError(`Error: server timeout for message id ${messageId}`); }; // Stop tracking a message whose `Result` arrived or timed out. removePending = ( // The message's id. id: number, ) => { delete this.pendingMessages[id]; if (Object.keys(this.pendingMessages).length === 0) { for (const callback of this.allAnsweredCallbacks.splice(0)) { callback(); } } }; // Resolve once every message sent so far has received its `Result` or // timed out. A message held in the `outbox` starts its timeout only when // sent, so while the websocket reconnects, this waits for the reconnection. allAnswered = () => new Promise((resolve) => { if (Object.keys(this.pendingMessages).length === 0) { resolve(); } else { this.allAnsweredCallbacks.push(resolve); } }); // Close the websocket once the `outbox` is sent. While the websocket // reconnects, closing it would either discard the `outbox` or, when a // reconnection is already scheduled, leave that reconnection to open a // websocket which then stays open (see `close` in // `ReconnectingWebSocket.cjs`). Instead, `onopen` closes the websocket // after sending the `outbox`. closeWebsocket = () => { this.closing = true; if (this.ws.readyState === WebSocket.OPEN) { this.ws.close(); } }; // Send a message to the Server or, while the websocket reconnects, hold it // in the `outbox`. Sending in that state would throw (see `send` in // `ReconnectingWebSocket.cjs`), losing the message; callers such as the // Client's autosave timer have no way to retry. send = ( // The message to send. editorMessage: EditorMessage, ) => { if (this.ws.readyState !== WebSocket.OPEN) { this.outbox.push(editorMessage); if (this.outbox.length > 3) { reportError("Unable to contact server...retrying."); } return; } this.ws.send(JSON.stringify(editorMessage)); // Time the Server's response from when the message was sent, not // queued. A `Result` answers an id assigned by the IDE or the Server, // so it never has a pending entry. const pendingMessage = this.pendingMessages[editorMessage.id]; if (pendingMessage !== undefined) { pendingMessage.timerId = window.setTimeout( this.reportServerTimeout, RESPONSE_TIMEOUT_MS, editorMessage.id, ); } }; // Send a message expecting a result to the server. sendMessage = ( // The message to send. message: EditorMessageContents, // The Server's `Result`, or a `MessageTimeout` error if none arrived in // time. This never rejects, so callers may ignore it. ): Promise => { const id = this.wsId; // The Client gets every third ID -- the IDE gets another third, while // the Server gets the final third. this.wsId += 3; // Add in the current filename to the message, if it's an `Update`. if (typeof message == "object" && "Update" in message) { assert(this.currentFilename !== undefined); message.Update.file_path = this.currentFilename!; // Update the version of this file if it's provided. this.version = message.Update.contents?.version ?? this.version; } consoleLog( `CodeChat Editor Client: sent message ${id}, ${formatStruct(message)}`, ); return new Promise((resolve) => { this.pendingMessages[id] = { resolve }; this.send({ id, message }); }); }; // This is called by the Client when the user navigates to another webpage. currentFile = (url: URL) => { // TODO: should we delay execution of user navigation until all previous // actions have finished, or ignore them and immediately perform the // user navigation? this.enqueue(() => { if (url.host === window.location.host) { // If this points to the Server, then tell the IDE to load a new // file. this.sendMessage({ CurrentFile: [url.toString(), null] }).then( () => this.setRootIframeSrc(url.toString()), ); } else { // Otherwise, navigate to the provided page. this.setRootIframeSrc(url.toString()); } }); }; // Send a result (a response to a message from the server) back to the // server. sendResult = (id: number, result?: ResultErrTypes) => { const message: EditorMessageContents = { Result: result === undefined ? { Ok: "Void" } : { Err: result }, }; consoleLog( `CodeChat Editor Client: sending result id = ${id}, message = ${formatStruct(message)}`, ); // We can't simply call `sendMessage` because that function expects a // result message back from the server. this.send({ id, message }); }; } // Return the `CodeChatEditor` object if the `rootIframe` contains the Client; // otherwise, this is `undefined`. const getClient = () => { // Handles cases where there's no root iframe or contentWindow and when the // root iframe holds a cross-origin page. try { return rootIframe?.contentWindow?.CodeChatEditor; } catch (_err) { return undefined; } }; // If the `rootIframe` contains the Client, save its modified contents, or wait // for a save already in progress, then report whether the Server accepted the // save. const saveClient = async ( // The action which requires this save, used in the error message. action: string, // The error to send in the `Result` for the message which requested this // action, or `undefined` if the save succeeded. ): Promise => { let result: MessageResult | undefined; try { result = await getClient()?.sendUpdate(true); } catch (err) { reportError(`Unable to save before ${action}: ${err}`); return { ClientUpdateError: getErrorMessage(err) }; } // The `Result` handler or `reportServerTimeout` has already reported this // error. if (result !== undefined && "Err" in result) { return { ClientUpdateError: JSON.stringify(result.Err) }; } return undefined; }; // Return the iframe with the given id in the page in the `rootIframe`, or // `undefined` if the page has none. The page belongs to the `rootIframe`'s // window, whose `HTMLIFrameElement` differs from this window's, so `instanceof` // can't identify the iframe. const getPageIframe = (id: string) => { const element = rootIframe!.contentDocument?.getElementById(id); return element?.tagName === "IFRAME" ? (element as HTMLIFrameElement) : undefined; }; // Show the current file's new contents in the `rootIframe`: in the Client, if // it's loaded; otherwise, by reloading the document which shows the file. const setContent = async ( contents: CodeChatForWeb, isReTranslation: boolean, cursorPosition?: CursorPosition, scrollLine?: number, ) => { const client = getClient(); if (client === undefined) { // The browser itself renders this file. The page shows it either in the // contents iframe of the [simple viewer](#Client-simple-viewer) or, // outside a project, as the page itself. Reload that document, rather // than writing `contents` to it: the Server serves the IDE's latest // contents, which the browser renders according to the file's type. // Writing them instead would parse them as HTML, collapsing a text // file's line breaks, and would throw for an XML document such as an // SVG image, since only an HTML document supports `document.open`. ( getPageIframe("CodeChat-contents")?.contentWindow ?? rootIframe!.contentWindow! ).location.reload(); } else { await rootIframe!.contentWindow!.CodeChatEditor.openLp( contents, isReTranslation, cursorPosition, scrollLine, ); } }; // Replace the contents of the TOC in the sidebar of the page in the // `rootIframe` -- the Client or the simple viewer. Replacing them in place, // rather than reloading the sidebar, preserves its scroll position, along with // the `navigate` listener which the page attached to the sidebar's window to // intercept clicks on the TOC's links. const setSidebarToc = (html: string) => { const sidebarIframe = getPageIframe("CodeChat-sidebar"); // A page outside a project has no sidebar. if (sidebarIframe === undefined) { return; } const replaceToc = () => { // Until the sidebar loads, its document is the initial `about:blank` or // a partially-parsed TOC. const tocDocument = sidebarIframe.contentDocument; if (tocDocument === null || tocDocument.readyState === "loading") { return false; } const toc = tocDocument.querySelector(".CodeChat-TOC"); if (toc === null) { return false; } toc.innerHTML = html; return true; }; // The Server sends this only after serving the sidebar its TOC, so a // sidebar which is still loading shows an older rendering; replace that // once it loads. Waiting here instead would stall every message behind this // one if the sidebar never finishes loading. if (!replaceToc()) { sidebarIframe.addEventListener("load", replaceToc, { once: true }); } }; // The iframe element which composes this page. let rootIframe: HTMLIFrameElement | undefined; // True when in test mode. let testMode = false; // Load the dynamic content into the static page. export const pageInit = ( // The pathname for the websocket to use. The remainder of the URL is // derived from the hosting page's URL. See the // [Location docs](https://developer.mozilla.org/en-US/docs/Web/API/Location) // for a nice, interactive definition of the components of a URL. wsPathname: string, // Test mode flag testMode_: boolean, ) => { testMode = testMode_; onDomContentLoaded(() => { // Provide basic error reporting for uncaught errors. window.addEventListener("unhandledrejection", onError); window.addEventListener("error", onError); // If the hosting page uses HTTPS, then use a secure websocket (WSS // protocol); otherwise, use an insecure websocket (WS). const protocol = window.location.protocol === "http:" ? "ws:" : "wss:"; // Build a websocket address based on the URL of the current page. webSocketComm = new WebSocketComm( `${protocol}//${window.location.host}/${wsPathname}`, ); const iframeElement = document.getElementById("CodeChat-iframe"); assert(iframeElement instanceof HTMLIFrameElement); rootIframe = iframeElement; window.CodeChatEditorFramework = { webSocketComm, }; }); }; // Tell TypeScript about the global namespace this program defines. declare global { interface Window { CodeChatEditorFramework: { webSocketComm: WebSocketComm; }; CodeChatEditor_test: unknown; } } const showToast = ( // The message to show. text: string, // How long to show the toast, in ms, or `TOAST_NO_TIMEOUT`; omit this for // the default. duration?: number, ) => { const client = getClient(); if (client === undefined) { showToastCore(text, duration); } else { client.showToast(text, duration); } }; // Format a complex data structure as a string when in debug mode. /*eslint-disable-next-line @typescript-eslint/no-explicit-any */ export const formatStruct = (complexDataStructure: any): string => DEBUG_ENABLED ? (JSON.stringify(complexDataStructure) ?? "undefined").substring( 0, MAX_MESSAGE_LENGTH, ) : ""; /*eslint-disable-next-line @typescript-eslint/no-explicit-any */ const reportError = (text: string, ...objs: any) => { console.error(text); if (objs.length > 0) { console.log(...objs); } showToast(text); };