mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-11-27 07:58:37 +03:00
To reduce the initial bundle size and the PWA precache size, Firebase and Mermaid are now lazy loaded. Both are out of the main bundle and the PWA precache. Each is downloaded the first time it's needed and then cached by the service worker, so it also works offline after that first use.
### How it's done
Rollup splits Mermaid into many chunks with arbitrary names (one per diagram type, plus shared deps), so `globIgnores` can't match them. A small build plugin (`lazyChunksPlugin` in `excalidraw-app/vite.config.mts`) finds the chunks that are only reachable through the dynamic `import("@excalidraw/mermaid-to-excalidraw")`. It then removes them from the precache manifest. Chunks that the main bundle also uses stay precached.
A new `lazy-chunks` runtime cache (`CacheFirst`, `/assets/*.js`, max 200 entries, 90 days) stores any JS chunk that isn't precached the first time it loads.
### Offline behaviour
- **Mermaid / text-to-diagram** is no longer cached at install. It works offline once it has been opened online at least once.
- While the Mermaid library loads, the preview shows a spinner (it used to flash an error).
- If the library fails to load:
- **Offline:** the preview shows "Couldn't load Mermaid. Check your internet connection and try again." with a Retry button. It also retries automatically when the browser comes back online.
- **Online** (e.g. a stale app version after a deploy): the preview shows "Couldn't load Mermaid. Reload the page to try again." On `vite:preloadError` the service worker checks for an update.
- **Chrome** keeps a failed dynamic import cached for the life of the page, so retrying can't work there. In Chrome the button reloads the page instead. The Mermaid definition being edited is saved before unload, so it isn't lost.
- Inserting a generated diagram while the library is unavailable shows a toast with the same message. If AI generation finishes while the library can't load, the Mermaid output is validated once the library loads.
- Pasting a Mermaid definition while the library can't load pastes it as plain text instead of failing.
- **Share / live collaboration** is hidden while offline, unless you're already in a session. This covers the top-right Share button, the main menu, the welcome screen and the command palette. An open Share dialog closes when you go offline. The online/offline state is read at startup, and changes to it are debounced by 1 s.
- **Not precached:** Mermaid and `firebaseSDK-*.js` are newly excluded. CodeMirror, font subsetting, QR code and locales were already excluded on `master`.
---------
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
323 lines
9.3 KiB
TypeScript
323 lines
9.3 KiB
TypeScript
import { reconcileElements } from "@excalidraw/excalidraw";
|
|
import { MIME_TYPES, toBrandedType } from "@excalidraw/common";
|
|
import { decompressData } from "@excalidraw/excalidraw/data/encode";
|
|
import {
|
|
encryptData,
|
|
decryptData,
|
|
} from "@excalidraw/excalidraw/data/encryption";
|
|
import { restoreElements } from "@excalidraw/excalidraw/data/restore";
|
|
import { getSceneVersion } from "@excalidraw/element";
|
|
|
|
import type { RemoteExcalidrawElement } from "@excalidraw/excalidraw/data/reconcile";
|
|
import type {
|
|
ExcalidrawElement,
|
|
FileId,
|
|
OrderedExcalidrawElement,
|
|
} from "@excalidraw/element/types";
|
|
import type {
|
|
AppState,
|
|
BinaryFileData,
|
|
BinaryFileMetadata,
|
|
DataURL,
|
|
} from "@excalidraw/excalidraw/types";
|
|
|
|
import { FILE_CACHE_MAX_AGE_SEC } from "../app_constants";
|
|
|
|
import { getSyncableElements } from ".";
|
|
|
|
import type { SyncableExcalidrawElement } from ".";
|
|
import type Portal from "../collab/Portal";
|
|
import type { Socket } from "socket.io-client";
|
|
import type { Bytes } from "firebase/firestore";
|
|
import type { UploadMetadata } from "firebase/storage";
|
|
|
|
// private
|
|
// -----------------------------------------------------------------------------
|
|
|
|
let FIREBASE_CONFIG: Record<string, any>;
|
|
try {
|
|
FIREBASE_CONFIG = JSON.parse(import.meta.env.VITE_APP_FIREBASE_CONFIG);
|
|
} catch (error: any) {
|
|
console.warn(
|
|
`Error JSON parsing firebase config. Supplied value: ${
|
|
import.meta.env.VITE_APP_FIREBASE_CONFIG
|
|
}`,
|
|
);
|
|
FIREBASE_CONFIG = {};
|
|
}
|
|
|
|
const lazy = <T>(load: () => Promise<T>) => {
|
|
let promise: Promise<T> | null = null;
|
|
return () =>
|
|
(promise ??= load().catch((error) => {
|
|
promise = null;
|
|
throw error;
|
|
}));
|
|
};
|
|
|
|
const _initializeFirebase = lazy(async () => {
|
|
const sdk = await import("./firebaseSDK");
|
|
return { sdk, app: sdk.initializeApp(FIREBASE_CONFIG) };
|
|
});
|
|
|
|
const _loadFirestore = lazy(async () => {
|
|
const { sdk, app } = await _initializeFirebase();
|
|
const { getFirestore, doc, getDoc, runTransaction, Bytes } = sdk;
|
|
return { firestore: getFirestore(app), doc, getDoc, runTransaction, Bytes };
|
|
});
|
|
|
|
const _loadStorage = lazy(async () => {
|
|
const { sdk, app } = await _initializeFirebase();
|
|
const { getStorage, ref, uploadBytes } = sdk;
|
|
return { storage: getStorage(app), ref, uploadBytes };
|
|
});
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
export const uploadBytesToFirebase = async (
|
|
path: string,
|
|
data: Blob | Uint8Array,
|
|
metadata?: UploadMetadata,
|
|
) => {
|
|
const { storage, ref, uploadBytes } = await _loadStorage();
|
|
return uploadBytes(ref(storage, path), data, metadata);
|
|
};
|
|
|
|
type FirebaseStoredScene = {
|
|
sceneVersion: number;
|
|
iv: Bytes;
|
|
ciphertext: Bytes;
|
|
};
|
|
|
|
const encryptElements = async (
|
|
key: string,
|
|
elements: readonly ExcalidrawElement[],
|
|
): Promise<{ ciphertext: ArrayBuffer; iv: Uint8Array }> => {
|
|
const json = JSON.stringify(elements);
|
|
const encoded = new TextEncoder().encode(json);
|
|
const { encryptedBuffer, iv } = await encryptData(key, encoded);
|
|
|
|
return { ciphertext: encryptedBuffer, iv };
|
|
};
|
|
|
|
const decryptElements = async (
|
|
data: FirebaseStoredScene,
|
|
roomKey: string,
|
|
): Promise<readonly ExcalidrawElement[]> => {
|
|
const ciphertext = data.ciphertext.toUint8Array() as Uint8Array<ArrayBuffer>;
|
|
const iv = data.iv.toUint8Array() as Uint8Array<ArrayBuffer>;
|
|
|
|
const decrypted = await decryptData(iv, ciphertext, roomKey);
|
|
const decodedData = new TextDecoder("utf-8").decode(
|
|
new Uint8Array(decrypted),
|
|
);
|
|
return JSON.parse(decodedData);
|
|
};
|
|
|
|
class FirebaseSceneVersionCache {
|
|
private static cache = new WeakMap<Socket, number>();
|
|
static get = (socket: Socket) => {
|
|
return FirebaseSceneVersionCache.cache.get(socket);
|
|
};
|
|
static set = (
|
|
socket: Socket,
|
|
elements: readonly SyncableExcalidrawElement[],
|
|
) => {
|
|
FirebaseSceneVersionCache.cache.set(socket, getSceneVersion(elements));
|
|
};
|
|
}
|
|
|
|
export const isSavedToFirebase = (
|
|
portal: Portal,
|
|
elements: readonly ExcalidrawElement[],
|
|
): boolean => {
|
|
if (portal.socket && portal.roomId && portal.roomKey) {
|
|
const sceneVersion = getSceneVersion(elements);
|
|
|
|
return FirebaseSceneVersionCache.get(portal.socket) === sceneVersion;
|
|
}
|
|
// if no room exists, consider the room saved so that we don't unnecessarily
|
|
// prevent unload (there's nothing we could do at that point anyway)
|
|
return true;
|
|
};
|
|
|
|
export const saveFilesToFirebase = async ({
|
|
prefix,
|
|
files,
|
|
}: {
|
|
prefix: string;
|
|
files: { id: FileId; buffer: Uint8Array }[];
|
|
}) => {
|
|
// failing to load the SDK must fail the whole save rather than be reported
|
|
// per file as `erroredFiles` (which share links ignore, and collab never
|
|
// retries)
|
|
const { storage, ref, uploadBytes } = await _loadStorage();
|
|
|
|
const erroredFiles: FileId[] = [];
|
|
const savedFiles: FileId[] = [];
|
|
|
|
await Promise.all(
|
|
files.map(async ({ id, buffer }) => {
|
|
try {
|
|
const storageRef = ref(storage, `${prefix}/${id}`);
|
|
await uploadBytes(storageRef, buffer, {
|
|
cacheControl: `public, max-age=${FILE_CACHE_MAX_AGE_SEC}`,
|
|
});
|
|
savedFiles.push(id);
|
|
} catch (error: any) {
|
|
erroredFiles.push(id);
|
|
}
|
|
}),
|
|
);
|
|
|
|
return { savedFiles, erroredFiles };
|
|
};
|
|
|
|
const createFirebaseSceneDocument = async (
|
|
elements: readonly SyncableExcalidrawElement[],
|
|
roomKey: string,
|
|
) => {
|
|
const sceneVersion = getSceneVersion(elements);
|
|
const { ciphertext, iv } = await encryptElements(roomKey, elements);
|
|
const { Bytes } = await _loadFirestore();
|
|
return {
|
|
sceneVersion,
|
|
ciphertext: Bytes.fromUint8Array(new Uint8Array(ciphertext)),
|
|
iv: Bytes.fromUint8Array(iv),
|
|
} as FirebaseStoredScene;
|
|
};
|
|
|
|
export const saveToFirebase = async (
|
|
portal: Portal,
|
|
elements: readonly SyncableExcalidrawElement[],
|
|
appState: AppState,
|
|
) => {
|
|
const { roomId, roomKey, socket } = portal;
|
|
if (
|
|
// bail if no room exists as there's nothing we can do at this point
|
|
!roomId ||
|
|
!roomKey ||
|
|
!socket ||
|
|
isSavedToFirebase(portal, elements)
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
const { firestore, doc, runTransaction } = await _loadFirestore();
|
|
const docRef = doc(firestore, "scenes", roomId);
|
|
|
|
const storedScene = await runTransaction(firestore, async (transaction) => {
|
|
const snapshot = await transaction.get(docRef);
|
|
|
|
if (!snapshot.exists()) {
|
|
const storedScene = await createFirebaseSceneDocument(elements, roomKey);
|
|
|
|
transaction.set(docRef, storedScene);
|
|
|
|
return storedScene;
|
|
}
|
|
|
|
const prevStoredScene = snapshot.data() as FirebaseStoredScene;
|
|
const prevStoredElements = getSyncableElements(
|
|
restoreElements(await decryptElements(prevStoredScene, roomKey), null),
|
|
);
|
|
const reconciledElements = getSyncableElements(
|
|
reconcileElements(
|
|
elements,
|
|
prevStoredElements as OrderedExcalidrawElement[] as RemoteExcalidrawElement[],
|
|
appState,
|
|
),
|
|
);
|
|
|
|
const storedScene = await createFirebaseSceneDocument(
|
|
reconciledElements,
|
|
roomKey,
|
|
);
|
|
|
|
transaction.update(docRef, storedScene);
|
|
|
|
// Return the stored elements as the in memory `reconciledElements` could have mutated in the meantime
|
|
return storedScene;
|
|
});
|
|
|
|
const storedElements = getSyncableElements(
|
|
restoreElements(await decryptElements(storedScene, roomKey), null),
|
|
);
|
|
|
|
FirebaseSceneVersionCache.set(socket, storedElements);
|
|
|
|
return toBrandedType<RemoteExcalidrawElement[]>(storedElements);
|
|
};
|
|
|
|
export const loadFromFirebase = async (
|
|
roomId: string,
|
|
roomKey: string,
|
|
socket: Socket | null,
|
|
): Promise<readonly SyncableExcalidrawElement[] | null> => {
|
|
const { firestore, doc, getDoc } = await _loadFirestore();
|
|
const docRef = doc(firestore, "scenes", roomId);
|
|
const docSnap = await getDoc(docRef);
|
|
if (!docSnap.exists()) {
|
|
return null;
|
|
}
|
|
const storedScene = docSnap.data() as FirebaseStoredScene;
|
|
const elements = getSyncableElements(
|
|
restoreElements(await decryptElements(storedScene, roomKey), null, {
|
|
deleteInvisibleElements: true,
|
|
}),
|
|
);
|
|
|
|
if (socket) {
|
|
FirebaseSceneVersionCache.set(socket, elements);
|
|
}
|
|
|
|
return elements;
|
|
};
|
|
|
|
export const loadFilesFromFirebase = async (
|
|
prefix: string,
|
|
decryptionKey: string,
|
|
filesIds: readonly FileId[],
|
|
) => {
|
|
const loadedFiles: BinaryFileData[] = [];
|
|
const erroredFiles = new Map<FileId, true>();
|
|
|
|
await Promise.all(
|
|
[...new Set(filesIds)].map(async (id) => {
|
|
try {
|
|
const url = `https://firebasestorage.googleapis.com/v0/b/${
|
|
FIREBASE_CONFIG.storageBucket
|
|
}/o/${encodeURIComponent(prefix.replace(/^\//, ""))}%2F${id}`;
|
|
const response = await fetch(`${url}?alt=media`);
|
|
if (response.status < 400) {
|
|
const arrayBuffer = await response.arrayBuffer();
|
|
|
|
const { data, metadata } = await decompressData<BinaryFileMetadata>(
|
|
new Uint8Array(arrayBuffer),
|
|
{
|
|
decryptionKey,
|
|
},
|
|
);
|
|
|
|
const dataURL = new TextDecoder().decode(data) as DataURL;
|
|
|
|
loadedFiles.push({
|
|
mimeType: metadata.mimeType || MIME_TYPES.binary,
|
|
id,
|
|
dataURL,
|
|
created: metadata?.created || Date.now(),
|
|
lastRetrieved: metadata?.created || Date.now(),
|
|
});
|
|
} else {
|
|
erroredFiles.set(id, true);
|
|
}
|
|
} catch (error: any) {
|
|
erroredFiles.set(id, true);
|
|
console.error(error);
|
|
}
|
|
}),
|
|
);
|
|
|
|
return { loadedFiles, erroredFiles };
|
|
};
|