Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

[POC] use serviceWorker from create-react-app (#1286)

Timur Khazamov4228c2e094d1
diff --git a/now.json b/now.json
index fae8694293..fa3a3204aa 100644
--- a/now.json
+++ b/now.json
@@ -21,7 +21,7 @@
},
{
"key": "Content-Security-Policy",
- "value": "default-src https: data: 'unsafe-inline'; connect-src https://*.excalidraw.com wss://excalidraw-socket.herokuapp.com https://excalidraw-socket.herokuapp.com https://sentry.io"
+ "value": "default-src https: data: 'unsafe-inline'; connect-src https://*.excalidraw.com https://*.excalidraw.now.sh wss://excalidraw-socket.herokuapp.com https://excalidraw-socket.herokuapp.com https://sentry.io;"
}
]
}
diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png
index 518c8962ef..e228a73235 100644
Binary files a/public/apple-touch-icon.png and b/public/apple-touch-icon.png differ
diff --git a/public/index.html b/public/index.html
index b8bf8f4cfb..11aaa50b6e 100644
--- a/public/index.html
+++ b/public/index.html
@@ -9,6 +9,8 @@
/>
<meta name="referrer" content="origin" />
<meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta name="mobile-web-app-capable" content="yes" />
+ <meta name="apple-touch-fullscreen" content="yes" />
<meta name="theme-color" content="#000000" />
@@ -64,24 +66,9 @@
<meta name="twitter:image" content="https://excalidraw.com/og-image.png" />
<meta
http-equiv="Content-Security-Policy"
- content="block-all-mixed-content; child-src 'self' https://codesandbox.io https://*.csb.app; connect-src 'self' https: wss: http: ws:; default-src 'self'; font-src 'self' data: https: filesystem:; img-src 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://www.google-analytics.com https://codesandbox.io https://*.csb.app https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https:;"
+ content="block-all-mixed-content; child-src 'self' https://codesandbox.io https://*.csb.app; worker-src 'self'; connect-src 'self' https: wss: http: ws:; default-src 'self'; font-src 'self' data: https: filesystem:; img-src 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://www.google-analytics.com https://codesandbox.io https://*.csb.app https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https:;"
/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
- <link rel="stylesheet" href="fonts.css" />
- <link
- rel="preload"
- href="FG_Virgil.woff2"
- as="font"
- type="font/woff2"
- crossorigin="anonymous"
- />
- <link
- rel="preload"
- href="Cascadia.woff2"
- as="font"
- type="font/woff2"
- crossorigin="anonymous"
- />
<link
href="https://excalidraw-socket.herokuapp.com/socket.io"
rel="preconnect"
diff --git a/src/components/App.tsx b/src/components/App.tsx
index c8c505ba4f..389bb091cf 100644
--- a/src/components/App.tsx
+++ b/src/components/App.tsx
@@ -2652,4 +2652,3 @@ if (
}
export default App;
-// -----------------------------------------------------------------------------
diff --git a/src/components/Dialog.scss b/src/components/Dialog.scss
index f0a7a8bf14..c35e42003a 100644
--- a/src/components/Dialog.scss
+++ b/src/components/Dialog.scss
@@ -1,4 +1,4 @@
-@import "../_variables";
+@import "../css/_variables";
.Dialog__title {
display: grid;
diff --git a/src/components/ExportDialog.scss b/src/components/ExportDialog.scss
index 6a88e3c18a..86d4642a87 100644
--- a/src/components/ExportDialog.scss
+++ b/src/components/ExportDialog.scss
@@ -1,4 +1,4 @@
-@import "../_variables";
+@import "../css/_variables";
.ExportDialog__preview {
--preview-padding: calc(var(--space-factor) * 4);
diff --git a/src/components/HintViewer.scss b/src/components/HintViewer.scss
index fbd9fc3d36..75df4c0a4e 100644
--- a/src/components/HintViewer.scss
+++ b/src/components/HintViewer.scss
@@ -1,4 +1,4 @@
-@import "../_variables";
+@import "../css/_variables";
.HintViewer {
color: $oc-gray-6;
diff --git a/src/components/Modal.scss b/src/components/Modal.scss
index eba4ac67ce..aa3cd20493 100644
--- a/src/components/Modal.scss
+++ b/src/components/Modal.scss
@@ -1,4 +1,4 @@
-@import "../_variables";
+@import "../css/_variables";
.Modal {
position: fixed;
diff --git a/src/components/RoomDialog.scss b/src/components/RoomDialog.scss
index 44975fb474..17d5db87a4 100644
--- a/src/components/RoomDialog.scss
+++ b/src/components/RoomDialog.scss
@@ -1,4 +1,4 @@
-@import "../_variables";
+@import "../css/_variables";
.RoomDialog-modalButton.is-collaborating {
background-color: $oc-green-0;
diff --git a/src/components/TextInput.scss b/src/components/TextInput.scss
index 36c2e61ac1..dfe412233f 100644
--- a/src/components/TextInput.scss
+++ b/src/components/TextInput.scss
@@ -1,4 +1,4 @@
-@import "../_variables.scss";
+@import "../css/_variables.scss";
.TextInput {
display: inline-block;
diff --git a/src/components/Toast.css b/src/components/Toast.css
new file mode 100644
index 0000000000..b4a418e7c1
--- /dev/null
+++ b/src/components/Toast.css
@@ -0,0 +1,33 @@
+.Toast__container {
+ position: fixed;
+ bottom: calc(var(--space-factor) * 2);
+ right: calc(var(--space-factor) * 2);
+ left: calc(var(--space-factor) * 2);
+ display: flex;
+ justify-content: center;
+ z-index: 1000;
+}
+
+.Toast {
+ position: relative;
+}
+
+.Toast__content {
+ padding-right: calc(var(--space-factor) * 9);
+ max-width: calc(var(--space-factor) * 50);
+}
+
+.Toast__close {
+ position: absolute;
+ width: calc(var(--space-factor) * 5);
+ height: calc(var(--space-factor) * 5);
+ top: calc(var(--space-factor) * -1);
+ right: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.Toast__close svg {
+ height: calc(var(--space-factor) * 3);
+}
diff --git a/src/components/Toast.tsx b/src/components/Toast.tsx
new file mode 100644
index 0000000000..84821d13a0
--- /dev/null
+++ b/src/components/Toast.tsx
@@ -0,0 +1,97 @@
+import React from "react";
+import { render } from "react-dom";
+import Stack from "./Stack";
+import { Island } from "./Island";
+import "./Toast.css";
+import { close } from "./icons";
+
+const TOAST_TIMEOUT = 7000;
+
+function ToastRenderer(props: {
+ toasts: Map<number, React.ReactNode>;
+ onCloseRequest: (id: number) => void;
+}) {
+ return (
+ <Stack.Col gap={2} align="center">
+ {[...props.toasts.entries()].map(([id, toast]) => (
+ <Island key={id} padding={3}>
+ <div className="Toast">
+ <div className="Toast__content">{toast}</div>
+ <button
+ className="Toast__close"
+ onClick={() => props.onCloseRequest(id)}
+ >
+ {close}
+ </button>
+ </div>
+ </Island>
+ ))}
+ </Stack.Col>
+ );
+}
+
+let toastsRootNode: HTMLDivElement;
+function getToastsRootNode() {
+ return toastsRootNode || (toastsRootNode = initToastsRootNode());
+}
+
+function initToastsRootNode() {
+ const div = window.document.createElement("div");
+ document.body.appendChild(div);
+ div.className = "Toast__container";
+ return div;
+}
+
+function renderToasts(
+ toasts: Map<number, React.ReactNode>,
+ onCloseRequest: (id: number) => void,
+) {
+ render(
+ <ToastRenderer toasts={toasts} onCloseRequest={onCloseRequest} />,
+ getToastsRootNode(),
+ );
+}
+
+let incrementalId = 0;
+function getToastId() {
+ return incrementalId++;
+}
+
+class ToastManager {
+ private toasts = new Map<number, React.ReactNode>();
+ private timers = new Map<number, number>();
+
+ public push(message: React.ReactNode, shiftAfterMs: number) {
+ const id = getToastId();
+ this.toasts.set(id, message);
+ if (isFinite(shiftAfterMs)) {
+ const handle = window.setTimeout(() => this.pop(id), shiftAfterMs);
+ this.timers.set(id, handle);
+ }
+ this.render();
+ }
+
+ private pop = (id: number) => {
+ const handle = this.timers.get(id);
+ if (handle) {
+ window.clearTimeout(handle);
+ this.timers.delete(id);
+ }
+ this.toasts.delete(id);
+ this.render();
+ };
+
+ private render() {
+ renderToasts(this.toasts, this.pop);
+ }
+}
+
+let toastManagerInstance: ToastManager;
+function getToastManager(): ToastManager {
+ return toastManagerInstance ?? (toastManagerInstance = new ToastManager());
+}
+
+export function push(message: React.ReactNode, manualClose = false) {
+ const toastManager = getToastManager();
+ toastManager.push(message, manualClose ? Infinity : TOAST_TIMEOUT);
+}
diff --git a/src/_variables.scss b/src/css/_variables.scss
similarity index 100%
rename from src/_variables.scss
rename to src/css/_variables.scss
diff --git a/public/fonts.css b/src/css/fonts.scss
similarity index 74%
rename from public/fonts.css
rename to src/css/fonts.scss
index 165bf6a5c1..87b5339efb 100644
--- a/public/fonts.css
+++ b/src/css/fonts.scss
@@ -1,13 +1,13 @@
/* http://www.eaglefonts.com/fg-virgil-ttf-131249.htm */
@font-face {
font-family: "Virgil";
- src: url("FG_Virgil.woff2");
+ src: url("../fonts/FG_Virgil.woff2");
font-display: swap;
}
/* https://github.com/microsoft/cascadia-code */
@font-face {
font-family: "Cascadia";
- src: url("Cascadia.woff2");
+ src: url("../fonts/Cascadia.woff2");
font-display: swap;
}
diff --git a/src/styles.scss b/src/css/styles.scss
similarity index 99%
rename from src/styles.scss
rename to src/css/styles.scss
index b5bb79b8a1..dfa40772cc 100644
--- a/src/styles.scss
+++ b/src/css/styles.scss
@@ -1,4 +1,6 @@
@import "./_variables";
+@import "./theme";
+@import "./fonts";
:root {
--sat: env(safe-area-inset-top);
diff --git a/src/css/theme.scss b/src/css/theme.scss
new file mode 100644
index 0000000000..8e8107ee29
--- /dev/null
+++ b/src/css/theme.scss
@@ -0,0 +1,7 @@
+:root {
+ --text-color-primary: #343a40;
+ --bg-color-main: #fff;
+ --shadow-island: 0 1px 5px rgba(0, 0, 0, 0.15);
+ --border-radius-m: 4px;
+ --space-factor: 0.25rem;
+}
diff --git a/public/Cascadia.ttf b/src/fonts/Cascadia.ttf
similarity index 100%
rename from public/Cascadia.ttf
rename to src/fonts/Cascadia.ttf
diff --git a/public/Cascadia.woff2 b/src/fonts/Cascadia.woff2
similarity index 100%
rename from public/Cascadia.woff2
rename to src/fonts/Cascadia.woff2
diff --git a/public/FG_Virgil.otf b/src/fonts/FG_Virgil.otf
similarity index 100%
rename from public/FG_Virgil.otf
rename to src/fonts/FG_Virgil.otf
diff --git a/public/FG_Virgil.ttf b/src/fonts/FG_Virgil.ttf
similarity index 100%
rename from public/FG_Virgil.ttf
rename to src/fonts/FG_Virgil.ttf
diff --git a/public/FG_Virgil.woff2 b/src/fonts/FG_Virgil.woff2
similarity index 100%
rename from public/FG_Virgil.woff2
rename to src/fonts/FG_Virgil.woff2
diff --git a/src/index-node.ts b/src/index-node.ts
index 29c83b4f04..d830d8a108 100644
--- a/src/index-node.ts
+++ b/src/index-node.ts
@@ -54,8 +54,9 @@ const elements = [
},
];
-registerFont("./public/FG_Virgil.ttf", { family: "Virgil" });
-registerFont("./public/Cascadia.ttf", { family: "Cascadia" });
+registerFont("./static/fonts/FG_Virgil.ttf", { family: "Virgil" });
+registerFont("./static/fonts/Cascadia.ttf", { family: "Cascadia" });
+
const canvas = exportToCanvas(
elements as any,
getDefaultAppState(),
diff --git a/src/index.tsx b/src/index.tsx
index 9cbe023da5..22692fc14e 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -2,10 +2,13 @@ import React from "react";
import ReactDOM from "react-dom";
import * as Sentry from "@sentry/browser";
import * as SentryIntegrations from "@sentry/integrations";
+
import { TopErrorBoundary } from "./components/TopErrorBoundary";
import { IsMobileProvider } from "./is-mobile";
import App from "./components/App";
-import "./styles.scss";
+import { register as registerServiceWorker } from "./serviceWorker";
+
+import "./css/styles.scss";
const SentryEnvHostnameMap: { [key: string]: string } = {
"excalidraw.com": "production",
@@ -52,3 +55,5 @@ ReactDOM.render(
</TopErrorBoundary>,
rootElement,
);
+
+registerServiceWorker();
diff --git a/src/scene/export.ts b/src/scene/export.ts
index 311a251862..3717850836 100644
--- a/src/scene/export.ts
+++ b/src/scene/export.ts
@@ -94,11 +94,11 @@ export function exportToSvg(
<style>
@font-face {
font-family: "Virgil";
- src: url("https://excalidraw.com/FG_Virgil.woff2");
+ src: url("https://excalidraw.com/static/fonts/FG_Virgil.woff2");
}
@font-face {
font-family: "Cascadia";
- src: url("https://excalidraw.com/Cascadia.woff2");
+ src: url("https://excalidraw.com/static/fonts/Cascadia.woff2");
}
</style>
</defs>
diff --git a/src/serviceWorker.tsx b/src/serviceWorker.tsx
new file mode 100644
index 0000000000..8e1a623142
--- /dev/null
+++ b/src/serviceWorker.tsx
@@ -0,0 +1,146 @@
+// This optional code is used to register a service worker.
+// register() is not called by default.
+
+import { push } from "./components/Toast";
+
+// This lets the app load faster on subsequent visits in production, and gives
+// it offline capabilities. However, it also means that developers (and users)
+// will only see deployed updates on subsequent visits to a page, after all the
+// existing tabs open on the page have been closed, since previously cached
+// resources are updated in the background.
+
+// To learn more about the benefits of this model and instructions on how to
+// opt-in, read https://bit.ly/CRA-PWA
+
+const isLocalhost = Boolean(
+ window.location.hostname === "localhost" ||
+ // [::1] is the IPv6 localhost address.
+ window.location.hostname === "[::1]" ||
+ // 127.0.0.0/8 are considered localhost for IPv4.
+ window.location.hostname.match(
+ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
+ ),
+);
+
+type Config = {
+ onSuccess?: (registration: ServiceWorkerRegistration) => void;
+ onUpdate?: (registration: ServiceWorkerRegistration) => void;
+};
+
+export function register(config?: Config) {
+ if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
+ // The URL constructor is available in all browsers that support SW.
+ const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
+ if (publicUrl.origin !== window.location.origin) {
+ // Our service worker won't work if PUBLIC_URL is on a different origin
+ // from what our page is served on. This might happen if a CDN is used to
+ // serve assets; see https://github.com/facebook/create-react-app/issues/2374
+ return;
+ }
+
+ window.addEventListener("load", () => {
+ const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+
+ if (isLocalhost) {
+ // This is running on localhost. Let's check if a service worker still exists or not.
+ checkValidServiceWorker(swUrl, config);
+
+ // Add some additional logging to localhost, pointing developers to the
+ // service worker/PWA documentation.
+ navigator.serviceWorker.ready.then(() => {
+ console.info(
+ "This web app is being served cache-first by a service " +
+ "worker. To learn more, visit https://bit.ly/CRA-PWA",
+ );
+ });
+ } else {
+ // Is not localhost. Just register service worker
+ registerValidSW(swUrl, config);
+ }
+ });
+ }
+}
+
+function registerValidSW(swUrl: string, config?: Config) {
+ navigator.serviceWorker
+ .register(swUrl)
+ .then((registration) => {
+ registration.onupdatefound = () => {
+ const installingWorker = registration.installing;
+ if (installingWorker == null) {
+ return;
+ }
+ installingWorker.onstatechange = () => {
+ if (installingWorker.state === "installed") {
+ if (navigator.serviceWorker.controller) {
+ // At this point, the updated precached content has been fetched,
+ // but the previous service worker will still serve the older
+ // content until all client tabs are closed.
+ push(
+ "New content is available and will be used when all " +
+ "tabs for this page are closed.",
+ );
+
+ // Execute callback
+ if (config && config.onUpdate) {
+ config.onUpdate(registration);
+ }
+ } else {
+ // At this point, everything has been precached.
+ // It's the perfect time to display a
+ // "Content is cached for offline use." message.
+ push("Content is cached for offline use.");
+
+ // Execute callback
+ if (config && config.onSuccess) {
+ config.onSuccess(registration);
+ }
+ }
+ }
+ };
+ };
+ })
+ .catch((error) => {
+ console.error("Error during service worker registration:", error);
+ });
+}
+
+function checkValidServiceWorker(swUrl: string, config?: Config) {
+ // Check if the service worker can be found. If it can't reload the page.
+ fetch(swUrl, {
+ headers: { "Service-Worker": "script" },
+ })
+ .then((response) => {
+ // Ensure service worker exists, and that we really are getting a JS file.
+ const contentType = response.headers.get("content-type");
+ if (
+ response.status === 404 ||
+ (contentType != null && contentType.indexOf("javascript") === -1)
+ ) {
+ // No service worker found. Probably a different app. Reload the page.
+ navigator.serviceWorker.ready.then((registration) => {
+ registration.unregister().then(() => {
+ window.location.reload();
+ });
+ });
+ } else {
+ // Service worker found. Proceed as normal.
+ registerValidSW(swUrl, config);
+ }
+ })
+ .catch(() => {
+ push("No internet connection found. App is running in offline mode.");
+ });
+}
+
+export function unregister() {
+ if ("serviceWorker" in navigator) {
+ navigator.serviceWorker.ready
+ .then((registration) => {
+ registration.unregister();
+ })
+ .catch((error) => {
+ console.error(error.message);
+ });
+ }
+}