Compare commits

..

5 Commits

Author SHA1 Message Date
dwelle 7f4b72010e fix changing font when editing text 2021-10-28 18:52:31 +02:00
ad1992 eff5871147 Add more redacted fonts 2021-10-28 21:59:50 +05:30
ad1992 4eb5ec70be Add blokk 2021-10-28 14:17:35 +05:30
ad1992 ae2ab5f03a Add scribble 2021-10-28 13:46:56 +05:30
ad1992 468f20ae58 feat: Add wireframe font redacted 2021-10-28 13:23:10 +05:30
166 changed files with 4147 additions and 5425 deletions
+5 -8
View File
@@ -1,8 +1,5 @@
REACT_APP_BACKEND_V2_GET_URL=https://json-dev.excalidraw.com/api/v2/ REACT_APP_BACKEND_V1_GET_URL=https://json.excalidraw.com/api/v1/
REACT_APP_BACKEND_V2_POST_URL=https://json-dev.excalidraw.com/api/v2/post/ REACT_APP_BACKEND_V2_GET_URL=https://json.excalidraw.com/api/v2/
REACT_APP_BACKEND_V2_POST_URL=https://json.excalidraw.com/api/v2/post/
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com REACT_APP_SOCKET_SERVER_URL=https://oss-collab-us1.excalidraw.com
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
REACT_APP_SOCKET_SERVER_URL=http://localhost:3000
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyCMkxA60XIW8KbqMYL7edC4qT5l4qHX2h8","authDomain":"excalidraw-oss-dev.firebaseapp.com","projectId":"excalidraw-oss-dev","storageBucket":"excalidraw-oss-dev.appspot.com","messagingSenderId":"664559512677","appId":"1:664559512677:web:a385181f2928d328a7aa8c"}'
-10
View File
@@ -1,11 +1 @@
REACT_APP_BACKEND_V2_GET_URL=https://json.excalidraw.com/api/v2/
REACT_APP_BACKEND_V2_POST_URL=https://json.excalidraw.com/api/v2/post/
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries
REACT_APP_SOCKET_SERVER_URL=https://oss-collab-us1.excalidraw.com
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
# production-only vars
REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13 REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13
+1 -2
View File
@@ -1,7 +1,6 @@
{ {
"extends": ["@excalidraw/eslint-config", "react-app"], "extends": ["@excalidraw/eslint-config", "react-app"],
"rules": { "rules": {
"import/no-anonymous-default-export": "off", "import/no-anonymous-default-export": "off"
"no-restricted-globals": "off"
} }
} }
-3
View File
@@ -10,7 +10,6 @@ updates:
- lipis - lipis
assignees: assignees:
- lipis - lipis
open-pull-requests-limit: 20
- package-ecosystem: npm - package-ecosystem: npm
directory: /src/packages/excalidraw/ directory: /src/packages/excalidraw/
@@ -22,7 +21,6 @@ updates:
- ad1992 - ad1992
assignees: assignees:
- ad1992 - ad1992
open-pull-requests-limit: 20
- package-ecosystem: npm - package-ecosystem: npm
directory: /src/packages/utils/ directory: /src/packages/utils/
@@ -34,4 +32,3 @@ updates:
- ad1992 - ad1992
assignees: assignees:
- ad1992 - ad1992
open-pull-requests-limit: 20
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- uses: docker/build-push-action@v2 - uses: docker/build-push-action@v1
with: with:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
-1
View File
@@ -1 +0,0 @@
yarn lint-staged
+27 -26
View File
@@ -21,26 +21,26 @@
"dependencies": { "dependencies": {
"@sentry/browser": "6.2.5", "@sentry/browser": "6.2.5",
"@sentry/integrations": "6.2.5", "@sentry/integrations": "6.2.5",
"@testing-library/jest-dom": "5.15.0", "@testing-library/jest-dom": "5.11.10",
"@testing-library/react": "12.1.2", "@testing-library/react": "11.2.6",
"@tldraw/vec": "0.1.3", "@tldraw/vec": "0.0.106",
"@types/jest": "27.0.2", "@types/jest": "26.0.22",
"@types/pica": "5.1.3", "@types/pica": "5.1.3",
"@types/react": "17.0.34", "@types/react": "17.0.3",
"@types/react-dom": "17.0.11", "@types/react-dom": "17.0.3",
"@types/socket.io-client": "1.4.36", "@types/socket.io-client": "1.4.36",
"browser-fs-access": "0.21.1", "browser-fs-access": "0.21.0",
"clsx": "1.1.1", "clsx": "1.1.1",
"fake-indexeddb": "3.1.7", "fake-indexeddb": "3.1.3",
"firebase": "8.3.3", "firebase": "8.3.3",
"i18next-browser-languagedetector": "6.1.2", "i18next-browser-languagedetector": "6.1.0",
"idb-keyval": "6.0.3", "idb-keyval": "5.1.3",
"image-blob-reduce": "3.0.1", "image-blob-reduce": "3.0.1",
"lodash.throttle": "4.1.1", "lodash.throttle": "4.1.1",
"nanoid": "3.1.30", "nanoid": "3.1.22",
"open-color": "1.9.1", "open-color": "1.8.0",
"pako": "1.0.11", "pako": "1.0.11",
"perfect-freehand": "1.0.16", "perfect-freehand": "1.0.15",
"png-chunk-text": "1.0.0", "png-chunk-text": "1.0.0",
"png-chunks-encode": "1.0.0", "png-chunks-encode": "1.0.0",
"png-chunks-extract": "1.0.0", "png-chunks-extract": "1.0.0",
@@ -49,36 +49,38 @@
"react": "17.0.2", "react": "17.0.2",
"react-dom": "17.0.2", "react-dom": "17.0.2",
"react-scripts": "4.0.3", "react-scripts": "4.0.3",
"roughjs": "4.5.0", "roughjs": "4.4.1",
"sass": "1.43.4", "sass": "1.32.10",
"socket.io-client": "2.3.1", "socket.io-client": "2.3.1",
"typescript": "4.5.2" "typescript": "4.2.4"
}, },
"devDependencies": { "devDependencies": {
"@excalidraw/eslint-config": "1.0.0", "@excalidraw/eslint-config": "1.0.0",
"@excalidraw/prettier-config": "1.0.2", "@excalidraw/prettier-config": "1.0.2",
"@types/chai": "4.2.22", "@types/chai": "4.2.22",
"@types/lodash.throttle": "4.1.6", "@types/lodash.throttle": "4.1.6",
"@types/pako": "1.0.2", "@types/pako": "1.0.1",
"@types/resize-observer-browser": "0.1.6", "@types/resize-observer-browser": "0.1.5",
"chai": "4.3.4", "chai": "4.3.4",
"eslint-config-prettier": "8.3.0", "eslint-config-prettier": "8.3.0",
"eslint-plugin-prettier": "3.3.1", "eslint-plugin-prettier": "3.3.1",
"firebase-tools": "9.22.0", "firebase-tools": "9.9.0",
"husky": "7.0.4", "husky": "4.3.8",
"jest-canvas-mock": "2.3.1", "jest-canvas-mock": "2.3.1",
"lint-staged": "12.0.1", "lint-staged": "10.5.4",
"pepjs": "0.5.3", "pepjs": "0.5.3",
"prettier": "2.4.1", "prettier": "2.2.1",
"rewire": "5.0.0" "rewire": "5.0.0"
}, },
"resolutions": {
"@typescript-eslint/typescript-estree": "5.3.0"
},
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
}, },
"homepage": ".", "homepage": ".",
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"jest": { "jest": {
"transformIgnorePatterns": [ "transformIgnorePatterns": [
"node_modules/(?!(roughjs|points-on-curve|path-data-parser|points-on-path|browser-fs-access)/)" "node_modules/(?!(roughjs|points-on-curve|path-data-parser|points-on-path|browser-fs-access)/)"
@@ -100,7 +102,6 @@
"fix": "yarn fix:other && yarn fix:code", "fix": "yarn fix:other && yarn fix:code",
"locales-coverage": "node scripts/build-locales-coverage.js", "locales-coverage": "node scripts/build-locales-coverage.js",
"locales-coverage:description": "node scripts/locales-coverage-description.js", "locales-coverage:description": "node scripts/locales-coverage-description.js",
"prepare": "husky install",
"prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore", "prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore",
"start": "react-scripts start", "start": "react-scripts start",
"test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watchAll=false", "test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watchAll=false",
Binary file not shown.
+30
View File
@@ -11,3 +11,33 @@
src: url("Cascadia.woff2"); src: url("Cascadia.woff2");
font-display: swap; font-display: swap;
} }
@font-face {
font-family: "REDACTED_REGULAR";
src: url("redacted-regular.woff2");
font-display: swap;
}
@font-face {
font-family: "REDACTED_SCRIPT_BOLD";
src: url("redacted-script-bold.woff2");
font-display: swap;
}
@font-face {
font-family: "REDACTED_SCRIPT_REGULAR";
src: url("redacted-script-regular.woff2");
font-display: swap;
}
@font-face {
font-family: "Scribble";
src: url("scribble-webfont.woff2");
font-display: swap;
}
@font-face {
font-family: "Blokk";
src: url("BLOKKNeue-Regular.woff2");
font-display: swap;
}
+12
View File
@@ -13,6 +13,18 @@
<meta name="theme-color" content="#000" /> <meta name="theme-color" content="#000" />
<!-- Declarative Link Capturing (https://web.dev/declarative-link-capturing/) -->
<meta
http-equiv="origin-trial"
content="Ak3VyzTheARtX2CnxBZ3ZKxImB0mNyvDakmMxeAChgxrWFMZ3IGN64VP+uj36VxM5OegsbLmrP258b1xvqp7+Q8AAABbeyJvcmlnaW4iOiJodHRwczovL2V4Y2FsaWRyYXcuY29tOjQ0MyIsImZlYXR1cmUiOiJXZWJBcHBMaW5rQ2FwdHVyaW5nIiwiZXhwaXJ5IjoxNjM0MDgzMTk5fQ=="
/>
<!-- File Handling (https://web.dev/file-handling/) -->
<meta
http-equiv="origin-trial"
content="AkMQsAnFmKfRfPKQHNCv2WmZREqgwkqhyt2M7aOwQiCStB+hPYnGnv+mNbkPDAsGXrwsj/waFi76wPzTDUaEeQ0AAABUeyJvcmlnaW4iOiJodHRwczovL2V4Y2FsaWRyYXcuY29tOjQ0MyIsImZlYXR1cmUiOiJGaWxlSGFuZGxpbmciLCJleHBpcnkiOjE2MzQwODMxOTl9"
/>
<!-- General tags --> <!-- General tags -->
<meta <meta
name="description" name="description"
+1
View File
@@ -26,6 +26,7 @@
} }
} }
], ],
"capture_links": "new-client",
"share_target": { "share_target": {
"action": "/web-share-target", "action": "/web-share-target",
"method": "POST", "method": "POST",
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -15,8 +15,8 @@ const publish = () => {
execSync(`yarn --frozen-lockfile`, { cwd: excalidrawDir }); execSync(`yarn --frozen-lockfile`, { cwd: excalidrawDir });
execSync(`yarn run build:umd`, { cwd: excalidrawDir }); execSync(`yarn run build:umd`, { cwd: excalidrawDir });
execSync(`yarn --cwd ${excalidrawDir} publish`); execSync(`yarn --cwd ${excalidrawDir} publish`);
} catch (error) { } catch (e) {
console.error(error); console.error(e);
} }
}; };
+9 -12
View File
@@ -1,16 +1,11 @@
const { readdirSync, writeFileSync } = require("fs"); const { readdirSync, writeFileSync } = require("fs");
const files = readdirSync(`${__dirname}/../src/locales`); const files = readdirSync(`${__dirname}/../src/locales`);
const flatten = (object = {}, result = {}, extraKey = "") => { const flatten = (object) =>
for (const key in object) { Object.keys(object).reduce(
if (typeof object[key] !== "object") { (initial, current) => ({ ...initial, ...object[current] }),
result[extraKey + key] = object[key]; {},
} else { );
flatten(object[key], result, `${extraKey}${key}.`);
}
}
return result;
};
const locales = files.filter( const locales = files.filter(
(file) => file !== "README.md" && file !== "percentages.json", (file) => file !== "README.md" && file !== "percentages.json",
@@ -24,8 +19,10 @@ for (let index = 0; index < locales.length; index++) {
const allKeys = Object.keys(data); const allKeys = Object.keys(data);
const translatedKeys = allKeys.filter((item) => data[item] !== ""); const translatedKeys = allKeys.filter((item) => data[item] !== "");
const percentage = Math.floor((100 * translatedKeys.length) / allKeys.length);
percentages[currentLocale.replace(".json", "")] = percentage; const percentage = (100 * translatedKeys.length) / allKeys.length;
percentages[currentLocale.replace(".json", "")] = parseInt(percentage);
} }
writeFileSync( writeFileSync(
+6 -21
View File
@@ -5,9 +5,7 @@ const THRESSHOLD = 85;
const crowdinMap = { const crowdinMap = {
"ar-SA": "en-ar", "ar-SA": "en-ar",
"bg-BG": "en-bg", "bg-BG": "en-bg",
"bn-BD": "en-bn",
"ca-ES": "en-ca", "ca-ES": "en-ca",
"da-DK": "en-da",
"de-DE": "en-de", "de-DE": "en-de",
"el-GR": "en-el", "el-GR": "en-el",
"es-ES": "en-es", "es-ES": "en-es",
@@ -33,14 +31,11 @@ const crowdinMap = {
"pt-PT": "en-pt", "pt-PT": "en-pt",
"ro-RO": "en-ro", "ro-RO": "en-ro",
"ru-RU": "en-ru", "ru-RU": "en-ru",
"si-LK": "en-silk",
"sk-SK": "en-sk", "sk-SK": "en-sk",
"sv-SE": "en-sv", "sv-SE": "en-sv",
"ta-IN": "en-ta",
"tr-TR": "en-tr", "tr-TR": "en-tr",
"uk-UA": "en-uk", "uk-UA": "en-uk",
"zh-CN": "en-zhcn", "zh-CN": "en-zhcn",
"zh-HK": "en-zhhk",
"zh-TW": "en-zhtw", "zh-TW": "en-zhtw",
"lv-LV": "en-lv", "lv-LV": "en-lv",
"cs-CZ": "en-cs", "cs-CZ": "en-cs",
@@ -50,10 +45,7 @@ const crowdinMap = {
const flags = { const flags = {
"ar-SA": "🇸🇦", "ar-SA": "🇸🇦",
"bg-BG": "🇧🇬", "bg-BG": "🇧🇬",
"bn-BD": "🇧🇩",
"ca-ES": "🏳", "ca-ES": "🏳",
"cs-CZ": "🇨🇿",
"da-DK": "🇩🇰",
"de-DE": "🇩🇪", "de-DE": "🇩🇪",
"el-GR": "🇬🇷", "el-GR": "🇬🇷",
"es-ES": "🇪🇸", "es-ES": "🇪🇸",
@@ -67,9 +59,7 @@ const flags = {
"it-IT": "🇮🇹", "it-IT": "🇮🇹",
"ja-JP": "🇯🇵", "ja-JP": "🇯🇵",
"kab-KAB": "🏳", "kab-KAB": "🏳",
"kk-KZ": "🇰🇿",
"ko-KR": "🇰🇷", "ko-KR": "🇰🇷",
"lv-LV": "🇱🇻",
"my-MM": "🇲🇲", "my-MM": "🇲🇲",
"nb-NO": "🇳🇴", "nb-NO": "🇳🇴",
"nl-NL": "🇳🇱", "nl-NL": "🇳🇱",
@@ -81,24 +71,21 @@ const flags = {
"pt-PT": "🇵🇹", "pt-PT": "🇵🇹",
"ro-RO": "🇷🇴", "ro-RO": "🇷🇴",
"ru-RU": "🇷🇺", "ru-RU": "🇷🇺",
"si-LK": "🇱🇰",
"sk-SK": "🇸🇰", "sk-SK": "🇸🇰",
"sv-SE": "🇸🇪", "sv-SE": "🇸🇪",
"ta-IN": "🇮🇳",
"tr-TR": "🇹🇷", "tr-TR": "🇹🇷",
"uk-UA": "🇺🇦", "uk-UA": "🇺🇦",
"zh-CN": "🇨🇳", "zh-CN": "🇨🇳",
"zh-HK": "🇭🇰",
"zh-TW": "🇹🇼", "zh-TW": "🇹🇼",
"lv-LV": "🇱🇻",
"cs-CZ": "🇨🇿",
"kk-KZ": "🇰🇿",
}; };
const languages = { const languages = {
"ar-SA": "العربية", "ar-SA": "العربية",
"bg-BG": "Български", "bg-BG": "Български",
"bn-BD": "Bengali",
"ca-ES": "Català", "ca-ES": "Català",
"cs-CZ": "Česky",
"da-DK": "Dansk",
"de-DE": "Deutsch", "de-DE": "Deutsch",
"el-GR": "Ελληνικά", "el-GR": "Ελληνικά",
"es-ES": "Español", "es-ES": "Español",
@@ -112,9 +99,7 @@ const languages = {
"it-IT": "Italiano", "it-IT": "Italiano",
"ja-JP": "日本語", "ja-JP": "日本語",
"kab-KAB": "Taqbaylit", "kab-KAB": "Taqbaylit",
"kk-KZ": "Қазақ тілі",
"ko-KR": "한국어", "ko-KR": "한국어",
"lv-LV": "Latviešu",
"my-MM": "Burmese", "my-MM": "Burmese",
"nb-NO": "Norsk bokmål", "nb-NO": "Norsk bokmål",
"nl-NL": "Nederlands", "nl-NL": "Nederlands",
@@ -126,15 +111,15 @@ const languages = {
"pt-PT": "Português", "pt-PT": "Português",
"ro-RO": "Română", "ro-RO": "Română",
"ru-RU": "Русский", "ru-RU": "Русский",
"si-LK": "සිංහල",
"sk-SK": "Slovenčina", "sk-SK": "Slovenčina",
"sv-SE": "Svenska", "sv-SE": "Svenska",
"ta-IN": "Tamil",
"tr-TR": "Türkçe", "tr-TR": "Türkçe",
"uk-UA": "Українська", "uk-UA": "Українська",
"zh-CN": "简体中文", "zh-CN": "简体中文",
"zh-HK": "繁體中文 (香港)",
"zh-TW": "繁體中文", "zh-TW": "繁體中文",
"lv-LV": "Latviešu",
"cs-CZ": "Česky",
"kk-KZ": "Қазақ тілі",
}; };
const percentages = fs.readFileSync( const percentages = fs.readFileSync(
+2 -2
View File
@@ -25,8 +25,8 @@ const release = async (nextVersion) => {
); );
/* eslint-disable no-console */ /* eslint-disable no-console */
console.log("Done!"); console.log("Done!");
} catch (error) { } catch (e) {
console.error(error); console.error(e);
process.exit(1); process.exit(1);
} }
}; };
+2 -2
View File
@@ -28,8 +28,8 @@ const getCommitHashForLastVersion = async () => {
`git log --format=format:"%H" --grep=${commitMessage}`, `git log --format=format:"%H" --grep=${commitMessage}`,
); );
return stdout; return stdout;
} catch (error) { } catch (e) {
console.error(error); console.error(e);
} }
}; };
+11 -45
View File
@@ -2,56 +2,22 @@ import { register } from "./register";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
import { deepCopyElement } from "../element/newElement"; import { deepCopyElement } from "../element/newElement";
import { randomId } from "../random";
import { t } from "../i18n";
export const actionAddToLibrary = register({ export const actionAddToLibrary = register({
name: "addToLibrary", name: "addToLibrary",
perform: (elements, appState, _, app) => { perform: (elements, appState, _, app) => {
if (elements.some((element) => element.type === "image")) { const selectedElements = getSelectedElements(
return { getNonDeletedElements(elements),
commitToHistory: false, appState,
appState: { );
...appState,
errorMessage: "Support for adding images to the library coming soon!",
},
};
}
return app.library app.library.loadLibrary().then((items) => {
.loadLibrary() app.library.saveLibrary([
.then((items) => { ...items,
return app.library.saveLibrary([ selectedElements.map(deepCopyElement),
{ ]);
id: randomId(), });
status: "unpublished", return false;
elements: getSelectedElements(
getNonDeletedElements(elements),
appState,
).map(deepCopyElement),
created: Date.now(),
},
...items,
]);
})
.then(() => {
return {
commitToHistory: false,
appState: {
...appState,
toastMessage: t("toast.addedToLibrary"),
},
};
})
.catch((error) => {
return {
commitToHistory: false,
appState: {
...appState,
errorMessage: error.message,
},
};
});
}, },
contextItemLabel: "labels.addToLibrary", contextItemLabel: "labels.addToLibrary",
}); });
+2 -2
View File
@@ -56,7 +56,7 @@ export const actionCopyAsSvg = register({
return { return {
commitToHistory: false, commitToHistory: false,
}; };
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
return { return {
appState: { appState: {
@@ -106,7 +106,7 @@ export const actionCopyAsPng = register({
}, },
commitToHistory: false, commitToHistory: false,
}; };
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
return { return {
appState: { appState: {
+4 -2
View File
@@ -110,8 +110,10 @@ export const actionDeleteSelected = register({
}; };
} }
let { elements: nextElements, appState: nextAppState } = let {
deleteSelectedElements(elements, appState); elements: nextElements,
appState: nextAppState,
} = deleteSelectedElements(elements, appState);
fixBindingsAfterDeletion( fixBindingsAfterDeletion(
nextElements, nextElements,
elements.filter(({ id }) => appState.selectedElementIds[id]), elements.filter(({ id }) => appState.selectedElementIds[id]),
+3 -8
View File
@@ -151,11 +151,9 @@ export const actionSaveToActiveFile = register({
: null, : null,
}, },
}; };
} catch (error: any) { } catch (error) {
if (error?.name !== "AbortError") { if (error?.name !== "AbortError") {
console.error(error); console.error(error);
} else {
console.warn(error);
} }
return { commitToHistory: false }; return { commitToHistory: false };
} }
@@ -183,11 +181,9 @@ export const actionSaveFileToDisk = register({
app.files, app.files,
); );
return { commitToHistory: false, appState: { ...appState, fileHandle } }; return { commitToHistory: false, appState: { ...appState, fileHandle } };
} catch (error: any) { } catch (error) {
if (error?.name !== "AbortError") { if (error?.name !== "AbortError") {
console.error(error); console.error(error);
} else {
console.warn(error);
} }
return { commitToHistory: false }; return { commitToHistory: false };
} }
@@ -223,9 +219,8 @@ export const actionLoadScene = register({
files, files,
commitToHistory: true, commitToHistory: true,
}; };
} catch (error: any) { } catch (error) {
if (error?.name === "AbortError") { if (error?.name === "AbortError") {
console.warn(error);
return false; return false;
} }
return { return {
+5 -2
View File
@@ -19,8 +19,11 @@ export const actionFinalize = register({
name: "finalize", name: "finalize",
perform: (elements, appState, _, { canvas, focusContainer }) => { perform: (elements, appState, _, { canvas, focusContainer }) => {
if (appState.editingLinearElement) { if (appState.editingLinearElement) {
const { elementId, startBindingElement, endBindingElement } = const {
appState.editingLinearElement; elementId,
startBindingElement,
endBindingElement,
} = appState.editingLinearElement;
const element = LinearElementEditor.getElement(elementId); const element = LinearElementEditor.getElement(elementId);
if (element) { if (element) {
+3 -2
View File
@@ -99,8 +99,9 @@ export const actionGroup = register({
// to the z order of the highest element in the layer stack // to the z order of the highest element in the layer stack
const elementsInGroup = getElementsInGroup(updatedElements, newGroupId); const elementsInGroup = getElementsInGroup(updatedElements, newGroupId);
const lastElementInGroup = elementsInGroup[elementsInGroup.length - 1]; const lastElementInGroup = elementsInGroup[elementsInGroup.length - 1];
const lastGroupElementIndex = const lastGroupElementIndex = updatedElements.lastIndexOf(
updatedElements.lastIndexOf(lastElementInGroup); lastElementInGroup,
);
const elementsAfterGroup = updatedElements.slice(lastGroupElementIndex + 1); const elementsAfterGroup = updatedElements.slice(lastGroupElementIndex + 1);
const elementsBeforeGroup = updatedElements const elementsBeforeGroup = updatedElements
.slice(0, lastGroupElementIndex) .slice(0, lastGroupElementIndex)
+39 -36
View File
@@ -13,9 +13,9 @@ import {
FillCrossHatchIcon, FillCrossHatchIcon,
FillHachureIcon, FillHachureIcon,
FillSolidIcon, FillSolidIcon,
FontFamilyCodeIcon, // FontFamilyCodeIcon,
FontFamilyHandDrawnIcon, // FontFamilyHandDrawnIcon,
FontFamilyNormalIcon, // FontFamilyNormalIcon,
FontSizeExtraLargeIcon, FontSizeExtraLargeIcon,
FontSizeLargeIcon, FontSizeLargeIcon,
FontSizeMediumIcon, FontSizeMediumIcon,
@@ -34,7 +34,7 @@ import {
import { import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
FONT_FAMILY, //FONT_FAMILY,
} from "../constants"; } from "../constants";
import { import {
getNonDeletedElements, getNonDeletedElements,
@@ -48,7 +48,7 @@ import {
ExcalidrawElement, ExcalidrawElement,
ExcalidrawLinearElement, ExcalidrawLinearElement,
ExcalidrawTextElement, ExcalidrawTextElement,
FontFamilyValues, //FontFamilyValues,
TextAlign, TextAlign,
} from "../element/types"; } from "../element/types";
import { getLanguage, t } from "../i18n"; import { getLanguage, t } from "../i18n";
@@ -62,6 +62,7 @@ import {
} from "../scene"; } from "../scene";
import { hasStrokeColor } from "../scene/comparisons"; import { hasStrokeColor } from "../scene/comparisons";
import { register } from "./register"; import { register } from "./register";
import FontsList from "../components/FontList";
const changeProperty = ( const changeProperty = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
@@ -506,41 +507,43 @@ export const actionChangeFontFamily = register({
}; };
}, },
PanelComponent: ({ elements, appState, updateData }) => { PanelComponent: ({ elements, appState, updateData }) => {
const options: { // const options: {
value: FontFamilyValues; // value: FontFamilyValues;
text: string; // text: string;
icon: JSX.Element; // icon: JSX.Element;
}[] = [ // }[] = [
{ // {
value: FONT_FAMILY.Virgil, // value: FONT_FAMILY.Virgil,
text: t("labels.handDrawn"), // text: t("labels.handDrawn"),
icon: <FontFamilyHandDrawnIcon theme={appState.theme} />, // icon: <FontFamilyHandDrawnIcon theme={appState.theme} />,
}, // },
{ // {
value: FONT_FAMILY.Helvetica, // value: FONT_FAMILY.Helvetica,
text: t("labels.normal"), // text: t("labels.normal"),
icon: <FontFamilyNormalIcon theme={appState.theme} />, // icon: <FontFamilyNormalIcon theme={appState.theme} />,
}, // },
{ // {
value: FONT_FAMILY.Cascadia, // value: FONT_FAMILY.Cascadia,
text: t("labels.code"), // text: t("labels.code"),
icon: <FontFamilyCodeIcon theme={appState.theme} />, // icon: <FontFamilyCodeIcon theme={appState.theme} />,
}, // },
]; // ];
return ( return (
<fieldset> <fieldset>
<legend>{t("labels.fontFamily")}</legend> <legend>{t("labels.fontFamily")}</legend>
<ButtonIconSelect<FontFamilyValues | false> <FontsList
group="font-family" onChange={(val) => {
options={options} updateData(val);
value={getFormValue( }}
elements, currentFontFamily={
appState, getFormValue(
(element) => isTextElement(element) && element.fontFamily, elements,
appState.currentItemFontFamily || DEFAULT_FONT_FAMILY, appState,
)} (element) => isTextElement(element) && element.fontFamily,
onChange={(value) => updateData(value)} appState.currentItemFontFamily || DEFAULT_FONT_FAMILY,
) || DEFAULT_FONT_FAMILY
}
/> />
</fieldset> </fieldset>
); );
+13 -1
View File
@@ -1,6 +1,13 @@
import { ExcalidrawElement } from "./element/types"; import { ExcalidrawElement } from "./element/types";
import { newElementWith } from "./element/mutateElement"; import { newElementWith } from "./element/mutateElement";
import { Box, getCommonBoundingBox } from "./element/bounds"; import { getCommonBounds } from "./element";
interface Box {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
export interface Alignment { export interface Alignment {
position: "start" | "center" | "end"; position: "start" | "center" | "end";
@@ -81,3 +88,8 @@ const calculateTranslation = (
(groupBoundingBox[min] + groupBoundingBox[max]) / 2, (groupBoundingBox[min] + groupBoundingBox[max]) / 2,
}; };
}; };
const getCommonBoundingBox = (elements: ExcalidrawElement[]): Box => {
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
return { minX, minY, maxX, maxY };
};
+5 -4
View File
@@ -96,9 +96,10 @@ const APP_STATE_STORAGE_CONF = (<
/** server (shareLink/collab/...) */ /** server (shareLink/collab/...) */
server: boolean; server: boolean;
}, },
T extends Record<keyof AppState, Values>, T extends Record<keyof AppState, Values>
>(config: { [K in keyof T]: K extends keyof AppState ? T[K] : never }) => >(
config)({ config: { [K in keyof T]: K extends keyof AppState ? T[K] : never },
) => config)({
theme: { browser: true, export: false, server: false }, theme: { browser: true, export: false, server: false },
collaborators: { browser: false, export: false, server: false }, collaborators: { browser: false, export: false, server: false },
currentChartType: { browser: true, export: false, server: false }, currentChartType: { browser: true, export: false, server: false },
@@ -171,7 +172,7 @@ const APP_STATE_STORAGE_CONF = (<
}); });
const _clearAppStateForStorage = < const _clearAppStateForStorage = <
ExportType extends "export" | "browser" | "server", ExportType extends "export" | "browser" | "server"
>( >(
appState: Partial<AppState>, appState: Partial<AppState>,
exportType: ExportType, exportType: ExportType,
+4 -4
View File
@@ -74,7 +74,7 @@ export const copyToClipboard = async (
try { try {
PREFER_APP_CLIPBOARD = false; PREFER_APP_CLIPBOARD = false;
await copyTextToSystemClipboard(json); await copyTextToSystemClipboard(json);
} catch (error: any) { } catch (error) {
PREFER_APP_CLIPBOARD = true; PREFER_APP_CLIPBOARD = true;
console.error(error); console.error(error);
} }
@@ -87,7 +87,7 @@ const getAppClipboard = (): Partial<ElementsClipboard> => {
try { try {
return JSON.parse(CLIPBOARD); return JSON.parse(CLIPBOARD);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
return {}; return {};
} }
@@ -179,7 +179,7 @@ export const copyTextToSystemClipboard = async (text: string | null) => {
// not focused // not focused
await navigator.clipboard.writeText(text || ""); await navigator.clipboard.writeText(text || "");
copied = true; copied = true;
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
} }
} }
@@ -219,7 +219,7 @@ const copyTextViaExecCommand = (text: string) => {
textarea.setSelectionRange(0, textarea.value.length); textarea.setSelectionRange(0, textarea.value.length);
success = document.execCommand("copy"); success = document.execCommand("copy");
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
} }
+75 -106
View File
@@ -43,8 +43,7 @@ import {
import { import {
APP_NAME, APP_NAME,
CURSOR_TYPE, CURSOR_TYPE,
DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_JPG, DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_OTHER,
DEFAULT_UI_OPTIONS, DEFAULT_UI_OPTIONS,
DEFAULT_VERTICAL_ALIGN, DEFAULT_VERTICAL_ALIGN,
DRAGGING_THRESHOLD, DRAGGING_THRESHOLD,
@@ -73,7 +72,7 @@ import {
import { loadFromBlob } from "../data"; import { loadFromBlob } from "../data";
import { isValidLibrary } from "../data/json"; import { isValidLibrary } from "../data/json";
import Library from "../data/library"; import Library from "../data/library";
import { restore, restoreElements, restoreLibraryItems } from "../data/restore"; import { restore, restoreElements } from "../data/restore";
import { import {
dragNewElement, dragNewElement,
dragSelectedElements, dragSelectedElements,
@@ -114,11 +113,7 @@ import {
updateBoundElements, updateBoundElements,
} from "../element/binding"; } from "../element/binding";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
import { import { bumpVersion, mutateElement } from "../element/mutateElement";
bumpVersion,
mutateElement,
newElementWith,
} from "../element/mutateElement";
import { deepCopyElement, newFreeDrawElement } from "../element/newElement"; import { deepCopyElement, newFreeDrawElement } from "../element/newElement";
import { import {
isBindingElement, isBindingElement,
@@ -223,7 +218,6 @@ import {
} from "../data/blob"; } from "../data/blob";
import { import {
getInitializedImageElements, getInitializedImageElements,
hasTransparentPixels,
loadHTMLImageElement, loadHTMLImageElement,
normalizeSVG, normalizeSVG,
updateImageCache as _updateImageCache, updateImageCache as _updateImageCache,
@@ -623,7 +617,7 @@ class App extends React.Component<AppProps, AppState> {
this.onBlur(); this.onBlur();
}; };
private disableEvent: EventListener = (event) => { private disableEvent: EventHandlerNonNull = (event) => {
event.preventDefault(); event.preventDefault();
}; };
@@ -657,19 +651,17 @@ class App extends React.Component<AppProps, AppState> {
if ( if (
token === this.id || token === this.id ||
window.confirm( window.confirm(
t("alerts.confirmAddLibrary", { t("alerts.confirmAddLibrary", { numShapes: json.library.length }),
numShapes: (json.libraryItems || json.library || []).length,
}),
) )
) { ) {
await this.library.importLibrary(blob, "published"); await this.library.importLibrary(blob);
// hack to rerender the library items after import // hack to rerender the library items after import
if (this.state.isLibraryOpen) { if (this.state.isLibraryOpen) {
this.setState({ isLibraryOpen: false }); this.setState({ isLibraryOpen: false });
} }
this.setState({ isLibraryOpen: true }); this.setState({ isLibraryOpen: true });
} }
} catch (error: any) { } catch (error) {
window.alert(t("alerts.errorLoadingLibrary")); window.alert(t("alerts.errorLoadingLibrary"));
console.error(error); console.error(error);
} finally { } finally {
@@ -736,10 +728,7 @@ class App extends React.Component<AppProps, AppState> {
try { try {
initialData = (await this.props.initialData) || null; initialData = (await this.props.initialData) || null;
if (initialData?.libraryItems) { if (initialData?.libraryItems) {
this.libraryItemsFromStorage = restoreLibraryItems( this.libraryItemsFromStorage = initialData.libraryItems;
initialData.libraryItems,
"unpublished",
) as LibraryItems;
} }
} catch (error: any) { } catch (error: any) {
console.error(error); console.error(error);
@@ -801,8 +790,7 @@ class App extends React.Component<AppProps, AppState> {
}; };
public async componentDidMount() { public async componentDidMount() {
this.excalidrawContainerValue.container = this.excalidrawContainerValue.container = this.excalidrawContainerRef.current;
this.excalidrawContainerRef.current;
if ( if (
process.env.NODE_ENV === ENV.TEST || process.env.NODE_ENV === ENV.TEST ||
@@ -844,8 +832,10 @@ class App extends React.Component<AppProps, AppState> {
this.resizeObserver = new ResizeObserver(() => { this.resizeObserver = new ResizeObserver(() => {
// compute isMobile state // compute isMobile state
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
const { width, height } = const {
this.excalidrawContainerRef.current!.getBoundingClientRect(); width,
height,
} = this.excalidrawContainerRef.current!.getBoundingClientRect();
this.isMobile = this.isMobile =
width < MQ_MAX_WIDTH_PORTRAIT || width < MQ_MAX_WIDTH_PORTRAIT ||
(height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE); (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE);
@@ -1249,8 +1239,9 @@ class App extends React.Component<AppProps, AppState> {
async (event: ClipboardEvent | null) => { async (event: ClipboardEvent | null) => {
// #686 // #686
const target = document.activeElement; const target = document.activeElement;
const isExcalidrawActive = const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
this.excalidrawContainerRef.current?.contains(target); target,
);
if (!isExcalidrawActive) { if (!isExcalidrawActive) {
return; return;
} }
@@ -1301,8 +1292,8 @@ class App extends React.Component<AppProps, AppState> {
if ((await this.props.onPaste(data, event)) === false) { if ((await this.props.onPaste(data, event)) === false) {
return; return;
} }
} catch (error: any) { } catch (e) {
console.error(error); console.error(e);
} }
} }
if (data.errorMessage) { if (data.errorMessage) {
@@ -1928,6 +1919,10 @@ class App extends React.Component<AppProps, AppState> {
this.setState({ this.setState({
draggingElement: null, draggingElement: null,
editingElement: null, editingElement: null,
selectedElementIds: {
...this.state.selectedElementIds,
[element.id]: true,
},
}); });
if (this.state.elementLocked) { if (this.state.elementLocked) {
setCursorForShape(this.canvas, this.state.elementType); setCursorForShape(this.canvas, this.state.elementType);
@@ -2212,10 +2207,7 @@ class App extends React.Component<AppProps, AppState> {
})); }));
this.resetShouldCacheIgnoreZoomDebounced(); this.resetShouldCacheIgnoreZoomDebounced();
} else { } else {
gesture.lastCenter = gesture.lastCenter = gesture.initialDistance = gesture.initialScale = null;
gesture.initialDistance =
gesture.initialScale =
null;
} }
if (isHoldingSpace || isPanning || isDraggingScrollBar) { if (isHoldingSpace || isPanning || isDraggingScrollBar) {
@@ -2524,11 +2516,13 @@ class App extends React.Component<AppProps, AppState> {
); );
} }
const onPointerMove = const onPointerMove = this.onPointerMoveFromPointerDownHandler(
this.onPointerMoveFromPointerDownHandler(pointerDownState); pointerDownState,
);
const onPointerUp = const onPointerUp = this.onPointerUpFromPointerDownHandler(
this.onPointerUpFromPointerDownHandler(pointerDownState); pointerDownState,
);
const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState); const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState); const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
@@ -2733,11 +2727,10 @@ class App extends React.Component<AppProps, AppState> {
allHitElements: [], allHitElements: [],
wasAddedToSelection: false, wasAddedToSelection: false,
hasBeenDuplicated: false, hasBeenDuplicated: false,
hasHitCommonBoundingBoxOfSelectedElements: hasHitCommonBoundingBoxOfSelectedElements: this.isHittingCommonBoundingBoxOfSelectedElements(
this.isHittingCommonBoundingBoxOfSelectedElements( origin,
origin, selectedElements,
selectedElements, ),
),
}, },
drag: { drag: {
hasOccurred: false, hasOccurred: false,
@@ -2814,15 +2807,14 @@ class App extends React.Component<AppProps, AppState> {
const elements = this.scene.getElements(); const elements = this.scene.getElements();
const selectedElements = getSelectedElements(elements, this.state); const selectedElements = getSelectedElements(elements, this.state);
if (selectedElements.length === 1 && !this.state.editingLinearElement) { if (selectedElements.length === 1 && !this.state.editingLinearElement) {
const elementWithTransformHandleType = const elementWithTransformHandleType = getElementWithTransformHandleType(
getElementWithTransformHandleType( elements,
elements, this.state,
this.state, pointerDownState.origin.x,
pointerDownState.origin.x, pointerDownState.origin.y,
pointerDownState.origin.y, this.state.zoom,
this.state.zoom, event.pointerType,
event.pointerType, );
);
if (elementWithTransformHandleType != null) { if (elementWithTransformHandleType != null) {
this.setState({ this.setState({
resizingElement: elementWithTransformHandleType.element, resizingElement: elementWithTransformHandleType.element,
@@ -2898,10 +2890,9 @@ class App extends React.Component<AppProps, AppState> {
); );
const hitElement = pointerDownState.hit.element; const hitElement = pointerDownState.hit.element;
const someHitElementIsSelected = const someHitElementIsSelected = pointerDownState.hit.allHitElements.some(
pointerDownState.hit.allHitElements.some((element) => (element) => this.isASelectedElement(element),
this.isASelectedElement(element), );
);
if ( if (
(hitElement === null || !someHitElementIsSelected) && (hitElement === null || !someHitElementIsSelected) &&
!event.shiftKey && !event.shiftKey &&
@@ -3563,8 +3554,8 @@ class App extends React.Component<AppProps, AppState> {
? { ? {
// if using ctrl/cmd, select the hitElement only if we // if using ctrl/cmd, select the hitElement only if we
// haven't box-selected anything else // haven't box-selected anything else
[pointerDownState.hit.element.id]: [pointerDownState.hit.element
!elementsWithinSelection.length, .id]: !elementsWithinSelection.length,
} }
: null), : null),
}, },
@@ -3712,7 +3703,7 @@ class App extends React.Component<AppProps, AppState> {
this.actionManager.executeAction(actionFinalize); this.actionManager.executeAction(actionFinalize);
}, },
); );
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
this.scene.replaceAllElements( this.scene.replaceAllElements(
this.scene this.scene
@@ -3981,7 +3972,7 @@ class App extends React.Component<AppProps, AppState> {
await normalizeSVG(await imageFile.text()), await normalizeSVG(await imageFile.text()),
imageFile.name, imageFile.name,
); );
} catch (error: any) { } catch (error) {
console.warn(error); console.warn(error);
throw new Error(t("errors.svgImageInsertError")); throw new Error(t("errors.svgImageInsertError"));
} }
@@ -4003,30 +3994,20 @@ class App extends React.Component<AppProps, AppState> {
const existingFileData = this.files[fileId]; const existingFileData = this.files[fileId];
if (!existingFileData?.dataURL) { if (!existingFileData?.dataURL) {
try { try {
if (!(await hasTransparentPixels(imageFile))) { imageFile = await resizeImageFile(
const _imageFile = await resizeImageFile(imageFile, { imageFile,
maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_JPG, DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
outputType: MIME_TYPES.jpg, );
}); } catch (error) {
if (_imageFile.size > MAX_ALLOWED_FILE_BYTES) {
imageFile = await resizeImageFile(imageFile, {
maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_OTHER,
outputType: MIME_TYPES.jpg,
});
} else {
imageFile = _imageFile;
}
} else {
imageFile = await resizeImageFile(imageFile, {
maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_OTHER,
});
}
} catch (error: any) {
console.error("error trying to resing image file on insertion", error); console.error("error trying to resing image file on insertion", error);
} }
if (imageFile.size > MAX_ALLOWED_FILE_BYTES) { if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
throw new Error(t("errors.fileTooBig")); throw new Error(
t("errors.fileTooBig", {
maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
}),
);
} }
} }
@@ -4078,7 +4059,7 @@ class App extends React.Component<AppProps, AppState> {
this.initializeImageDimensions(imageElement, true); this.initializeImageDimensions(imageElement, true);
} }
resolve(imageElement); resolve(imageElement);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
reject(new Error(t("errors.imageInsertError"))); reject(new Error(t("errors.imageInsertError")));
} finally { } finally {
@@ -4109,7 +4090,7 @@ class App extends React.Component<AppProps, AppState> {
imageElement, imageElement,
showCursorImagePreview, showCursorImagePreview,
}); });
} catch (error: any) { } catch (error) {
mutateElement(imageElement, { mutateElement(imageElement, {
isDeleted: true, isDeleted: true,
}); });
@@ -4125,9 +4106,7 @@ class App extends React.Component<AppProps, AppState> {
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
const cursorImageSizePx = 96; const cursorImageSizePx = 96;
const imagePreview = await resizeImageFile(imageFile, { const imagePreview = await resizeImageFile(imageFile, cursorImageSizePx);
maxWidthOrHeight: cursorImageSizePx,
});
let previewDataURL = await getDataURL(imagePreview); let previewDataURL = await getDataURL(imagePreview);
@@ -4206,11 +4185,9 @@ class App extends React.Component<AppProps, AppState> {
}, },
); );
} }
} catch (error: any) { } catch (error) {
if (error.name !== "AbortError") { if (error.name !== "AbortError") {
console.error(error); console.error(error);
} else {
console.warn(error);
} }
this.setState( this.setState(
{ {
@@ -4293,24 +4270,16 @@ class App extends React.Component<AppProps, AppState> {
if (updatedFiles.has(element.fileId)) { if (updatedFiles.has(element.fileId)) {
invalidateShapeForElement(element); invalidateShapeForElement(element);
} }
if (erroredFiles.has(element.fileId)) {
mutateElement(
element,
{ status: "error" },
/* informMutation */ false,
);
}
} }
} }
if (erroredFiles.size) {
this.scene.replaceAllElements(
this.scene.getElementsIncludingDeleted().map((element) => {
if (
isInitializedImageElement(element) &&
erroredFiles.has(element.fileId)
) {
return newElementWith(element, {
status: "error",
});
}
return element;
}),
);
}
return { updatedFiles, erroredFiles }; return { updatedFiles, erroredFiles };
}; };
@@ -4452,9 +4421,7 @@ class App extends React.Component<AppProps, AppState> {
// This will only work as of Chrome 86, // This will only work as of Chrome 86,
// but can be safely ignored on older releases. // but can be safely ignored on older releases.
const item = event.dataTransfer.items[0]; const item = event.dataTransfer.items[0];
(file as any).handle = await ( (file as any).handle = await (item as any).getAsFileSystemHandle();
item as any
).getAsFileSystemHandle();
} catch (error: any) { } catch (error: any) {
console.warn(error.name, error.message); console.warn(error.name, error.message);
} }
@@ -4576,8 +4543,10 @@ class App extends React.Component<AppProps, AppState> {
const type = element ? "element" : "canvas"; const type = element ? "element" : "canvas";
const container = this.excalidrawContainerRef.current!; const container = this.excalidrawContainerRef.current!;
const { top: offsetTop, left: offsetLeft } = const {
container.getBoundingClientRect(); top: offsetTop,
left: offsetLeft,
} = container.getBoundingClientRect();
const left = event.clientX - offsetLeft; const left = event.clientX - offsetLeft;
const top = event.clientY - offsetTop; const top = event.clientY - offsetTop;
+5 -8
View File
@@ -7,18 +7,15 @@ import "./CheckboxItem.scss";
export const CheckboxItem: React.FC<{ export const CheckboxItem: React.FC<{
checked: boolean; checked: boolean;
onChange: (checked: boolean) => void; onChange: (checked: boolean) => void;
className?: string; }> = ({ children, checked, onChange }) => {
}> = ({ children, checked, onChange, className }) => {
return ( return (
<div <div
className={clsx("Checkbox", className, { "is-checked": checked })} className={clsx("Checkbox", { "is-checked": checked })}
onClick={(event) => { onClick={(event) => {
onChange(!checked); onChange(!checked);
( ((event.currentTarget as HTMLDivElement).querySelector(
(event.currentTarget as HTMLDivElement).querySelector( ".Checkbox-box",
".Checkbox-box", ) as HTMLButtonElement).focus();
) as HTMLButtonElement
).focus();
}} }}
> >
<button className="Checkbox-box" role="checkbox" aria-checked={checked}> <button className="Checkbox-box" role="checkbox" aria-checked={checked}>
@@ -1,21 +1,22 @@
@import "../css/variables.module"; @import "../css/variables.module";
.excalidraw { .excalidraw {
.confirm-dialog { .clear-canvas {
&-buttons { &-buttons {
display: flex; display: flex;
padding: 0.2rem 0; padding: 0.2rem 0;
justify-content: flex-end; justify-content: flex-end;
}
.ToolIcon__icon {
min-width: 2.5rem;
width: auto;
font-size: 1rem;
}
.ToolIcon_type_button { .ToolIcon__icon {
margin-left: 0.8rem; min-width: 2.5rem;
padding: 0 0.5rem; width: auto;
font-size: 1rem;
}
.ToolIcon_type_button {
margin-left: 1.5rem;
padding: 0 0.5rem;
}
} }
&__content { &__content {
@@ -33,5 +34,9 @@
color: $oc-white; color: $oc-white;
} }
} }
&--cancel.ToolIcon_type_button {
background-color: $oc-gray-2;
}
} }
} }
+33 -9
View File
@@ -1,10 +1,11 @@
import { useState } from "react"; import { useState } from "react";
import { t } from "../i18n"; import { t } from "../i18n";
import { useIsMobile } from "./App"; import { useIsMobile } from "./App";
import { Dialog } from "./Dialog";
import { trash } from "./icons"; import { trash } from "./icons";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import ConfirmDialog from "./ConfirmDialog"; import "./ClearCanvas.scss";
const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => { const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => {
const [showDialog, setShowDialog] = useState(false); const [showDialog, setShowDialog] = useState(false);
@@ -25,16 +26,39 @@ const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => {
/> />
{showDialog && ( {showDialog && (
<ConfirmDialog <Dialog
onConfirm={() => { onCloseRequest={toggleDialog}
onConfirm();
toggleDialog();
}}
onCancel={toggleDialog}
title={t("clearCanvasDialog.title")} title={t("clearCanvasDialog.title")}
className="clear-canvas"
small={true}
> >
<p className="clear-canvas__content"> {t("alerts.clearReset")}</p> <>
</ConfirmDialog> <p className="clear-canvas__content"> {t("alerts.clearReset")}</p>
<div className="clear-canvas-buttons">
<ToolButton
type="button"
title={t("buttons.clear")}
aria-label={t("buttons.clear")}
label={t("buttons.clear")}
onClick={() => {
onConfirm();
toggleDialog();
}}
data-testid="confirm-clear-canvas-button"
className="clear-canvas--confirm"
/>
<ToolButton
type="button"
title={t("buttons.cancel")}
aria-label={t("buttons.cancel")}
label={t("buttons.cancel")}
onClick={toggleDialog}
data-testid="cancel-clear-canvas-button"
className="clear-canvas--cancel"
/>
</div>
</>
</Dialog>
)} )}
</> </>
); );
-52
View File
@@ -1,52 +0,0 @@
import { t } from "../i18n";
import { Dialog, DialogProps } from "./Dialog";
import { ToolButton } from "./ToolButton";
import "./ConfirmDialog.scss";
interface Props extends Omit<DialogProps, "onCloseRequest"> {
onConfirm: () => void;
onCancel: () => void;
confirmText?: string;
cancelText?: string;
}
const ConfirmDialog = (props: Props) => {
const {
onConfirm,
onCancel,
children,
confirmText = t("buttons.confirm"),
cancelText = t("buttons.cancel"),
className = "",
...rest
} = props;
return (
<Dialog
onCloseRequest={onCancel}
small={true}
{...rest}
className={`confirm-dialog ${className}`}
>
{children}
<div className="confirm-dialog-buttons">
<ToolButton
type="button"
title={cancelText}
aria-label={cancelText}
label={cancelText}
onClick={onCancel}
className="confirm-dialog--cancel"
/>
<ToolButton
type="button"
title={confirmText}
aria-label={confirmText}
label={confirmText}
onClick={onConfirm}
className="confirm-dialog--confirm"
/>
</div>
</Dialog>
);
};
export default ConfirmDialog;
+2 -6
View File
@@ -10,7 +10,7 @@ import { Island } from "./Island";
import { Modal } from "./Modal"; import { Modal } from "./Modal";
import { AppState } from "../types"; import { AppState } from "../types";
export interface DialogProps { export const Dialog = (props: {
children: React.ReactNode; children: React.ReactNode;
className?: string; className?: string;
small?: boolean; small?: boolean;
@@ -18,10 +18,7 @@ export interface DialogProps {
title: React.ReactNode; title: React.ReactNode;
autofocus?: boolean; autofocus?: boolean;
theme?: AppState["theme"]; theme?: AppState["theme"];
closeOnClickOutside?: boolean; }) => {
}
export const Dialog = (props: DialogProps) => {
const [islandNode, setIslandNode] = useCallbackRefState<HTMLDivElement>(); const [islandNode, setIslandNode] = useCallbackRefState<HTMLDivElement>();
const [lastActiveElement] = useState(document.activeElement); const [lastActiveElement] = useState(document.activeElement);
const { id } = useExcalidrawContainer(); const { id } = useExcalidrawContainer();
@@ -84,7 +81,6 @@ export const Dialog = (props: DialogProps) => {
maxWidth={props.small ? 550 : 800} maxWidth={props.small ? 550 : 800}
onCloseRequest={onClose} onCloseRequest={onClose}
theme={props.theme} theme={props.theme}
closeOnClickOutside={props.closeOnClickOutside}
> >
<Island ref={setIslandNode}> <Island ref={setIslandNode}>
<h2 id={`${id}-dialog-title`} className="Dialog__title"> <h2 id={`${id}-dialog-title`} className="Dialog__title">
+53
View File
@@ -0,0 +1,53 @@
import { FONT_FAMILY } from "../constants";
import { FontFamilyValues } from "../element/types";
const FontsList = ({
onChange,
currentFontFamily,
}: {
onChange: (val: FontFamilyValues) => void;
currentFontFamily: FontFamilyValues;
}) => {
return (
<select
className="dropdown-select"
onChange={(event) => {
onChange(Number(event.target.value));
}}
value={currentFontFamily}
>
<option key="virgil" value={FONT_FAMILY.Virgil}>
Hand-Drawn
</option>
<option key="helvetica" value={FONT_FAMILY.Helvetica}>
Normal
</option>
<option key="cascadia" value={FONT_FAMILY.Cascadia}>
code
</option>
<option key="redacted-regular" value={FONT_FAMILY.REDACTED_REGULAR}>
Redacted Regular
</option>
<option
key="redacted-script-regular"
value={FONT_FAMILY.REDACTED_SCRIPT_REGULAR}
>
Redacted Script
</option>
<option
key="redacted-script-bold"
value={FONT_FAMILY.REDACTED_SCRIPT_BOLD}
>
Redacted Script BOLD
</option>
<option key="Scribble" value={FONT_FAMILY.SCRIBBLE}>
Scribble
</option>
<option key="Blokk" value={FONT_FAMILY.BLOKK}>
Blokk
</option>
</select>
);
};
export default FontsList;
+3 -15
View File
@@ -11,16 +11,14 @@ import {
} from "../element/typeChecks"; } from "../element/typeChecks";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
interface HintViewerProps { interface Hint {
appState: AppState; appState: AppState;
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
isMobile: boolean;
} }
const getHints = ({ appState, elements, isMobile }: HintViewerProps) => { const getHints = ({ appState, elements }: Hint) => {
const { elementType, isResizing, isRotating, lastPointerDownWith } = appState; const { elementType, isResizing, isRotating, lastPointerDownWith } = appState;
const multiMode = appState.multiElement !== null; const multiMode = appState.multiElement !== null;
if (elementType === "arrow" || elementType === "line") { if (elementType === "arrow" || elementType === "line") {
if (!multiMode) { if (!multiMode) {
return t("hints.linearElement"); return t("hints.linearElement");
@@ -41,7 +39,6 @@ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => {
} }
const selectedElements = getSelectedElements(elements, appState); const selectedElements = getSelectedElements(elements, appState);
if ( if (
isResizing && isResizing &&
lastPointerDownWith === "mouse" && lastPointerDownWith === "mouse" &&
@@ -77,22 +74,13 @@ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => {
return t("hints.text_editing"); return t("hints.text_editing");
} }
if (elementType === "selection" && !selectedElements.length && !isMobile) {
return t("hints.canvasPanning");
}
return null; return null;
}; };
export const HintViewer = ({ export const HintViewer = ({ appState, elements }: Hint) => {
appState,
elements,
isMobile,
}: HintViewerProps) => {
let hint = getHints({ let hint = getHints({
appState, appState,
elements, elements,
isMobile,
}); });
if (!hint) { if (!hint) {
return null; return null;
+36
View File
@@ -1,6 +1,42 @@
@import "open-color/open-color"; @import "open-color/open-color";
.excalidraw { .excalidraw {
.layer-ui__library {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
.layer-ui__library-header {
display: flex;
align-items: center;
width: 100%;
margin: 2px 0;
button {
// 2px from the left to account for focus border of left-most button
margin: 0 2px;
}
a {
margin-inline-start: auto;
// 17px for scrollbar (needed for overlay scrollbars on Big Sur?) + 1px extra
padding-inline-end: 18px;
white-space: nowrap;
}
}
}
.layer-ui__library-message {
padding: 10px 20px;
max-width: 200px;
}
.layer-ui__library-items {
max-height: 50vh;
overflow: auto;
}
.layer-ui__wrapper { .layer-ui__wrapper {
z-index: var(--zIndex-layerUI); z-index: var(--zIndex-layerUI);
+353 -51
View File
@@ -1,15 +1,29 @@
import clsx from "clsx"; import clsx from "clsx";
import React, { useCallback } from "react"; import React, {
RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
import { CLASSES } from "../constants"; import { CLASSES } from "../constants";
import { exportCanvas } from "../data"; import { exportCanvas } from "../data";
import { importLibraryFromJSON, saveLibraryAsJSON } from "../data/json";
import { isTextElement, showSelectedShapeActions } from "../element"; import { isTextElement, showSelectedShapeActions } from "../element";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { Language, t } from "../i18n"; import { Language, t } from "../i18n";
import { useIsMobile } from "../components/App"; import { useIsMobile } from "../components/App";
import { calculateScrollCenter, getSelectedElements } from "../scene"; import { calculateScrollCenter, getSelectedElements } from "../scene";
import { ExportType } from "../scene/types"; import { ExportType } from "../scene/types";
import { AppProps, AppState, ExcalidrawProps, BinaryFiles } from "../types"; import {
AppProps,
AppState,
ExcalidrawProps,
BinaryFiles,
LibraryItem,
LibraryItems,
} from "../types";
import { muteFSAbortError } from "../utils"; import { muteFSAbortError } from "../utils";
import { SelectedShapeActions, ShapesSwitcher, ZoomActions } from "./Actions"; import { SelectedShapeActions, ShapesSwitcher, ZoomActions } from "./Actions";
import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle"; import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
@@ -18,8 +32,10 @@ import { ErrorDialog } from "./ErrorDialog";
import { ExportCB, ImageExportDialog } from "./ImageExportDialog"; import { ExportCB, ImageExportDialog } from "./ImageExportDialog";
import { FixedSideContainer } from "./FixedSideContainer"; import { FixedSideContainer } from "./FixedSideContainer";
import { HintViewer } from "./HintViewer"; import { HintViewer } from "./HintViewer";
import { exportFile, load, trash } from "./icons";
import { Island } from "./Island"; import { Island } from "./Island";
import "./LayerUI.scss"; import "./LayerUI.scss";
import { LibraryUnit } from "./LibraryUnit";
import { LoadingMessage } from "./LoadingMessage"; import { LoadingMessage } from "./LoadingMessage";
import { LockButton } from "./LockButton"; import { LockButton } from "./LockButton";
import { MobileMenu } from "./MobileMenu"; import { MobileMenu } from "./MobileMenu";
@@ -27,13 +43,13 @@ import { PasteChartDialog } from "./PasteChartDialog";
import { Section } from "./Section"; import { Section } from "./Section";
import { HelpDialog } from "./HelpDialog"; import { HelpDialog } from "./HelpDialog";
import Stack from "./Stack"; import Stack from "./Stack";
import { ToolButton } from "./ToolButton";
import { Tooltip } from "./Tooltip"; import { Tooltip } from "./Tooltip";
import { UserList } from "./UserList"; import { UserList } from "./UserList";
import Library from "../data/library"; import Library from "../data/library";
import { JSONExportDialog } from "./JSONExportDialog"; import { JSONExportDialog } from "./JSONExportDialog";
import { LibraryButton } from "./LibraryButton"; import { LibraryButton } from "./LibraryButton";
import { isImageFileHandle } from "../data/blob"; import { isImageFileHandle } from "../data/blob";
import { LibraryMenu } from "./LibraryMenu";
interface LayerUIProps { interface LayerUIProps {
actionManager: ActionManager; actionManager: ActionManager;
@@ -65,6 +81,302 @@ interface LayerUIProps {
onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void; onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void;
} }
const useOnClickOutside = (
ref: RefObject<HTMLElement>,
cb: (event: MouseEvent) => void,
) => {
useEffect(() => {
const listener = (event: MouseEvent) => {
if (!ref.current) {
return;
}
if (
event.target instanceof Element &&
(ref.current.contains(event.target) ||
!document.body.contains(event.target))
) {
return;
}
cb(event);
};
document.addEventListener("pointerdown", listener, false);
return () => {
document.removeEventListener("pointerdown", listener);
};
}, [ref, cb]);
};
const LibraryMenuItems = ({
libraryItems,
onRemoveFromLibrary,
onAddToLibrary,
onInsertShape,
pendingElements,
theme,
setAppState,
setLibraryItems,
libraryReturnUrl,
focusContainer,
library,
files,
id,
}: {
libraryItems: LibraryItems;
pendingElements: LibraryItem;
onRemoveFromLibrary: (index: number) => void;
onInsertShape: (elements: LibraryItem) => void;
onAddToLibrary: (elements: LibraryItem) => void;
theme: AppState["theme"];
files: BinaryFiles;
setAppState: React.Component<any, AppState>["setState"];
setLibraryItems: (library: LibraryItems) => void;
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
focusContainer: () => void;
library: Library;
id: string;
}) => {
const isMobile = useIsMobile();
const numCells = libraryItems.length + (pendingElements.length > 0 ? 1 : 0);
const CELLS_PER_ROW = isMobile ? 4 : 6;
const numRows = Math.max(1, Math.ceil(numCells / CELLS_PER_ROW));
const rows = [];
let addedPendingElements = false;
const referrer =
libraryReturnUrl || window.location.origin + window.location.pathname;
rows.push(
<div className="layer-ui__library-header" key="library-header">
<ToolButton
key="import"
type="button"
title={t("buttons.load")}
aria-label={t("buttons.load")}
icon={load}
onClick={() => {
importLibraryFromJSON(library)
.then(() => {
// Close and then open to get the libraries updated
setAppState({ isLibraryOpen: false });
setAppState({ isLibraryOpen: true });
})
.catch(muteFSAbortError)
.catch((error) => {
setAppState({ errorMessage: error.message });
});
}}
/>
{!!libraryItems.length && (
<>
<ToolButton
key="export"
type="button"
title={t("buttons.export")}
aria-label={t("buttons.export")}
icon={exportFile}
onClick={() => {
saveLibraryAsJSON(library)
.catch(muteFSAbortError)
.catch((error) => {
setAppState({ errorMessage: error.message });
});
}}
/>
<ToolButton
key="reset"
type="button"
title={t("buttons.resetLibrary")}
aria-label={t("buttons.resetLibrary")}
icon={trash}
onClick={() => {
if (window.confirm(t("alerts.resetLibrary"))) {
library.resetLibrary();
setLibraryItems([]);
focusContainer();
}
}}
/>
</>
)}
<a
href={`https://libraries.excalidraw.com?target=${
window.name || "_blank"
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}`}
target="_excalidraw_libraries"
>
{t("labels.libraries")}
</a>
</div>,
);
for (let row = 0; row < numRows; row++) {
const y = CELLS_PER_ROW * row;
const children = [];
for (let x = 0; x < CELLS_PER_ROW; x++) {
const shouldAddPendingElements: boolean =
pendingElements.length > 0 &&
!addedPendingElements &&
y + x >= libraryItems.length;
addedPendingElements = addedPendingElements || shouldAddPendingElements;
children.push(
<Stack.Col key={x}>
<LibraryUnit
elements={libraryItems[y + x]}
files={files}
pendingElements={
shouldAddPendingElements ? pendingElements : undefined
}
onRemoveFromLibrary={onRemoveFromLibrary.bind(null, y + x)}
onClick={
shouldAddPendingElements
? onAddToLibrary.bind(null, pendingElements)
: onInsertShape.bind(null, libraryItems[y + x])
}
/>
</Stack.Col>,
);
}
rows.push(
<Stack.Row align="center" gap={1} key={row}>
{children}
</Stack.Row>,
);
}
return (
<Stack.Col align="start" gap={1} className="layer-ui__library-items">
{rows}
</Stack.Col>
);
};
const LibraryMenu = ({
onClickOutside,
onInsertShape,
pendingElements,
onAddToLibrary,
theme,
setAppState,
files,
libraryReturnUrl,
focusContainer,
library,
id,
}: {
pendingElements: LibraryItem;
onClickOutside: (event: MouseEvent) => void;
onInsertShape: (elements: LibraryItem) => void;
onAddToLibrary: () => void;
theme: AppState["theme"];
files: BinaryFiles;
setAppState: React.Component<any, AppState>["setState"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
focusContainer: () => void;
library: Library;
id: string;
}) => {
const ref = useRef<HTMLDivElement | null>(null);
useOnClickOutside(ref, (event) => {
// If click on the library icon, do nothing.
if ((event.target as Element).closest(".ToolIcon_type_button__library")) {
return;
}
onClickOutside(event);
});
const [libraryItems, setLibraryItems] = useState<LibraryItems>([]);
const [loadingState, setIsLoading] = useState<
"preloading" | "loading" | "ready"
>("preloading");
const loadingTimerRef = useRef<number | null>(null);
useEffect(() => {
Promise.race([
new Promise((resolve) => {
loadingTimerRef.current = window.setTimeout(() => {
resolve("loading");
}, 100);
}),
library.loadLibrary().then((items) => {
setLibraryItems(items);
setIsLoading("ready");
}),
]).then((data) => {
if (data === "loading") {
setIsLoading("loading");
}
});
return () => {
clearTimeout(loadingTimerRef.current!);
};
}, [library]);
const removeFromLibrary = useCallback(
async (indexToRemove) => {
const items = await library.loadLibrary();
const nextItems = items.filter((_, index) => index !== indexToRemove);
library.saveLibrary(nextItems).catch((error) => {
setLibraryItems(items);
setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
});
setLibraryItems(nextItems);
},
[library, setAppState],
);
const addToLibrary = useCallback(
async (elements: LibraryItem) => {
if (elements.some((element) => element.type === "image")) {
return setAppState({
errorMessage: "Support for adding images to the library coming soon!",
});
}
const items = await library.loadLibrary();
const nextItems = [...items, elements];
onAddToLibrary();
library.saveLibrary(nextItems).catch((error) => {
setLibraryItems(items);
setAppState({ errorMessage: t("alerts.errorAddingToLibrary") });
});
setLibraryItems(nextItems);
},
[onAddToLibrary, library, setAppState],
);
return loadingState === "preloading" ? null : (
<Island padding={1} ref={ref} className="layer-ui__library">
{loadingState === "loading" ? (
<div className="layer-ui__library-message">
{t("labels.libraryLoadingMessage")}
</div>
) : (
<LibraryMenuItems
libraryItems={libraryItems}
onRemoveFromLibrary={removeFromLibrary}
onAddToLibrary={addToLibrary}
onInsertShape={onInsertShape}
pendingElements={pendingElements}
setAppState={setAppState}
setLibraryItems={setLibraryItems}
libraryReturnUrl={libraryReturnUrl}
focusContainer={focusContainer}
library={library}
theme={theme}
files={files}
id={id}
/>
)}
</Island>
);
};
const LayerUI = ({ const LayerUI = ({
actionManager, actionManager,
appState, appState,
@@ -114,34 +426,34 @@ const LayerUI = ({
return null; return null;
} }
const createExporter = const createExporter = (type: ExportType): ExportCB => async (
(type: ExportType): ExportCB => exportedElements,
async (exportedElements) => { ) => {
const fileHandle = await exportCanvas( const fileHandle = await exportCanvas(
type, type,
exportedElements, exportedElements,
appState, appState,
files, files,
{ {
exportBackground: appState.exportBackground, exportBackground: appState.exportBackground,
name: appState.name, name: appState.name,
viewBackgroundColor: appState.viewBackgroundColor, viewBackgroundColor: appState.viewBackgroundColor,
}, },
) )
.catch(muteFSAbortError) .catch(muteFSAbortError)
.catch((error) => { .catch((error) => {
console.error(error); console.error(error);
setAppState({ errorMessage: error.message }); setAppState({ errorMessage: error.message });
}); });
if ( if (
appState.exportEmbedScene && appState.exportEmbedScene &&
fileHandle && fileHandle &&
isImageFileHandle(fileHandle) isImageFileHandle(fileHandle)
) { ) {
setAppState({ fileHandle }); setAppState({ fileHandle });
} }
}; };
return ( return (
<ImageExportDialog <ImageExportDialog
@@ -249,15 +561,12 @@ const LayerUI = ({
</Section> </Section>
); );
const closeLibrary = useCallback(() => { const closeLibrary = useCallback(
const isDialogOpen = !!document.querySelector(".Dialog"); (event) => {
setAppState({ isLibraryOpen: false });
// Prevent closing if any dialog is open },
if (isDialogOpen) { [setAppState],
return; );
}
setAppState({ isLibraryOpen: false });
}, [setAppState]);
const deselectItems = useCallback(() => { const deselectItems = useCallback(() => {
setAppState({ setAppState({
@@ -269,7 +578,7 @@ const LayerUI = ({
const libraryMenu = appState.isLibraryOpen ? ( const libraryMenu = appState.isLibraryOpen ? (
<LibraryMenu <LibraryMenu
pendingElements={getSelectedElements(elements, appState)} pendingElements={getSelectedElements(elements, appState)}
onClose={closeLibrary} onClickOutside={closeLibrary}
onInsertShape={onInsertElements} onInsertShape={onInsertElements}
onAddToLibrary={deselectItems} onAddToLibrary={deselectItems}
setAppState={setAppState} setAppState={setAppState}
@@ -279,7 +588,6 @@ const LayerUI = ({
theme={appState.theme} theme={appState.theme}
files={files} files={files}
id={id} id={id}
appState={appState}
/> />
) : null; ) : null;
@@ -316,11 +624,7 @@ const LayerUI = ({
padding={1} padding={1}
className={clsx({ "zen-mode": zenModeEnabled })} className={clsx({ "zen-mode": zenModeEnabled })}
> >
<HintViewer <HintViewer appState={appState} elements={elements} />
appState={appState}
elements={elements}
isMobile={isMobile}
/>
{heading} {heading}
<Stack.Row gap={1}> <Stack.Row gap={1}>
<ShapesSwitcher <ShapesSwitcher
@@ -401,8 +705,7 @@ const LayerUI = ({
{!viewModeEnabled && ( {!viewModeEnabled && (
<div <div
className={clsx("undo-redo-buttons zen-mode-transition", { className={clsx("undo-redo-buttons zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom": "layer-ui__wrapper__footer-left--transition-bottom": zenModeEnabled,
zenModeEnabled,
})} })}
> >
{actionManager.renderAction("undo", { size: "small" })} {actionManager.renderAction("undo", { size: "small" })}
@@ -416,13 +719,13 @@ const LayerUI = ({
className={clsx( className={clsx(
"layer-ui__wrapper__footer-center zen-mode-transition", "layer-ui__wrapper__footer-center zen-mode-transition",
{ {
"layer-ui__wrapper__footer-left--transition-bottom": "layer-ui__wrapper__footer-left--transition-bottom": zenModeEnabled,
zenModeEnabled,
}, },
)} )}
> >
{renderCustomFooter?.(false, appState)} {renderCustomFooter?.(false, appState)}
</div> </div>
<div <div
className={clsx( className={clsx(
"layer-ui__wrapper__footer-right zen-mode-transition", "layer-ui__wrapper__footer-right zen-mode-transition",
@@ -543,7 +846,6 @@ const areEqual = (prev: LayerUIProps, next: LayerUIProps) => {
prev.renderCustomFooter === next.renderCustomFooter && prev.renderCustomFooter === next.renderCustomFooter &&
prev.langCode === next.langCode && prev.langCode === next.langCode &&
prev.elements === next.elements && prev.elements === next.elements &&
prev.files === next.files &&
keys.every((key) => prevAppState[key] === nextAppState[key]) keys.every((key) => prevAppState[key] === nextAppState[key])
); );
}; };
-55
View File
@@ -1,55 +0,0 @@
@import "open-color/open-color";
.excalidraw {
.layer-ui__library {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
.layer-ui__library-header {
display: flex;
align-items: center;
width: 100%;
margin: 2px 0;
button {
// 2px from the left to account for focus border of left-most button
margin: 0 2px;
}
a {
margin-inline-start: auto;
// 17px for scrollbar (needed for overlay scrollbars on Big Sur?) + 1px extra
padding-inline-end: 18px;
white-space: nowrap;
}
}
}
.layer-ui__library-message {
padding: 10px 20px;
max-width: 200px;
}
.publish-library-success {
.Dialog__content {
display: flex;
flex-direction: column;
}
&-close.ToolIcon_type_button {
background-color: $oc-blue-6;
align-self: flex-end;
&:hover {
background-color: $oc-blue-8;
}
.ToolIcon__icon {
width: auto;
font-size: 1rem;
color: $oc-white;
padding: 0 0.5rem;
}
}
}
}
-287
View File
@@ -1,287 +0,0 @@
import { useRef, useState, useEffect, useCallback, RefObject } from "react";
import Library from "../data/library";
import { t } from "../i18n";
import { randomId } from "../random";
import {
LibraryItems,
LibraryItem,
AppState,
BinaryFiles,
ExcalidrawProps,
} from "../types";
import { Dialog } from "./Dialog";
import { Island } from "./Island";
import PublishLibrary from "./PublishLibrary";
import { ToolButton } from "./ToolButton";
import "./LibraryMenu.scss";
import LibraryMenuItems from "./LibraryMenuItems";
import { EVENT } from "../constants";
import { KEYS } from "../keys";
const useOnClickOutside = (
ref: RefObject<HTMLElement>,
cb: (event: MouseEvent) => void,
) => {
useEffect(() => {
const listener = (event: MouseEvent) => {
if (!ref.current) {
return;
}
if (
event.target instanceof Element &&
(ref.current.contains(event.target) ||
!document.body.contains(event.target))
) {
return;
}
cb(event);
};
document.addEventListener("pointerdown", listener, false);
return () => {
document.removeEventListener("pointerdown", listener);
};
}, [ref, cb]);
};
const getSelectedItems = (
libraryItems: LibraryItems,
selectedItems: LibraryItem["id"][],
) => libraryItems.filter((item) => selectedItems.includes(item.id));
export const LibraryMenu = ({
onClose,
onInsertShape,
pendingElements,
onAddToLibrary,
theme,
setAppState,
files,
libraryReturnUrl,
focusContainer,
library,
id,
appState,
}: {
pendingElements: LibraryItem["elements"];
onClose: () => void;
onInsertShape: (elements: LibraryItem["elements"]) => void;
onAddToLibrary: () => void;
theme: AppState["theme"];
files: BinaryFiles;
setAppState: React.Component<any, AppState>["setState"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
focusContainer: () => void;
library: Library;
id: string;
appState: AppState;
}) => {
const ref = useRef<HTMLDivElement | null>(null);
useOnClickOutside(ref, (event) => {
// If click on the library icon, do nothing.
if ((event.target as Element).closest(".ToolIcon__library")) {
return;
}
onClose();
});
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === KEYS.ESCAPE) {
onClose();
}
};
document.addEventListener(EVENT.KEYDOWN, handleKeyDown);
return () => {
document.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
};
}, [onClose]);
const [libraryItems, setLibraryItems] = useState<LibraryItems>([]);
const [loadingState, setIsLoading] = useState<
"preloading" | "loading" | "ready"
>("preloading");
const [selectedItems, setSelectedItems] = useState<LibraryItem["id"][]>([]);
const [showPublishLibraryDialog, setShowPublishLibraryDialog] =
useState(false);
const [publishLibSuccess, setPublishLibSuccess] = useState<null | {
url: string;
authorName: string;
}>(null);
const loadingTimerRef = useRef<number | null>(null);
useEffect(() => {
Promise.race([
new Promise((resolve) => {
loadingTimerRef.current = window.setTimeout(() => {
resolve("loading");
}, 100);
}),
library.loadLibrary().then((items) => {
setLibraryItems(items);
setIsLoading("ready");
}),
]).then((data) => {
if (data === "loading") {
setIsLoading("loading");
}
});
return () => {
clearTimeout(loadingTimerRef.current!);
};
}, [library]);
const removeFromLibrary = useCallback(async () => {
const items = await library.loadLibrary();
const nextItems = items.filter((item) => !selectedItems.includes(item.id));
library.saveLibrary(nextItems).catch((error) => {
setLibraryItems(items);
setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
});
setSelectedItems([]);
setLibraryItems(nextItems);
}, [library, setAppState, selectedItems, setSelectedItems]);
const resetLibrary = useCallback(() => {
library.resetLibrary();
setLibraryItems([]);
focusContainer();
}, [library, focusContainer]);
const addToLibrary = useCallback(
async (elements: LibraryItem["elements"]) => {
if (elements.some((element) => element.type === "image")) {
return setAppState({
errorMessage: "Support for adding images to the library coming soon!",
});
}
const items = await library.loadLibrary();
const nextItems: LibraryItems = [
{
status: "unpublished",
elements,
id: randomId(),
created: Date.now(),
},
...items,
];
onAddToLibrary();
library.saveLibrary(nextItems).catch((error) => {
setLibraryItems(items);
setAppState({ errorMessage: t("alerts.errorAddingToLibrary") });
});
setLibraryItems(nextItems);
},
[onAddToLibrary, library, setAppState],
);
const renderPublishSuccess = useCallback(() => {
return (
<Dialog
onCloseRequest={() => setPublishLibSuccess(null)}
title={t("publishSuccessDialog.title")}
className="publish-library-success"
small={true}
>
<p>
{t("publishSuccessDialog.content", {
authorName: publishLibSuccess!.authorName,
})}{" "}
<a
href={publishLibSuccess?.url}
target="_blank"
rel="noopener noreferrer"
>
{t("publishSuccessDialog.link")}
</a>
</p>
<ToolButton
type="button"
title={t("buttons.close")}
aria-label={t("buttons.close")}
label={t("buttons.close")}
onClick={() => setPublishLibSuccess(null)}
data-testid="publish-library-success-close"
className="publish-library-success-close"
/>
</Dialog>
);
}, [setPublishLibSuccess, publishLibSuccess]);
const onPublishLibSuccess = useCallback(
(data) => {
setShowPublishLibraryDialog(false);
setPublishLibSuccess({ url: data.url, authorName: data.authorName });
const nextLibItems = libraryItems.slice();
nextLibItems.forEach((libItem) => {
if (selectedItems.includes(libItem.id)) {
libItem.status = "published";
}
});
library.saveLibrary(nextLibItems);
setLibraryItems(nextLibItems);
},
[
setShowPublishLibraryDialog,
setPublishLibSuccess,
libraryItems,
selectedItems,
library,
],
);
return loadingState === "preloading" ? null : (
<Island padding={1} ref={ref} className="layer-ui__library">
{showPublishLibraryDialog && (
<PublishLibrary
onClose={() => setShowPublishLibraryDialog(false)}
libraryItems={getSelectedItems(libraryItems, selectedItems)}
appState={appState}
onSuccess={onPublishLibSuccess}
onError={(error) => window.alert(error)}
updateItemsInStorage={() => library.saveLibrary(libraryItems)}
onRemove={(id: string) =>
setSelectedItems(selectedItems.filter((_id) => _id !== id))
}
/>
)}
{publishLibSuccess && renderPublishSuccess()}
{loadingState === "loading" ? (
<div className="layer-ui__library-message">
{t("labels.libraryLoadingMessage")}
</div>
) : (
<LibraryMenuItems
libraryItems={libraryItems}
onRemoveFromLibrary={removeFromLibrary}
onAddToLibrary={addToLibrary}
onInsertShape={onInsertShape}
pendingElements={pendingElements}
setAppState={setAppState}
libraryReturnUrl={libraryReturnUrl}
library={library}
theme={theme}
files={files}
id={id}
selectedItems={selectedItems}
onToggle={(id) => {
if (!selectedItems.includes(id)) {
setSelectedItems([...selectedItems, id]);
} else {
setSelectedItems(selectedItems.filter((_id) => _id !== id));
}
}}
onPublish={() => setShowPublishLibraryDialog(true)}
resetLibrary={resetLibrary}
/>
)}
</Island>
);
};
-102
View File
@@ -1,102 +0,0 @@
@import "open-color/open-color";
.excalidraw {
.library-menu-items-container {
.library-actions {
display: flex;
button .library-actions-counter {
position: absolute;
right: 2px;
bottom: 2px;
border-radius: 50%;
width: 1em;
height: 1em;
padding: 1px;
font-size: 0.7rem;
background: #fff;
}
&--remove {
background-color: $oc-red-7;
&:hover {
background-color: $oc-red-8;
}
&:active {
background-color: $oc-red-9;
}
svg {
color: $oc-white;
}
.library-actions-counter {
color: $oc-red-7;
}
}
&--export {
background-color: $oc-lime-5;
&:hover {
background-color: $oc-lime-7;
}
&:active {
background-color: $oc-lime-8;
}
svg {
color: $oc-white;
}
.library-actions-counter {
color: $oc-lime-5;
}
}
&--publish {
background-color: $oc-cyan-6;
&:hover {
background-color: $oc-cyan-7;
}
&:active {
background-color: $oc-cyan-9;
}
svg {
color: $oc-white;
}
label {
margin-left: -0.2em;
margin-right: 1.1em;
color: $oc-white;
font-size: 0.86em;
}
.library-actions-counter {
color: $oc-cyan-6;
}
}
&--load {
background-color: $oc-blue-6;
&:hover {
background-color: $oc-blue-7;
}
&:active {
background-color: $oc-blue-9;
}
svg {
color: $oc-white;
}
}
}
&__items {
max-height: 50vh;
overflow: auto;
margin-top: 0.5rem;
}
.separator {
font-weight: 500;
font-size: 0.9rem;
margin: 0.6em 0.2em;
color: var(--text-primary-color);
}
}
}
-322
View File
@@ -1,322 +0,0 @@
import { chunk } from "lodash";
import { useCallback, useState } from "react";
import { importLibraryFromJSON, saveLibraryAsJSON } from "../data/json";
import Library from "../data/library";
import { ExcalidrawElement, NonDeleted } from "../element/types";
import { t } from "../i18n";
import {
AppState,
BinaryFiles,
ExcalidrawProps,
LibraryItem,
LibraryItems,
} from "../types";
import { muteFSAbortError } from "../utils";
import { useIsMobile } from "./App";
import ConfirmDialog from "./ConfirmDialog";
import { exportToFileIcon, load, publishIcon, trash } from "./icons";
import { LibraryUnit } from "./LibraryUnit";
import Stack from "./Stack";
import { ToolButton } from "./ToolButton";
import { Tooltip } from "./Tooltip";
import "./LibraryMenuItems.scss";
const LibraryMenuItems = ({
libraryItems,
onRemoveFromLibrary,
onAddToLibrary,
onInsertShape,
pendingElements,
theme,
setAppState,
libraryReturnUrl,
library,
files,
id,
selectedItems,
onToggle,
onPublish,
resetLibrary,
}: {
libraryItems: LibraryItems;
pendingElements: LibraryItem["elements"];
onRemoveFromLibrary: () => void;
onInsertShape: (elements: LibraryItem["elements"]) => void;
onAddToLibrary: (elements: LibraryItem["elements"]) => void;
theme: AppState["theme"];
files: BinaryFiles;
setAppState: React.Component<any, AppState>["setState"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
library: Library;
id: string;
selectedItems: LibraryItem["id"][];
onToggle: (id: LibraryItem["id"]) => void;
onPublish: () => void;
resetLibrary: () => void;
}) => {
const renderRemoveLibAlert = useCallback(() => {
const content = selectedItems.length
? t("alerts.removeItemsFromsLibrary", { count: selectedItems.length })
: t("alerts.resetLibrary");
const title = selectedItems.length
? t("confirmDialog.removeItemsFromLib")
: t("confirmDialog.resetLibrary");
return (
<ConfirmDialog
onConfirm={() => {
if (selectedItems.length) {
onRemoveFromLibrary();
} else {
resetLibrary();
}
setShowRemoveLibAlert(false);
}}
onCancel={() => {
setShowRemoveLibAlert(false);
}}
title={title}
>
<p>{content}</p>
</ConfirmDialog>
);
}, [selectedItems, onRemoveFromLibrary, resetLibrary]);
const [showRemoveLibAlert, setShowRemoveLibAlert] = useState(false);
const isMobile = useIsMobile();
const renderLibraryActions = () => {
const itemsSelected = !!selectedItems.length;
const items = itemsSelected
? libraryItems.filter((item) => selectedItems.includes(item.id))
: libraryItems;
const resetLabel = itemsSelected
? t("buttons.remove")
: t("buttons.resetLibrary");
return (
<div className="library-actions">
{(!itemsSelected || !isMobile) && (
<ToolButton
key="import"
type="button"
title={t("buttons.load")}
aria-label={t("buttons.load")}
icon={load}
onClick={() => {
importLibraryFromJSON(library)
.then(() => {
// Close and then open to get the libraries updated
setAppState({ isLibraryOpen: false });
setAppState({ isLibraryOpen: true });
})
.catch(muteFSAbortError)
.catch((error) => {
setAppState({ errorMessage: error.message });
});
}}
className="library-actions--load"
/>
)}
{!!items.length && (
<>
<ToolButton
key="export"
type="button"
title={t("buttons.export")}
aria-label={t("buttons.export")}
icon={exportToFileIcon}
onClick={async () => {
const libraryItems = itemsSelected
? items
: await library.loadLibrary();
saveLibraryAsJSON(libraryItems)
.catch(muteFSAbortError)
.catch((error) => {
setAppState({ errorMessage: error.message });
});
}}
className="library-actions--export"
>
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
<ToolButton
key="reset"
type="button"
title={resetLabel}
aria-label={resetLabel}
icon={trash}
onClick={() => setShowRemoveLibAlert(true)}
className="library-actions--remove"
>
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
</>
)}
{itemsSelected && !isPublished && (
<Tooltip label={t("hints.publishLibrary")}>
<ToolButton
type="button"
aria-label={t("buttons.publishLibrary")}
label={t("buttons.publishLibrary")}
icon={publishIcon}
className="library-actions--publish"
onClick={onPublish}
>
{!isMobile && <label>{t("buttons.publishLibrary")}</label>}
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
</Tooltip>
)}
</div>
);
};
const CELLS_PER_ROW = isMobile ? 4 : 6;
const referrer =
libraryReturnUrl || window.location.origin + window.location.pathname;
const isPublished = selectedItems.some(
(id) => libraryItems.find((item) => item.id === id)?.status === "published",
);
const createLibraryItemCompo = (params: {
item:
| LibraryItem
| /* pending library item */ {
id: null;
elements: readonly NonDeleted<ExcalidrawElement>[];
}
| null;
onClick?: () => void;
key: string;
}) => {
return (
<Stack.Col key={params.key}>
<LibraryUnit
elements={params.item?.elements}
files={files}
isPending={!params.item?.id && !!params.item?.elements}
onClick={params.onClick || (() => {})}
id={params.item?.id || null}
selected={!!params.item?.id && selectedItems.includes(params.item.id)}
onToggle={() => {
if (params.item?.id) {
onToggle(params.item.id);
}
}}
/>
</Stack.Col>
);
};
const renderLibrarySection = (
items: (
| LibraryItem
| /* pending library item */ {
id: null;
elements: readonly NonDeleted<ExcalidrawElement>[];
}
)[],
) => {
const _items = items.map((item) => {
if (item.id) {
return createLibraryItemCompo({
item,
onClick: () => onInsertShape(item.elements),
key: item.id,
});
}
return createLibraryItemCompo({
key: "__pending__item__",
item,
onClick: () => onAddToLibrary(pendingElements),
});
});
// ensure we render all empty cells if no items are present
let rows = chunk(_items, CELLS_PER_ROW);
if (!rows.length) {
rows = [[]];
}
return rows.map((rowItems, index, rows) => {
if (index === rows.length - 1) {
// pad row with empty cells
rowItems = rowItems.concat(
new Array(CELLS_PER_ROW - rowItems.length)
.fill(null)
.map((_, index) => {
return createLibraryItemCompo({
key: `empty_${index}`,
item: null,
});
}),
);
}
return (
<Stack.Row align="center" gap={1} key={index}>
{rowItems}
</Stack.Row>
);
});
};
const publishedItems = libraryItems.filter(
(item) => item.status === "published",
);
const unpublishedItems = [
// append pending library item
...(pendingElements.length
? [{ id: null, elements: pendingElements }]
: []),
...libraryItems.filter((item) => item.status !== "published"),
];
return (
<div className="library-menu-items-container">
{showRemoveLibAlert && renderRemoveLibAlert()}
<div className="layer-ui__library-header" key="library-header">
{renderLibraryActions()}
<a
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
window.name || "_blank"
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}`}
target="_excalidraw_libraries"
>
{t("labels.libraries")}
</a>
</div>
<Stack.Col
className="library-menu-items-container__items"
align="start"
gap={1}
>
<>
<div className="separator">{t("labels.personalLib")}</div>
{renderLibrarySection(unpublishedItems)}
</>
<>
<div className="separator">{t("labels.excalidrawLib")} </div>
{renderLibrarySection(publishedItems)}
</>
</Stack.Col>
</div>
);
};
export default LibraryMenuItems;
+15 -59
View File
@@ -1,5 +1,3 @@
@import "../css/variables.module";
.excalidraw { .excalidraw {
.library-unit { .library-unit {
align-items: center; align-items: center;
@@ -9,20 +7,6 @@
position: relative; position: relative;
width: 63px; width: 63px;
height: 63px; // match width height: 63px; // match width
&--hover {
box-shadow: inset 0px 0px 0px 2px $oc-blue-5;
border-color: $oc-blue-5;
}
&--selected {
box-shadow: inset 0px 0px 0px 2px $oc-blue-8;
border-color: $oc-blue-8;
}
}
&.theme--dark .library-unit {
border-color: rgb(48, 48, 48);
} }
.library-unit__dragger { .library-unit__dragger {
@@ -38,9 +22,9 @@
max-width: 100%; max-width: 100%;
} }
.library-unit__checkbox-container, .library-unit__removeFromLibrary,
.library-unit__checkbox-container:hover, .library-unit__removeFromLibrary:hover,
.library-unit__checkbox-container:active { .library-unit__removeFromLibrary:active {
align-items: center; align-items: center;
background: none; background: none;
border: none; border: none;
@@ -48,35 +32,10 @@
display: flex; display: flex;
justify-content: center; justify-content: center;
margin: 0; margin: 0;
padding: 0.5rem; padding: 0;
position: absolute; position: absolute;
left: 2rem; right: 5px;
bottom: 2rem; top: 5px;
cursor: pointer;
input {
cursor: pointer;
}
}
.library-unit__checkbox {
position: absolute;
left: 2.3rem;
bottom: 2.3rem;
.Checkbox-box {
width: 13px;
height: 13px;
border-radius: 2px;
margin: 0.5em 0.5em 0.2em 0.2em;
background-color: $oc-blue-1;
}
&.Checkbox:hover {
.Checkbox-box {
background-color: $oc-blue-2;
}
}
} }
.library-unit__removeFromLibrary > svg { .library-unit__removeFromLibrary > svg {
@@ -84,32 +43,29 @@
width: 16px; width: 16px;
} }
.library-unit__adder { .library-unit__pulse {
transform: scale(1); transform: scale(1);
animation: library-unit__adder-animation 1s ease-in infinite; animation: library-unit__pulse-animation 1s ease-in infinite;
} }
.library-unit__adder { .library-unit__adder {
position: absolute; position: absolute;
left: 40%; left: 50%;
top: 40%; top: 50%;
width: 2rem; width: 20px;
height: 2rem; height: 20px;
margin-left: -10px; margin-left: -10px;
margin-top: -10px; margin-top: -10px;
pointer-events: none; pointer-events: none;
} }
.library-unit--hover .library-unit__adder {
color: $oc-blue-7;
}
.library-unit__active { .library-unit__active {
cursor: pointer; cursor: pointer;
} }
@keyframes library-unit__adder-animation { @keyframes library-unit__pulse-animation {
0% { 0% {
transform: scale(0.85); transform: scale(0.95);
} }
50% { 50% {
@@ -117,7 +73,7 @@
} }
100% { 100% {
transform: scale(0.85); transform: scale(0.95);
} }
} }
} }
+24 -25
View File
@@ -1,12 +1,13 @@
import clsx from "clsx"; import clsx from "clsx";
import oc from "open-color"; import oc from "open-color";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { close } from "../components/icons";
import { MIME_TYPES } from "../constants"; import { MIME_TYPES } from "../constants";
import { t } from "../i18n";
import { useIsMobile } from "../components/App"; import { useIsMobile } from "../components/App";
import { exportToSvg } from "../scene/export"; import { exportToSvg } from "../scene/export";
import { BinaryFiles, LibraryItem } from "../types"; import { BinaryFiles, LibraryItem } from "../types";
import "./LibraryUnit.scss"; import "./LibraryUnit.scss";
import { CheckboxItem } from "./CheckboxItem";
// fa-plus // fa-plus
const PLUS_ICON = ( const PLUS_ICON = (
@@ -19,21 +20,17 @@ const PLUS_ICON = (
); );
export const LibraryUnit = ({ export const LibraryUnit = ({
id,
elements, elements,
files, files,
isPending, pendingElements,
onRemoveFromLibrary,
onClick, onClick,
selected,
onToggle,
}: { }: {
id: LibraryItem["id"] | /** for pending item */ null; elements?: LibraryItem;
elements?: LibraryItem["elements"];
files: BinaryFiles; files: BinaryFiles;
isPending?: boolean; pendingElements?: LibraryItem;
onRemoveFromLibrary: () => void;
onClick: () => void; onClick: () => void;
selected: boolean;
onToggle: (id: string) => void;
}) => { }) => {
const ref = useRef<HTMLDivElement | null>(null); const ref = useRef<HTMLDivElement | null>(null);
useEffect(() => { useEffect(() => {
@@ -43,11 +40,12 @@ export const LibraryUnit = ({
} }
(async () => { (async () => {
if (!elements) { const elementsToRender = elements || pendingElements;
if (!elementsToRender) {
return; return;
} }
const svg = await exportToSvg( const svg = await exportToSvg(
elements, elementsToRender,
{ {
exportBackground: false, exportBackground: false,
viewBackgroundColor: oc.white, viewBackgroundColor: oc.white,
@@ -60,31 +58,30 @@ export const LibraryUnit = ({
return () => { return () => {
node.innerHTML = ""; node.innerHTML = "";
}; };
}, [elements, files]); }, [elements, pendingElements, files]);
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const adder = isPending && (
const adder = (isHovered || isMobile) && pendingElements && (
<div className="library-unit__adder">{PLUS_ICON}</div> <div className="library-unit__adder">{PLUS_ICON}</div>
); );
return ( return (
<div <div
className={clsx("library-unit", { className={clsx("library-unit", {
"library-unit__active": elements, "library-unit__active": elements || pendingElements,
"library-unit--hover": elements && isHovered,
"library-unit--selected": selected,
})} })}
onMouseEnter={() => setIsHovered(true)} onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)} onMouseLeave={() => setIsHovered(false)}
> >
<div <div
className={clsx("library-unit__dragger", { className={clsx("library-unit__dragger", {
"library-unit__pulse": !!isPending, "library-unit__pulse": !!pendingElements,
})} })}
ref={ref} ref={ref}
draggable={!!elements} draggable={!!elements}
onClick={!!elements || !!isPending ? onClick : undefined} onClick={!!elements || !!pendingElements ? onClick : undefined}
onDragStart={(event) => { onDragStart={(event) => {
setIsHovered(false); setIsHovered(false);
event.dataTransfer.setData( event.dataTransfer.setData(
@@ -94,12 +91,14 @@ export const LibraryUnit = ({
}} }}
/> />
{adder} {adder}
{id && elements && (isHovered || isMobile || selected) && ( {elements && (isHovered || isMobile) && (
<CheckboxItem <button
checked={selected} className="library-unit__removeFromLibrary"
onChange={() => onToggle(id)} aria-label={t("labels.removeFromLibrary")}
className="library-unit__checkbox" onClick={onRemoveFromLibrary}
/> >
{close}
</button>
)} )}
</div> </div>
); );
+1 -1
View File
@@ -92,7 +92,7 @@ export const MobileMenu = ({
</Stack.Col> </Stack.Col>
)} )}
</Section> </Section>
<HintViewer appState={appState} elements={elements} isMobile={true} /> <HintViewer appState={appState} elements={elements} />
</FixedSideContainer> </FixedSideContainer>
); );
}; };
+2 -6
View File
@@ -15,9 +15,8 @@ export const Modal = (props: {
onCloseRequest(): void; onCloseRequest(): void;
labelledBy: string; labelledBy: string;
theme?: AppState["theme"]; theme?: AppState["theme"];
closeOnClickOutside?: boolean;
}) => { }) => {
const { theme = THEME.LIGHT, closeOnClickOutside = true } = props; const { theme = THEME.LIGHT } = props;
const modalRoot = useBodyRoot(theme); const modalRoot = useBodyRoot(theme);
if (!modalRoot) { if (!modalRoot) {
@@ -40,10 +39,7 @@ export const Modal = (props: {
onKeyDown={handleKeydown} onKeyDown={handleKeydown}
aria-labelledby={props.labelledBy} aria-labelledby={props.labelledBy}
> >
<div <div className="Modal__background" onClick={props.onCloseRequest}></div>
className="Modal__background"
onClick={closeOnClickOutside ? props.onCloseRequest : undefined}
></div>
<div <div
className="Modal__content" className="Modal__content"
style={{ "--max-width": `${props.maxWidth}px` }} style={{ "--max-width": `${props.maxWidth}px` }}
+1 -1
View File
@@ -82,7 +82,7 @@ export const PasteChartDialog = ({
appState: AppState; appState: AppState;
onClose: () => void; onClose: () => void;
setAppState: React.Component<any, AppState>["setState"]; setAppState: React.Component<any, AppState>["setState"];
onInsertChart: (elements: LibraryItem["elements"]) => void; onInsertChart: (elements: LibraryItem) => void;
}) => { }) => {
const handleClose = React.useCallback(() => { const handleClose = React.useCallback(() => {
if (onClose) { if (onClose) {
-1
View File
@@ -42,7 +42,6 @@ export const ProjectName = (props: Props) => {
</label> </label>
{props.isNameEditable ? ( {props.isNameEditable ? (
<input <input
type="text"
className="TextInput" className="TextInput"
onBlur={handleBlur} onBlur={handleBlur}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
-92
View File
@@ -1,92 +0,0 @@
@import "../css/variables.module";
.excalidraw {
.publish-library {
&__fields {
display: flex;
flex-direction: column;
label {
padding: 1em;
display: flex;
justify-content: space-between;
align-items: center;
span {
font-weight: 500;
font-size: 1rem;
color: $oc-gray-6;
}
input,
textarea {
width: 70%;
padding: 0.6em;
font-family: var(--ui-font);
}
.required {
color: $oc-red-8;
margin: 0.2rem;
}
}
}
&__buttons {
display: flex;
padding: 0.2rem 0;
justify-content: flex-end;
.ToolIcon__icon {
min-width: 2.5rem;
width: auto;
font-size: 1rem;
}
.ToolIcon_type_button {
margin-left: 1rem;
padding: 0 0.5rem;
}
&--confirm.ToolIcon_type_button {
background-color: $oc-blue-6;
&:hover {
background-color: $oc-blue-8;
}
}
&--cancel.ToolIcon_type_button {
background-color: $oc-gray-5;
&:hover {
background-color: $oc-gray-6;
}
}
.ToolIcon__icon {
color: $oc-white;
.Spinner {
--spinner-color: #fff;
svg {
padding: 0.5rem;
}
}
}
}
.selected-library-items {
display: flex;
padding: 0 0.8rem;
flex-wrap: wrap;
.single-library-item-wrapper {
width: 9rem;
}
}
&-note {
padding: 1em;
font-style: italic;
font-size: 14px;
display: block;
}
}
}
-429
View File
@@ -1,429 +0,0 @@
import { ReactNode, useCallback, useEffect, useState } from "react";
import oc from "open-color";
import { Dialog } from "./Dialog";
import { t } from "../i18n";
import { ToolButton } from "./ToolButton";
import { AppState, LibraryItems, LibraryItem } from "../types";
import { exportToBlob } from "../packages/utils";
import { EXPORT_DATA_TYPES, EXPORT_SOURCE } from "../constants";
import { ExportedLibraryData } from "../data/types";
import "./PublishLibrary.scss";
import { ExcalidrawElement } from "../element/types";
import { newElement } from "../element";
import { mutateElement } from "../element/mutateElement";
import { getCommonBoundingBox } from "../element/bounds";
import SingleLibraryItem from "./SingleLibraryItem";
interface PublishLibraryDataParams {
authorName: string;
githubHandle: string;
name: string;
description: string;
twitterHandle: string;
website: string;
}
const LOCAL_STORAGE_KEY_PUBLISH_LIBRARY = "publish-library-data";
const savePublishLibDataToStorage = (data: PublishLibraryDataParams) => {
try {
localStorage.setItem(
LOCAL_STORAGE_KEY_PUBLISH_LIBRARY,
JSON.stringify(data),
);
} catch (error: any) {
// Unable to access window.localStorage
console.error(error);
}
};
const importPublishLibDataFromStorage = () => {
try {
const data = localStorage.getItem(LOCAL_STORAGE_KEY_PUBLISH_LIBRARY);
if (data) {
return JSON.parse(data);
}
} catch (error: any) {
// Unable to access localStorage
console.error(error);
}
return null;
};
const PublishLibrary = ({
onClose,
libraryItems,
appState,
onSuccess,
onError,
updateItemsInStorage,
onRemove,
}: {
onClose: () => void;
libraryItems: LibraryItems;
appState: AppState;
onSuccess: (data: {
url: string;
authorName: string;
items: LibraryItems;
}) => void;
onError: (error: Error) => void;
updateItemsInStorage: (items: LibraryItems) => void;
onRemove: (id: string) => void;
}) => {
const [libraryData, setLibraryData] = useState<PublishLibraryDataParams>({
authorName: "",
githubHandle: "",
name: "",
description: "",
twitterHandle: "",
website: "",
});
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
const data = importPublishLibDataFromStorage();
if (data) {
setLibraryData(data);
}
}, []);
const [clonedLibItems, setClonedLibItems] = useState<LibraryItems>(
libraryItems.slice(),
);
useEffect(() => {
setClonedLibItems(libraryItems.slice());
}, [libraryItems]);
const onInputChange = (event: any) => {
setLibraryData({
...libraryData,
[event.target.name]: event.target.value,
});
};
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setIsSubmitting(true);
const erroredLibItems: LibraryItem[] = [];
let isError = false;
clonedLibItems.forEach((libItem) => {
let error = "";
if (!libItem.name) {
error = t("publishDialog.errors.required");
isError = true;
}
erroredLibItems.push({ ...libItem, error });
});
if (isError) {
setClonedLibItems(erroredLibItems);
setIsSubmitting(false);
return;
}
const elements: ExcalidrawElement[] = [];
const prevBoundingBox = { minX: 0, minY: 0, maxX: 0, maxY: 0 };
clonedLibItems.forEach((libItem) => {
const boundingBox = getCommonBoundingBox(libItem.elements);
const width = boundingBox.maxX - boundingBox.minX + 30;
const height = boundingBox.maxY - boundingBox.minY + 30;
const offset = {
x: prevBoundingBox.maxX - boundingBox.minX,
y: prevBoundingBox.maxY - boundingBox.minY,
};
const itemsWithUpdatedCoords = libItem.elements.map((element) => {
element = mutateElement(element, {
x: element.x + offset.x + 15,
y: element.y + offset.y + 15,
});
return element;
});
const items = [
...itemsWithUpdatedCoords,
newElement({
type: "rectangle",
width,
height,
x: prevBoundingBox.maxX,
y: prevBoundingBox.maxY,
strokeColor: "#ced4da",
backgroundColor: "transparent",
strokeStyle: "solid",
opacity: 100,
roughness: 0,
strokeSharpness: "sharp",
fillStyle: "solid",
strokeWidth: 1,
}),
];
elements.push(...items);
prevBoundingBox.maxX = prevBoundingBox.maxX + width + 30;
});
const png = await exportToBlob({
elements,
mimeType: "image/png",
appState: {
...appState,
viewBackgroundColor: oc.white,
exportBackground: true,
},
files: null,
});
const libContent: ExportedLibraryData = {
type: EXPORT_DATA_TYPES.excalidrawLibrary,
version: 2,
source: EXPORT_SOURCE,
libraryItems: clonedLibItems,
};
const content = JSON.stringify(libContent, null, 2);
const lib = new Blob([content], { type: "application/json" });
const formData = new FormData();
formData.append("excalidrawLib", lib);
formData.append("excalidrawPng", png!);
formData.append("title", libraryData.name);
formData.append("authorName", libraryData.authorName);
formData.append("githubHandle", libraryData.githubHandle);
formData.append("name", libraryData.name);
formData.append("description", libraryData.description);
formData.append("twitterHandle", libraryData.twitterHandle);
formData.append("website", libraryData.website);
fetch(`${process.env.REACT_APP_LIBRARY_BACKEND}/submit`, {
method: "post",
body: formData,
})
.then(
(response) => {
if (response.ok) {
return response.json().then(({ url }) => {
// flush data from local storage
localStorage.removeItem(LOCAL_STORAGE_KEY_PUBLISH_LIBRARY);
onSuccess({
url,
authorName: libraryData.authorName,
items: clonedLibItems,
});
});
}
return response
.json()
.catch(() => {
throw new Error(response.statusText || "something went wrong");
})
.then((error) => {
throw new Error(
error.message || response.statusText || "something went wrong",
);
});
},
(err) => {
console.error(err);
onError(err);
setIsSubmitting(false);
},
)
.catch((err) => {
console.error(err);
onError(err);
setIsSubmitting(false);
});
};
const renderLibraryItems = () => {
const items: ReactNode[] = [];
clonedLibItems.forEach((libItem, index) => {
items.push(
<div className="single-library-item-wrapper" key={index}>
<SingleLibraryItem
libItem={libItem}
appState={appState}
index={index}
onChange={(val, index) => {
const items = clonedLibItems.slice();
items[index].name = val;
setClonedLibItems(items);
}}
onRemove={onRemove}
/>
</div>,
);
});
return <div className="selected-library-items">{items}</div>;
};
const onDialogClose = useCallback(() => {
updateItemsInStorage(clonedLibItems);
savePublishLibDataToStorage(libraryData);
onClose();
}, [clonedLibItems, onClose, updateItemsInStorage, libraryData]);
const shouldRenderForm = !!libraryItems.length;
return (
<Dialog
onCloseRequest={onDialogClose}
title={t("publishDialog.title")}
className="publish-library"
>
{shouldRenderForm ? (
<form onSubmit={onSubmit}>
<div className="publish-library-note">
{t("publishDialog.noteDescription.pre")}
<a
href="https://libraries.excalidraw.com"
target="_blank"
rel="noopener noreferrer"
>
{t("publishDialog.noteDescription.link")}
</a>{" "}
{t("publishDialog.noteDescription.post")}
</div>
<span className="publish-library-note">
{t("publishDialog.noteGuidelines.pre")}
<a
href="https://github.com/excalidraw/excalidraw-libraries#guidelines"
target="_blank"
rel="noopener noreferrer"
>
{t("publishDialog.noteGuidelines.link")}
</a>
{t("publishDialog.noteGuidelines.post")}
</span>
<div className="publish-library-note">
{t("publishDialog.noteItems")}
</div>
{renderLibraryItems()}
<div className="publish-library__fields">
<label>
<div>
<span>{t("publishDialog.libraryName")}</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<input
type="text"
name="name"
required
value={libraryData.name}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.libraryName")}
/>
</label>
<label style={{ alignItems: "flex-start" }}>
<div>
<span>{t("publishDialog.libraryDesc")}</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<textarea
name="description"
rows={4}
required
value={libraryData.description}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.libraryDesc")}
/>
</label>
<label>
<div>
<span>{t("publishDialog.authorName")}</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<input
type="text"
name="authorName"
required
value={libraryData.authorName}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.authorName")}
/>
</label>
<label>
<span>{t("publishDialog.githubUsername")}</span>
<input
type="text"
name="githubHandle"
value={libraryData.githubHandle}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.githubHandle")}
/>
</label>
<label>
<span>{t("publishDialog.twitterUsername")}</span>
<input
type="text"
name="twitterHandle"
value={libraryData.twitterHandle}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.twitterHandle")}
/>
</label>
<label>
<span>{t("publishDialog.website")}</span>
<input
type="text"
name="website"
pattern="https?://.+"
title={t("publishDialog.errors.website")}
value={libraryData.website}
onChange={onInputChange}
placeholder={t("publishDialog.placeholder.website")}
/>
</label>
<span className="publish-library-note">
{t("publishDialog.noteLicense.pre")}
<a
href="https://github.com/excalidraw/excalidraw-libraries/blob/main/LICENSE"
target="_blank"
rel="noopener noreferrer"
>
{t("publishDialog.noteLicense.link")}
</a>
{t("publishDialog.noteLicense.post")}
</span>
</div>
<div className="publish-library__buttons">
<ToolButton
type="button"
title={t("buttons.cancel")}
aria-label={t("buttons.cancel")}
label={t("buttons.cancel")}
onClick={onDialogClose}
data-testid="cancel-clear-canvas-button"
className="publish-library__buttons--cancel"
/>
<ToolButton
type="submit"
title={t("buttons.submit")}
aria-label={t("buttons.submit")}
label={t("buttons.submit")}
className="publish-library__buttons--confirm"
isLoading={isSubmitting}
/>
</div>
</form>
) : (
<p style={{ padding: "1em", textAlign: "center", fontWeight: 500 }}>
{t("publishDialog.atleastOneLibItem")}
</p>
)}
</Dialog>
);
};
export default PublishLibrary;
-66
View File
@@ -1,66 +0,0 @@
@import "../css/variables.module";
.excalidraw {
.single-library-item {
position: relative;
&__svg {
width: 7.5rem;
height: 7.5rem;
border: 1px solid var(--button-gray-2);
margin: 0.3rem;
svg {
width: 100%;
height: 100%;
}
}
.ToolIcon__icon {
background-color: $oc-white;
width: auto;
height: auto;
margin: 0 0.5rem;
}
.ToolIcon,
.ToolIcon_type_button:hover {
background-color: white;
}
.required,
.error {
color: $oc-red-8;
font-weight: bold;
font-size: 1rem;
margin: 0.2rem;
}
.error {
font-weight: 500;
margin: 0;
padding: 0.3em 0;
}
&--remove {
position: absolute;
top: 0.2rem;
right: 1.3rem;
.ToolIcon__icon {
margin: 0;
}
.ToolIcon__icon {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-7;
}
&:active {
background-color: $oc-red-8;
}
}
svg {
color: $oc-white;
padding: 0.26rem;
border-radius: 0.3em;
width: 1rem;
height: 1rem;
}
}
}
}
-99
View File
@@ -1,99 +0,0 @@
import oc from "open-color";
import { useEffect, useRef } from "react";
import { t } from "../i18n";
import { exportToSvg } from "../packages/utils";
import { AppState, LibraryItem } from "../types";
import { close } from "./icons";
import "./SingleLibraryItem.scss";
import { ToolButton } from "./ToolButton";
const SingleLibraryItem = ({
libItem,
appState,
index,
onChange,
onRemove,
}: {
libItem: LibraryItem;
appState: AppState;
index: number;
onChange: (val: string, index: number) => void;
onRemove: (id: string) => void;
}) => {
const svgRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
const node = svgRef.current;
if (!node) {
return;
}
(async () => {
const svg = await exportToSvg({
elements: libItem.elements,
appState: {
...appState,
viewBackgroundColor: oc.white,
exportBackground: true,
},
files: null,
});
node.innerHTML = svg.outerHTML;
})();
}, [libItem.elements, appState]);
return (
<div className="single-library-item">
<div ref={svgRef} className="single-library-item__svg" />
<ToolButton
aria-label={t("buttons.remove")}
type="button"
icon={close}
className="single-library-item--remove"
onClick={onRemove.bind(null, libItem.id)}
title={t("buttons.remove")}
/>
<div
style={{
display: "flex",
margin: "0.8rem 0.3rem",
width: "100%",
fontSize: "14px",
fontWeight: 500,
flexDirection: "column",
}}
>
<label
style={{
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
}}
>
<div style={{ padding: "0.5em 0" }}>
<span style={{ fontWeight: 500, color: oc.gray[6] }}>
{t("publishDialog.itemName")}
</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<input
type="text"
ref={inputRef}
style={{ width: "80%", padding: "0.2rem" }}
defaultValue={libItem.name}
placeholder="Item name"
onChange={(event) => {
onChange(event.target.value, index);
}}
/>
</label>
<span className="error">{libItem.error}</span>
</div>
</div>
);
};
export default SingleLibraryItem;
+18
View File
@@ -2,6 +2,24 @@
.excalidraw { .excalidraw {
.TextInput { .TextInput {
color: var(--text-primary-color);
display: inline-block; display: inline-block;
border: 1.5px solid var(--button-gray-1);
line-height: 1;
padding: 0.75rem;
white-space: nowrap;
border-radius: var(--space-factor);
background-color: var(--input-bg-color);
&:not(:focus) {
&:hover {
background-color: var(--input-hover-bg-color);
}
}
&:focus {
outline: none;
box-shadow: 0 0 0 2px var(--focus-highlight-color);
}
} }
} }
+4 -20
View File
@@ -25,7 +25,6 @@ type ToolButtonBaseProps = {
visible?: boolean; visible?: boolean;
selected?: boolean; selected?: boolean;
className?: string; className?: string;
isLoading?: boolean;
}; };
type ToolButtonProps = type ToolButtonProps =
@@ -34,11 +33,6 @@ type ToolButtonProps =
children?: React.ReactNode; children?: React.ReactNode;
onClick?(event: React.MouseEvent): void; onClick?(event: React.MouseEvent): void;
}) })
| (ToolButtonBaseProps & {
type: "submit";
children?: React.ReactNode;
onClick?(event: React.MouseEvent): void;
})
| (ToolButtonBaseProps & { | (ToolButtonBaseProps & {
type: "icon"; type: "icon";
children?: React.ReactNode; children?: React.ReactNode;
@@ -67,11 +61,9 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => {
try { try {
setIsLoading(true); setIsLoading(true);
await ret; await ret;
} catch (error: any) { } catch (error) {
if (!(error instanceof AbortError)) { if (!(error instanceof AbortError)) {
throw error; throw error;
} else {
console.warn(error);
} }
} finally { } finally {
if (isMountedRef.current) { if (isMountedRef.current) {
@@ -90,14 +82,7 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => {
const lastPointerTypeRef = useRef<PointerType | null>(null); const lastPointerTypeRef = useRef<PointerType | null>(null);
if ( if (props.type === "button" || props.type === "icon") {
props.type === "button" ||
props.type === "icon" ||
props.type === "submit"
) {
const type = (props.type === "icon" ? "button" : props.type) as
| "button"
| "submit";
return ( return (
<button <button
className={clsx( className={clsx(
@@ -117,10 +102,10 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => {
hidden={props.hidden} hidden={props.hidden}
title={props.title} title={props.title}
aria-label={props["aria-label"]} aria-label={props["aria-label"]}
type={type} type="button"
onClick={onClick} onClick={onClick}
ref={innerRef} ref={innerRef}
disabled={isLoading || props.isLoading} disabled={isLoading}
> >
{(props.icon || props.label) && ( {(props.icon || props.label) && (
<div className="ToolIcon__icon" aria-hidden="true"> <div className="ToolIcon__icon" aria-hidden="true">
@@ -130,7 +115,6 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => {
{props.keyBindingLabel} {props.keyBindingLabel}
</span> </span>
)} )}
{props.isLoading && <Spinner />}
</div> </div>
)} )}
{props.showAriaLabel && ( {props.showAriaLabel && (
+1
View File
@@ -6,6 +6,7 @@
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
position: relative; position: relative;
font-family: Cascadia;
cursor: pointer; cursor: pointer;
-webkit-tap-highlight-color: transparent; -webkit-tap-highlight-color: transparent;
border-radius: var(--space-factor); border-radius: var(--space-factor);
+4 -2
View File
@@ -34,8 +34,10 @@ const updateTooltip = (
width: itemWidth, width: itemWidth,
} = item.getBoundingClientRect(); } = item.getBoundingClientRect();
const { width: labelWidth, height: labelHeight } = const {
tooltip.getBoundingClientRect(); width: labelWidth,
height: labelHeight,
} = tooltip.getBoundingClientRect();
const viewportWidth = window.innerWidth; const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight; const viewportHeight = window.innerHeight;
+3 -3
View File
@@ -27,7 +27,7 @@ export class TopErrorBoundary extends React.Component<
for (const [key, value] of Object.entries({ ...localStorage })) { for (const [key, value] of Object.entries({ ...localStorage })) {
try { try {
_localStorage[key] = JSON.parse(value); _localStorage[key] = JSON.parse(value);
} catch (error: any) { } catch (error) {
_localStorage[key] = value; _localStorage[key] = value;
} }
} }
@@ -60,7 +60,7 @@ export class TopErrorBoundary extends React.Component<
) )
).default; ).default;
body = encodeURIComponent(templateStrFn(this.state.sentryEventId)); body = encodeURIComponent(templateStrFn(this.state.sentryEventId));
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
} }
@@ -86,7 +86,7 @@ export class TopErrorBoundary extends React.Component<
try { try {
localStorage.clear(); localStorage.clear();
window.location.reload(); window.location.reload();
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
} }
}} }}
+14 -15
View File
@@ -30,12 +30,8 @@ export const createIcon = (
d: string | React.ReactNode, d: string | React.ReactNode,
opts: number | Opts = 512, opts: number | Opts = 512,
) => { ) => {
const { const { width = 512, height = width, mirror, style } =
width = 512, typeof opts === "number" ? ({ width: opts } as Opts) : opts;
height = width,
mirror,
style,
} = typeof opts === "number" ? ({ width: opts } as Opts) : opts;
return ( return (
<svg <svg
aria-hidden="true" aria-hidden="true"
@@ -85,7 +81,6 @@ export const clipboard = createIcon(
export const trash = createIcon( export const trash = createIcon(
"M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z", "M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z",
{ width: 448, height: 512 }, { width: 448, height: 512 },
); );
@@ -852,6 +847,18 @@ export const FontFamilyCodeIcon = React.memo(({ theme }: { theme: Theme }) =>
), ),
); );
export const FontFamilyWireframeIcon = React.memo(
({ theme }: { theme: Theme }) =>
createIcon(
<>
<path
fill={iconFillColor(theme)}
d="M448 75.2v361.7c0 24.3-19 43.2-43.2 43.2H43.2C19.3 480 0 461.4 0 436.8V75.2C0 51.1 18.8 32 43.2 32h361.7c24 0 43.1 18.8 43.1 43.2zm-37.3 361.6V75.2c0-3-2.6-5.8-5.8-5.8h-9.3L285.3 144 224 94.1 162.8 144 52.5 69.3h-9.3c-3.2 0-5.8 2.8-5.8 5.8v361.7c0 3 2.6 5.8 5.8 5.8h361.7c3.2.1 5.8-2.7 5.8-5.8zM150.2 186v37H76.7v-37h73.5zm0 74.4v37.3H76.7v-37.3h73.5zm11.1-147.3l54-43.7H96.8l64.5 43.7zm210 72.9v37h-196v-37h196zm0 74.4v37.3h-196v-37.3h196zm-84.6-147.3l64.5-43.7H232.8l53.9 43.7zM371.3 335v37.3h-99.4V335h99.4z"
></path>
</>,
),
);
export const TextAlignLeftIcon = React.memo(({ theme }: { theme: Theme }) => export const TextAlignLeftIcon = React.memo(({ theme }: { theme: Theme }) =>
createIcon( createIcon(
<path <path
@@ -883,11 +890,3 @@ export const TextAlignRightIcon = React.memo(({ theme }: { theme: Theme }) =>
{ width: 448, height: 512 }, { width: 448, height: 512 },
), ),
); );
export const publishIcon = createIcon(
<path
d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z"
fill="currentColor"
/>,
{ width: 640, height: 512 },
);
+6 -4
View File
@@ -68,6 +68,11 @@ export const FONT_FAMILY = {
Virgil: 1, Virgil: 1,
Helvetica: 2, Helvetica: 2,
Cascadia: 3, Cascadia: 3,
REDACTED_REGULAR: 4,
REDACTED_SCRIPT_REGULAR: 5,
REDACTED_SCRIPT_BOLD: 6,
SCRIBBLE: 7,
BLOKK: 8,
}; };
export const THEME = { export const THEME = {
@@ -162,8 +167,7 @@ export const MAX_DECIMALS_FOR_SVG_EXPORT = 2;
export const EXPORT_SCALES = [1, 2, 3]; export const EXPORT_SCALES = [1, 2, 3];
export const DEFAULT_EXPORT_PADDING = 10; // px export const DEFAULT_EXPORT_PADDING = 10; // px
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_JPG = 10000; export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT = 1440;
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_OTHER = 1440;
export const ALLOWED_IMAGE_MIME_TYPES = [ export const ALLOWED_IMAGE_MIME_TYPES = [
MIME_TYPES.png, MIME_TYPES.png,
@@ -175,5 +179,3 @@ export const ALLOWED_IMAGE_MIME_TYPES = [
export const MAX_ALLOWED_FILE_BYTES = 2 * 1024 * 1024; export const MAX_ALLOWED_FILE_BYTES = 2 * 1024 * 1024;
export const SVG_NS = "http://www.w3.org/2000/svg"; export const SVG_NS = "http://www.w3.org/2000/svg";
export const ENCRYPTION_KEY_BITS = 128;
-21
View File
@@ -517,27 +517,6 @@
} }
} }
input[type="text"],
textarea:not(.excalidraw-wysiwyg) {
color: var(--text-primary-color);
border: 1.5px solid var(--input-border-color);
padding: 0.75rem;
white-space: nowrap;
border-radius: var(--space-factor);
background-color: var(--input-bg-color);
&:not(:focus) {
&:hover {
background-color: var(--input-hover-bg-color);
}
}
&:focus {
outline: none;
box-shadow: 0 0 0 2px var(--focus-highlight-color);
}
}
@media print { @media print {
.App-bottom-bar, .App-bottom-bar,
.FixedSideContainer, .FixedSideContainer,
+1 -2
View File
@@ -16,7 +16,7 @@
--icon-green-fill-color: #{$oc-green-9}; --icon-green-fill-color: #{$oc-green-9};
--default-bg-color: #{$oc-white}; --default-bg-color: #{$oc-white};
--input-bg-color: #{$oc-white}; --input-bg-color: #{$oc-white};
--input-border-color: #{$oc-gray-4}; --input-border-color: #{$oc-gray-3};
--input-hover-bg-color: #{$oc-gray-1}; --input-hover-bg-color: #{$oc-gray-1};
--input-label-color: #{$oc-gray-7}; --input-label-color: #{$oc-gray-7};
--island-bg-color: rgba(255, 255, 255, 0.96); --island-bg-color: rgba(255, 255, 255, 0.96);
@@ -64,7 +64,6 @@
--input-label-color: #{$oc-gray-2}; --input-label-color: #{$oc-gray-2};
--island-bg-color: rgba(30, 30, 30, 0.98); --island-bg-color: rgba(30, 30, 30, 0.98);
--keybinding-color: #{$oc-gray-6}; --keybinding-color: #{$oc-gray-6};
--link-color: #{$oc-blue-4};
--overlay-bg-color: #{transparentize($oc-gray-8, 0.88)}; --overlay-bg-color: #{transparentize($oc-gray-8, 0.88)};
--popup-bg-color: #2c2c2c; --popup-bg-color: #2c2c2c;
--popup-secondary-bg-color: #222; --popup-secondary-bg-color: #222;
+19 -28
View File
@@ -11,7 +11,6 @@ import { CanvasError } from "../errors";
import { t } from "../i18n"; import { t } from "../i18n";
import { calculateScrollCenter } from "../scene"; import { calculateScrollCenter } from "../scene";
import { AppState, DataURL } from "../types"; import { AppState, DataURL } from "../types";
import { bytesToHexString } from "../utils";
import { FileSystemHandle } from "./filesystem"; import { FileSystemHandle } from "./filesystem";
import { isValidExcalidrawData } from "./json"; import { isValidExcalidrawData } from "./json";
import { restore } from "./restore"; import { restore } from "./restore";
@@ -25,7 +24,7 @@ const parseFileContents = async (blob: Blob | File) => {
return await ( return await (
await import(/* webpackChunkName: "image" */ "./image") await import(/* webpackChunkName: "image" */ "./image")
).decodePngMetadata(blob); ).decodePngMetadata(blob);
} catch (error: any) { } catch (error) {
if (error.message === "INVALID") { if (error.message === "INVALID") {
throw new DOMException( throw new DOMException(
t("alerts.imageDoesNotContainScene"), t("alerts.imageDoesNotContainScene"),
@@ -59,7 +58,7 @@ const parseFileContents = async (blob: Blob | File) => {
).decodeSvgMetadata({ ).decodeSvgMetadata({
svg: contents, svg: contents,
}); });
} catch (error: any) { } catch (error) {
if (error.message === "INVALID") { if (error.message === "INVALID") {
throw new DOMException( throw new DOMException(
t("alerts.imageDoesNotContainScene"), t("alerts.imageDoesNotContainScene"),
@@ -157,7 +156,7 @@ export const loadFromBlob = async (
); );
return result; return result;
} catch (error: any) { } catch (error) {
console.error(error.message); console.error(error.message);
throw new Error(t("alerts.couldNotLoadInvalidFile")); throw new Error(t("alerts.couldNotLoadInvalidFile"));
} }
@@ -188,7 +187,7 @@ export const canvasToBlob = async (
} }
resolve(blob); resolve(blob);
}); });
} catch (error: any) { } catch (error) {
reject(error); reject(error);
} }
}); });
@@ -196,18 +195,26 @@ export const canvasToBlob = async (
/** generates SHA-1 digest from supplied file (if not supported, falls back /** generates SHA-1 digest from supplied file (if not supported, falls back
to a 40-char base64 random id) */ to a 40-char base64 random id) */
export const generateIdFromFile = async (file: File): Promise<FileId> => { export const generateIdFromFile = async (file: File) => {
let id: FileId;
try { try {
const hashBuffer = await window.crypto.subtle.digest( const hashBuffer = await window.crypto.subtle.digest(
"SHA-1", "SHA-1",
await file.arrayBuffer(), await file.arrayBuffer(),
); );
return bytesToHexString(new Uint8Array(hashBuffer)) as FileId; id =
} catch (error: any) { // convert buffer to byte array
Array.from(new Uint8Array(hashBuffer))
// convert to hex string
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
console.error(error); console.error(error);
// length 40 to align with the HEX length of SHA-1 (which is 160 bit) // length 40 to align with the HEX length of SHA-1 (which is 160 bit)
return nanoid(40) as FileId; id = nanoid(40) as FileId;
} }
return id;
}; };
export const getDataURL = async (file: Blob | File): Promise<DataURL> => { export const getDataURL = async (file: Blob | File): Promise<DataURL> => {
@@ -237,11 +244,7 @@ export const dataURLToFile = (dataURL: DataURL, filename = "") => {
export const resizeImageFile = async ( export const resizeImageFile = async (
file: File, file: File,
opts: { maxWidthOrHeight: number,
/** undefined indicates auto */
outputType?: typeof MIME_TYPES["jpg"];
maxWidthOrHeight: number;
},
): Promise<File> => { ): Promise<File> => {
// SVG files shouldn't a can't be resized // SVG files shouldn't a can't be resized
if (file.type === MIME_TYPES.svg) { if (file.type === MIME_TYPES.svg) {
@@ -261,16 +264,6 @@ export const resizeImageFile = async (
pica: pica({ features: ["js", "wasm"] }), pica: pica({ features: ["js", "wasm"] }),
}); });
if (opts.outputType) {
const { outputType } = opts;
reduce._create_blob = function (env) {
return this.pica.toBlob(env.out_canvas, outputType, 0.8).then((blob) => {
env.out_blob = blob;
return env;
});
};
}
const fileType = file.type; const fileType = file.type;
if (!isSupportedImageFile(file)) { if (!isSupportedImageFile(file)) {
@@ -278,11 +271,9 @@ export const resizeImageFile = async (
} }
return new File( return new File(
[await reduce.toBlob(file, { max: opts.maxWidthOrHeight })], [await reduce.toBlob(file, { max: maxWidthOrHeight })],
file.name, file.name,
{ { type: fileType },
type: fileType,
},
); );
}; };
+2 -2
View File
@@ -85,7 +85,7 @@ export const encode = async ({
if (compress !== false) { if (compress !== false) {
try { try {
deflated = await toByteString(deflate(text)); deflated = await toByteString(deflate(text));
} catch (error: any) { } catch (error) {
console.error("encode: cannot deflate", error); console.error("encode: cannot deflate", error);
} }
} }
@@ -367,7 +367,7 @@ export const decompressData = async <T extends Record<string, any>>(
/** data can be anything so the caller must decode it */ /** data can be anything so the caller must decode it */
data: contentsBuffer, data: contentsBuffer,
}; };
} catch (error: any) { } catch (error) {
console.error( console.error(
`Error during decompressing and decrypting the file.`, `Error during decompressing and decrypting the file.`,
encodingMetadata, encodingMetadata,
+8 -21
View File
@@ -1,5 +1,3 @@
import { ENCRYPTION_KEY_BITS } from "../constants";
export const IV_LENGTH_BYTES = 12; export const IV_LENGTH_BYTES = 12;
export const createIV = () => { export const createIV = () => {
@@ -7,27 +5,19 @@ export const createIV = () => {
return window.crypto.getRandomValues(arr); return window.crypto.getRandomValues(arr);
}; };
export const generateEncryptionKey = async < export const generateEncryptionKey = async () => {
T extends "string" | "cryptoKey" = "string",
>(
returnAs?: T,
): Promise<T extends "cryptoKey" ? CryptoKey : string> => {
const key = await window.crypto.subtle.generateKey( const key = await window.crypto.subtle.generateKey(
{ {
name: "AES-GCM", name: "AES-GCM",
length: ENCRYPTION_KEY_BITS, length: 128,
}, },
true, // extractable true, // extractable
["encrypt", "decrypt"], ["encrypt", "decrypt"],
); );
return ( return (await window.crypto.subtle.exportKey("jwk", key)).k;
returnAs === "cryptoKey"
? key
: (await window.crypto.subtle.exportKey("jwk", key)).k
) as T extends "cryptoKey" ? CryptoKey : string;
}; };
export const getCryptoKey = (key: string, usage: KeyUsage) => export const getImportedKey = (key: string, usage: KeyUsage) =>
window.crypto.subtle.importKey( window.crypto.subtle.importKey(
"jwk", "jwk",
{ {
@@ -39,18 +29,17 @@ export const getCryptoKey = (key: string, usage: KeyUsage) =>
}, },
{ {
name: "AES-GCM", name: "AES-GCM",
length: ENCRYPTION_KEY_BITS, length: 128,
}, },
false, // extractable false, // extractable
[usage], [usage],
); );
export const encryptData = async ( export const encryptData = async (
key: string | CryptoKey, key: string,
data: Uint8Array | ArrayBuffer | Blob | File | string, data: Uint8Array | ArrayBuffer | Blob | File | string,
): Promise<{ encryptedBuffer: ArrayBuffer; iv: Uint8Array }> => { ): Promise<{ encryptedBuffer: ArrayBuffer; iv: Uint8Array }> => {
const importedKey = const importedKey = await getImportedKey(key, "encrypt");
typeof key === "string" ? await getCryptoKey(key, "encrypt") : key;
const iv = createIV(); const iv = createIV();
const buffer: ArrayBuffer | Uint8Array = const buffer: ArrayBuffer | Uint8Array =
typeof data === "string" typeof data === "string"
@@ -61,8 +50,6 @@ export const encryptData = async (
? await data.arrayBuffer() ? await data.arrayBuffer()
: data; : data;
// We use symmetric encryption. AES-GCM is the recommended algorithm and
// includes checks that the ciphertext has not been modified by an attacker.
const encryptedBuffer = await window.crypto.subtle.encrypt( const encryptedBuffer = await window.crypto.subtle.encrypt(
{ {
name: "AES-GCM", name: "AES-GCM",
@@ -80,7 +67,7 @@ export const decryptData = async (
encrypted: Uint8Array | ArrayBuffer, encrypted: Uint8Array | ArrayBuffer,
privateKey: string, privateKey: string,
): Promise<ArrayBuffer> => { ): Promise<ArrayBuffer> => {
const key = await getCryptoKey(privateKey, "decrypt"); const key = await getImportedKey(privateKey, "decrypt");
return window.crypto.subtle.decrypt( return window.crypto.subtle.decrypt(
{ {
name: "AES-GCM", name: "AES-GCM",
+2 -2
View File
@@ -22,7 +22,7 @@ const INPUT_CHANGE_INTERVAL_MS = 500;
export const fileOpen = <M extends boolean | undefined = false>(opts: { export const fileOpen = <M extends boolean | undefined = false>(opts: {
extensions?: FILE_EXTENSION[]; extensions?: FILE_EXTENSION[];
description: string; description?: string;
multiple?: M; multiple?: M;
}): Promise< }): Promise<
M extends false | undefined ? FileWithHandle : FileWithHandle[] M extends false | undefined ? FileWithHandle : FileWithHandle[]
@@ -94,7 +94,7 @@ export const fileSave = (
name: string; name: string;
/** file extension */ /** file extension */
extension: FILE_EXTENSION; extension: FILE_EXTENSION;
description: string; description?: string;
/** existing FileSystemHandle */ /** existing FileSystemHandle */
fileHandle?: FileSystemHandle | null; fileHandle?: FileSystemHandle | null;
}, },
+5 -34
View File
@@ -1,11 +1,8 @@
import extractPngChunks from "png-chunks-extract"; import decodePng from "png-chunks-extract";
import tEXt from "png-chunk-text"; import tEXt from "png-chunk-text";
import encodePng from "png-chunks-encode"; import encodePng from "png-chunks-encode";
import { stringToBase64, encode, decode, base64ToString } from "./encode"; import { stringToBase64, encode, decode, base64ToString } from "./encode";
import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants"; import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants";
import { PngChunk } from "../types";
export { extractPngChunks };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// PNG // PNG
@@ -31,9 +28,7 @@ const blobToArrayBuffer = (blob: Blob): Promise<ArrayBuffer> => {
export const getTEXtChunk = async ( export const getTEXtChunk = async (
blob: Blob, blob: Blob,
): Promise<{ keyword: string; text: string } | null> => { ): Promise<{ keyword: string; text: string } | null> => {
const chunks = extractPngChunks( const chunks = decodePng(new Uint8Array(await blobToArrayBuffer(blob)));
new Uint8Array(await blobToArrayBuffer(blob)),
);
const metadataChunk = chunks.find((chunk) => chunk.name === "tEXt"); const metadataChunk = chunks.find((chunk) => chunk.name === "tEXt");
if (metadataChunk) { if (metadataChunk) {
return tEXt.decode(metadataChunk.data); return tEXt.decode(metadataChunk.data);
@@ -41,28 +36,6 @@ export const getTEXtChunk = async (
return null; return null;
}; };
export const findPngChunk = (
chunks: PngChunk[],
name: PngChunk["name"],
/** this makes the search stop before IDAT chunk (before which most
* metadata chunks reside). This is a perf optim. */
breakBeforeIDAT = true,
) => {
let i = 0;
const len = chunks.length;
while (i <= len) {
const chunk = chunks[i];
if (chunk.name === name) {
return chunk;
}
if (breakBeforeIDAT && chunk.name === "IDAT") {
return null;
}
i++;
}
return null;
};
export const encodePngMetadata = async ({ export const encodePngMetadata = async ({
blob, blob,
metadata, metadata,
@@ -70,9 +43,7 @@ export const encodePngMetadata = async ({
blob: Blob; blob: Blob;
metadata: string; metadata: string;
}) => { }) => {
const chunks = extractPngChunks( const chunks = decodePng(new Uint8Array(await blobToArrayBuffer(blob)));
new Uint8Array(await blobToArrayBuffer(blob)),
);
const metadataChunk = tEXt.encode( const metadataChunk = tEXt.encode(
MIME_TYPES.excalidraw, MIME_TYPES.excalidraw,
@@ -105,7 +76,7 @@ export const decodePngMetadata = async (blob: Blob) => {
throw new Error("FAILED"); throw new Error("FAILED");
} }
return await decode(encodedData); return await decode(encodedData);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
throw new Error("FAILED"); throw new Error("FAILED");
} }
@@ -156,7 +127,7 @@ export const decodeSvgMetadata = async ({ svg }: { svg: string }) => {
throw new Error("FAILED"); throw new Error("FAILED");
} }
return await decode(encodedData); return await decode(encodedData);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
throw new Error("FAILED"); throw new Error("FAILED");
} }
+1 -3
View File
@@ -54,7 +54,6 @@ export const exportCanvas = async (
return await fileSave( return await fileSave(
new Blob([tempSvg.outerHTML], { type: MIME_TYPES.svg }), new Blob([tempSvg.outerHTML], { type: MIME_TYPES.svg }),
{ {
description: "Export to SVG",
name, name,
extension: "svg", extension: "svg",
fileHandle, fileHandle,
@@ -87,7 +86,6 @@ export const exportCanvas = async (
} }
return await fileSave(blob, { return await fileSave(blob, {
description: "Export to PNG",
name, name,
extension: "png", extension: "png",
fileHandle, fileHandle,
@@ -95,7 +93,7 @@ export const exportCanvas = async (
} else if (type === "clipboard") { } else if (type === "clipboard") {
try { try {
await copyBlobToClipboardAsPng(blob); await copyBlobToClipboardAsPng(blob);
} catch (error: any) { } catch (error) {
if (error.name === "CANVAS_POSSIBLY_TOO_BIG") { if (error.name === "CANVAS_POSSIBLY_TOO_BIG") {
throw error; throw error;
} }
+6 -5
View File
@@ -3,7 +3,7 @@ import { cleanAppStateForExport, clearAppStateForDatabase } from "../appState";
import { EXPORT_DATA_TYPES, EXPORT_SOURCE, MIME_TYPES } from "../constants"; import { EXPORT_DATA_TYPES, EXPORT_SOURCE, MIME_TYPES } from "../constants";
import { clearElementsForDatabase, clearElementsForExport } from "../element"; import { clearElementsForDatabase, clearElementsForExport } from "../element";
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { AppState, BinaryFiles, LibraryItems } from "../types"; import { AppState, BinaryFiles } from "../types";
import { isImageFileHandle, loadFromBlob } from "./blob"; import { isImageFileHandle, loadFromBlob } from "./blob";
import { import {
@@ -114,16 +114,17 @@ export const isValidLibrary = (json: any) => {
typeof json === "object" && typeof json === "object" &&
json && json &&
json.type === EXPORT_DATA_TYPES.excalidrawLibrary && json.type === EXPORT_DATA_TYPES.excalidrawLibrary &&
(json.version === 1 || json.version === 2) json.version === 1
); );
}; };
export const saveLibraryAsJSON = async (libraryItems: LibraryItems) => { export const saveLibraryAsJSON = async (library: Library) => {
const libraryItems = await library.loadLibrary();
const data: ExportedLibraryData = { const data: ExportedLibraryData = {
type: EXPORT_DATA_TYPES.excalidrawLibrary, type: EXPORT_DATA_TYPES.excalidrawLibrary,
version: 2, version: 1,
source: EXPORT_SOURCE, source: EXPORT_SOURCE,
libraryItems, library: libraryItems,
}; };
const serialized = JSON.stringify(data, null, 2); const serialized = JSON.stringify(data, null, 2);
await fileSave( await fileSave(
+17 -24
View File
@@ -1,6 +1,6 @@
import { loadLibraryFromBlob } from "./blob"; import { loadLibraryFromBlob } from "./blob";
import { LibraryItems, LibraryItem } from "../types"; import { LibraryItems, LibraryItem } from "../types";
import { restoreElements, restoreLibraryItems } from "./restore"; import { restoreElements } from "./restore";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
import type App from "../components/App"; import type App from "../components/App";
@@ -18,16 +18,14 @@ class Library {
}; };
restoreLibraryItem = (libraryItem: LibraryItem): LibraryItem | null => { restoreLibraryItem = (libraryItem: LibraryItem): LibraryItem | null => {
const elements = getNonDeletedElements( const elements = getNonDeletedElements(restoreElements(libraryItem, null));
restoreElements(libraryItem.elements, null), return elements.length ? elements : null;
);
return elements.length ? { ...libraryItem, elements } : null;
}; };
/** imports library (currently merges, removing duplicates) */ /** imports library (currently merges, removing duplicates) */
async importLibrary(blob: Blob, defaultStatus = "unpublished") { async importLibrary(blob: Blob) {
const libraryFile = await loadLibraryFromBlob(blob); const libraryFile = await loadLibraryFromBlob(blob);
if (!libraryFile || !(libraryFile.libraryItems || libraryFile.library)) { if (!libraryFile || !libraryFile.library) {
return; return;
} }
@@ -39,17 +37,17 @@ class Library {
targetLibraryItem: LibraryItem, targetLibraryItem: LibraryItem,
) => { ) => {
return !existingLibraryItems.find((libraryItem) => { return !existingLibraryItems.find((libraryItem) => {
if (libraryItem.elements.length !== targetLibraryItem.elements.length) { if (libraryItem.length !== targetLibraryItem.length) {
return false; return false;
} }
// detect z-index difference by checking the excalidraw elements // detect z-index difference by checking the excalidraw elements
// are in order // are in order
return libraryItem.elements.every((libItemExcalidrawItem, idx) => { return libraryItem.every((libItemExcalidrawItem, idx) => {
return ( return (
libItemExcalidrawItem.id === targetLibraryItem.elements[idx].id && libItemExcalidrawItem.id === targetLibraryItem[idx].id &&
libItemExcalidrawItem.versionNonce === libItemExcalidrawItem.versionNonce ===
targetLibraryItem.elements[idx].versionNonce targetLibraryItem[idx].versionNonce
); );
}); });
}); });
@@ -57,20 +55,15 @@ class Library {
const existingLibraryItems = await this.loadLibrary(); const existingLibraryItems = await this.loadLibrary();
const library = libraryFile.libraryItems || libraryFile.library || []; const filtered = libraryFile.library!.reduce((acc, libraryItem) => {
const restoredLibItems = restoreLibraryItems( const restoredItem = this.restoreLibraryItem(libraryItem);
library,
defaultStatus as "published" | "unpublished",
);
const filteredItems = [];
for (const item of restoredLibItems) {
const restoredItem = this.restoreLibraryItem(item as LibraryItem);
if (restoredItem && isUniqueitem(existingLibraryItems, restoredItem)) { if (restoredItem && isUniqueitem(existingLibraryItems, restoredItem)) {
filteredItems.push(restoredItem); acc.push(restoredItem);
} }
} return acc;
}, [] as Mutable<LibraryItems>);
await this.saveLibrary([...filteredItems, ...existingLibraryItems]); await this.saveLibrary([...existingLibraryItems, ...filtered]);
} }
loadLibrary = (): Promise<LibraryItems> => { loadLibrary = (): Promise<LibraryItems> => {
@@ -97,7 +90,7 @@ class Library {
this.libraryCache = JSON.parse(JSON.stringify(items)); this.libraryCache = JSON.parse(JSON.stringify(items));
resolve(items); resolve(items);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
resolve([]); resolve([]);
} }
@@ -112,7 +105,7 @@ class Library {
// immediately // immediately
this.libraryCache = JSON.parse(serializedItems); this.libraryCache = JSON.parse(serializedItems);
await this.app.props.onLibraryChange?.(items); await this.app.props.onLibraryChange?.(items);
} catch (error: any) { } catch (error) {
this.libraryCache = prevLibraryItems; this.libraryCache = prevLibraryItems;
throw error; throw error;
} }
+8 -39
View File
@@ -3,12 +3,7 @@ import {
ExcalidrawSelectionElement, ExcalidrawSelectionElement,
FontFamilyValues, FontFamilyValues,
} from "../element/types"; } from "../element/types";
import { import { AppState, BinaryFiles, NormalizedZoomValue } from "../types";
AppState,
BinaryFiles,
LibraryItem,
NormalizedZoomValue,
} from "../types";
import { ImportedDataState } from "./types"; import { ImportedDataState } from "./types";
import { import {
getElementMap, getElementMap,
@@ -64,7 +59,7 @@ const getFontFamilyByName = (fontFamilyName: string): FontFamilyValues => {
const restoreElementWithProperties = < const restoreElementWithProperties = <
T extends ExcalidrawElement, T extends ExcalidrawElement,
K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>, K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>
>( >(
element: Required<T>, element: Required<T>,
extra: Pick< extra: Pick<
@@ -103,11 +98,11 @@ const restoreElementWithProperties = <
boundElementIds: element.boundElementIds ?? [], boundElementIds: element.boundElementIds ?? [],
}; };
return { return ({
...base, ...base,
...getNormalizedDimensions(base), ...getNormalizedDimensions(base),
...extra, ...extra,
} as unknown as T; } as unknown) as T;
}; };
const restoreElement = ( const restoreElement = (
@@ -118,9 +113,10 @@ const restoreElement = (
let fontSize = element.fontSize; let fontSize = element.fontSize;
let fontFamily = element.fontFamily; let fontFamily = element.fontFamily;
if ("font" in element) { if ("font" in element) {
const [fontPx, _fontFamily]: [string, string] = ( const [fontPx, _fontFamily]: [
element as any string,
).font.split(" "); string,
] = (element as any).font.split(" ");
fontSize = parseInt(fontPx, 10); fontSize = parseInt(fontPx, 10);
fontFamily = getFontFamilyByName(_fontFamily); fontFamily = getFontFamilyByName(_fontFamily);
} }
@@ -278,30 +274,3 @@ export const restore = (
files: data?.files || {}, files: data?.files || {},
}; };
}; };
export const restoreLibraryItems = (
libraryItems: NonOptional<ImportedDataState["libraryItems"]>,
defaultStatus: LibraryItem["status"],
) => {
const restoredItems: LibraryItem[] = [];
for (const item of libraryItems) {
// migrate older libraries
if (Array.isArray(item)) {
restoredItems.push({
status: defaultStatus,
elements: item,
id: randomId(),
created: Date.now(),
});
} else {
const _item = item as MarkOptional<LibraryItem, "id" | "status">;
restoredItems.push({
..._item,
id: _item.id || randomId(),
status: _item.status || defaultStatus,
created: _item.created || Date.now(),
});
}
}
return restoredItems;
};
+5 -8
View File
@@ -1,5 +1,5 @@
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { AppState, BinaryFiles, LibraryItems, LibraryItems_v1 } from "../types"; import { AppState, BinaryFiles, LibraryItems } from "../types";
import type { cleanAppStateForExport } from "../appState"; import type { cleanAppStateForExport } from "../appState";
export interface ExportedDataState { export interface ExportedDataState {
@@ -18,18 +18,15 @@ export interface ImportedDataState {
elements?: readonly ExcalidrawElement[] | null; elements?: readonly ExcalidrawElement[] | null;
appState?: Readonly<Partial<AppState>> | null; appState?: Readonly<Partial<AppState>> | null;
scrollToContent?: boolean; scrollToContent?: boolean;
libraryItems?: LibraryItems | LibraryItems_v1; libraryItems?: LibraryItems;
files?: BinaryFiles; files?: BinaryFiles;
} }
export interface ExportedLibraryData { export interface ExportedLibraryData {
type: string; type: string;
version: 2; version: number;
source: string; source: string;
libraryItems: LibraryItems; library: LibraryItems;
} }
export interface ImportedLibraryData extends Partial<ExportedLibraryData> { export interface ImportedLibraryData extends Partial<ExportedLibraryData> {}
/** @deprecated v1 */
library?: LibraryItems;
}
+25 -28
View File
@@ -137,13 +137,14 @@ export const bindOrUnbindSelectedElements = (
const maybeBindBindableElement = ( const maybeBindBindableElement = (
bindableElement: NonDeleted<ExcalidrawBindableElement>, bindableElement: NonDeleted<ExcalidrawBindableElement>,
): void => { ): void => {
getElligibleElementsForBindableElementAndWhere(bindableElement).forEach( getElligibleElementsForBindableElementAndWhere(
([linearElement, where]) => bindableElement,
bindOrUnbindLinearElement( ).forEach(([linearElement, where]) =>
linearElement, bindOrUnbindLinearElement(
where === "end" ? "keep" : bindableElement, linearElement,
where === "start" ? "keep" : bindableElement, where === "end" ? "keep" : bindableElement,
), where === "start" ? "keep" : bindableElement,
),
); );
}; };
@@ -292,11 +293,9 @@ export const updateBoundElements = (
const simultaneouslyUpdatedElementIds = getSimultaneouslyUpdatedElementIds( const simultaneouslyUpdatedElementIds = getSimultaneouslyUpdatedElementIds(
simultaneouslyUpdated, simultaneouslyUpdated,
); );
( (Scene.getScene(changedElement)!.getNonDeletedElements(
Scene.getScene(changedElement)!.getNonDeletedElements( boundElementIds,
boundElementIds, ) as NonDeleted<ExcalidrawLinearElement>[]).forEach((linearElement) => {
) as NonDeleted<ExcalidrawLinearElement>[]
).forEach((linearElement) => {
const bindableElement = changedElement as ExcalidrawBindableElement; const bindableElement = changedElement as ExcalidrawBindableElement;
// In case the boundElementIds are stale // In case the boundElementIds are stale
if (!doesNeedUpdate(linearElement, bindableElement)) { if (!doesNeedUpdate(linearElement, bindableElement)) {
@@ -581,11 +580,9 @@ export const fixBindingsAfterDuplication = (
}); });
// Update the linear elements // Update the linear elements
( (sceneElements.filter(({ id }) =>
sceneElements.filter(({ id }) => allBoundElementIds.has(id),
allBoundElementIds.has(id), ) as ExcalidrawLinearElement[]).forEach((element) => {
) as ExcalidrawLinearElement[]
).forEach((element) => {
const { startBinding, endBinding } = element; const { startBinding, endBinding } = element;
mutateElement(element, { mutateElement(element, {
startBinding: newBindingAfterDuplication( startBinding: newBindingAfterDuplication(
@@ -645,17 +642,17 @@ export const fixBindingsAfterDeletion = (
}); });
} }
}); });
( (sceneElements.filter(({ id }) =>
sceneElements.filter(({ id }) => boundElementIds.has(id),
boundElementIds.has(id), ) as ExcalidrawLinearElement[]).forEach(
) as ExcalidrawLinearElement[] (element: ExcalidrawLinearElement) => {
).forEach((element: ExcalidrawLinearElement) => { const { startBinding, endBinding } = element;
const { startBinding, endBinding } = element; mutateElement(element, {
mutateElement(element, { startBinding: newBindingAfterDeletion(startBinding, deletedElementIds),
startBinding: newBindingAfterDeletion(startBinding, deletedElementIds), endBinding: newBindingAfterDeletion(endBinding, deletedElementIds),
endBinding: newBindingAfterDeletion(endBinding, deletedElementIds), });
}); },
}); );
}; };
const newBindingAfterDeletion = ( const newBindingAfterDeletion = (
+2 -17
View File
@@ -3,7 +3,6 @@ import {
ExcalidrawLinearElement, ExcalidrawLinearElement,
Arrowhead, Arrowhead,
ExcalidrawFreeDrawElement, ExcalidrawFreeDrawElement,
NonDeleted,
} from "./types"; } from "./types";
import { distance2d, rotate } from "../math"; import { distance2d, rotate } from "../math";
import rough from "roughjs/bin/rough"; import rough from "roughjs/bin/rough";
@@ -79,7 +78,7 @@ const getMinMaxXYFromCurvePathOps = (
// move, bcurveTo, lineTo, and curveTo // move, bcurveTo, lineTo, and curveTo
if (op === "move") { if (op === "move") {
// change starting point // change starting point
currentP = data as unknown as Point; currentP = (data as unknown) as Point;
// move operation does not draw anything; so, it always // move operation does not draw anything; so, it always
// returns false // returns false
} else if (op === "bcurveTo") { } else if (op === "bcurveTo") {
@@ -228,7 +227,7 @@ export const getArrowheadPoints = (
const prevOp = ops[index - 1]; const prevOp = ops[index - 1];
let p0: Point = [0, 0]; let p0: Point = [0, 0];
if (prevOp.op === "move") { if (prevOp.op === "move") {
p0 = prevOp.data as unknown as Point; p0 = (prevOp.data as unknown) as Point;
} else if (prevOp.op === "bcurveTo") { } else if (prevOp.op === "bcurveTo") {
p0 = [prevOp.data[4], prevOp.data[5]]; p0 = [prevOp.data[4], prevOp.data[5]];
} }
@@ -514,17 +513,3 @@ export const getClosestElementBounds = (
return getElementBounds(closestElement); return getElementBounds(closestElement);
}; };
export interface Box {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
export const getCommonBoundingBox = (
elements: ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[],
): Box => {
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
return { minX, minY, maxX, maxY };
};
+1 -1
View File
@@ -866,7 +866,7 @@ const hitTestRoughShape = (
// move, bcurveTo, lineTo, and curveTo // move, bcurveTo, lineTo, and curveTo
if (op === "move") { if (op === "move") {
// change starting point // change starting point
currentP = data as unknown as Point; currentP = (data as unknown) as Point;
// move operation does not draw anything; so, it always // move operation does not draw anything; so, it always
// returns false // returns false
} else if (op === "bcurveTo") { } else if (op === "bcurveTo") {
+1 -80
View File
@@ -3,7 +3,6 @@
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
import { MIME_TYPES, SVG_NS } from "../constants"; import { MIME_TYPES, SVG_NS } from "../constants";
import { getDataURL } from "../data/blob";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppClassProperties, DataURL, BinaryFiles } from "../types"; import { AppClassProperties, DataURL, BinaryFiles } from "../types";
import { isInitializedImageElement } from "./typeChecks"; import { isInitializedImageElement } from "./typeChecks";
@@ -64,7 +63,7 @@ export const updateImageCache = async ({
const image = await imagePromise; const image = await imagePromise;
imageCache.set(fileId, { ...data, image }); imageCache.set(fileId, { ...data, image });
} catch (error: any) { } catch (error) {
erroredFiles.set(fileId, true); erroredFiles.set(fileId, true);
} }
})(), })(),
@@ -110,81 +109,3 @@ export const normalizeSVG = async (SVGString: string) => {
return svg.outerHTML; return svg.outerHTML;
} }
}; };
/**
* To improve perf, uses `createImageBitmap` is available. But there are
* quality issues across browsers, so don't use this API where quality matters.
*/
export const speedyImageToCanvas = async (imageFile: Blob | File) => {
let imageSrc: HTMLImageElement | ImageBitmap;
if (
typeof ImageBitmap !== "undefined" &&
ImageBitmap.prototype &&
ImageBitmap.prototype.close &&
window.createImageBitmap
) {
imageSrc = await window.createImageBitmap(imageFile);
} else {
imageSrc = await loadHTMLImageElement(await getDataURL(imageFile));
}
const { width, height } = imageSrc;
const canvas = document.createElement("canvas");
canvas.height = height;
canvas.width = width;
const context = canvas.getContext("2d")!;
context.drawImage(imageSrc, 0, 0, width, height);
if (typeof ImageBitmap !== "undefined" && imageSrc instanceof ImageBitmap) {
imageSrc.close();
}
return { canvas, context, width, height };
};
/**
* Does its best at figuring out if an image (PNG) has any (semi)transparent
* pixels. If not PNG, always returns false.
*/
export const hasTransparentPixels = async (imageFile: Blob | File) => {
if (imageFile.type !== MIME_TYPES.png) {
return false;
}
const { findPngChunk, extractPngChunks } = await import("../data/image");
const buffer = await imageFile.arrayBuffer();
const chunks = extractPngChunks(new Uint8Array(buffer));
// early exit if tRNS not found and IHDR states no support for alpha
// -----------------------------------------------------------------------
const IHDR = findPngChunk(chunks, "IHDR");
if (
IHDR &&
IHDR.data[9] !== 4 &&
IHDR.data[9] !== 6 &&
!findPngChunk(chunks, "tRNS")
) {
return false;
}
// otherwise loop through pixels to check if there's any actually
// (semi)transparent pixel
// -----------------------------------------------------------------------
const { width, height, context } = await speedyImageToCanvas(imageFile);
{
const { data } = context.getImageData(0, 0, width, height);
const len = data.byteLength;
let i = 3;
while (i <= len) {
if (data[i] !== 255) {
return true;
}
i += 4;
}
}
return false;
};
+7 -4
View File
@@ -150,8 +150,9 @@ export class LinearElementEditor {
) )
: null; : null;
binding = { binding = {
[activePointIndex === 0 ? "startBindingElement" : "endBindingElement"]: [activePointIndex === 0
bindingElement, ? "startBindingElement"
: "endBindingElement"]: bindingElement,
}; };
} }
return { return {
@@ -235,8 +236,10 @@ export class LinearElementEditor {
// from the end points of the `linearElement` - this is to allow disabling // from the end points of the `linearElement` - this is to allow disabling
// binding (which needs to happen at the point the user finishes moving // binding (which needs to happen at the point the user finishes moving
// the point). // the point).
const { startBindingElement, endBindingElement } = const {
appState.editingLinearElement; startBindingElement,
endBindingElement,
} = appState.editingLinearElement;
if (isBindingEnabled(appState) && isBindingElement(element)) { if (isBindingEnabled(appState) && isBindingElement(element)) {
bindOrUnbindLinearElement( bindOrUnbindLinearElement(
element, element,
+10 -6
View File
@@ -464,12 +464,16 @@ export const resizeSingleElement = (
} }
} }
const [newBoundsX1, newBoundsY1, newBoundsX2, newBoundsY2] = const [
getResizedElementAbsoluteCoords( newBoundsX1,
stateAtResizeStart, newBoundsY1,
eleNewWidth, newBoundsX2,
eleNewHeight, newBoundsY2,
); ] = getResizedElementAbsoluteCoords(
stateAtResizeStart,
eleNewWidth,
eleNewHeight,
);
const newBoundsWidth = newBoundsX2 - newBoundsX1; const newBoundsWidth = newBoundsX2 - newBoundsX1;
const newBoundsHeight = newBoundsY2 - newBoundsY1; const newBoundsHeight = newBoundsY2 - newBoundsY1;
+10 -6
View File
@@ -36,8 +36,10 @@ export const resizeTest = (
return false; return false;
} }
const { rotation: rotationTransformHandle, ...transformHandles } = const {
getTransformHandles(element, zoom, pointerType); rotation: rotationTransformHandle,
...transformHandles
} = getTransformHandles(element, zoom, pointerType);
if ( if (
rotationTransformHandle && rotationTransformHandle &&
@@ -47,8 +49,9 @@ export const resizeTest = (
} }
const filter = Object.keys(transformHandles).filter((key) => { const filter = Object.keys(transformHandles).filter((key) => {
const transformHandle = const transformHandle = transformHandles[
transformHandles[key as Exclude<TransformHandleType, "rotation">]!; key as Exclude<TransformHandleType, "rotation">
]!;
if (!transformHandle) { if (!transformHandle) {
return false; return false;
} }
@@ -102,8 +105,9 @@ export const getTransformHandleTypeFromCoords = (
); );
const found = Object.keys(transformHandles).find((key) => { const found = Object.keys(transformHandles).find((key) => {
const transformHandle = const transformHandle = transformHandles[
transformHandles[key as Exclude<TransformHandleType, "rotation">]!; key as Exclude<TransformHandleType, "rotation">
]!;
return ( return (
transformHandle && transformHandle &&
isInsideTransformHandle(transformHandle, scenePointerX, scenePointerY) isInsideTransformHandle(transformHandle, scenePointerX, scenePointerY)
+3 -2
View File
@@ -108,7 +108,6 @@ export const textWysiwyg = ({
editable.dataset.type = "wysiwyg"; editable.dataset.type = "wysiwyg";
// prevent line wrapping on Safari // prevent line wrapping on Safari
editable.wrap = "off"; editable.wrap = "off";
editable.classList.add("excalidraw-wysiwyg");
Object.assign(editable.style, { Object.assign(editable.style, {
position: "absolute", position: "absolute",
@@ -320,7 +319,9 @@ export const textWysiwyg = ({
// prevent blur when changing properties from the menu // prevent blur when changing properties from the menu
const onPointerDown = (event: MouseEvent) => { const onPointerDown = (event: MouseEvent) => {
if ( if (event.target instanceof HTMLSelectElement) {
handleSubmit();
} else if (
(event.target instanceof HTMLElement || (event.target instanceof HTMLElement ||
event.target instanceof SVGElement) && event.target instanceof SVGElement) &&
event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) && event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) &&
+3 -3
View File
@@ -17,9 +17,9 @@ export type TransformHandleDirection =
export type TransformHandleType = TransformHandleDirection | "rotation"; export type TransformHandleType = TransformHandleDirection | "rotation";
export type TransformHandle = [number, number, number, number]; export type TransformHandle = [number, number, number, number];
export type TransformHandles = Partial<{ export type TransformHandles = Partial<
[T in TransformHandleType]: TransformHandle; { [T in TransformHandleType]: TransformHandle }
}>; >;
export type MaybeTransformHandleType = TransformHandleType | false; export type MaybeTransformHandleType = TransformHandleType | false;
const transformHandleSizes: { [k in PointerType]: number } = { const transformHandleSizes: { [k in PointerType]: number } = {
-2
View File
@@ -23,5 +23,3 @@ export const FIREBASE_STORAGE_PREFIXES = {
shareLinkFiles: `/files/shareLinks`, shareLinkFiles: `/files/shareLinks`,
collabFiles: `/files/rooms`, collabFiles: `/files/rooms`,
}; };
export const ROOM_ID_BYTES = 10;
+28 -43
View File
@@ -24,6 +24,7 @@ import {
SYNC_FULL_SCENE_INTERVAL_MS, SYNC_FULL_SCENE_INTERVAL_MS,
} from "../app_constants"; } from "../app_constants";
import { import {
decryptAESGEM,
generateCollaborationLinkData, generateCollaborationLinkData,
getCollaborationLink, getCollaborationLink,
SocketUpdateDataSource, SocketUpdateDataSource,
@@ -59,12 +60,11 @@ import {
isImageElement, isImageElement,
isInitializedImageElement, isInitializedImageElement,
} from "../../element/typeChecks"; } from "../../element/typeChecks";
import { newElementWith } from "../../element/mutateElement"; import { mutateElement } from "../../element/mutateElement";
import { import {
ReconciledElements, ReconciledElements,
reconcileElements as _reconcileElements, reconcileElements as _reconcileElements,
} from "./reconciliation"; } from "./reconciliation";
import { decryptData } from "../../data/encryption";
interface CollabState { interface CollabState {
modalIsShown: boolean; modalIsShown: boolean;
@@ -230,7 +230,7 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
) => { ) => {
try { try {
await saveToFirebase(this.portal, syncableElements); await saveToFirebase(this.portal, syncableElements);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
} }
}; };
@@ -241,9 +241,6 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
}; };
closePortal = () => { closePortal = () => {
this.queueBroadcastAllElements.cancel();
this.loadImageFiles.cancel();
this.saveCollabRoomToFirebase(); this.saveCollabRoomToFirebase();
if (window.confirm(t("alerts.collabStopOverridePrompt"))) { if (window.confirm(t("alerts.collabStopOverridePrompt"))) {
window.history.pushState({}, APP_NAME, window.location.origin); window.history.pushState({}, APP_NAME, window.location.origin);
@@ -256,7 +253,7 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
.getSceneElementsIncludingDeleted() .getSceneElementsIncludingDeleted()
.map((element) => { .map((element) => {
if (isImageElement(element) && element.status === "saved") { if (isImageElement(element) && element.status === "saved") {
return newElementWith(element, { status: "pending" }); return mutateElement(element, { status: "pending" }, false);
} }
return element; return element;
}); });
@@ -301,27 +298,6 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
return await this.fileManager.getFiles(unfetchedImages); return await this.fileManager.getFiles(unfetchedImages);
}; };
private decryptPayload = async (
iv: Uint8Array,
encryptedData: ArrayBuffer,
decryptionKey: string,
) => {
try {
const decrypted = await decryptData(iv, encryptedData, decryptionKey);
const decodedData = new TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
return JSON.parse(decodedData);
} catch (error) {
window.alert(t("alerts.decryptFailed"));
console.error(error);
return {
type: "INVALID_RESPONSE",
};
}
};
private initializeSocketClient = async ( private initializeSocketClient = async (
existingRoomLinkData: null | { roomId: string; roomKey: string }, existingRoomLinkData: null | { roomId: string; roomKey: string },
): Promise<ImportedDataState | null> => { ): Promise<ImportedDataState | null> => {
@@ -368,14 +344,18 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
scrollToContent: true, scrollToContent: true,
}); });
} }
} catch (error: any) { } catch (error) {
// log the error and move on. other peers will sync us the scene. // log the error and move on. other peers will sync us the scene.
console.error(error); console.error(error);
} }
} else { } else {
const elements = this.excalidrawAPI.getSceneElements().map((element) => { const elements = this.excalidrawAPI.getSceneElements().map((element) => {
if (isImageElement(element) && element.status === "saved") { if (isImageElement(element) && element.status === "saved") {
return newElementWith(element, { status: "pending" }); return mutateElement(
element,
{ status: "pending" },
/* informMutation */ false,
);
} }
return element; return element;
}); });
@@ -409,11 +389,10 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
if (!this.portal.roomKey) { if (!this.portal.roomKey) {
return; return;
} }
const decryptedData = await decryptAESGEM(
const decryptedData = await this.decryptPayload(
iv,
encryptedData, encryptedData,
this.portal.roomKey, this.portal.roomKey,
iv,
); );
switch (decryptedData.type) { switch (decryptedData.type) {
@@ -441,8 +420,12 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
); );
break; break;
case "MOUSE_LOCATION": { case "MOUSE_LOCATION": {
const { pointer, button, username, selectedElementIds } = const {
decryptedData.payload; pointer,
button,
username,
selectedElementIds,
} = decryptedData.payload;
const socketId: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["socketId"] = const socketId: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["socketId"] =
decryptedData.payload.socketId || decryptedData.payload.socketId ||
// @ts-ignore legacy, see #2094 (#2097) // @ts-ignore legacy, see #2094 (#2097)
@@ -521,10 +504,12 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
}; };
private loadImageFiles = throttle(async () => { private loadImageFiles = throttle(async () => {
const { loadedFiles, erroredFiles } = const {
await this.fetchImageFilesFromFirebase({ loadedFiles,
elements: this.excalidrawAPI.getSceneElementsIncludingDeleted(), erroredFiles,
}); } = await this.fetchImageFilesFromFirebase({
elements: this.excalidrawAPI.getSceneElementsIncludingDeleted(),
});
this.excalidrawAPI.addFiles(loadedFiles); this.excalidrawAPI.addFiles(loadedFiles);
@@ -607,8 +592,9 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
setCollaborators(sockets: string[]) { setCollaborators(sockets: string[]) {
this.setState((state) => { this.setState((state) => {
const collaborators: InstanceType<typeof CollabWrapper>["collaborators"] = const collaborators: InstanceType<
new Map(); typeof CollabWrapper
>["collaborators"] = new Map();
for (const socketId of sockets) { for (const socketId of sockets) {
if (this.collaborators.has(socketId)) { if (this.collaborators.has(socketId)) {
collaborators.set(socketId, this.collaborators.get(socketId)!); collaborators.set(socketId, this.collaborators.get(socketId)!);
@@ -710,8 +696,7 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
this.contextValue.initializeSocketClient = this.initializeSocketClient; this.contextValue.initializeSocketClient = this.initializeSocketClient;
this.contextValue.onCollabButtonClick = this.onCollabButtonClick; this.contextValue.onCollabButtonClick = this.onCollabButtonClick;
this.contextValue.broadcastElements = this.broadcastElements; this.contextValue.broadcastElements = this.broadcastElements;
this.contextValue.fetchImageFilesFromFirebase = this.contextValue.fetchImageFilesFromFirebase = this.fetchImageFilesFromFirebase;
this.fetchImageFilesFromFirebase;
return this.contextValue; return this.contextValue;
}; };
+23 -20
View File
@@ -1,4 +1,8 @@
import { SocketUpdateData, SocketUpdateDataSource } from "../data"; import {
encryptAESGEM,
SocketUpdateData,
SocketUpdateDataSource,
} from "../data";
import CollabWrapper from "./CollabWrapper"; import CollabWrapper from "./CollabWrapper";
@@ -7,9 +11,8 @@ import { BROADCAST, FILE_UPLOAD_TIMEOUT, SCENE } from "../app_constants";
import { UserIdleState } from "../../types"; import { UserIdleState } from "../../types";
import { trackEvent } from "../../analytics"; import { trackEvent } from "../../analytics";
import { throttle } from "lodash"; import { throttle } from "lodash";
import { newElementWith } from "../../element/mutateElement"; import { mutateElement } from "../../element/mutateElement";
import { BroadcastedExcalidrawElement } from "./reconciliation"; import { BroadcastedExcalidrawElement } from "./reconciliation";
import { encryptData } from "../../data/encryption";
class Portal { class Portal {
collab: CollabWrapper; collab: CollabWrapper;
@@ -51,7 +54,6 @@ class Portal {
if (!this.socket) { if (!this.socket) {
return; return;
} }
this.queueFileUpload.flush();
this.socket.close(); this.socket.close();
this.socket = null; this.socket = null;
this.roomId = null; this.roomId = null;
@@ -76,13 +78,12 @@ class Portal {
if (this.isOpen()) { if (this.isOpen()) {
const json = JSON.stringify(data); const json = JSON.stringify(data);
const encoded = new TextEncoder().encode(json); const encoded = new TextEncoder().encode(json);
const { encryptedBuffer, iv } = await encryptData(this.roomKey!, encoded); const encrypted = await encryptAESGEM(encoded, this.roomKey!);
this.socket!.emit(
this.socket?.emit(
volatile ? BROADCAST.SERVER_VOLATILE : BROADCAST.SERVER, volatile ? BROADCAST.SERVER_VOLATILE : BROADCAST.SERVER,
this.roomId, this.roomId,
encryptedBuffer, encrypted.data,
iv, encrypted.iv,
); );
} }
} }
@@ -93,14 +94,12 @@ class Portal {
elements: this.collab.excalidrawAPI.getSceneElementsIncludingDeleted(), elements: this.collab.excalidrawAPI.getSceneElementsIncludingDeleted(),
files: this.collab.excalidrawAPI.getFiles(), files: this.collab.excalidrawAPI.getFiles(),
}); });
} catch (error: any) { } catch (error) {
if (error.name !== "AbortError") { this.collab.excalidrawAPI.updateScene({
this.collab.excalidrawAPI.updateScene({ appState: {
appState: { errorMessage: error.message,
errorMessage: error.message, },
}, });
});
}
} }
this.collab.excalidrawAPI.updateScene({ this.collab.excalidrawAPI.updateScene({
@@ -111,7 +110,11 @@ class Portal {
// this will signal collaborators to pull image data from server // this will signal collaborators to pull image data from server
// (using mutation instead of newElementWith otherwise it'd break // (using mutation instead of newElementWith otherwise it'd break
// in-progress dragging) // in-progress dragging)
return newElementWith(element, { status: "saved" }); return mutateElement(
element,
{ status: "saved" },
/* informMutation */ false,
);
} }
return element; return element;
}), }),
@@ -208,8 +211,8 @@ class Portal {
socketId: this.socket.id, socketId: this.socket.id,
pointer: payload.pointer, pointer: payload.pointer,
button: payload.button || "up", button: payload.button || "up",
selectedElementIds: selectedElementIds: this.collab.excalidrawAPI.getAppState()
this.collab.excalidrawAPI.getAppState().selectedElementIds, .selectedElementIds,
username: this.collab.state.username, username: this.collab.state.username,
}, },
}; };
+6 -1
View File
@@ -6,7 +6,7 @@
margin: 1.5em 0; margin: 1.5em 0;
} }
input.RoomDialog-link { .RoomDialog-link {
color: var(--text-primary-color); color: var(--text-primary-color);
min-width: 0; min-width: 0;
flex: 1 1 auto; flex: 1 1 auto;
@@ -14,6 +14,8 @@
display: inline-block; display: inline-block;
cursor: pointer; cursor: pointer;
border: none; border: none;
height: 2.5rem;
line-height: 2.5rem;
padding: 0 0.5rem; padding: 0 0.5rem;
white-space: nowrap; white-space: nowrap;
border-radius: var(--space-factor); border-radius: var(--space-factor);
@@ -53,7 +55,10 @@
margin-top: 0.5em; margin-top: 0.5em;
margin-inline-start: 0; margin-inline-start: 0;
} }
height: 2.5rem;
font-size: 1em; font-size: 1em;
line-height: 1.5;
padding: 0 0.5rem;
} }
.RoomDialog-sessionStartButtonContainer { .RoomDialog-sessionStartButtonContainer {
+2 -4
View File
@@ -53,7 +53,7 @@ const RoomDialog = ({
const copyRoomLink = async () => { const copyRoomLink = async () => {
try { try {
await copyTextToSystemClipboard(activeRoomLink); await copyTextToSystemClipboard(activeRoomLink);
} catch (error: any) { } catch (error) {
setErrorMessage(error.message); setErrorMessage(error.message);
} }
if (roomLinkInput.current) { if (roomLinkInput.current) {
@@ -68,7 +68,7 @@ const RoomDialog = ({
text: t("roomDialog.shareTitle"), text: t("roomDialog.shareTitle"),
url: activeRoomLink, url: activeRoomLink,
}); });
} catch (error: any) { } catch (error) {
// Just ignore. // Just ignore.
} }
}; };
@@ -124,7 +124,6 @@ const RoomDialog = ({
/> />
</Stack.Row> </Stack.Row>
<input <input
type="text"
value={activeRoomLink} value={activeRoomLink}
readOnly={true} readOnly={true}
className="RoomDialog-link" className="RoomDialog-link"
@@ -137,7 +136,6 @@ const RoomDialog = ({
{t("labels.yourName")} {t("labels.yourName")}
</label> </label>
<input <input
type="text"
id="username" id="username"
value={username || ""} value={username || ""}
className="RoomDialog-username TextInput" className="RoomDialog-username TextInput"
+3 -2
View File
@@ -54,8 +54,9 @@ export const reconcileElements = (
remoteElements: readonly BroadcastedExcalidrawElement[], remoteElements: readonly BroadcastedExcalidrawElement[],
localAppState: AppState, localAppState: AppState,
): ReconciledElements => { ): ReconciledElements => {
const localElementsData = const localElementsData = getElementsMapWithIndex<ExcalidrawElement>(
getElementsMapWithIndex<ExcalidrawElement>(localElements); localElements,
);
const reconciledElements: ExcalidrawElement[] = localElements.slice(); const reconciledElements: ExcalidrawElement[] = localElements.slice();
@@ -93,11 +93,9 @@ export const ExportToExcalidrawPlus: React.FC<{
onClick={async () => { onClick={async () => {
try { try {
await exportToExcalidrawPlus(elements, appState, files); await exportToExcalidrawPlus(elements, appState, files);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
if (error.name !== "AbortError") { onError(new Error(t("exportDialog.excalidrawplus_exportError")));
onError(new Error(t("exportDialog.excalidrawplus_exportError")));
}
} }
}} }}
/> />
@@ -14,8 +14,9 @@ export const GitHubCorner = React.memo(
className="rtl-mirror" className="rtl-mirror"
style={{ style={{
marginTop: "calc(var(--space-factor) * -1)", marginTop: "calc(var(--space-factor) * -1)",
[dir === "rtl" ? "marginLeft" : "marginRight"]: [dir === "rtl"
"calc(var(--space-factor) * -1)", ? "marginLeft"
: "marginRight"]: "calc(var(--space-factor) * -1)",
}} }}
> >
<a <a
+19 -7
View File
@@ -1,5 +1,5 @@
import { compressData } from "../../data/encode"; import { compressData } from "../../data/encode";
import { newElementWith } from "../../element/mutateElement"; import { mutateElement } from "../../element/mutateElement";
import { isInitializedImageElement } from "../../element/typeChecks"; import { isInitializedImageElement } from "../../element/typeChecks";
import { import {
ExcalidrawElement, ExcalidrawElement,
@@ -31,11 +31,15 @@ export class FileManager {
getFiles, getFiles,
saveFiles, saveFiles,
}: { }: {
getFiles: (fileIds: FileId[]) => Promise<{ getFiles: (
fileIds: FileId[],
) => Promise<{
loadedFiles: BinaryFileData[]; loadedFiles: BinaryFileData[];
erroredFiles: Map<FileId, true>; erroredFiles: Map<FileId, true>;
}>; }>;
saveFiles: (data: { addedFiles: Map<FileId, BinaryFileData> }) => Promise<{ saveFiles: (data: {
addedFiles: Map<FileId, BinaryFileData>;
}) => Promise<{
savedFiles: Map<FileId, true>; savedFiles: Map<FileId, true>;
erroredFiles: Map<FileId, true>; erroredFiles: Map<FileId, true>;
}>; }>;
@@ -199,7 +203,11 @@ export const encodeFilesForUpload = async ({
}); });
if (buffer.byteLength > maxBytes) { if (buffer.byteLength > maxBytes) {
throw new Error(t("errors.fileTooBig")); throw new Error(
t("errors.fileTooBig", {
maxSize: `${Math.trunc(maxBytes / 1024 / 1024)}MB`,
}),
);
} }
processedFiles.push({ processedFiles.push({
@@ -227,9 +235,13 @@ export const updateStaleImageStatuses = (params: {
isInitializedImageElement(element) && isInitializedImageElement(element) &&
params.erroredFiles.has(element.fileId) params.erroredFiles.has(element.fileId)
) { ) {
return newElementWith(element, { return mutateElement(
status: "error", element,
}); {
status: "error",
},
false,
);
} }
return element; return element;
}), }),
+28 -11
View File
@@ -5,7 +5,7 @@ import { restoreElements } from "../../data/restore";
import { BinaryFileData, BinaryFileMetadata, DataURL } from "../../types"; import { BinaryFileData, BinaryFileMetadata, DataURL } from "../../types";
import { FILE_CACHE_MAX_AGE_SEC } from "../app_constants"; import { FILE_CACHE_MAX_AGE_SEC } from "../app_constants";
import { decompressData } from "../../data/encode"; import { decompressData } from "../../data/encode";
import { encryptData, decryptData } from "../../data/encryption"; import { getImportedKey, createIV } from "../../data/encryption";
import { MIME_TYPES } from "../../constants"; import { MIME_TYPES } from "../../constants";
// private // private
@@ -13,8 +13,9 @@ import { MIME_TYPES } from "../../constants";
const FIREBASE_CONFIG = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG); const FIREBASE_CONFIG = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG);
let firebasePromise: Promise<typeof import("firebase/app").default> | null = let firebasePromise: Promise<
null; typeof import("firebase/app").default
> | null = null;
let firestorePromise: Promise<any> | null | true = null; let firestorePromise: Promise<any> | null | true = null;
let firebaseStoragePromise: Promise<any> | null | true = null; let firebaseStoragePromise: Promise<any> | null | true = null;
@@ -28,7 +29,7 @@ const _loadFirebase = async () => {
if (!isFirebaseInitialized) { if (!isFirebaseInitialized) {
try { try {
firebase.initializeApp(FIREBASE_CONFIG); firebase.initializeApp(FIREBASE_CONFIG);
} catch (error: any) { } catch (error) {
// trying initialize again throws. Usually this is harmless, and happens // trying initialize again throws. Usually this is harmless, and happens
// mainly in dev (HMR) // mainly in dev (HMR)
if (error.code === "app/duplicate-app") { if (error.code === "app/duplicate-app") {
@@ -92,11 +93,20 @@ const encryptElements = async (
key: string, key: string,
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
): Promise<{ ciphertext: ArrayBuffer; iv: Uint8Array }> => { ): Promise<{ ciphertext: ArrayBuffer; iv: Uint8Array }> => {
const importedKey = await getImportedKey(key, "encrypt");
const iv = createIV();
const json = JSON.stringify(elements); const json = JSON.stringify(elements);
const encoded = new TextEncoder().encode(json); const encoded = new TextEncoder().encode(json);
const { encryptedBuffer, iv } = await encryptData(key, encoded); const ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
},
importedKey,
encoded,
);
return { ciphertext: encryptedBuffer, iv }; return { ciphertext, iv };
}; };
const decryptElements = async ( const decryptElements = async (
@@ -104,7 +114,16 @@ const decryptElements = async (
iv: Uint8Array, iv: Uint8Array,
ciphertext: ArrayBuffer | Uint8Array, ciphertext: ArrayBuffer | Uint8Array,
): Promise<readonly ExcalidrawElement[]> => { ): Promise<readonly ExcalidrawElement[]> => {
const decrypted = await decryptData(iv, ciphertext, key); const importedKey = await getImportedKey(key, "decrypt");
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv,
},
importedKey,
ciphertext,
);
const decodedData = new TextDecoder("utf-8").decode( const decodedData = new TextDecoder("utf-8").decode(
new Uint8Array(decrypted), new Uint8Array(decrypted),
); );
@@ -154,7 +173,7 @@ export const saveFilesToFirebase = async ({
}, },
); );
savedFiles.set(id, true); savedFiles.set(id, true);
} catch (error: any) { } catch (error) {
erroredFiles.set(id, true); erroredFiles.set(id, true);
} }
}), }),
@@ -275,10 +294,8 @@ export const loadFilesFromFirebase = async (
dataURL, dataURL,
created: metadata?.created || Date.now(), created: metadata?.created || Date.now(),
}); });
} else {
erroredFiles.set(id, true);
} }
} catch (error: any) { } catch (error) {
erroredFiles.set(id, true); erroredFiles.set(id, true);
console.error(error); console.error(error);
} }
+128 -38
View File
@@ -1,7 +1,7 @@
import { import {
decryptData, createIV,
encryptData,
generateEncryptionKey, generateEncryptionKey,
getImportedKey,
IV_LENGTH_BYTES, IV_LENGTH_BYTES,
} from "../../data/encryption"; } from "../../data/encryption";
import { serializeAsJSON } from "../../data/json"; import { serializeAsJSON } from "../../data/json";
@@ -16,18 +16,20 @@ import {
BinaryFiles, BinaryFiles,
UserIdleState, UserIdleState,
} from "../../types"; } from "../../types";
import { bytesToHexString } from "../../utils"; import { FILE_UPLOAD_MAX_BYTES } from "../app_constants";
import { FILE_UPLOAD_MAX_BYTES, ROOM_ID_BYTES } from "../app_constants";
import { encodeFilesForUpload } from "./FileManager"; import { encodeFilesForUpload } from "./FileManager";
import { saveFilesToFirebase } from "./firebase"; import { saveFilesToFirebase } from "./firebase";
const byteToHex = (byte: number): string => `0${byte.toString(16)}`.slice(-2);
const BACKEND_GET = process.env.REACT_APP_BACKEND_V1_GET_URL;
const BACKEND_V2_GET = process.env.REACT_APP_BACKEND_V2_GET_URL; const BACKEND_V2_GET = process.env.REACT_APP_BACKEND_V2_GET_URL;
const BACKEND_V2_POST = process.env.REACT_APP_BACKEND_V2_POST_URL; const BACKEND_V2_POST = process.env.REACT_APP_BACKEND_V2_POST_URL;
const generateRoomId = async () => { const generateRandomID = async () => {
const buffer = new Uint8Array(ROOM_ID_BYTES); const arr = new Uint8Array(10);
window.crypto.getRandomValues(buffer); window.crypto.getRandomValues(arr);
return bytesToHexString(buffer); return Array.from(arr, byteToHex).join("");
}; };
export const SOCKET_SERVER = process.env.REACT_APP_SOCKET_SERVER_URL; export const SOCKET_SERVER = process.env.REACT_APP_SOCKET_SERVER_URL;
@@ -76,10 +78,57 @@ export type SocketUpdateDataIncoming =
type: "INVALID_RESPONSE"; type: "INVALID_RESPONSE";
}; };
export type SocketUpdateData = export type SocketUpdateData = SocketUpdateDataSource[keyof SocketUpdateDataSource] & {
SocketUpdateDataSource[keyof SocketUpdateDataSource] & { _brand: "socketUpdateData";
_brand: "socketUpdateData"; };
export const encryptAESGEM = async (
data: Uint8Array,
key: string,
): Promise<EncryptedData> => {
const importedKey = await getImportedKey(key, "encrypt");
const iv = createIV();
return {
data: await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
},
importedKey,
data,
),
iv,
}; };
};
export const decryptAESGEM = async (
data: ArrayBuffer,
key: string,
iv: Uint8Array,
): Promise<SocketUpdateDataIncoming> => {
try {
const importedKey = await getImportedKey(key, "decrypt");
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv,
},
importedKey,
data,
);
const decodedData = new TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
return JSON.parse(decodedData);
} catch (error) {
window.alert(t("alerts.decryptFailed"));
console.error(error);
}
return {
type: "INVALID_RESPONSE",
};
};
export const getCollaborationLinkData = (link: string) => { export const getCollaborationLinkData = (link: string) => {
const hash = new URL(link).hash; const hash = new URL(link).hash;
@@ -92,7 +141,7 @@ export const getCollaborationLinkData = (link: string) => {
}; };
export const generateCollaborationLinkData = async () => { export const generateCollaborationLinkData = async () => {
const roomId = await generateRoomId(); const roomId = await generateRandomID();
const roomKey = await generateEncryptionKey(); const roomKey = await generateEncryptionKey();
if (!roomKey) { if (!roomKey) {
@@ -109,42 +158,66 @@ export const getCollaborationLink = (data: {
return `${window.location.origin}${window.location.pathname}#room=${data.roomId},${data.roomKey}`; return `${window.location.origin}${window.location.pathname}#room=${data.roomId},${data.roomKey}`;
}; };
const importFromBackend = async ( export const decryptImported = async (
id: string, iv: ArrayBuffer | Uint8Array,
encrypted: ArrayBuffer,
privateKey: string, privateKey: string,
): Promise<ArrayBuffer> => {
const key = await getImportedKey(privateKey, "decrypt");
return window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv,
},
key,
encrypted,
);
};
const importFromBackend = async (
id: string | null,
privateKey?: string | null,
): Promise<ImportedDataState> => { ): Promise<ImportedDataState> => {
try { try {
const response = await fetch(`${BACKEND_V2_GET}${id}`); const response = await fetch(
privateKey ? `${BACKEND_V2_GET}${id}` : `${BACKEND_GET}${id}.json`,
);
if (!response.ok) { if (!response.ok) {
window.alert(t("alerts.importBackendFailed")); window.alert(t("alerts.importBackendFailed"));
return {}; return {};
} }
const buffer = await response.arrayBuffer(); let data: ImportedDataState;
if (privateKey) {
const buffer = await response.arrayBuffer();
let decrypted: ArrayBuffer; let decrypted: ArrayBuffer;
try { try {
// Buffer should contain both the IV (fixed length) and encrypted data // Buffer should contain both the IV (fixed length) and encrypted data
const iv = buffer.slice(0, IV_LENGTH_BYTES); const iv = buffer.slice(0, IV_LENGTH_BYTES);
const encrypted = buffer.slice(IV_LENGTH_BYTES, buffer.byteLength); const encrypted = buffer.slice(IV_LENGTH_BYTES, buffer.byteLength);
decrypted = await decryptData(new Uint8Array(iv), encrypted, privateKey); decrypted = await decryptImported(iv, encrypted, privateKey);
} catch (error: any) { } catch (error) {
// Fixed IV (old format, backward compatibility) // Fixed IV (old format, backward compatibility)
const fixedIv = new Uint8Array(IV_LENGTH_BYTES); const fixedIv = new Uint8Array(IV_LENGTH_BYTES);
decrypted = await decryptData(fixedIv, buffer, privateKey); decrypted = await decryptImported(fixedIv, buffer, privateKey);
}
// We need to convert the decrypted array buffer to a string
const string = new window.TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
data = JSON.parse(string);
} else {
// Legacy format
data = await response.json();
} }
// We need to convert the decrypted array buffer to a string
const string = new window.TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
const data: ImportedDataState = JSON.parse(string);
return { return {
elements: data.elements || null, elements: data.elements || null,
appState: data.appState || null, appState: data.appState || null,
}; };
} catch (error: any) { } catch (error) {
window.alert(t("alerts.importBackendFailed")); window.alert(t("alerts.importBackendFailed"));
console.error(error); console.error(error);
return {}; return {};
@@ -160,7 +233,7 @@ export const loadScene = async (
localDataState: ImportedDataState | undefined | null, localDataState: ImportedDataState | undefined | null,
) => { ) => {
let data; let data;
if (id != null && privateKey != null) { if (id != null) {
// the private key is used to decrypt the content from the server, take // the private key is used to decrypt the content from the server, take
// extra care not to leak it // extra care not to leak it
data = restore( data = restore(
@@ -191,12 +264,29 @@ export const exportToBackend = async (
const json = serializeAsJSON(elements, appState, files, "database"); const json = serializeAsJSON(elements, appState, files, "database");
const encoded = new TextEncoder().encode(json); const encoded = new TextEncoder().encode(json);
const cryptoKey = await generateEncryptionKey("cryptoKey"); const cryptoKey = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 128,
},
true, // extractable
["encrypt", "decrypt"],
);
const { encryptedBuffer, iv } = await encryptData(cryptoKey, encoded); const iv = createIV();
// We use symmetric encryption. AES-GCM is the recommended algorithm and
// includes checks that the ciphertext has not been modified by an attacker.
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
},
cryptoKey,
encoded,
);
// Concatenate IV with encrypted data (IV does not have to be secret). // Concatenate IV with encrypted data (IV does not have to be secret).
const payloadBlob = new Blob([iv.buffer, encryptedBuffer]); const payloadBlob = new Blob([iv.buffer, encrypted]);
const payload = await new Response(payloadBlob).arrayBuffer(); const payload = await new Response(payloadBlob).arrayBuffer();
// We use jwk encoding to be able to extract just the base64 encoded key. // We use jwk encoding to be able to extract just the base64 encoded key.
@@ -242,7 +332,7 @@ export const exportToBackend = async (
} else { } else {
window.alert(t("alerts.couldNotCreateShareableLink")); window.alert(t("alerts.couldNotCreateShareableLink"));
} }
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
window.alert(t("alerts.couldNotCreateShareableLink")); window.alert(t("alerts.couldNotCreateShareableLink"));
} }
+8 -8
View File
@@ -20,7 +20,7 @@ export const saveUsernameToLocalStorage = (username: string) => {
STORAGE_KEYS.LOCAL_STORAGE_COLLAB, STORAGE_KEYS.LOCAL_STORAGE_COLLAB,
JSON.stringify({ username }), JSON.stringify({ username }),
); );
} catch (error: any) { } catch (error) {
// Unable to access window.localStorage // Unable to access window.localStorage
console.error(error); console.error(error);
} }
@@ -32,7 +32,7 @@ export const importUsernameFromLocalStorage = (): string | null => {
if (data) { if (data) {
return JSON.parse(data).username; return JSON.parse(data).username;
} }
} catch (error: any) { } catch (error) {
// Unable to access localStorage // Unable to access localStorage
console.error(error); console.error(error);
} }
@@ -53,7 +53,7 @@ export const saveToLocalStorage = (
STORAGE_KEYS.LOCAL_STORAGE_APP_STATE, STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
JSON.stringify(clearAppStateForLocalStorage(appState)), JSON.stringify(clearAppStateForLocalStorage(appState)),
); );
} catch (error: any) { } catch (error) {
// Unable to access window.localStorage // Unable to access window.localStorage
console.error(error); console.error(error);
} }
@@ -66,7 +66,7 @@ export const importFromLocalStorage = () => {
try { try {
savedElements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS); savedElements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS);
savedState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE); savedState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE);
} catch (error: any) { } catch (error) {
// Unable to access localStorage // Unable to access localStorage
console.error(error); console.error(error);
} }
@@ -75,7 +75,7 @@ export const importFromLocalStorage = () => {
if (savedElements) { if (savedElements) {
try { try {
elements = clearElementsForLocalStorage(JSON.parse(savedElements)); elements = clearElementsForLocalStorage(JSON.parse(savedElements));
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
// Do nothing because elements array is already empty // Do nothing because elements array is already empty
} }
@@ -90,7 +90,7 @@ export const importFromLocalStorage = () => {
JSON.parse(savedState) as Partial<AppState>, JSON.parse(savedState) as Partial<AppState>,
), ),
}; };
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
// Do nothing because appState is already null // Do nothing because appState is already null
} }
@@ -103,7 +103,7 @@ export const getElementsStorageSize = () => {
const elements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS); const elements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS);
const elementsSize = elements?.length || 0; const elementsSize = elements?.length || 0;
return elementsSize; return elementsSize;
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
return 0; return 0;
} }
@@ -122,7 +122,7 @@ export const getTotalStorageSize = () => {
const librarySize = library?.length || 0; const librarySize = library?.length || 0;
return appStateSize + collabSize + librarySize + getElementsStorageSize(); return appStateSize + collabSize + librarySize + getElementsStorageSize();
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
return 0; return 0;
} }
+22 -25
View File
@@ -64,7 +64,7 @@ import { ExportToExcalidrawPlus } from "./components/ExportToExcalidrawPlus";
import { getMany, set, del, keys, createStore } from "idb-keyval"; import { getMany, set, del, keys, createStore } from "idb-keyval";
import { FileManager, updateStaleImageStatuses } from "./data/FileManager"; import { FileManager, updateStaleImageStatuses } from "./data/FileManager";
import { newElementWith } from "../element/mutateElement"; import { mutateElement } from "../element/mutateElement";
import { isInitializedImageElement } from "../element/typeChecks"; import { isInitializedImageElement } from "../element/typeChecks";
import { loadFilesFromFirebase } from "./data/firebase"; import { loadFilesFromFirebase } from "./data/firebase";
@@ -109,7 +109,7 @@ const localFileStorage = new FileManager({
try { try {
await set(id, fileData, filesStore); await set(id, fileData, filesStore);
savedFiles.set(id, true); savedFiles.set(id, true);
} catch (error: any) { } catch (error) {
console.error(error); console.error(error);
erroredFiles.set(id, true); erroredFiles.set(id, true);
} }
@@ -163,7 +163,7 @@ const initializeScene = async (opts: {
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
const id = searchParams.get("id"); const id = searchParams.get("id");
const jsonBackendMatch = window.location.hash.match( const jsonBackendMatch = window.location.hash.match(
/^#json=([a-zA-Z0-9_-]+),([a-zA-Z0-9_-]+)$/, /^#json=([0-9]+),([a-zA-Z0-9_-]+)$/,
); );
const externalUrlMatch = window.location.hash.match(/^#url=(.*)$/); const externalUrlMatch = window.location.hash.match(/^#url=(.*)$/);
@@ -184,7 +184,10 @@ const initializeScene = async (opts: {
// otherwise, prompt whether user wants to override current scene // otherwise, prompt whether user wants to override current scene
window.confirm(t("alerts.loadSceneOverridePrompt")) window.confirm(t("alerts.loadSceneOverridePrompt"))
) { ) {
if (jsonBackendMatch) { // Backwards compatibility with legacy url format
if (id) {
scene = await loadScene(id, null, localDataState);
} else if (jsonBackendMatch) {
scene = await loadScene( scene = await loadScene(
jsonBackendMatch[1], jsonBackendMatch[1],
jsonBackendMatch[2], jsonBackendMatch[2],
@@ -225,7 +228,7 @@ const initializeScene = async (opts: {
) { ) {
return { scene: data, isExternalScene }; return { scene: data, isExternalScene };
} }
} catch (error: any) { } catch (error) {
return { return {
scene: { scene: {
appState: { appState: {
@@ -273,10 +276,7 @@ const PlusLinkJSX = (
const ExcalidrawWrapper = () => { const ExcalidrawWrapper = () => {
const [errorMessage, setErrorMessage] = useState(""); const [errorMessage, setErrorMessage] = useState("");
let currentLangCode = languageDetector.detect() || defaultLang.code; const currentLangCode = languageDetector.detect() || defaultLang.code;
if (Array.isArray(currentLangCode)) {
currentLangCode = currentLangCode[0];
}
const [langCode, setLangCode] = useState(currentLangCode); const [langCode, setLangCode] = useState(currentLangCode);
// initial state // initial state
@@ -286,8 +286,7 @@ const ExcalidrawWrapper = () => {
promise: ResolvablePromise<ImportedDataState | null>; promise: ResolvablePromise<ImportedDataState | null>;
}>({ promise: null! }); }>({ promise: null! });
if (!initialStatePromiseRef.current.promise) { if (!initialStatePromiseRef.current.promise) {
initialStatePromiseRef.current.promise = initialStatePromiseRef.current.promise = resolvablePromise<ImportedDataState | null>();
resolvablePromise<ImportedDataState | null>();
} }
useEffect(() => { useEffect(() => {
@@ -297,8 +296,10 @@ const ExcalidrawWrapper = () => {
}, VERSION_TIMEOUT); }, VERSION_TIMEOUT);
}, []); }, []);
const [excalidrawAPI, excalidrawRefCallback] = const [
useCallbackRefState<ExcalidrawImperativeAPI>(); excalidrawAPI,
excalidrawRefCallback,
] = useCallbackRefState<ExcalidrawImperativeAPI>();
const collabAPI = useContext(CollabContext)?.api; const collabAPI = useContext(CollabContext)?.api;
@@ -377,8 +378,8 @@ const ExcalidrawWrapper = () => {
JSON.parse( JSON.parse(
localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY) as string, localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY) as string,
) || []; ) || [];
} catch (error: any) { } catch (e) {
console.error(error); console.error(e);
} }
}; };
@@ -459,17 +460,16 @@ const ExcalidrawWrapper = () => {
if (excalidrawAPI) { if (excalidrawAPI) {
let didChange = false; let didChange = false;
let pendingImageElement = appState.pendingImageElement;
const elements = excalidrawAPI const elements = excalidrawAPI
.getSceneElementsIncludingDeleted() .getSceneElementsIncludingDeleted()
.map((element) => { .map((element) => {
if (localFileStorage.shouldUpdateImageElementStatus(element)) { if (localFileStorage.shouldUpdateImageElementStatus(element)) {
didChange = true; didChange = true;
const newEl = newElementWith(element, { status: "saved" }); return mutateElement(
if (pendingImageElement === element) { element,
pendingImageElement = newEl; { status: "saved" },
} /* informMutation */ false,
return newEl; );
} }
return element; return element;
}); });
@@ -477,9 +477,6 @@ const ExcalidrawWrapper = () => {
if (didChange) { if (didChange) {
excalidrawAPI.updateScene({ excalidrawAPI.updateScene({
elements, elements,
appState: {
pendingImageElement,
},
}); });
} }
} }
@@ -508,7 +505,7 @@ const ExcalidrawWrapper = () => {
}, },
files, files,
); );
} catch (error: any) { } catch (error) {
if (error.name !== "AbortError") { if (error.name !== "AbortError") {
const { width, height } = canvas; const { width, height } = canvas;
console.error(error, { width, height }); console.error(error, { width, height });
+1 -1
View File
@@ -67,7 +67,7 @@ export const nvector = (value: number = 0, index: number = 0): NVector => {
if (value !== 0) { if (value !== 0) {
result[index] = value; result[index] = value;
} }
return result as unknown as NVector; return (result as unknown) as NVector;
}; };
const STRING_EPSILON = 0.000001; const STRING_EPSILON = 0.000001;
+1 -1
View File
@@ -36,7 +36,7 @@ export const orthogonalThrough = (against: Point, intersection: Point): Line =>
export const parallel = (line: Line, distance: number): Line => { export const parallel = (line: Line, distance: number): Line => {
const result = line.slice(); const result = line.slice();
result[1] -= distance; result[1] -= distance;
return result as unknown as Line; return (result as unknown) as Line;
}; };
export const parallelThrough = (line: Line, point: Point): Line => export const parallelThrough = (line: Line, point: Point): Line =>
+10 -17
View File
@@ -1,5 +1,3 @@
// import type {PngChunk} from "./types";
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Document { interface Document {
fonts?: { fonts?: {
@@ -21,6 +19,7 @@ interface Window {
// https://github.com/facebook/create-react-app/blob/ddcb7d5/packages/react-scripts/lib/react-app.d.ts // https://github.com/facebook/create-react-app/blob/ddcb7d5/packages/react-scripts/lib/react-app.d.ts
declare namespace NodeJS { declare namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
readonly REACT_APP_BACKEND_V1_GET_URL: string;
readonly REACT_APP_BACKEND_V2_GET_URL: string; readonly REACT_APP_BACKEND_V2_GET_URL: string;
readonly REACT_APP_BACKEND_V2_POST_URL: string; readonly REACT_APP_BACKEND_V2_POST_URL: string;
readonly REACT_APP_SOCKET_SERVER_URL: string; readonly REACT_APP_SOCKET_SERVER_URL: string;
@@ -50,12 +49,13 @@ type MarkRequired<T, RK extends keyof T> = Exclude<T, RK> &
type MarkNonNullable<T, K extends keyof T> = { type MarkNonNullable<T, K extends keyof T> = {
[P in K]-?: P extends K ? NonNullable<T[P]> : T[P]; [P in K]-?: P extends K ? NonNullable<T[P]> : T[P];
} & { [P in keyof T]: T[P] }; } &
{ [P in keyof T]: T[P] };
type NonOptional<T> = Exclude<T, undefined>;
// PNG encoding/decoding // PNG encoding/decoding
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
type TEXtChunk = { name: "tEXt"; data: Uint8Array };
declare module "png-chunk-text" { declare module "png-chunk-text" {
function encode( function encode(
name: string, name: string,
@@ -64,11 +64,11 @@ declare module "png-chunk-text" {
function decode(data: Uint8Array): { keyword: string; text: string }; function decode(data: Uint8Array): { keyword: string; text: string };
} }
declare module "png-chunks-encode" { declare module "png-chunks-encode" {
function encode(chunks: import("./types").PngChunk[]): Uint8Array; function encode(chunks: TEXtChunk[]): Uint8Array;
export = encode; export = encode;
} }
declare module "png-chunks-extract" { declare module "png-chunks-extract" {
function extract(buffer: Uint8Array): import("./types").PngChunk[]; function extract(buffer: Uint8Array): TEXtChunk[];
export = extract; export = extract;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@@ -102,26 +102,19 @@ declare module "*.scss";
// (due to TS structural typing) // (due to TS structural typing)
// https://github.com/microsoft/TypeScript/issues/31311#issuecomment-490690695 // https://github.com/microsoft/TypeScript/issues/31311#issuecomment-490690695
interface ArrayBuffer { interface ArrayBuffer {
_brand?: "ArrayBuffer"; private _brand?: "ArrayBuffer";
} }
interface Uint8Array { interface Uint8Array {
_brand?: "Uint8Array"; private _brand?: "Uint8Array";
} }
// --------------------------------------------------------------------------— // --------------------------------------------------------------------------—
// https://github.com/nodeca/image-blob-reduce/issues/23#issuecomment-783271848 // https://github.com/nodeca/image-blob-reduce/issues/23#issuecomment-783271848
declare module "image-blob-reduce" { declare module "image-blob-reduce" {
import { PicaResizeOptions, Pica } from "pica"; import { PicaResizeOptions } from "pica";
namespace ImageBlobReduce { namespace ImageBlobReduce {
interface ImageBlobReduce { interface ImageBlobReduce {
toBlob(file: File, options: ImageBlobReduceOptions): Promise<Blob>; toBlob(file: File, options: ImageBlobReduceOptions): Promise<Blob>;
_create_blob(
this: { pica: Pica },
env: {
out_canvas: HTMLCanvasElement;
out_blob: Blob;
},
): Promise<any>;
} }
interface ImageBlobReduceStatic { interface ImageBlobReduceStatic {
+2 -5
View File
@@ -105,10 +105,7 @@ const findPartsForData = (data: any, parts: string[]) => {
return data; return data;
}; };
export const t = ( export const t = (path: string, replacement?: { [key: string]: string }) => {
path: string,
replacement?: { [key: string]: string | number },
) => {
if (currentLang.code.startsWith(TEST_LANG_CODE)) { if (currentLang.code.startsWith(TEST_LANG_CODE)) {
const name = replacement const name = replacement
? `${path}(${JSON.stringify(replacement).slice(1, -1)})` ? `${path}(${JSON.stringify(replacement).slice(1, -1)})`
@@ -126,7 +123,7 @@ export const t = (
if (replacement) { if (replacement) {
for (const key in replacement) { for (const key in replacement) {
translation = translation.replace(`{{${key}}}`, String(replacement[key])); translation = translation.replace(`{{${key}}}`, replacement[key]);
} }
} }
return translation; return translation;

Some files were not shown because too many files have changed in this diff Show More