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

* Service worker with toast notifications

* Update CSP to allow fetches from now.sh

* Fixed clearing timers

* rounded icon for pwa (#1301)

* rounded icon for pwa

* cirle pwa app icon

* fix fonts caching

* fix app

* fix css import

* Updated csp tp inlcude worker-src: self

* add worker CSP rule

* use square icon

Co-authored-by: Timur Khazamov <t1mmaas@skbkontur.ru>
Co-authored-by: Faustino Kialungila <Faustino.kialungila@gmail.com>
Co-authored-by: kbariotis <konmpar@gmail.com>
This commit is contained in:
Timur Khazamov 2020-04-13 16:08:39 +02:00 committed by GitHub
parent e158dbc45a
commit 4228c2e094
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 308 additions and 31 deletions

View File

@ -21,7 +21,7 @@
}, },
{ {
"key": "Content-Security-Policy", "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;"
} }
] ]
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 9.0 KiB

View File

@ -9,6 +9,8 @@
/> />
<meta name="referrer" content="origin" /> <meta name="referrer" content="origin" />
<meta name="apple-mobile-web-app-capable" content="yes" /> <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" /> <meta name="theme-color" content="#000000" />
@ -64,24 +66,9 @@
<meta name="twitter:image" content="https://excalidraw.com/og-image.png" /> <meta name="twitter:image" content="https://excalidraw.com/og-image.png" />
<meta <meta
http-equiv="Content-Security-Policy" 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="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 <link
href="https://excalidraw-socket.herokuapp.com/socket.io" href="https://excalidraw-socket.herokuapp.com/socket.io"
rel="preconnect" rel="preconnect"

View File

@ -2652,4 +2652,3 @@ if (
} }
export default App; export default App;
// -----------------------------------------------------------------------------

View File

@ -1,4 +1,4 @@
@import "../_variables"; @import "../css/_variables";
.Dialog__title { .Dialog__title {
display: grid; display: grid;

View File

@ -1,4 +1,4 @@
@import "../_variables"; @import "../css/_variables";
.ExportDialog__preview { .ExportDialog__preview {
--preview-padding: calc(var(--space-factor) * 4); --preview-padding: calc(var(--space-factor) * 4);

View File

@ -1,4 +1,4 @@
@import "../_variables"; @import "../css/_variables";
.HintViewer { .HintViewer {
color: $oc-gray-6; color: $oc-gray-6;

View File

@ -1,4 +1,4 @@
@import "../_variables"; @import "../css/_variables";
.Modal { .Modal {
position: fixed; position: fixed;

View File

@ -1,4 +1,4 @@
@import "../_variables"; @import "../css/_variables";
.RoomDialog-modalButton.is-collaborating { .RoomDialog-modalButton.is-collaborating {
background-color: $oc-green-0; background-color: $oc-green-0;

View File

@ -1,4 +1,4 @@
@import "../_variables.scss"; @import "../css/_variables.scss";
.TextInput { .TextInput {
display: inline-block; display: inline-block;

33
src/components/Toast.css Normal file
View File

@ -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);
}

97
src/components/Toast.tsx Normal file
View File

@ -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);
}

View File

@ -1,13 +1,13 @@
/* http://www.eaglefonts.com/fg-virgil-ttf-131249.htm */ /* http://www.eaglefonts.com/fg-virgil-ttf-131249.htm */
@font-face { @font-face {
font-family: "Virgil"; font-family: "Virgil";
src: url("FG_Virgil.woff2"); src: url("../fonts/FG_Virgil.woff2");
font-display: swap; font-display: swap;
} }
/* https://github.com/microsoft/cascadia-code */ /* https://github.com/microsoft/cascadia-code */
@font-face { @font-face {
font-family: "Cascadia"; font-family: "Cascadia";
src: url("Cascadia.woff2"); src: url("../fonts/Cascadia.woff2");
font-display: swap; font-display: swap;
} }

View File

@ -1,4 +1,6 @@
@import "./_variables"; @import "./_variables";
@import "./theme";
@import "./fonts";
:root { :root {
--sat: env(safe-area-inset-top); --sat: env(safe-area-inset-top);

7
src/css/theme.scss Normal file
View File

@ -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;
}

View File

@ -54,8 +54,9 @@ const elements = [
}, },
]; ];
registerFont("./public/FG_Virgil.ttf", { family: "Virgil" }); registerFont("./static/fonts/FG_Virgil.ttf", { family: "Virgil" });
registerFont("./public/Cascadia.ttf", { family: "Cascadia" }); registerFont("./static/fonts/Cascadia.ttf", { family: "Cascadia" });
const canvas = exportToCanvas( const canvas = exportToCanvas(
elements as any, elements as any,
getDefaultAppState(), getDefaultAppState(),

View File

@ -2,10 +2,13 @@ import React from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import * as Sentry from "@sentry/browser"; import * as Sentry from "@sentry/browser";
import * as SentryIntegrations from "@sentry/integrations"; import * as SentryIntegrations from "@sentry/integrations";
import { TopErrorBoundary } from "./components/TopErrorBoundary"; import { TopErrorBoundary } from "./components/TopErrorBoundary";
import { IsMobileProvider } from "./is-mobile"; import { IsMobileProvider } from "./is-mobile";
import App from "./components/App"; import App from "./components/App";
import "./styles.scss"; import { register as registerServiceWorker } from "./serviceWorker";
import "./css/styles.scss";
const SentryEnvHostnameMap: { [key: string]: string } = { const SentryEnvHostnameMap: { [key: string]: string } = {
"excalidraw.com": "production", "excalidraw.com": "production",
@ -52,3 +55,5 @@ ReactDOM.render(
</TopErrorBoundary>, </TopErrorBoundary>,
rootElement, rootElement,
); );
registerServiceWorker();

View File

@ -94,11 +94,11 @@ export function exportToSvg(
<style> <style>
@font-face { @font-face {
font-family: "Virgil"; font-family: "Virgil";
src: url("https://excalidraw.com/FG_Virgil.woff2"); src: url("https://excalidraw.com/static/fonts/FG_Virgil.woff2");
} }
@font-face { @font-face {
font-family: "Cascadia"; font-family: "Cascadia";
src: url("https://excalidraw.com/Cascadia.woff2"); src: url("https://excalidraw.com/static/fonts/Cascadia.woff2");
} }
</style> </style>
</defs> </defs>

146
src/serviceWorker.tsx Normal file
View File

@ -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);
});
}
}