Compare commits

..

15 Commits

Author SHA1 Message Date
Aakansha Doshi
ef8bcbe1f8 cache the visible point indexes 2022-09-16 16:57:41 +05:30
Aakansha Doshi
02d5cc4174 Merge remote-tracking branch 'origin/master' into aakansha-hide-close-linear-element-points 2022-09-16 16:53:50 +05:30
Aakansha Doshi
2f4d051ea1 fix specs 2022-09-01 18:26:43 +05:30
Aakansha Doshi
0b0846bd8e fix index 2022-09-01 18:03:49 +05:30
Aakansha Doshi
330b3a0530 hide n-1 point if distance is less than threshold 2022-09-01 17:51:50 +05:30
Aakansha Doshi
cd195374bc don't allow dragging hidden points 2022-09-01 17:30:31 +05:30
Aakansha Doshi
8971d06655 Merge remote-tracking branch 'origin/master' into aakansha-hide-close-linear-element-points 2022-09-01 16:18:52 +05:30
Aakansha Doshi
1e4e37b87f empty 2022-08-26 21:16:51 +05:30
Aakansha Doshi
189a557ed6 update visible point indexes when zooming 2022-08-26 20:49:50 +05:30
Aakansha Doshi
bff2f9178d update visiblePointIndexes when points added 2022-08-26 18:53:15 +05:30
Aakansha Doshi
9b5715623a don't update points unitil deselected 2022-08-26 14:14:01 +05:30
Aakansha Doshi
3487f0ab26 Always show extreme points 2022-08-24 16:48:57 +05:30
Aakansha Doshi
76910828c2 check for 2 pointer arrows 2022-08-24 16:04:17 +05:30
Aakansha Doshi
fde521ef4d fix 2022-08-24 15:58:43 +05:30
Aakansha Doshi
bcb45f7cf6 fix: hide points outside linear element editor when close enough 2022-08-24 15:49:04 +05:30
296 changed files with 15249 additions and 24579 deletions

View File

@@ -1,6 +1,5 @@
* *
!.env.development !.env
!.env.production
!.eslintrc.json !.eslintrc.json
!.npmrc !.npmrc
!.prettierrc !.prettierrc

View File

@@ -20,5 +20,3 @@ REACT_APP_DEV_ENABLE_SW=
# whether to disable live reload / HMR. Usuaully what you want to do when # whether to disable live reload / HMR. Usuaully what you want to do when
# debugging Service Workers. # debugging Service Workers.
REACT_APP_DEV_DISABLE_LIVE_RELOAD= REACT_APP_DEV_DISABLE_LIVE_RELOAD=
FAST_REFRESH=false

View File

@@ -2,7 +2,7 @@ name: Auto release excalidraw next
on: on:
push: push:
branches: branches:
- release - master
jobs: jobs:
Auto-release-excalidraw-next: Auto-release-excalidraw-next:

View File

@@ -3,7 +3,7 @@ name: Build Docker image
on: on:
push: push:
branches: branches:
- release - master
jobs: jobs:
build-docker: build-docker:

View File

@@ -3,7 +3,7 @@ name: Cancel previous runs
on: on:
push: push:
branches: branches:
- release - master
pull_request: pull_request:
jobs: jobs:

View File

@@ -3,7 +3,7 @@ name: Publish Docker
on: on:
push: push:
branches: branches:
- release - master
jobs: jobs:
publish-docker: publish-docker:

View File

@@ -3,7 +3,7 @@ name: New Sentry production release
on: on:
push: push:
branches: branches:
- release - master
jobs: jobs:
sentry: sentry:

1
.gitignore vendored
View File

@@ -25,3 +25,4 @@ src/packages/excalidraw/types
src/packages/excalidraw/example/public/bundle.js src/packages/excalidraw/example/public/bundle.js
src/packages/excalidraw/example/public/excalidraw-assets-dev src/packages/excalidraw/example/public/excalidraw-assets-dev
src/packages/excalidraw/example/public/excalidraw.development.js src/packages/excalidraw/example/public/excalidraw.development.js

View File

@@ -4755,9 +4755,9 @@ loader-runner@^4.2.0:
integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==
loader-utils@^2.0.0: loader-utils@^2.0.0:
version "2.0.4" version "2.0.2"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.2.tgz#d6e3b4fb81870721ae4e0868ab11dd638368c129"
integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== integrity sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==
dependencies: dependencies:
big.js "^5.2.2" big.js "^5.2.2"
emojis-list "^3.0.0" emojis-list "^3.0.0"

View File

@@ -31,7 +31,6 @@
"@types/socket.io-client": "1.4.36", "@types/socket.io-client": "1.4.36",
"browser-fs-access": "0.29.1", "browser-fs-access": "0.29.1",
"clsx": "1.1.1", "clsx": "1.1.1",
"cross-env": "7.0.3",
"fake-indexeddb": "3.1.7", "fake-indexeddb": "3.1.7",
"firebase": "8.3.3", "firebase": "8.3.3",
"i18next-browser-languagedetector": "6.1.4", "i18next-browser-languagedetector": "6.1.4",
@@ -42,7 +41,7 @@
"nanoid": "3.3.3", "nanoid": "3.3.3",
"open-color": "1.9.1", "open-color": "1.9.1",
"pako": "1.0.11", "pako": "1.0.11",
"perfect-freehand": "1.2.0", "perfect-freehand": "1.0.16",
"pica": "7.1.1", "pica": "7.1.1",
"png-chunk-text": "1.0.0", "png-chunk-text": "1.0.0",
"png-chunks-encode": "1.0.0", "png-chunks-encode": "1.0.0",
@@ -51,23 +50,11 @@
"pwacompat": "2.0.17", "pwacompat": "2.0.17",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-scripts": "5.0.1", "react-scripts": "4.0.3",
"roughjs": "4.5.2", "roughjs": "4.5.2",
"sass": "1.51.0", "sass": "1.51.0",
"socket.io-client": "2.3.1", "socket.io-client": "2.3.1",
"typescript": "4.9.4", "typescript": "4.5.5"
"workbox-background-sync": "^6.5.4",
"workbox-broadcast-update": "^6.5.4",
"workbox-cacheable-response": "^6.5.4",
"workbox-core": "^6.5.4",
"workbox-expiration": "^6.5.4",
"workbox-google-analytics": "^6.5.4",
"workbox-navigation-preload": "^6.5.4",
"workbox-precaching": "^6.5.4",
"workbox-range-requests": "^6.5.4",
"workbox-routing": "^6.5.4",
"workbox-strategies": "^6.5.4",
"workbox-streams": "^6.5.4"
}, },
"devDependencies": { "devDependencies": {
"@excalidraw/eslint-config": "1.0.0", "@excalidraw/eslint-config": "1.0.0",
@@ -80,7 +67,6 @@
"dotenv": "16.0.1", "dotenv": "16.0.1",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.5.0",
"eslint-plugin-prettier": "3.3.1", "eslint-plugin-prettier": "3.3.1",
"http-server": "14.1.1",
"husky": "7.0.4", "husky": "7.0.4",
"jest-canvas-mock": "2.4.0", "jest-canvas-mock": "2.4.0",
"lint-staged": "12.3.7", "lint-staged": "12.3.7",
@@ -88,6 +74,9 @@
"prettier": "2.6.2", "prettier": "2.6.2",
"rewire": "6.0.0" "rewire": "6.0.0"
}, },
"resolutions": {
"@typescript-eslint/typescript-estree": "5.10.2"
},
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
}, },
@@ -104,9 +93,10 @@
"scripts": { "scripts": {
"build-node": "node ./scripts/build-node.js", "build-node": "node ./scripts/build-node.js",
"build:app:docker": "REACT_APP_DISABLE_SENTRY=true react-scripts build", "build:app:docker": "REACT_APP_DISABLE_SENTRY=true react-scripts build",
"build:app": "cross-env REACT_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA react-scripts build", "build:app": "REACT_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA react-scripts build",
"build:version": "node ./scripts/build-version.js", "build:version": "node ./scripts/build-version.js",
"build": "yarn build:app && yarn build:version", "build:prebuild": "node ./scripts/prebuild.js",
"build": "yarn build:prebuild && yarn build:app && yarn build:version",
"eject": "react-scripts eject", "eject": "react-scripts eject",
"fix:code": "yarn test:code --fix", "fix:code": "yarn test:code --fix",
"fix:other": "yarn prettier --write", "fix:other": "yarn prettier --write",
@@ -116,7 +106,6 @@
"prepare": "husky install", "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",
"start:production": "npm run build && npx http-server build -a localhost -p 5001 -o",
"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",
"test:app": "react-scripts test --passWithNoTests", "test:app": "react-scripts test --passWithNoTests",
"test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .", "test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .",

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -11,28 +11,3 @@
src: url("Cascadia.woff2"); src: url("Cascadia.woff2");
font-display: swap; font-display: swap;
} }
@font-face {
font-family: "Assistant";
src: url("Assistant-Regular.woff2");
font-display: swap;
font-weight: 400;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-Medium.woff2");
font-display: swap;
font-weight: 500;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-SemiBold.woff2");
font-display: swap;
font-weight: 600;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-Bold.woff2");
font-display: swap;
font-weight: 700;
}

View File

@@ -8,76 +8,49 @@
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no"
/> />
<meta name="referrer" content="origin" /> <meta name="referrer" content="origin" />
<meta name="mobile-web-app-capable" content="yes" /> <meta name="mobile-web-app-capable" content="yes" />
<meta name="theme-color" content="#121212" />
<!-- Primary Meta Tags --> <meta name="theme-color" content="#000" />
<meta
name="title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta
name="description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta name="image" content="https://excalidraw.com/og-general-v1.png" />
<!-- Open Graph / Facebook -->
<meta property="og:site_name" content="Excalidraw" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://excalidraw.com" />
<meta
property="og:title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta property="og:image:alt" content="Excalidraw logo" />
<meta
property="og:description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta property="og:image" content="https://excalidraw.com/og-fb-v1.png" />
<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:site" content="@excalidraw" />
<meta property="twitter:url" content="https://excalidraw.com" />
<meta
property="twitter:title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta
property="twitter:description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta
property="twitter:image"
content="https://excalidraw.com/og-twitter-v1.png"
/>
<!-- General tags --> <!-- General tags -->
<meta <meta
name="description" name="description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them." content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/> />
<meta name="image" content="og-image.png" />
<!-------------------------------------------------------------------------> <!-- OpenGraph tags -->
<!-- to minimize white flash on load when user has dark mode enabled --> <meta property="og:url" content="https://excalidraw.com" />
<script> <meta property="og:site_name" content="Excalidraw" />
try { <meta property="og:type" content="website" />
// <meta property="og:title" content="Excalidraw" />
const theme = window.localStorage.getItem("excalidraw-theme"); <meta
if (theme === "dark") { property="og:description"
document.documentElement.classList.add("dark"); content="Excalidraw is a whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
} />
} catch {} <!-- OG tags require an absolute url for images -->
</script> <meta
<style> property="og:image"
html.dark { name="twitter:image"
background-color: #121212; content="https://excalidraw.com/og-image.png"
color: #fff; />
} <meta
</style> property="og:image:secure_url"
<!-------------------------------------------------------------------------> name="twitter:image"
content="https://excalidraw.com/og-image.png"
/>
<meta property="og:image:width" content="1280" />
<meta property="og:image:height" content="669" />
<meta property="og:image:alt" content="Excalidraw logo with byline." />
<!-- Twitter Card tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Excalidraw" />
<meta
name="twitter:description"
content="Excalidraw is a whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<script> <script>
// Redirect Excalidraw+ users which have auto-redirect enabled. // Redirect Excalidraw+ users which have auto-redirect enabled.
@@ -125,7 +98,7 @@
/> />
<link rel="stylesheet" href="fonts.css" type="text/css" /> <link rel="stylesheet" href="fonts.css" type="text/css" />
<% if (process.env.REACT_APP_DEV_DISABLE_LIVE_RELOAD==="true" ) { %> <% if (process.env.REACT_APP_DEV_DISABLE_LIVE_RELOAD === "true") { %>
<script> <script>
{ {
const _WebSocket = window.WebSocket; const _WebSocket = window.WebSocket;
@@ -166,8 +139,8 @@
body, body,
html { html {
margin: 0; margin: 0;
--ui-font: Assistant, system-ui, BlinkMacSystemFont, -apple-system, --ui-font: system-ui, BlinkMacSystemFont, -apple-system, Segoe UI,
Segoe UI, Roboto, Helvetica, Arial, sans-serif; Roboto, Helvetica, Arial, sans-serif;
font-family: var(--ui-font); font-family: var(--ui-font);
-webkit-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
@@ -182,7 +155,7 @@
width: 1px; width: 1px;
overflow: hidden; overflow: hidden;
clip: rect(1px, 1px, 1px, 1px); clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap; white-space: nowrap; /* added line */
user-select: none; user-select: none;
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -1,9 +1,3 @@
User-agent: Twitterbot
Disallow:
User-agent: facebookexternalhit
Disallow:
user-agent: * user-agent: *
Allow: /$ Allow: /$
Disallow: / Disallow: /

81
public/service-worker.js Normal file
View File

@@ -0,0 +1,81 @@
// eslint-disable-next-line no-restricted-globals
// eslint-disable-next-line no-unused-expressions
/* eslint-disable no-restricted-globals */
/* global importScripts, workbox */
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
// in dev, `process` is undefined because this file is not compiled until build
const IS_DEVELOPMENT =
typeof process === "undefined" || process.env.NODE_ENV !== "production";
if (IS_DEVELOPMENT) {
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js",
);
workbox.setConfig({
debug: true,
});
} else {
importScripts("/workbox/workbox-sw.js");
workbox.setConfig({
modulePathPrefix: "/workbox/",
});
}
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
workbox.core.clientsClaim();
if (!IS_DEVELOPMENT) {
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
workbox.routing.registerNavigationRoute(
workbox.precaching.getCacheKeyForURL("./index.html"),
{
blacklist: [/^\/_/, /\/[^/?]+\.[^/]+$/],
},
);
}
// Cache relevant font files
workbox.routing.registerRoute(
new RegExp("/(fonts.css|.+.(ttf|woff2|otf))"),
new workbox.strategies.StaleWhileRevalidate({
cacheName: "fonts",
plugins: [new workbox.expiration.Plugin({ maxEntries: 10 })],
}),
);
self.addEventListener("fetch", (event) => {
if (
event.request.method === "POST" &&
event.request.url.endsWith("/web-share-target")
) {
return event.respondWith(
(async () => {
const formData = await event.request.formData();
const file = formData.get("file");
const webShareTargetCache = await caches.open("web-share-target");
await webShareTargetCache.put("shared-file", new Response(file));
return Response.redirect("/?web-share-target", 303);
})(),
);
}
});

View File

@@ -15,7 +15,6 @@ const crowdinMap = {
"fa-IR": "en-fa", "fa-IR": "en-fa",
"fi-FI": "en-fi", "fi-FI": "en-fi",
"fr-FR": "en-fr", "fr-FR": "en-fr",
"gl-ES": "en-gl",
"he-IL": "en-he", "he-IL": "en-he",
"hi-IN": "en-hi", "hi-IN": "en-hi",
"hu-HU": "en-hu", "hu-HU": "en-hu",
@@ -24,7 +23,6 @@ const crowdinMap = {
"ja-JP": "en-ja", "ja-JP": "en-ja",
"kab-KAB": "en-kab", "kab-KAB": "en-kab",
"ko-KR": "en-ko", "ko-KR": "en-ko",
"ku-TR": "en-ku",
"my-MM": "en-my", "my-MM": "en-my",
"nb-NO": "en-nb", "nb-NO": "en-nb",
"nl-NL": "en-nl", "nl-NL": "en-nl",
@@ -50,8 +48,8 @@ const crowdinMap = {
"lv-LV": "en-lv", "lv-LV": "en-lv",
"cs-CZ": "en-cs", "cs-CZ": "en-cs",
"kk-KZ": "en-kk", "kk-KZ": "en-kk",
"vi-VN": "en-vi", "vi-vn": "en-vi",
"mr-IN": "en-mr", "mr-in": "en-mr",
}; };
const flags = { const flags = {
@@ -67,7 +65,6 @@ const flags = {
"fa-IR": "🇮🇷", "fa-IR": "🇮🇷",
"fi-FI": "🇫🇮", "fi-FI": "🇫🇮",
"fr-FR": "🇫🇷", "fr-FR": "🇫🇷",
"gl-ES": "🇪🇸",
"he-IL": "🇮🇱", "he-IL": "🇮🇱",
"hi-IN": "🇮🇳", "hi-IN": "🇮🇳",
"hu-HU": "🇭🇺", "hu-HU": "🇭🇺",
@@ -77,7 +74,6 @@ const flags = {
"kab-KAB": "🏳", "kab-KAB": "🏳",
"kk-KZ": "🇰🇿", "kk-KZ": "🇰🇿",
"ko-KR": "🇰🇷", "ko-KR": "🇰🇷",
"ku-TR": "🏳",
"lt-LT": "🇱🇹", "lt-LT": "🇱🇹",
"lv-LV": "🇱🇻", "lv-LV": "🇱🇻",
"my-MM": "🇲🇲", "my-MM": "🇲🇲",
@@ -120,7 +116,6 @@ const languages = {
"fa-IR": "فارسی", "fa-IR": "فارسی",
"fi-FI": "Suomi", "fi-FI": "Suomi",
"fr-FR": "Français", "fr-FR": "Français",
"gl-ES": "Galego",
"he-IL": "עברית", "he-IL": "עברית",
"hi-IN": "हिन्दी", "hi-IN": "हिन्दी",
"hu-HU": "Magyar", "hu-HU": "Magyar",
@@ -130,7 +125,6 @@ const languages = {
"kab-KAB": "Taqbaylit", "kab-KAB": "Taqbaylit",
"kk-KZ": "Қазақ тілі", "kk-KZ": "Қазақ тілі",
"ko-KR": "한국어", "ko-KR": "한국어",
"ku-TR": "Kurdî",
"lt-LT": "Lietuvių", "lt-LT": "Lietuvių",
"lv-LV": "Latviešu", "lv-LV": "Latviešu",
"my-MM": "Burmese", "my-MM": "Burmese",

21
scripts/prebuild.js Normal file
View File

@@ -0,0 +1,21 @@
const fs = require("fs");
const path = require("path");
// for development purposes we want to have the service-worker.js file
// accessible from the public folder. On build though, we need to compile it
// and CRA expects that file to be in src/ folder.
const moveServiceWorkerScript = () => {
const oldPath = path.resolve(__dirname, "../public/service-worker.js");
const newPath = path.resolve(__dirname, "../src/service-worker.js");
fs.rename(oldPath, newPath, (error) => {
if (error) {
throw error;
}
console.info("public/service-worker.js moved to src/");
});
};
// -----------------------------------------------------------------------------
moveServiceWorkerScript();

View File

@@ -60,7 +60,7 @@ export const actionAlignTop = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={AlignTopIcon} icon={<AlignTopIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignTop")}${getShortcutKey( title={`${t("labels.alignTop")}${getShortcutKey(
"CtrlOrCmd+Shift+Up", "CtrlOrCmd+Shift+Up",
@@ -90,7 +90,7 @@ export const actionAlignBottom = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={AlignBottomIcon} icon={<AlignBottomIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignBottom")}${getShortcutKey( title={`${t("labels.alignBottom")}${getShortcutKey(
"CtrlOrCmd+Shift+Down", "CtrlOrCmd+Shift+Down",
@@ -120,7 +120,7 @@ export const actionAlignLeft = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={AlignLeftIcon} icon={<AlignLeftIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignLeft")}${getShortcutKey( title={`${t("labels.alignLeft")}${getShortcutKey(
"CtrlOrCmd+Shift+Left", "CtrlOrCmd+Shift+Left",
@@ -151,7 +151,7 @@ export const actionAlignRight = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={AlignRightIcon} icon={<AlignRightIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignRight")}${getShortcutKey( title={`${t("labels.alignRight")}${getShortcutKey(
"CtrlOrCmd+Shift+Right", "CtrlOrCmd+Shift+Right",
@@ -180,7 +180,7 @@ export const actionAlignVerticallyCentered = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={CenterVerticallyIcon} icon={<CenterVerticallyIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={t("labels.centerVertically")} title={t("labels.centerVertically")}
aria-label={t("labels.centerVertically")} aria-label={t("labels.centerVertically")}
@@ -206,7 +206,7 @@ export const actionAlignHorizontallyCentered = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={CenterHorizontallyIcon} icon={<CenterHorizontallyIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={t("labels.centerHorizontally")} title={t("labels.centerHorizontally")}
aria-label={t("labels.centerHorizontally")} aria-label={t("labels.centerHorizontally")}

View File

@@ -6,10 +6,6 @@ import {
measureText, measureText,
redrawTextBoundingBox, redrawTextBoundingBox,
} from "../element/textElement"; } from "../element/textElement";
import {
getOriginalContainerHeightFromCache,
resetOriginalContainerCache,
} from "../element/textWysiwyg";
import { import {
hasBoundTextElement, hasBoundTextElement,
isTextBindableContainer, isTextBindableContainer,
@@ -42,11 +38,6 @@ export const actionUnbindText = register({
boundTextElement.originalText, boundTextElement.originalText,
getFontString(boundTextElement), getFontString(boundTextElement),
); );
const originalContainerHeight = getOriginalContainerHeightFromCache(
element.id,
);
resetOriginalContainerCache(element.id);
mutateElement(boundTextElement as ExcalidrawTextElement, { mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null, containerId: null,
width, width,
@@ -58,9 +49,6 @@ export const actionUnbindText = register({
boundElements: element.boundElements?.filter( boundElements: element.boundElements?.filter(
(ele) => ele.id !== boundTextElement.id, (ele) => ele.id !== boundTextElement.id,
), ),
height: originalContainerHeight
? originalContainerHeight
: element.height,
}); });
} }
}); });

View File

@@ -1,13 +1,8 @@
import { ColorPicker } from "../components/ColorPicker"; import { ColorPicker } from "../components/ColorPicker";
import { import { eraser, zoomIn, zoomOut } from "../components/icons";
eraser,
MoonIcon,
SunIcon,
ZoomInIcon,
ZoomOutIcon,
} from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { MIN_ZOOM, THEME, ZOOM_STEP } from "../constants"; import { DarkModeToggle } from "../components/DarkModeToggle";
import { THEME, ZOOM_STEP } from "../constants";
import { getCommonBounds, getNonDeletedElements } from "../element"; import { getCommonBounds, getNonDeletedElements } from "../element";
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
@@ -23,8 +18,6 @@ import { newElementWith } from "../element/mutateElement";
import { getDefaultAppState, isEraserActive } from "../appState"; import { getDefaultAppState, isEraserActive } from "../appState";
import ClearCanvas from "../components/ClearCanvas"; import ClearCanvas from "../components/ClearCanvas";
import clsx from "clsx"; import clsx from "clsx";
import MenuItem from "../components/MenuItem";
import { getShortcutFromShortcutName } from "./shortcuts";
export const actionChangeViewBackgroundColor = register({ export const actionChangeViewBackgroundColor = register({
name: "changeViewBackgroundColor", name: "changeViewBackgroundColor",
@@ -90,7 +83,6 @@ export const actionClearCanvas = register({
export const actionZoomIn = register({ export const actionZoomIn = register({
name: "zoomIn", name: "zoomIn",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -111,13 +103,13 @@ export const actionZoomIn = register({
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
className="zoom-in-button zoom-button" icon={zoomIn}
icon={ZoomInIcon}
title={`${t("buttons.zoomIn")}${getShortcutKey("CtrlOrCmd++")}`} title={`${t("buttons.zoomIn")}${getShortcutKey("CtrlOrCmd++")}`}
aria-label={t("buttons.zoomIn")} aria-label={t("buttons.zoomIn")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
/> />
), ),
keyTest: (event) => keyTest: (event) =>
@@ -127,7 +119,6 @@ export const actionZoomIn = register({
export const actionZoomOut = register({ export const actionZoomOut = register({
name: "zoomOut", name: "zoomOut",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -148,13 +139,13 @@ export const actionZoomOut = register({
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
className="zoom-out-button zoom-button" icon={zoomOut}
icon={ZoomOutIcon}
title={`${t("buttons.zoomOut")}${getShortcutKey("CtrlOrCmd+-")}`} title={`${t("buttons.zoomOut")}${getShortcutKey("CtrlOrCmd+-")}`}
aria-label={t("buttons.zoomOut")} aria-label={t("buttons.zoomOut")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
/> />
), ),
keyTest: (event) => keyTest: (event) =>
@@ -164,7 +155,6 @@ export const actionZoomOut = register({
export const actionResetZoom = register({ export const actionResetZoom = register({
name: "resetZoom", name: "resetZoom",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -186,12 +176,13 @@ export const actionResetZoom = register({
<Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}> <Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}>
<ToolButton <ToolButton
type="button" type="button"
className="reset-zoom-button zoom-button" className="reset-zoom-button"
title={t("buttons.resetZoom")} title={t("buttons.resetZoom")}
aria-label={t("buttons.resetZoom")} aria-label={t("buttons.resetZoom")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
> >
{(appState.zoom.value * 100).toFixed(0)}% {(appState.zoom.value * 100).toFixed(0)}%
</ToolButton> </ToolButton>
@@ -215,7 +206,7 @@ const zoomValueToFitBoundsOnViewport = (
const zoomAdjustedToSteps = const zoomAdjustedToSteps =
Math.floor(smallestZoomValue / ZOOM_STEP) * ZOOM_STEP; Math.floor(smallestZoomValue / ZOOM_STEP) * ZOOM_STEP;
const clampedZoomValueToFitElements = Math.min( const clampedZoomValueToFitElements = Math.min(
Math.max(zoomAdjustedToSteps, MIN_ZOOM), Math.max(zoomAdjustedToSteps, ZOOM_STEP),
1, 1,
); );
return clampedZoomValueToFitElements as NormalizedZoomValue; return clampedZoomValueToFitElements as NormalizedZoomValue;
@@ -274,7 +265,6 @@ export const actionZoomToSelected = register({
export const actionZoomToFit = register({ export const actionZoomToFit = register({
name: "zoomToFit", name: "zoomToFit",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (elements, appState) => zoomToFitElements(elements, appState, false), perform: (elements, appState) => zoomToFitElements(elements, appState, false),
keyTest: (event) => keyTest: (event) =>
@@ -286,7 +276,6 @@ export const actionZoomToFit = register({
export const actionToggleTheme = register({ export const actionToggleTheme = register({
name: "toggleTheme", name: "toggleTheme",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_, appState, value) => { perform: (_, appState, value) => {
return { return {
@@ -299,19 +288,14 @@ export const actionToggleTheme = register({
}; };
}, },
PanelComponent: ({ appState, updateData }) => ( PanelComponent: ({ appState, updateData }) => (
<MenuItem <div style={{ marginInlineStart: "0.25rem" }}>
label={ <DarkModeToggle
appState.theme === "dark" value={appState.theme}
? t("buttons.lightMode") onChange={(theme) => {
: t("buttons.darkMode") updateData(theme);
} }}
onClick={() => { />
updateData(appState.theme === THEME.LIGHT ? THEME.DARK : THEME.LIGHT); </div>
}}
icon={appState.theme === "dark" ? SunIcon : MoonIcon}
dataTestId="toggle-dark-mode"
shortcut={getShortcutFromShortcutName("toggleTheme")}
/>
), ),
keyTest: (event) => event.altKey && event.shiftKey && event.code === CODES.D, keyTest: (event) => event.altKey && event.shiftKey && event.code === CODES.D,
}); });

View File

@@ -3,7 +3,6 @@ import { register } from "./register";
import { import {
copyTextToSystemClipboard, copyTextToSystemClipboard,
copyToClipboard, copyToClipboard,
probablySupportsClipboardBlob,
probablySupportsClipboardWriteText, probablySupportsClipboardWriteText,
} from "../clipboard"; } from "../clipboard";
import { actionDeleteSelected } from "./actionDeleteSelected"; import { actionDeleteSelected } from "./actionDeleteSelected";
@@ -24,31 +23,11 @@ export const actionCopy = register({
commitToHistory: false, commitToHistory: false,
}; };
}, },
contextItemPredicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.copy", contextItemLabel: "labels.copy",
// don't supply a shortcut since we handle this conditionally via onCopy event // don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined, keyTest: undefined,
}); });
export const actionPaste = register({
name: "paste",
trackEvent: { category: "element" },
perform: (elements: any, appStates: any, data, app) => {
app.pasteFromClipboard(null);
return {
commitToHistory: false,
};
},
contextItemPredicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.paste",
// don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined,
});
export const actionCut = register({ export const actionCut = register({
name: "cut", name: "cut",
trackEvent: { category: "element" }, trackEvent: { category: "element" },
@@ -56,11 +35,8 @@ export const actionCut = register({
actionCopy.perform(elements, appState, data, app); actionCopy.perform(elements, appState, data, app);
return actionDeleteSelected.perform(elements, appState); return actionDeleteSelected.perform(elements, appState);
}, },
contextItemPredicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.cut", contextItemLabel: "labels.cut",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.X,
}); });
export const actionCopyAsSvg = register({ export const actionCopyAsSvg = register({
@@ -101,9 +77,6 @@ export const actionCopyAsSvg = register({
}; };
} }
}, },
contextItemPredicate: (elements) => {
return probablySupportsClipboardWriteText && elements.length > 0;
},
contextItemLabel: "labels.copyAsSvg", contextItemLabel: "labels.copyAsSvg",
}); });
@@ -158,9 +131,6 @@ export const actionCopyAsPng = register({
}; };
} }
}, },
contextItemPredicate: (elements) => {
return probablySupportsClipboardBlob && elements.length > 0;
},
contextItemLabel: "labels.copyAsPng", contextItemLabel: "labels.copyAsPng",
keyTest: (event) => event.code === CODES.C && event.altKey && event.shiftKey, keyTest: (event) => event.code === CODES.C && event.altKey && event.shiftKey,
}); });

View File

@@ -1,6 +1,7 @@
import { isSomeElementSelected } from "../scene"; import { isSomeElementSelected } from "../scene";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { trash } from "../components/icons";
import { t } from "../i18n"; import { t } from "../i18n";
import { register } from "./register"; import { register } from "./register";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
@@ -12,7 +13,6 @@ import { LinearElementEditor } from "../element/linearElementEditor";
import { fixBindingsAfterDeletion } from "../element/binding"; import { fixBindingsAfterDeletion } from "../element/binding";
import { isBoundToContainer } from "../element/typeChecks"; import { isBoundToContainer } from "../element/typeChecks";
import { updateActiveTool } from "../utils"; import { updateActiveTool } from "../utils";
import { TrashIcon } from "../components/icons";
const deleteSelectedElements = ( const deleteSelectedElements = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
@@ -72,22 +72,13 @@ export const actionDeleteSelected = register({
if (!element) { if (!element) {
return false; return false;
} }
// case: no point selected → do nothing, as deleting the whole element if (
// is most likely a mistake, where you wanted to delete a specific point // case: no point selected delete whole element
// but failed to select it (or you thought it's selected, while it was selectedPointsIndices == null ||
// only in a hover state) // case: deleting last remaining point
if (selectedPointsIndices == null) { element.points.length < 2
return false; ) {
} const nextElements = elements.filter((el) => el.id !== element.id);
// case: deleting last remaining point
if (element.points.length < 2) {
const nextElements = elements.map((el) => {
if (el.id === element.id) {
return newElementWith(el, { isDeleted: true });
}
return el;
});
const nextAppState = handleGroupEditingState(appState, nextElements); const nextAppState = handleGroupEditingState(appState, nextElements);
return { return {
@@ -158,7 +149,7 @@ export const actionDeleteSelected = register({
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={TrashIcon} icon={trash}
title={t("labels.delete")} title={t("labels.delete")}
aria-label={t("labels.delete")} aria-label={t("labels.delete")}
onClick={() => updateData(null)} onClick={() => updateData(null)}

View File

@@ -56,7 +56,7 @@ export const distributeHorizontally = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={DistributeHorizontallyIcon} icon={<DistributeHorizontallyIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.distributeHorizontally")}${getShortcutKey( title={`${t("labels.distributeHorizontally")}${getShortcutKey(
"Alt+H", "Alt+H",
@@ -86,7 +86,7 @@ export const distributeVertically = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={DistributeVerticallyIcon} icon={<DistributeVerticallyIcon theme={appState.theme} />}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.distributeVertically")}${getShortcutKey("Alt+V")}`} title={`${t("labels.distributeVertically")}${getShortcutKey("Alt+V")}`}
aria-label={t("labels.distributeVertically")} aria-label={t("labels.distributeVertically")}

View File

@@ -4,6 +4,7 @@ import { ExcalidrawElement } from "../element/types";
import { duplicateElement, getNonDeletedElements } from "../element"; import { duplicateElement, getNonDeletedElements } from "../element";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { clone } from "../components/icons";
import { t } from "../i18n"; import { t } from "../i18n";
import { arrayToMap, getShortcutKey } from "../utils"; import { arrayToMap, getShortcutKey } from "../utils";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
@@ -18,7 +19,6 @@ import { ActionResult } from "./types";
import { GRID_SIZE } from "../constants"; import { GRID_SIZE } from "../constants";
import { bindTextToShapeAfterDuplication } from "../element/textElement"; import { bindTextToShapeAfterDuplication } from "../element/textElement";
import { isBoundToContainer } from "../element/typeChecks"; import { isBoundToContainer } from "../element/typeChecks";
import { DuplicateIcon } from "../components/icons";
export const actionDuplicateSelection = register({ export const actionDuplicateSelection = register({
name: "duplicateSelection", name: "duplicateSelection",
@@ -49,7 +49,7 @@ export const actionDuplicateSelection = register({
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={DuplicateIcon} icon={clone}
title={`${t("labels.duplicateSelection")}${getShortcutKey( title={`${t("labels.duplicateSelection")}${getShortcutKey(
"CtrlOrCmd+D", "CtrlOrCmd+D",
)}`} )}`}

View File

@@ -1,4 +1,4 @@
import { LoadIcon, questionCircle, saveAs } from "../components/icons"; import { load, questionCircle, saveAs } from "../components/icons";
import { ProjectName } from "../components/ProjectName"; import { ProjectName } from "../components/ProjectName";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import "../components/ToolIcon.scss"; import "../components/ToolIcon.scss";
@@ -19,8 +19,6 @@ import { ActiveFile } from "../components/ActiveFile";
import { isImageFileHandle } from "../data/blob"; import { isImageFileHandle } from "../data/blob";
import { nativeFileSystemSupported } from "../data/filesystem"; import { nativeFileSystemSupported } from "../data/filesystem";
import { Theme } from "../element/types"; import { Theme } from "../element/types";
import MenuItem from "../components/MenuItem";
import { getShortcutFromShortcutName } from "./shortcuts";
export const actionChangeProjectName = register({ export const actionChangeProjectName = register({
name: "changeProjectName", name: "changeProjectName",
@@ -179,7 +177,6 @@ export const actionSaveToActiveFile = register({
export const actionSaveFileToDisk = register({ export const actionSaveFileToDisk = register({
name: "saveFileToDisk", name: "saveFileToDisk",
viewMode: true,
trackEvent: { category: "export" }, trackEvent: { category: "export" },
perform: async (elements, appState, value, app) => { perform: async (elements, appState, value, app) => {
try { try {
@@ -248,12 +245,14 @@ export const actionLoadScene = register({
}, },
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.O, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.O,
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
<MenuItem <ToolButton
label={t("buttons.load")} type="button"
icon={LoadIcon} icon={load}
title={t("buttons.load")}
aria-label={t("buttons.load")}
showAriaLabel={useDevice().isMobile}
onClick={updateData} onClick={updateData}
dataTestId="load-button" data-testid="load-button"
shortcut={getShortcutFromShortcutName("loadScene")}
/> />
), ),
}); });

View File

@@ -33,6 +33,9 @@ export const actionFinalize = register({
endBindingElement, endBindingElement,
); );
} }
const selectedLinearElement = appState.selectedLinearElement
? new LinearElementEditor(element, scene, appState)
: null;
return { return {
elements: elements:
element.points.length < 2 || isInvisiblySmallElement(element) element.points.length < 2 || isInvisiblySmallElement(element)
@@ -42,6 +45,7 @@ export const actionFinalize = register({
...appState, ...appState,
cursorButton: "up", cursorButton: "up",
editingLinearElement: null, editingLinearElement: null,
selectedLinearElement,
}, },
commitToHistory: true, commitToHistory: true,
}; };
@@ -184,7 +188,7 @@ export const actionFinalize = register({
// To select the linear element when user has finished mutipoint editing // To select the linear element when user has finished mutipoint editing
selectedLinearElement: selectedLinearElement:
multiPointElement && isLinearElement(multiPointElement) multiPointElement && isLinearElement(multiPointElement)
? new LinearElementEditor(multiPointElement, scene) ? new LinearElementEditor(multiPointElement, scene, appState)
: appState.selectedLinearElement, : appState.selectedLinearElement,
pendingImageElementId: null, pendingImageElementId: null,
}, },

View File

@@ -6,15 +6,10 @@ import { ExcalidrawElement, NonDeleted } from "../element/types";
import { normalizeAngle, resizeSingleElement } from "../element/resizeElements"; import { normalizeAngle, resizeSingleElement } from "../element/resizeElements";
import { AppState } from "../types"; import { AppState } from "../types";
import { getTransformHandles } from "../element/transformHandles"; import { getTransformHandles } from "../element/transformHandles";
import { isFreeDrawElement, isLinearElement } from "../element/typeChecks";
import { updateBoundElements } from "../element/binding"; import { updateBoundElements } from "../element/binding";
import { arrayToMap } from "../utils";
import {
getElementAbsoluteCoords,
getElementPointsCoords,
} from "../element/bounds";
import { isLinearElement } from "../element/typeChecks";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
import { KEYS } from "../keys"; import { arrayToMap } from "../utils";
const enableActionFlipHorizontal = ( const enableActionFlipHorizontal = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
@@ -64,8 +59,7 @@ export const actionFlipVertical = register({
commitToHistory: true, commitToHistory: true,
}; };
}, },
keyTest: (event) => keyTest: (event) => event.shiftKey && event.code === "KeyV",
event.shiftKey && event.code === "KeyV" && !event[KEYS.CTRL_OR_CMD],
contextItemLabel: "labels.flipVertical", contextItemLabel: "labels.flipVertical",
contextItemPredicate: (elements, appState) => contextItemPredicate: (elements, appState) =>
enableActionFlipVertical(elements, appState), enableActionFlipVertical(elements, appState),
@@ -124,6 +118,13 @@ const flipElement = (
const height = element.height; const height = element.height;
const originalAngle = normalizeAngle(element.angle); const originalAngle = normalizeAngle(element.angle);
let finalOffsetX = 0;
if (isLinearElement(element) || isFreeDrawElement(element)) {
finalOffsetX =
element.points.reduce((max, point) => Math.max(max, point[0]), 0) * 2 -
element.width;
}
// Rotate back to zero, if necessary // Rotate back to zero, if necessary
mutateElement(element, { mutateElement(element, {
angle: normalizeAngle(0), angle: normalizeAngle(0),
@@ -131,6 +132,7 @@ const flipElement = (
// Flip unrotated by pulling TransformHandle to opposite side // Flip unrotated by pulling TransformHandle to opposite side
const transformHandles = getTransformHandles(element, appState.zoom); const transformHandles = getTransformHandles(element, appState.zoom);
let usingNWHandle = true; let usingNWHandle = true;
let newNCoordsX = 0;
let nHandle = transformHandles.nw; let nHandle = transformHandles.nw;
if (!nHandle) { if (!nHandle) {
// Use ne handle instead // Use ne handle instead
@@ -144,47 +146,30 @@ const flipElement = (
} }
} }
let finalOffsetX = 0;
if (isLinearElement(element) && element.points.length < 3) {
finalOffsetX =
element.points.reduce((max, point) => Math.max(max, point[0]), 0) * 2 -
element.width;
}
let initialPointsCoords;
if (isLinearElement(element)) { if (isLinearElement(element)) {
initialPointsCoords = getElementPointsCoords(element, element.points);
}
const initialElementAbsoluteCoords = getElementAbsoluteCoords(element);
if (isLinearElement(element) && element.points.length < 3) {
for (let index = 1; index < element.points.length; index++) { for (let index = 1; index < element.points.length; index++) {
LinearElementEditor.movePoints(element, [ LinearElementEditor.movePoints(element, [
{ { index, point: [-element.points[index][0], element.points[index][1]] },
index,
point: [-element.points[index][0], element.points[index][1]],
},
]); ]);
} }
LinearElementEditor.normalizePoints(element); LinearElementEditor.normalizePoints(element);
} else { } else {
const elWidth = initialPointsCoords // calculate new x-coord for transformation
? initialPointsCoords[2] - initialPointsCoords[0] newNCoordsX = usingNWHandle ? element.x + 2 * width : element.x - 2 * width;
: initialElementAbsoluteCoords[2] - initialElementAbsoluteCoords[0];
const startPoint = initialPointsCoords
? [initialPointsCoords[0], initialPointsCoords[1]]
: [initialElementAbsoluteCoords[0], initialElementAbsoluteCoords[1]];
resizeSingleElement( resizeSingleElement(
new Map().set(element.id, element), new Map().set(element.id, element),
false, true,
element, element,
usingNWHandle ? "nw" : "ne", usingNWHandle ? "nw" : "ne",
true, false,
usingNWHandle ? startPoint[0] + elWidth : startPoint[0] - elWidth, newNCoordsX,
startPoint[1], nHandle[1],
); );
// fix the size to account for handle sizes
mutateElement(element, {
width,
height,
});
} }
// Rotate by (360 degrees - original angle) // Rotate by (360 degrees - original angle)
@@ -201,30 +186,9 @@ const flipElement = (
mutateElement(element, { mutateElement(element, {
x: originalX + finalOffsetX, x: originalX + finalOffsetX,
y: originalY, y: originalY,
width,
height,
}); });
updateBoundElements(element); updateBoundElements(element);
if (initialPointsCoords && isLinearElement(element)) {
// Adjusting origin because when a beizer curve path exceeds min/max points it offsets the origin.
// There's still room for improvement since when the line roughness is > 1
// we still have a small offset of the origin when fliipping the element.
const finalPointsCoords = getElementPointsCoords(element, element.points);
const topLeftCoordsDiff = initialPointsCoords[0] - finalPointsCoords[0];
const topRightCoordDiff = initialPointsCoords[2] - finalPointsCoords[2];
const coordsDiff = topLeftCoordsDiff + topRightCoordDiff;
mutateElement(element, {
x: element.x + coordsDiff * 0.5,
y: element.y,
width,
height,
});
}
}; };
const rotateElement = (element: ExcalidrawElement, rotationAngle: number) => { const rotateElement = (element: ExcalidrawElement, rotationAngle: number) => {

View File

@@ -1,4 +1,4 @@
import { KEYS } from "../keys"; import { CODES, KEYS } from "../keys";
import { t } from "../i18n"; import { t } from "../i18n";
import { arrayToMap, getShortcutKey } from "../utils"; import { arrayToMap, getShortcutKey } from "../utils";
import { register } from "./register"; import { register } from "./register";
@@ -132,7 +132,7 @@ export const actionGroup = register({
contextItemPredicate: (elements, appState) => contextItemPredicate: (elements, appState) =>
enableActionGroup(elements, appState), enableActionGroup(elements, appState),
keyTest: (event) => keyTest: (event) =>
!event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.key === KEYS.G, !event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.code === CODES.G,
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
@@ -189,9 +189,7 @@ export const actionUngroup = register({
}; };
}, },
keyTest: (event) => keyTest: (event) =>
event.shiftKey && event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.code === CODES.G,
event[KEYS.CTRL_OR_CMD] &&
event.key === KEYS.G.toUpperCase(),
contextItemLabel: "labels.ungroup", contextItemLabel: "labels.ungroup",
contextItemPredicate: (elements, appState) => contextItemPredicate: (elements, appState) =>
getSelectedGroupIds(appState).length > 0, getSelectedGroupIds(appState).length > 0,

View File

@@ -1,5 +1,5 @@
import { Action, ActionResult } from "./types"; import { Action, ActionResult } from "./types";
import { UndoIcon, RedoIcon } from "../components/icons"; import { undo, redo } from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n"; import { t } from "../i18n";
import History, { HistoryEntry } from "../history"; import History, { HistoryEntry } from "../history";
@@ -72,7 +72,7 @@ export const createUndoAction: ActionCreator = (history) => ({
PanelComponent: ({ updateData, data }) => ( PanelComponent: ({ updateData, data }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={UndoIcon} icon={undo}
aria-label={t("buttons.undo")} aria-label={t("buttons.undo")}
onClick={updateData} onClick={updateData}
size={data?.size || "medium"} size={data?.size || "medium"}
@@ -94,7 +94,7 @@ export const createRedoAction: ActionCreator = (history) => ({
PanelComponent: ({ updateData, data }) => ( PanelComponent: ({ updateData, data }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={RedoIcon} icon={redo}
aria-label={t("buttons.redo")} aria-label={t("buttons.redo")}
onClick={updateData} onClick={updateData}
size={data?.size || "medium"} size={data?.size || "medium"}

View File

@@ -1,49 +0,0 @@
import { getNonDeletedElements } from "../element";
import { LinearElementEditor } from "../element/linearElementEditor";
import { isLinearElement } from "../element/typeChecks";
import { ExcalidrawLinearElement } from "../element/types";
import { getSelectedElements } from "../scene";
import { register } from "./register";
export const actionToggleLinearEditor = register({
name: "toggleLinearEditor",
trackEvent: {
category: "element",
},
contextItemPredicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
return true;
}
return false;
},
perform(elements, appState, _, app) {
const selectedElement = getSelectedElements(
getNonDeletedElements(elements),
appState,
true,
)[0] as ExcalidrawLinearElement;
const editingLinearElement =
appState.editingLinearElement?.elementId === selectedElement.id
? null
: new LinearElementEditor(selectedElement, app.scene);
return {
appState: {
...appState,
editingLinearElement,
},
commitToHistory: false,
};
},
contextItemLabel: (elements, appState) => {
const selectedElement = getSelectedElements(
getNonDeletedElements(elements),
appState,
true,
)[0] as ExcalidrawLinearElement;
return appState.editingLinearElement?.elementId === selectedElement.id
? "labels.lineEditor.exit"
: "labels.lineEditor.edit";
},
});

View File

@@ -1,12 +1,11 @@
import { HamburgerMenuIcon, HelpIcon, palette } from "../components/icons"; import { menu, palette } from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n"; import { t } from "../i18n";
import { showSelectedShapeActions, getNonDeletedElements } from "../element"; import { showSelectedShapeActions, getNonDeletedElements } from "../element";
import { register } from "./register"; import { register } from "./register";
import { allowFullScreen, exitFullScreen, isFullScreen } from "../utils"; import { allowFullScreen, exitFullScreen, isFullScreen } from "../utils";
import { KEYS } from "../keys"; import { CODES, KEYS } from "../keys";
import { HelpButton } from "../components/HelpButton"; import { HelpIcon } from "../components/HelpIcon";
import MenuItem from "../components/MenuItem";
export const actionToggleCanvasMenu = register({ export const actionToggleCanvasMenu = register({
name: "toggleCanvasMenu", name: "toggleCanvasMenu",
@@ -21,7 +20,7 @@ export const actionToggleCanvasMenu = register({
PanelComponent: ({ appState, updateData }) => ( PanelComponent: ({ appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={HamburgerMenuIcon} icon={menu}
aria-label={t("buttons.menu")} aria-label={t("buttons.menu")}
onClick={updateData} onClick={updateData}
selected={appState.openMenu === "canvas"} selected={appState.openMenu === "canvas"}
@@ -56,7 +55,6 @@ export const actionToggleEditMenu = register({
export const actionFullScreen = register({ export const actionFullScreen = register({
name: "toggleFullScreen", name: "toggleFullScreen",
viewMode: true,
trackEvent: { category: "canvas", predicate: (appState) => !isFullScreen() }, trackEvent: { category: "canvas", predicate: (appState) => !isFullScreen() },
perform: () => { perform: () => {
if (!isFullScreen()) { if (!isFullScreen()) {
@@ -69,36 +67,26 @@ export const actionFullScreen = register({
commitToHistory: false, commitToHistory: false,
}; };
}, },
keyTest: (event) => event.key === KEYS.F && !event[KEYS.CTRL_OR_CMD], keyTest: (event) => event.code === CODES.F && !event[KEYS.CTRL_OR_CMD],
}); });
export const actionShortcuts = register({ export const actionShortcuts = register({
name: "toggleShortcuts", name: "toggleShortcuts",
viewMode: true,
trackEvent: { category: "menu", action: "toggleHelpDialog" }, trackEvent: { category: "menu", action: "toggleHelpDialog" },
perform: (_elements, appState, _, { focusContainer }) => { perform: (_elements, appState, _, { focusContainer }) => {
if (appState.openDialog === "help") { if (appState.showHelpDialog) {
focusContainer(); focusContainer();
} }
return { return {
appState: { appState: {
...appState, ...appState,
openDialog: appState.openDialog === "help" ? null : "help", showHelpDialog: !appState.showHelpDialog,
}, },
commitToHistory: false, commitToHistory: false,
}; };
}, },
PanelComponent: ({ updateData, isInHamburgerMenu }) => PanelComponent: ({ updateData }) => (
isInHamburgerMenu ? ( <HelpIcon title={t("helpDialog.title")} onClick={updateData} />
<MenuItem ),
label={t("helpDialog.title")}
dataTestId="help-menu-item"
icon={HelpIcon}
onClick={updateData}
shortcut="?"
/>
) : (
<HelpButton title={t("helpDialog.title")} onClick={updateData} />
),
keyTest: (event) => event.key === KEYS.QUESTION_MARK, keyTest: (event) => event.key === KEYS.QUESTION_MARK,
}); });

View File

@@ -6,7 +6,6 @@ import { register } from "./register";
export const actionGoToCollaborator = register({ export const actionGoToCollaborator = register({
name: "goToCollaborator", name: "goToCollaborator",
viewMode: true,
trackEvent: { category: "collab" }, trackEvent: { category: "collab" },
perform: (_elements, appState, value) => { perform: (_elements, appState, value) => {
const point = value as Collaborator["pointer"]; const point = value as Collaborator["pointer"];

View File

@@ -2,47 +2,42 @@ import { AppState } from "../../src/types";
import { ButtonIconSelect } from "../components/ButtonIconSelect"; import { ButtonIconSelect } from "../components/ButtonIconSelect";
import { ColorPicker } from "../components/ColorPicker"; import { ColorPicker } from "../components/ColorPicker";
import { IconPicker } from "../components/IconPicker"; import { IconPicker } from "../components/IconPicker";
// TODO barnabasmolnar/editor-redesign
// TextAlignTopIcon, TextAlignBottomIcon,TextAlignMiddleIcon,
// ArrowHead icons
import { import {
ArrowheadArrowIcon, ArrowheadArrowIcon,
ArrowheadBarIcon, ArrowheadBarIcon,
ArrowheadDotIcon, ArrowheadDotIcon,
ArrowheadTriangleIcon, ArrowheadTriangleIcon,
ArrowheadNoneIcon, ArrowheadNoneIcon,
StrokeStyleDashedIcon, EdgeRoundIcon,
StrokeStyleDottedIcon, EdgeSharpIcon,
TextAlignTopIcon,
TextAlignBottomIcon,
TextAlignMiddleIcon,
FillHachureIcon,
FillCrossHatchIcon, FillCrossHatchIcon,
FillHachureIcon,
FillSolidIcon, FillSolidIcon,
FontFamilyCodeIcon,
FontFamilyHandDrawnIcon,
FontFamilyNormalIcon,
FontSizeExtraLargeIcon,
FontSizeLargeIcon,
FontSizeMediumIcon,
FontSizeSmallIcon,
SloppinessArchitectIcon, SloppinessArchitectIcon,
SloppinessArtistIcon, SloppinessArtistIcon,
SloppinessCartoonistIcon, SloppinessCartoonistIcon,
StrokeWidthBaseIcon, StrokeStyleDashedIcon,
StrokeWidthBoldIcon, StrokeStyleDottedIcon,
StrokeWidthExtraBoldIcon, StrokeStyleSolidIcon,
FontSizeSmallIcon, StrokeWidthIcon,
FontSizeMediumIcon,
FontSizeLargeIcon,
FontSizeExtraLargeIcon,
EdgeSharpIcon,
EdgeRoundIcon,
FreedrawIcon,
FontFamilyNormalIcon,
FontFamilyCodeIcon,
TextAlignLeftIcon,
TextAlignCenterIcon, TextAlignCenterIcon,
TextAlignLeftIcon,
TextAlignRightIcon, TextAlignRightIcon,
TextAlignTopIcon,
TextAlignBottomIcon,
TextAlignMiddleIcon,
} from "../components/icons"; } from "../components/icons";
import { import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
FONT_FAMILY, FONT_FAMILY,
ROUNDNESS,
VERTICAL_ALIGN, VERTICAL_ALIGN,
} from "../constants"; } from "../constants";
import { import {
@@ -58,7 +53,7 @@ import {
import { import {
isBoundToContainer, isBoundToContainer,
isLinearElement, isLinearElement,
isUsingAdaptiveRadius, isLinearElementType,
} from "../element/typeChecks"; } from "../element/typeChecks";
import { import {
Arrowhead, Arrowhead,
@@ -73,7 +68,7 @@ import { getLanguage, t } from "../i18n";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { randomInteger } from "../random"; import { randomInteger } from "../random";
import { import {
canChangeRoundness, canChangeSharpness,
canHaveArrowheads, canHaveArrowheads,
getCommonAttributeOfSelectedElements, getCommonAttributeOfSelectedElements,
getSelectedElements, getSelectedElements,
@@ -201,23 +196,12 @@ export const actionChangeStrokeColor = register({
name: "changeStrokeColor", name: "changeStrokeColor",
trackEvent: false, trackEvent: false,
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
const containers = getSelectedElements(elements, appState, false)
.filter((el) => el.boundElements)
.map((el) => el.id);
return { return {
...(value.currentItemStrokeColor && { ...(value.currentItemStrokeColor && {
elements: changeProperty( elements: changeProperty(
elements, elements,
appState, appState,
(el) => { (el) => {
if (
isTextElement(el) &&
el.containerId &&
containers.includes(el.containerId) &&
getContainerElement(el)?.strokeColor !== el.strokeColor
) {
return el;
}
return hasStrokeColor(el.type) return hasStrokeColor(el.type)
? newElementWith(el, { ? newElementWith(el, {
strokeColor: value.currentItemStrokeColor, strokeColor: value.currentItemStrokeColor,
@@ -323,17 +307,17 @@ export const actionChangeFillStyle = register({
{ {
value: "hachure", value: "hachure",
text: t("labels.hachure"), text: t("labels.hachure"),
icon: FillHachureIcon, icon: <FillHachureIcon theme={appState.theme} />,
}, },
{ {
value: "cross-hatch", value: "cross-hatch",
text: t("labels.crossHatch"), text: t("labels.crossHatch"),
icon: FillCrossHatchIcon, icon: <FillCrossHatchIcon theme={appState.theme} />,
}, },
{ {
value: "solid", value: "solid",
text: t("labels.solid"), text: t("labels.solid"),
icon: FillSolidIcon, icon: <FillSolidIcon theme={appState.theme} />,
}, },
]} ]}
group="fill" group="fill"
@@ -374,17 +358,17 @@ export const actionChangeStrokeWidth = register({
{ {
value: 1, value: 1,
text: t("labels.thin"), text: t("labels.thin"),
icon: StrokeWidthBaseIcon, icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={2} />,
}, },
{ {
value: 2, value: 2,
text: t("labels.bold"), text: t("labels.bold"),
icon: StrokeWidthBoldIcon, icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={6} />,
}, },
{ {
value: 4, value: 4,
text: t("labels.extraBold"), text: t("labels.extraBold"),
icon: StrokeWidthExtraBoldIcon, icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={10} />,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -423,17 +407,17 @@ export const actionChangeSloppiness = register({
{ {
value: 0, value: 0,
text: t("labels.architect"), text: t("labels.architect"),
icon: SloppinessArchitectIcon, icon: <SloppinessArchitectIcon theme={appState.theme} />,
}, },
{ {
value: 1, value: 1,
text: t("labels.artist"), text: t("labels.artist"),
icon: SloppinessArtistIcon, icon: <SloppinessArtistIcon theme={appState.theme} />,
}, },
{ {
value: 2, value: 2,
text: t("labels.cartoonist"), text: t("labels.cartoonist"),
icon: SloppinessCartoonistIcon, icon: <SloppinessCartoonistIcon theme={appState.theme} />,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -471,17 +455,17 @@ export const actionChangeStrokeStyle = register({
{ {
value: "solid", value: "solid",
text: t("labels.strokeStyle_solid"), text: t("labels.strokeStyle_solid"),
icon: StrokeWidthBaseIcon, icon: <StrokeStyleSolidIcon theme={appState.theme} />,
}, },
{ {
value: "dashed", value: "dashed",
text: t("labels.strokeStyle_dashed"), text: t("labels.strokeStyle_dashed"),
icon: StrokeStyleDashedIcon, icon: <StrokeStyleDashedIcon theme={appState.theme} />,
}, },
{ {
value: "dotted", value: "dotted",
text: t("labels.strokeStyle_dotted"), text: t("labels.strokeStyle_dotted"),
icon: StrokeStyleDottedIcon, icon: <StrokeStyleDottedIcon theme={appState.theme} />,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -551,25 +535,25 @@ export const actionChangeFontSize = register({
{ {
value: 16, value: 16,
text: t("labels.small"), text: t("labels.small"),
icon: FontSizeSmallIcon, icon: <FontSizeSmallIcon theme={appState.theme} />,
testId: "fontSize-small", testId: "fontSize-small",
}, },
{ {
value: 20, value: 20,
text: t("labels.medium"), text: t("labels.medium"),
icon: FontSizeMediumIcon, icon: <FontSizeMediumIcon theme={appState.theme} />,
testId: "fontSize-medium", testId: "fontSize-medium",
}, },
{ {
value: 28, value: 28,
text: t("labels.large"), text: t("labels.large"),
icon: FontSizeLargeIcon, icon: <FontSizeLargeIcon theme={appState.theme} />,
testId: "fontSize-large", testId: "fontSize-large",
}, },
{ {
value: 36, value: 36,
text: t("labels.veryLarge"), text: t("labels.veryLarge"),
icon: FontSizeExtraLargeIcon, icon: <FontSizeExtraLargeIcon theme={appState.theme} />,
testId: "fontSize-veryLarge", testId: "fontSize-veryLarge",
}, },
]} ]}
@@ -674,17 +658,17 @@ export const actionChangeFontFamily = register({
{ {
value: FONT_FAMILY.Virgil, value: FONT_FAMILY.Virgil,
text: t("labels.handDrawn"), text: t("labels.handDrawn"),
icon: FreedrawIcon, icon: <FontFamilyHandDrawnIcon theme={appState.theme} />,
}, },
{ {
value: FONT_FAMILY.Helvetica, value: FONT_FAMILY.Helvetica,
text: t("labels.normal"), text: t("labels.normal"),
icon: FontFamilyNormalIcon, icon: <FontFamilyNormalIcon theme={appState.theme} />,
}, },
{ {
value: FONT_FAMILY.Cascadia, value: FONT_FAMILY.Cascadia,
text: t("labels.code"), text: t("labels.code"),
icon: FontFamilyCodeIcon, icon: <FontFamilyCodeIcon theme={appState.theme} />,
}, },
]; ];
@@ -755,17 +739,17 @@ export const actionChangeTextAlign = register({
{ {
value: "left", value: "left",
text: t("labels.left"), text: t("labels.left"),
icon: TextAlignLeftIcon, icon: <TextAlignLeftIcon theme={appState.theme} />,
}, },
{ {
value: "center", value: "center",
text: t("labels.center"), text: t("labels.center"),
icon: TextAlignCenterIcon, icon: <TextAlignCenterIcon theme={appState.theme} />,
}, },
{ {
value: "right", value: "right",
text: t("labels.right"), text: t("labels.right"),
icon: TextAlignRightIcon, icon: <TextAlignRightIcon theme={appState.theme} />,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -828,19 +812,16 @@ export const actionChangeVerticalAlign = register({
value: VERTICAL_ALIGN.TOP, value: VERTICAL_ALIGN.TOP,
text: t("labels.alignTop"), text: t("labels.alignTop"),
icon: <TextAlignTopIcon theme={appState.theme} />, icon: <TextAlignTopIcon theme={appState.theme} />,
testId: "align-top",
}, },
{ {
value: VERTICAL_ALIGN.MIDDLE, value: VERTICAL_ALIGN.MIDDLE,
text: t("labels.centerVertically"), text: t("labels.centerVertically"),
icon: <TextAlignMiddleIcon theme={appState.theme} />, icon: <TextAlignMiddleIcon theme={appState.theme} />,
testId: "align-middle",
}, },
{ {
value: VERTICAL_ALIGN.BOTTOM, value: VERTICAL_ALIGN.BOTTOM,
text: t("labels.alignBottom"), text: t("labels.alignBottom"),
icon: <TextAlignBottomIcon theme={appState.theme} />, icon: <TextAlignBottomIcon theme={appState.theme} />,
testId: "align-bottom",
}, },
]} ]}
value={getFormValue(elements, appState, (element) => { value={getFormValue(elements, appState, (element) => {
@@ -860,71 +841,69 @@ export const actionChangeVerticalAlign = register({
}, },
}); });
export const actionChangeRoundness = register({ export const actionChangeSharpness = register({
name: "changeRoundness", name: "changeSharpness",
trackEvent: false, trackEvent: false,
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
return {
elements: changeProperty(elements, appState, (el) =>
newElementWith(el, {
roundness:
value === "round"
? {
type: isUsingAdaptiveRadius(el.type)
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
}),
),
appState: {
...appState,
currentItemRoundness: value,
},
commitToHistory: true,
};
},
PanelComponent: ({ elements, appState, updateData }) => {
const targetElements = getTargetElements( const targetElements = getTargetElements(
getNonDeletedElements(elements), getNonDeletedElements(elements),
appState, appState,
); );
const shouldUpdateForNonLinearElements = targetElements.length
const hasLegacyRoundness = targetElements.some( ? targetElements.every((el) => !isLinearElement(el))
(el) => el.roundness?.type === ROUNDNESS.LEGACY, : !isLinearElementType(appState.activeTool.type);
); const shouldUpdateForLinearElements = targetElements.length
? targetElements.every(isLinearElement)
return ( : isLinearElementType(appState.activeTool.type);
<fieldset> return {
<legend>{t("labels.edges")}</legend> elements: changeProperty(elements, appState, (el) =>
<ButtonIconSelect newElementWith(el, {
group="edges" strokeSharpness: value,
options={[ }),
{ ),
value: "sharp", appState: {
text: t("labels.sharp"), ...appState,
icon: EdgeSharpIcon, currentItemStrokeSharpness: shouldUpdateForNonLinearElements
}, ? value
{ : appState.currentItemStrokeSharpness,
value: "round", currentItemLinearStrokeSharpness: shouldUpdateForLinearElements
text: t("labels.round"), ? value
icon: EdgeRoundIcon, : appState.currentItemLinearStrokeSharpness,
}, },
]} commitToHistory: true,
value={getFormValue( };
elements,
appState,
(element) =>
hasLegacyRoundness ? null : element.roundness ? "round" : "sharp",
(canChangeRoundness(appState.activeTool.type) &&
appState.currentItemRoundness) ||
null,
)}
onChange={(value) => updateData(value)}
/>
</fieldset>
);
}, },
PanelComponent: ({ elements, appState, updateData }) => (
<fieldset>
<legend>{t("labels.edges")}</legend>
<ButtonIconSelect
group="edges"
options={[
{
value: "sharp",
text: t("labels.sharp"),
icon: <EdgeSharpIcon theme={appState.theme} />,
},
{
value: "round",
text: t("labels.round"),
icon: <EdgeRoundIcon theme={appState.theme} />,
},
]}
value={getFormValue(
elements,
appState,
(element) => element.strokeSharpness,
(canChangeSharpness(appState.activeTool.type) &&
(isLinearElementType(appState.activeTool.type)
? appState.currentItemLinearStrokeSharpness
: appState.currentItemStrokeSharpness)) ||
null,
)}
onChange={(value) => updateData(value)}
/>
</fieldset>
),
}); });
export const actionChangeArrowhead = register({ export const actionChangeArrowhead = register({
@@ -970,38 +949,42 @@ export const actionChangeArrowhead = register({
return ( return (
<fieldset> <fieldset>
<legend>{t("labels.arrowheads")}</legend> <legend>{t("labels.arrowheads")}</legend>
<div className="iconSelectList buttonList"> <div className="iconSelectList">
<IconPicker <IconPicker
label="arrowhead_start" label="arrowhead_start"
options={[ options={[
{ {
value: null, value: null,
text: t("labels.arrowhead_none"), text: t("labels.arrowhead_none"),
icon: ArrowheadNoneIcon, icon: <ArrowheadNoneIcon theme={appState.theme} />,
keyBinding: "q", keyBinding: "q",
}, },
{ {
value: "arrow", value: "arrow",
text: t("labels.arrowhead_arrow"), text: t("labels.arrowhead_arrow"),
icon: <ArrowheadArrowIcon flip={!isRTL} />, icon: (
<ArrowheadArrowIcon theme={appState.theme} flip={!isRTL} />
),
keyBinding: "w", keyBinding: "w",
}, },
{ {
value: "bar", value: "bar",
text: t("labels.arrowhead_bar"), text: t("labels.arrowhead_bar"),
icon: <ArrowheadBarIcon flip={!isRTL} />, icon: <ArrowheadBarIcon theme={appState.theme} flip={!isRTL} />,
keyBinding: "e", keyBinding: "e",
}, },
{ {
value: "dot", value: "dot",
text: t("labels.arrowhead_dot"), text: t("labels.arrowhead_dot"),
icon: <ArrowheadDotIcon flip={!isRTL} />, icon: <ArrowheadDotIcon theme={appState.theme} flip={!isRTL} />,
keyBinding: "r", keyBinding: "r",
}, },
{ {
value: "triangle", value: "triangle",
text: t("labels.arrowhead_triangle"), text: t("labels.arrowhead_triangle"),
icon: <ArrowheadTriangleIcon flip={!isRTL} />, icon: (
<ArrowheadTriangleIcon theme={appState.theme} flip={!isRTL} />
),
keyBinding: "t", keyBinding: "t",
}, },
]} ]}
@@ -1024,30 +1007,34 @@ export const actionChangeArrowhead = register({
value: null, value: null,
text: t("labels.arrowhead_none"), text: t("labels.arrowhead_none"),
keyBinding: "q", keyBinding: "q",
icon: ArrowheadNoneIcon, icon: <ArrowheadNoneIcon theme={appState.theme} />,
}, },
{ {
value: "arrow", value: "arrow",
text: t("labels.arrowhead_arrow"), text: t("labels.arrowhead_arrow"),
keyBinding: "w", keyBinding: "w",
icon: <ArrowheadArrowIcon flip={isRTL} />, icon: (
<ArrowheadArrowIcon theme={appState.theme} flip={isRTL} />
),
}, },
{ {
value: "bar", value: "bar",
text: t("labels.arrowhead_bar"), text: t("labels.arrowhead_bar"),
keyBinding: "e", keyBinding: "e",
icon: <ArrowheadBarIcon flip={isRTL} />, icon: <ArrowheadBarIcon theme={appState.theme} flip={isRTL} />,
}, },
{ {
value: "dot", value: "dot",
text: t("labels.arrowhead_dot"), text: t("labels.arrowhead_dot"),
keyBinding: "r", keyBinding: "r",
icon: <ArrowheadDotIcon flip={isRTL} />, icon: <ArrowheadDotIcon theme={appState.theme} flip={isRTL} />,
}, },
{ {
value: "triangle", value: "triangle",
text: t("labels.arrowhead_triangle"), text: t("labels.arrowhead_triangle"),
icon: <ArrowheadTriangleIcon flip={isRTL} />, icon: (
<ArrowheadTriangleIcon theme={appState.theme} flip={isRTL} />
),
keyBinding: "t", keyBinding: "t",
}, },
]} ]}

View File

@@ -35,7 +35,7 @@ export const actionSelectAll = register({
// single linear element selected // single linear element selected
Object.keys(selectedElementIds).length === 1 && Object.keys(selectedElementIds).length === 1 &&
isLinearElement(elements[0]) isLinearElement(elements[0])
? new LinearElementEditor(elements[0], app.scene) ? new LinearElementEditor(elements[0], app.scene, appState)
: null, : null,
editingGroupId: null, editingGroupId: null,
selectedElementIds, selectedElementIds,

View File

@@ -13,11 +13,7 @@ import {
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
} from "../constants"; } from "../constants";
import { getBoundTextElement } from "../element/textElement"; import { getBoundTextElement } from "../element/textElement";
import { import { hasBoundTextElement } from "../element/typeChecks";
hasBoundTextElement,
canApplyRoundnessTypeToElement,
getDefaultRoundnessTypeForElement,
} from "../element/typeChecks";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
// `copiedStyles` is exported only for tests. // `copiedStyles` is exported only for tests.
@@ -81,14 +77,6 @@ export const actionPasteStyles = register({
fillStyle: elementStylesToCopyFrom?.fillStyle, fillStyle: elementStylesToCopyFrom?.fillStyle,
opacity: elementStylesToCopyFrom?.opacity, opacity: elementStylesToCopyFrom?.opacity,
roughness: elementStylesToCopyFrom?.roughness, roughness: elementStylesToCopyFrom?.roughness,
roundness: elementStylesToCopyFrom.roundness
? canApplyRoundnessTypeToElement(
elementStylesToCopyFrom.roundness.type,
element,
)
? elementStylesToCopyFrom.roundness
: getDefaultRoundnessTypeForElement(element)
: null,
}); });
if (isTextElement(newElement)) { if (isTextElement(newElement)) {

View File

@@ -5,7 +5,6 @@ import { AppState } from "../types";
export const actionToggleGridMode = register({ export const actionToggleGridMode = register({
name: "gridMode", name: "gridMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.gridSize, predicate: (appState) => !appState.gridSize,
@@ -20,9 +19,6 @@ export const actionToggleGridMode = register({
}; };
}, },
checked: (appState: AppState) => appState.gridSize !== null, checked: (appState: AppState) => appState.gridSize !== null,
contextItemPredicate: (element, appState, props) => {
return typeof props.gridModeEnabled === "undefined";
},
contextItemLabel: "labels.showGrid", contextItemLabel: "labels.showGrid",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.QUOTE, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.QUOTE,
}); });

View File

@@ -41,9 +41,15 @@ export const actionToggleLock = register({
: "labels.elementLock.lock"; : "labels.elementLock.lock";
} }
return getOperation(selected) === "lock" if (selected.length > 1) {
? "labels.elementLock.lockAll" return getOperation(selected) === "lock"
: "labels.elementLock.unlockAll"; ? "labels.elementLock.lockAll"
: "labels.elementLock.unlockAll";
}
throw new Error(
"Unexpected zero elements to lock/unlock. This should never happen.",
);
}, },
keyTest: (event, appState, elements) => { keyTest: (event, appState, elements) => {
return ( return (

View File

@@ -3,7 +3,6 @@ import { CODES, KEYS } from "../keys";
export const actionToggleStats = register({ export const actionToggleStats = register({
name: "stats", name: "stats",
viewMode: true,
trackEvent: { category: "menu" }, trackEvent: { category: "menu" },
perform(elements, appState) { perform(elements, appState) {
return { return {

View File

@@ -3,7 +3,6 @@ import { register } from "./register";
export const actionToggleViewMode = register({ export const actionToggleViewMode = register({
name: "viewMode", name: "viewMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.viewModeEnabled, predicate: (appState) => !appState.viewModeEnabled,
@@ -18,9 +17,6 @@ export const actionToggleViewMode = register({
}; };
}, },
checked: (appState) => appState.viewModeEnabled, checked: (appState) => appState.viewModeEnabled,
contextItemPredicate: (elements, appState, appProps) => {
return typeof appProps.viewModeEnabled === "undefined";
},
contextItemLabel: "labels.viewMode", contextItemLabel: "labels.viewMode",
keyTest: (event) => keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R, !event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R,

View File

@@ -3,7 +3,6 @@ import { register } from "./register";
export const actionToggleZenMode = register({ export const actionToggleZenMode = register({
name: "zenMode", name: "zenMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.zenModeEnabled, predicate: (appState) => !appState.zenModeEnabled,
@@ -18,9 +17,6 @@ export const actionToggleZenMode = register({
}; };
}, },
checked: (appState) => appState.zenModeEnabled, checked: (appState) => appState.zenModeEnabled,
contextItemPredicate: (elements, appState, appProps) => {
return typeof appProps.zenModeEnabled === "undefined";
},
contextItemLabel: "buttons.zenMode", contextItemLabel: "buttons.zenMode",
keyTest: (event) => keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.Z, !event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.Z,

View File

@@ -10,10 +10,10 @@ import { t } from "../i18n";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import { register } from "./register"; import { register } from "./register";
import { import {
BringForwardIcon,
BringToFrontIcon,
SendBackwardIcon, SendBackwardIcon,
BringToFrontIcon,
SendToBackIcon, SendToBackIcon,
BringForwardIcon,
} from "../components/icons"; } from "../components/icons";
export const actionSendBackward = register({ export const actionSendBackward = register({
@@ -39,7 +39,7 @@ export const actionSendBackward = register({
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.sendBackward")}${getShortcutKey("CtrlOrCmd+[")}`} title={`${t("labels.sendBackward")}${getShortcutKey("CtrlOrCmd+[")}`}
> >
{SendBackwardIcon} <SendBackwardIcon theme={appState.theme} />
</button> </button>
), ),
}); });
@@ -67,7 +67,7 @@ export const actionBringForward = register({
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.bringForward")}${getShortcutKey("CtrlOrCmd+]")}`} title={`${t("labels.bringForward")}${getShortcutKey("CtrlOrCmd+]")}`}
> >
{BringForwardIcon} <BringForwardIcon theme={appState.theme} />
</button> </button>
), ),
}); });
@@ -102,7 +102,7 @@ export const actionSendToBack = register({
: getShortcutKey("CtrlOrCmd+Shift+[") : getShortcutKey("CtrlOrCmd+Shift+[")
}`} }`}
> >
{SendToBackIcon} <SendToBackIcon theme={appState.theme} />
</button> </button>
), ),
}); });
@@ -138,7 +138,7 @@ export const actionBringToFront = register({
: getShortcutKey("CtrlOrCmd+Shift+]") : getShortcutKey("CtrlOrCmd+Shift+]")
}`} }`}
> >
{BringToFrontIcon} <BringToFrontIcon theme={appState.theme} />
</button> </button>
), ),
}); });

View File

@@ -85,4 +85,3 @@ export { actionToggleStats } from "./actionToggleStats";
export { actionUnbindText, actionBindText } from "./actionBoundText"; export { actionUnbindText, actionBindText } from "./actionBoundText";
export { actionLink } from "../element/Hyperlink"; export { actionLink } from "../element/Hyperlink";
export { actionToggleLock } from "./actionToggleLock"; export { actionToggleLock } from "./actionToggleLock";
export { actionToggleLinearEditor } from "./actionLinearEditor";

View File

@@ -9,6 +9,7 @@ import {
} from "./types"; } from "./types";
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { AppClassProperties, AppState } from "../types"; import { AppClassProperties, AppState } from "../types";
import { MODES } from "../constants";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
const trackAction = ( const trackAction = (
@@ -102,8 +103,11 @@ export class ActionManager {
const action = data[0]; const action = data[0];
if (this.getAppState().viewModeEnabled && action.viewMode !== true) { const { viewModeEnabled } = this.getAppState();
return false; if (viewModeEnabled) {
if (!Object.values(MODES).includes(data[0].name)) {
return false;
}
} }
const elements = this.getElementsIncludingDeleted(); const elements = this.getElementsIncludingDeleted();
@@ -131,11 +135,7 @@ export class ActionManager {
/** /**
* @param data additional data sent to the PanelComponent * @param data additional data sent to the PanelComponent
*/ */
renderAction = ( renderAction = (name: ActionName, data?: PanelComponentProps["data"]) => {
name: ActionName,
data?: PanelComponentProps["data"],
isInHamburgerMenu = false,
) => {
const canvasActions = this.app.props.UIOptions.canvasActions; const canvasActions = this.app.props.UIOptions.canvasActions;
if ( if (
@@ -170,7 +170,6 @@ export class ActionManager {
updateData={updateData} updateData={updateData}
appProps={this.app.props} appProps={this.app.props}
data={data} data={data}
isInHamburgerMenu={isInHamburgerMenu}
/> />
); );
} }

View File

@@ -3,52 +3,43 @@ import { isDarwin } from "../keys";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import { ActionName } from "./types"; import { ActionName } from "./types";
export type ShortcutName = export type ShortcutName = SubtypeOf<
| SubtypeOf< ActionName,
ActionName, | "cut"
| "toggleTheme" | "copy"
| "loadScene" | "paste"
| "cut" | "copyStyles"
| "copy" | "pasteStyles"
| "paste" | "selectAll"
| "copyStyles" | "deleteSelectedElements"
| "pasteStyles" | "duplicateSelection"
| "selectAll" | "sendBackward"
| "deleteSelectedElements" | "bringForward"
| "duplicateSelection" | "sendToBack"
| "sendBackward" | "bringToFront"
| "bringForward" | "copyAsPng"
| "sendToBack" | "copyAsSvg"
| "bringToFront" | "group"
| "copyAsPng" | "ungroup"
| "copyAsSvg" | "gridMode"
| "group" | "zenMode"
| "ungroup" | "stats"
| "gridMode" | "addToLibrary"
| "zenMode" | "viewMode"
| "stats" | "flipHorizontal"
| "addToLibrary" | "flipVertical"
| "viewMode" | "hyperlink"
| "flipHorizontal" | "toggleLock"
| "flipVertical" >;
| "hyperlink"
| "toggleLock"
>
| "saveScene"
| "imageExport";
const shortcutMap: Record<ShortcutName, string[]> = { const shortcutMap: Record<ShortcutName, string[]> = {
toggleTheme: [getShortcutKey("Shift+Alt+D")],
saveScene: [getShortcutKey("CtrlOrCmd+S")],
loadScene: [getShortcutKey("CtrlOrCmd+O")],
imageExport: [getShortcutKey("CtrlOrCmd+Shift+E")],
cut: [getShortcutKey("CtrlOrCmd+X")], cut: [getShortcutKey("CtrlOrCmd+X")],
copy: [getShortcutKey("CtrlOrCmd+C")], copy: [getShortcutKey("CtrlOrCmd+C")],
paste: [getShortcutKey("CtrlOrCmd+V")], paste: [getShortcutKey("CtrlOrCmd+V")],
copyStyles: [getShortcutKey("CtrlOrCmd+Alt+C")], copyStyles: [getShortcutKey("CtrlOrCmd+Alt+C")],
pasteStyles: [getShortcutKey("CtrlOrCmd+Alt+V")], pasteStyles: [getShortcutKey("CtrlOrCmd+Alt+V")],
selectAll: [getShortcutKey("CtrlOrCmd+A")], selectAll: [getShortcutKey("CtrlOrCmd+A")],
deleteSelectedElements: [getShortcutKey("Delete")], deleteSelectedElements: [getShortcutKey("Del")],
duplicateSelection: [ duplicateSelection: [
getShortcutKey("CtrlOrCmd+D"), getShortcutKey("CtrlOrCmd+D"),
getShortcutKey(`Alt+${t("helpDialog.drag")}`), getShortcutKey(`Alt+${t("helpDialog.drag")}`),

View File

@@ -91,7 +91,7 @@ export type ActionName =
| "ungroup" | "ungroup"
| "goToCollaborator" | "goToCollaborator"
| "addToLibrary" | "addToLibrary"
| "changeRoundness" | "changeSharpness"
| "alignTop" | "alignTop"
| "alignBottom" | "alignBottom"
| "alignLeft" | "alignLeft"
@@ -111,8 +111,7 @@ export type ActionName =
| "hyperlink" | "hyperlink"
| "eraser" | "eraser"
| "bindText" | "bindText"
| "toggleLock" | "toggleLock";
| "toggleLinearEditor";
export type PanelComponentProps = { export type PanelComponentProps = {
elements: readonly ExcalidrawElement[]; elements: readonly ExcalidrawElement[];
@@ -124,9 +123,7 @@ export type PanelComponentProps = {
export interface Action { export interface Action {
name: ActionName; name: ActionName;
PanelComponent?: React.FC< PanelComponent?: React.FC<PanelComponentProps>;
PanelComponentProps & { isInHamburgerMenu: boolean }
>;
perform: ActionFn; perform: ActionFn;
keyPriority?: number; keyPriority?: number;
keyTest?: ( keyTest?: (
@@ -143,8 +140,6 @@ export interface Action {
contextItemPredicate?: ( contextItemPredicate?: (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
appState: AppState, appState: AppState,
appProps: ExcalidrawProps,
app: AppClassProperties,
) => boolean; ) => boolean;
checked?: (appState: Readonly<AppState>) => boolean; checked?: (appState: Readonly<AppState>) => boolean;
trackEvent: trackEvent:
@@ -166,7 +161,4 @@ export interface Action {
value: any, value: any,
) => boolean; ) => boolean;
}; };
/** if set to `true`, allow action to be performed in viewMode.
* Defaults to `false` */
viewMode?: boolean;
} }

View File

@@ -19,7 +19,6 @@ export const getDefaultAppState = (): Omit<
"offsetTop" | "offsetLeft" | "width" | "height" "offsetTop" | "offsetLeft" | "width" | "height"
> => { > => {
return { return {
showWelcomeScreen: false,
theme: THEME.LIGHT, theme: THEME.LIGHT,
collaborators: new Map(), collaborators: new Map(),
currentChartType: "bar", currentChartType: "bar",
@@ -28,11 +27,12 @@ export const getDefaultAppState = (): Omit<
currentItemFillStyle: "hachure", currentItemFillStyle: "hachure",
currentItemFontFamily: DEFAULT_FONT_FAMILY, currentItemFontFamily: DEFAULT_FONT_FAMILY,
currentItemFontSize: DEFAULT_FONT_SIZE, currentItemFontSize: DEFAULT_FONT_SIZE,
currentItemLinearStrokeSharpness: "round",
currentItemOpacity: 100, currentItemOpacity: 100,
currentItemRoughness: 1, currentItemRoughness: 1,
currentItemStartArrowhead: null, currentItemStartArrowhead: null,
currentItemStrokeColor: oc.black, currentItemStrokeColor: oc.black,
currentItemRoundness: "round", currentItemStrokeSharpness: "sharp",
currentItemStrokeStyle: "solid", currentItemStrokeStyle: "solid",
currentItemStrokeWidth: 1, currentItemStrokeWidth: 1,
currentItemTextAlign: DEFAULT_TEXT_ALIGN, currentItemTextAlign: DEFAULT_TEXT_ALIGN,
@@ -57,18 +57,16 @@ export const getDefaultAppState = (): Omit<
fileHandle: null, fileHandle: null,
gridSize: null, gridSize: null,
isBindingEnabled: true, isBindingEnabled: true,
isSidebarDocked: false, isLibraryOpen: false,
isLibraryMenuDocked: false,
isLoading: false, isLoading: false,
isResizing: false, isResizing: false,
isRotating: false, isRotating: false,
lastPointerDownWith: "mouse", lastPointerDownWith: "mouse",
multiElement: null, multiElement: null,
name: `${t("labels.untitled")}-${getDateTime()}`, name: `${t("labels.untitled")}-${getDateTime()}`,
contextMenu: null,
openMenu: null, openMenu: null,
openPopup: null, openPopup: null,
openSidebar: null,
openDialog: null,
pasteDialog: { shown: false, data: null }, pasteDialog: { shown: false, data: null },
previousSelectedElementIds: {}, previousSelectedElementIds: {},
resizingElement: null, resizingElement: null,
@@ -79,6 +77,7 @@ export const getDefaultAppState = (): Omit<
selectedGroupIds: {}, selectedGroupIds: {},
selectionElement: null, selectionElement: null,
shouldCacheIgnoreZoom: false, shouldCacheIgnoreZoom: false,
showHelpDialog: false,
showStats: false, showStats: false,
startBoundElement: null, startBoundElement: null,
suggestedBindings: [], suggestedBindings: [],
@@ -111,7 +110,6 @@ const APP_STATE_STORAGE_CONF = (<
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: { [K in keyof T]: K extends keyof AppState ? T[K] : never }) =>
config)({ config)({
showWelcomeScreen: { browser: true, export: false, server: false },
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 },
@@ -120,7 +118,7 @@ const APP_STATE_STORAGE_CONF = (<
currentItemFillStyle: { browser: true, export: false, server: false }, currentItemFillStyle: { browser: true, export: false, server: false },
currentItemFontFamily: { browser: true, export: false, server: false }, currentItemFontFamily: { browser: true, export: false, server: false },
currentItemFontSize: { browser: true, export: false, server: false }, currentItemFontSize: { browser: true, export: false, server: false },
currentItemRoundness: { currentItemLinearStrokeSharpness: {
browser: true, browser: true,
export: false, export: false,
server: false, server: false,
@@ -129,6 +127,7 @@ const APP_STATE_STORAGE_CONF = (<
currentItemRoughness: { browser: true, export: false, server: false }, currentItemRoughness: { browser: true, export: false, server: false },
currentItemStartArrowhead: { browser: true, export: false, server: false }, currentItemStartArrowhead: { browser: true, export: false, server: false },
currentItemStrokeColor: { browser: true, export: false, server: false }, currentItemStrokeColor: { browser: true, export: false, server: false },
currentItemStrokeSharpness: { browser: true, export: false, server: false },
currentItemStrokeStyle: { browser: true, export: false, server: false }, currentItemStrokeStyle: { browser: true, export: false, server: false },
currentItemStrokeWidth: { browser: true, export: false, server: false }, currentItemStrokeWidth: { browser: true, export: false, server: false },
currentItemTextAlign: { browser: true, export: false, server: false }, currentItemTextAlign: { browser: true, export: false, server: false },
@@ -149,7 +148,8 @@ const APP_STATE_STORAGE_CONF = (<
gridSize: { browser: true, export: true, server: true }, gridSize: { browser: true, export: true, server: true },
height: { browser: false, export: false, server: false }, height: { browser: false, export: false, server: false },
isBindingEnabled: { browser: false, export: false, server: false }, isBindingEnabled: { browser: false, export: false, server: false },
isSidebarDocked: { browser: true, export: false, server: false }, isLibraryOpen: { browser: true, export: false, server: false },
isLibraryMenuDocked: { browser: true, export: false, server: false },
isLoading: { browser: false, export: false, server: false }, isLoading: { browser: false, export: false, server: false },
isResizing: { browser: false, export: false, server: false }, isResizing: { browser: false, export: false, server: false },
isRotating: { browser: false, export: false, server: false }, isRotating: { browser: false, export: false, server: false },
@@ -158,11 +158,8 @@ const APP_STATE_STORAGE_CONF = (<
name: { browser: true, export: false, server: false }, name: { browser: true, export: false, server: false },
offsetLeft: { browser: false, export: false, server: false }, offsetLeft: { browser: false, export: false, server: false },
offsetTop: { browser: false, export: false, server: false }, offsetTop: { browser: false, export: false, server: false },
contextMenu: { browser: false, export: false, server: false },
openMenu: { browser: true, export: false, server: false }, openMenu: { browser: true, export: false, server: false },
openPopup: { browser: false, export: false, server: false }, openPopup: { browser: false, export: false, server: false },
openSidebar: { browser: true, export: false, server: false },
openDialog: { browser: false, export: false, server: false },
pasteDialog: { browser: false, export: false, server: false }, pasteDialog: { browser: false, export: false, server: false },
previousSelectedElementIds: { browser: true, export: false, server: false }, previousSelectedElementIds: { browser: true, export: false, server: false },
resizingElement: { browser: false, export: false, server: false }, resizingElement: { browser: false, export: false, server: false },
@@ -173,6 +170,7 @@ const APP_STATE_STORAGE_CONF = (<
selectedGroupIds: { browser: true, export: false, server: false }, selectedGroupIds: { browser: true, export: false, server: false },
selectionElement: { browser: false, export: false, server: false }, selectionElement: { browser: false, export: false, server: false },
shouldCacheIgnoreZoom: { browser: true, export: false, server: false }, shouldCacheIgnoreZoom: { browser: true, export: false, server: false },
showHelpDialog: { browser: false, export: false, server: false },
showStats: { browser: true, export: false, server: false }, showStats: { browser: true, export: false, server: false },
startBoundElement: { browser: false, export: false, server: false }, startBoundElement: { browser: false, export: false, server: false },
suggestedBindings: { browser: false, export: false, server: false }, suggestedBindings: { browser: false, export: false, server: false },

View File

@@ -172,7 +172,7 @@ const commonProps = {
opacity: 100, opacity: 100,
roughness: 1, roughness: 1,
strokeColor: colors.elementStroke[0], strokeColor: colors.elementStroke[0],
roundness: null, strokeSharpness: "sharp",
strokeStyle: "solid", strokeStyle: "solid",
strokeWidth: 1, strokeWidth: 1,
verticalAlign: VERTICAL_ALIGN.MIDDLE, verticalAlign: VERTICAL_ALIGN.MIDDLE,
@@ -322,7 +322,7 @@ const chartBaseElements = (
text: spreadsheet.title, text: spreadsheet.title,
x: x + chartWidth / 2, x: x + chartWidth / 2,
y: y - BAR_HEIGHT - BAR_GAP * 2 - DEFAULT_FONT_SIZE, y: y - BAR_HEIGHT - BAR_GAP * 2 - DEFAULT_FONT_SIZE,
roundness: null, strokeSharpness: "sharp",
strokeStyle: "solid", strokeStyle: "solid",
textAlign: "center", textAlign: "center",
}) })

View File

@@ -11,18 +11,27 @@ export const getClientColors = (clientId: string, appState: AppState) => {
// Naive way of getting an integer out of the clientId // Naive way of getting an integer out of the clientId
const sum = clientId.split("").reduce((a, str) => a + str.charCodeAt(0), 0); const sum = clientId.split("").reduce((a, str) => a + str.charCodeAt(0), 0);
// Skip transparent & gray colors // Skip transparent background.
const backgrounds = colors.elementBackground.slice(3); const backgrounds = colors.elementBackground.slice(1);
const strokes = colors.elementStroke.slice(3); const strokes = colors.elementStroke.slice(1);
return { return {
background: backgrounds[sum % backgrounds.length], background: backgrounds[sum % backgrounds.length],
stroke: strokes[sum % strokes.length], stroke: strokes[sum % strokes.length],
}; };
}; };
export const getClientInitials = (userName?: string | null) => { export const getClientInitials = (username?: string | null) => {
if (!userName) { if (!username) {
return "?"; return "?";
} }
return userName.trim()[0].toUpperCase(); const names = username.trim().split(" ");
if (names.length < 2) {
return names[0].substring(0, 2).toUpperCase();
}
const firstName = names[0];
const lastName = names[names.length - 1];
return (firstName[0] + lastName[0]).toUpperCase();
}; };

View File

@@ -1,27 +0,0 @@
import { parseClipboard } from "./clipboard";
describe("Test parseClipboard", () => {
it("should parse valid json correctly", async () => {
let text = "123";
let clipboardData = await parseClipboard({
//@ts-ignore
clipboardData: {
getData: () => text,
},
});
expect(clipboardData.text).toBe(text);
text = "[123]";
clipboardData = await parseClipboard({
//@ts-ignore
clipboardData: {
getData: () => text,
},
});
expect(clipboardData.text).toBe(text);
});
});

View File

@@ -109,16 +109,16 @@ const parsePotentialSpreadsheet = (
* Retrieves content from system clipboard (either from ClipboardEvent or * Retrieves content from system clipboard (either from ClipboardEvent or
* via async clipboard API if supported) * via async clipboard API if supported)
*/ */
export const getSystemClipboard = async ( const getSystemClipboard = async (
event: ClipboardEvent | null, event: ClipboardEvent | null,
): Promise<string> => { ): Promise<string> => {
try { try {
const text = event const text = event
? event.clipboardData?.getData("text/plain") ? event.clipboardData?.getData("text/plain").trim()
: probablySupportsClipboardReadText && : probablySupportsClipboardReadText &&
(await navigator.clipboard.readText()); (await navigator.clipboard.readText());
return (text || "").trim(); return text || "";
} catch { } catch {
return ""; return "";
} }
@@ -129,25 +129,19 @@ export const getSystemClipboard = async (
*/ */
export const parseClipboard = async ( export const parseClipboard = async (
event: ClipboardEvent | null, event: ClipboardEvent | null,
isPlainPaste = false,
): Promise<ClipboardData> => { ): Promise<ClipboardData> => {
const systemClipboard = await getSystemClipboard(event); const systemClipboard = await getSystemClipboard(event);
// if system clipboard empty, couldn't be resolved, or contains previously // if system clipboard empty, couldn't be resolved, or contains previously
// copied excalidraw scene as SVG, fall back to previously copied excalidraw // copied excalidraw scene as SVG, fall back to previously copied excalidraw
// elements // elements
if ( if (!systemClipboard || systemClipboard.includes(SVG_EXPORT_TAG)) {
!systemClipboard ||
(!isPlainPaste && systemClipboard.includes(SVG_EXPORT_TAG))
) {
return getAppClipboard(); return getAppClipboard();
} }
// if system clipboard contains spreadsheet, use it even though it's // if system clipboard contains spreadsheet, use it even though it's
// technically possible it's staler than in-app clipboard // technically possible it's staler than in-app clipboard
const spreadsheetResult = const spreadsheetResult = parsePotentialSpreadsheet(systemClipboard);
!isPlainPaste && parsePotentialSpreadsheet(systemClipboard);
if (spreadsheetResult) { if (spreadsheetResult) {
return spreadsheetResult; return spreadsheetResult;
} }
@@ -160,23 +154,17 @@ export const parseClipboard = async (
return { return {
elements: systemClipboardData.elements, elements: systemClipboardData.elements,
files: systemClipboardData.files, files: systemClipboardData.files,
text: isPlainPaste
? JSON.stringify(systemClipboardData.elements, null, 2)
: undefined,
}; };
} }
} catch (e) {} return appClipboardData;
// system clipboard doesn't contain excalidraw elements → return plaintext } catch {
// unless we set a flag to prefer in-app clipboard because browser didn't // system clipboard doesn't contain excalidraw elements → return plaintext
// support storing to system clipboard on copy // unless we set a flag to prefer in-app clipboard because browser didn't
return PREFER_APP_CLIPBOARD && appClipboardData.elements // support storing to system clipboard on copy
? { return PREFER_APP_CLIPBOARD && appClipboardData.elements
...appClipboardData, ? appClipboardData
text: isPlainPaste : { text: systemClipboard };
? JSON.stringify(appClipboardData.elements, null, 2) }
: undefined,
}
: { text: systemClipboard };
}; };
export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => { export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => {

View File

@@ -1,92 +0,0 @@
.zoom-actions,
.undo-redo-buttons {
background-color: var(--island-bg-color);
border-radius: var(--border-radius-lg);
}
.zoom-button,
.undo-redo-buttons button {
border: 1px solid var(--default-border-color) !important;
border-radius: 0 !important;
background-color: transparent !important;
font-size: 0.875rem !important;
width: var(--lg-button-size);
height: var(--lg-button-size);
svg {
width: var(--lg-icon-size) !important;
height: var(--lg-icon-size) !important;
}
.ToolIcon__icon {
width: 100%;
height: 100%;
}
}
.reset-zoom-button {
border-left: 0 !important;
border-right: 0 !important;
padding: 0 0.625rem !important;
width: 3.75rem !important;
justify-content: center;
color: var(--text-primary-color);
}
.zoom-out-button {
border-top-left-radius: var(--border-radius-lg) !important;
border-bottom-left-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
}
.zoom-in-button {
border-top-right-radius: var(--border-radius-lg) !important;
border-bottom-right-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
}
.undo-redo-buttons {
.undo-button-container button {
border-top-left-radius: var(--border-radius-lg) !important;
border-bottom-left-radius: var(--border-radius-lg) !important;
border-right: 0 !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
}
.redo-button-container button {
border-top-right-radius: var(--border-radius-lg) !important;
border-bottom-right-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
}
}

View File

@@ -5,7 +5,7 @@ import { ExcalidrawElement, PointerType } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "../components/App"; import { useDevice } from "../components/App";
import { import {
canChangeRoundness, canChangeSharpness,
canHaveArrowheads, canHaveArrowheads,
getTargetElements, getTargetElements,
hasBackground, hasBackground,
@@ -25,12 +25,9 @@ import Stack from "./Stack";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import { hasStrokeColor } from "../scene/comparisons"; import { hasStrokeColor } from "../scene/comparisons";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { hasBoundTextElement } from "../element/typeChecks"; import { hasBoundTextElement, isBoundToContainer } from "../element/typeChecks";
import clsx from "clsx"; import clsx from "clsx";
import { actionToggleZenMode } from "../actions"; import { actionToggleZenMode } from "../actions";
import "./Actions.scss";
import { Tooltip } from "./Tooltip";
import { shouldAllowVerticalAlign } from "../element/textElement";
export const SelectedShapeActions = ({ export const SelectedShapeActions = ({
appState, appState,
@@ -82,16 +79,12 @@ export const SelectedShapeActions = ({
return ( return (
<div className="panelColumn"> <div className="panelColumn">
<div> {((hasStrokeColor(appState.activeTool.type) &&
{((hasStrokeColor(appState.activeTool.type) && appState.activeTool.type !== "image" &&
appState.activeTool.type !== "image" && commonSelectedType !== "image") ||
commonSelectedType !== "image") || targetElements.some((element) => hasStrokeColor(element.type))) &&
targetElements.some((element) => hasStrokeColor(element.type))) && renderAction("changeStrokeColor")}
renderAction("changeStrokeColor")} {showChangeBackgroundIcons && renderAction("changeBackgroundColor")}
</div>
{showChangeBackgroundIcons && (
<div>{renderAction("changeBackgroundColor")}</div>
)}
{showFillIcons && renderAction("changeFillStyle")} {showFillIcons && renderAction("changeFillStyle")}
{(hasStrokeWidth(appState.activeTool.type) || {(hasStrokeWidth(appState.activeTool.type) ||
@@ -110,9 +103,9 @@ export const SelectedShapeActions = ({
</> </>
)} )}
{(canChangeRoundness(appState.activeTool.type) || {(canChangeSharpness(appState.activeTool.type) ||
targetElements.some((element) => canChangeRoundness(element.type))) && ( targetElements.some((element) => canChangeSharpness(element.type))) && (
<>{renderAction("changeRoundness")}</> <>{renderAction("changeSharpness")}</>
)} )}
{(hasText(appState.activeTool.type) || {(hasText(appState.activeTool.type) ||
@@ -126,8 +119,10 @@ export const SelectedShapeActions = ({
</> </>
)} )}
{shouldAllowVerticalAlign(targetElements) && {targetElements.some(
renderAction("changeVerticalAlign")} (element) =>
hasBoundTextElement(element) || isBoundToContainer(element),
) && renderAction("changeVerticalAlign")}
{(canHaveArrowheads(appState.activeTool.type) || {(canHaveArrowheads(appState.activeTool.type) ||
targetElements.some((element) => canHaveArrowheads(element.type))) && ( targetElements.some((element) => canHaveArrowheads(element.type))) && (
<>{renderAction("changeArrowhead")}</> <>{renderAction("changeArrowhead")}</>
@@ -168,16 +163,7 @@ export const SelectedShapeActions = ({
)} )}
{targetElements.length > 2 && {targetElements.length > 2 &&
renderAction("distributeHorizontally")} renderAction("distributeHorizontally")}
{/* breaks the row ˇˇ */} <div className="iconRow">
<div style={{ flexBasis: "100%", height: 0 }} />
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: ".5rem",
marginTop: "-0.5rem",
}}
>
{renderAction("alignTop")} {renderAction("alignTop")}
{renderAction("alignVerticallyCentered")} {renderAction("alignVerticallyCentered")}
{renderAction("alignBottom")} {renderAction("alignBottom")}
@@ -217,25 +203,25 @@ export const ShapesSwitcher = ({
appState: AppState; appState: AppState;
}) => ( }) => (
<> <>
{SHAPES.map(({ value, icon, key, numericKey, fillable }, index) => { {SHAPES.map(({ value, icon, key }, index) => {
const label = t(`toolBar.${value}`); const label = t(`toolBar.${value}`);
const letter = key && (typeof key === "string" ? key : key[0]); const letter = key && (typeof key === "string" ? key : key[0]);
const shortcut = letter const shortcut = letter
? `${capitalizeString(letter)} ${t("helpDialog.or")} ${numericKey}` ? `${capitalizeString(letter)} ${t("helpDialog.or")} ${index + 1}`
: `${numericKey}`; : `${index + 1}`;
return ( return (
<ToolButton <ToolButton
className={clsx("Shape", { fillable })} className="Shape"
key={value} key={value}
type="radio" type="radio"
icon={icon} icon={icon}
checked={activeTool.type === value} checked={activeTool.type === value}
name="editor-current-shape" name="editor-current-shape"
title={`${capitalizeString(label)}${shortcut}`} title={`${capitalizeString(label)}${shortcut}`}
keyBindingLabel={numericKey} keyBindingLabel={`${index + 1}`}
aria-label={capitalizeString(label)} aria-label={capitalizeString(label)}
aria-keyshortcuts={shortcut} aria-keyshortcuts={shortcut}
data-testid={`toolbar-${value}`} data-testid={value}
onPointerDown={({ pointerType }) => { onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") { if (!appState.penDetected && pointerType === "pen") {
setAppState({ setAppState({
@@ -277,11 +263,11 @@ export const ZoomActions = ({
renderAction: ActionManager["renderAction"]; renderAction: ActionManager["renderAction"];
zoom: Zoom; zoom: Zoom;
}) => ( }) => (
<Stack.Col gap={1} className="zoom-actions"> <Stack.Col gap={1}>
<Stack.Row align="center"> <Stack.Row gap={1} align="center">
{renderAction("zoomOut")} {renderAction("zoomOut")}
{renderAction("resetZoom")}
{renderAction("zoomIn")} {renderAction("zoomIn")}
{renderAction("resetZoom")}
</Stack.Row> </Stack.Row>
</Stack.Col> </Stack.Col>
); );
@@ -294,12 +280,8 @@ export const UndoRedoActions = ({
className?: string; className?: string;
}) => ( }) => (
<div className={`undo-redo-buttons ${className}`}> <div className={`undo-redo-buttons ${className}`}>
<div className="undo-button-container"> {renderAction("undo", { size: "small" })}
<Tooltip label={t("buttons.undo")}>{renderAction("undo")}</Tooltip> {renderAction("redo", { size: "small" })}
</div>
<div className="redo-button-container">
<Tooltip label={t("buttons.redo")}> {renderAction("redo")}</Tooltip>
</div>
</div> </div>
); );

View File

@@ -1,11 +1,9 @@
// TODO barnabasmolnar/editor-redesign import Stack from "../components/Stack";
// this icon is not great import { ToolButton } from "../components/ToolButton";
import { getShortcutFromShortcutName } from "../actions/shortcuts"; import { save, file } from "../components/icons";
import { save } from "../components/icons";
import { t } from "../i18n"; import { t } from "../i18n";
import "./ActiveFile.scss"; import "./ActiveFile.scss";
import MenuItem from "./MenuItem";
type ActiveFileProps = { type ActiveFileProps = {
fileName?: string; fileName?: string;
@@ -13,11 +11,18 @@ type ActiveFileProps = {
}; };
export const ActiveFile = ({ fileName, onSave }: ActiveFileProps) => ( export const ActiveFile = ({ fileName, onSave }: ActiveFileProps) => (
<MenuItem <Stack.Row className="ActiveFile" gap={1} align="center">
label={`${t("buttons.save")}`} <span className="ActiveFile__fileName">
shortcut={getShortcutFromShortcutName("saveScene")} {file}
dataTestId="save-button" <span>{fileName}</span>
onClick={onSave} </span>
icon={save} <ToolButton
/> type="icon"
icon={save}
title={t("buttons.save")}
aria-label={t("buttons.save")}
onClick={onSave}
data-testid="save-button"
/>
</Stack.Row>
); );

File diff suppressed because it is too large Load Diff

View File

@@ -2,35 +2,21 @@
.excalidraw { .excalidraw {
.Avatar { .Avatar {
width: 1.25rem; width: 2.5rem;
height: 1.25rem; height: 2.5rem;
position: relative; border-radius: 1.25rem;
border-radius: 100%;
outline-offset: 2px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
color: $oc-white; color: $oc-white;
cursor: pointer; cursor: pointer;
font-size: 0.625rem; font-size: 0.8rem;
font-weight: 500; font-weight: 500;
line-height: 1;
&-img { &-img {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 100%; border-radius: 100%;
} }
&::before {
content: "";
position: absolute;
top: -3px;
right: -3px;
bottom: -3px;
left: -3px;
border: 1px solid var(--avatar-border-color);
border-radius: 100%;
}
} }
} }

View File

@@ -11,11 +11,13 @@ type AvatarProps = {
src?: string; src?: string;
}; };
export const Avatar = ({ color, onClick, name, src }: AvatarProps) => { export const Avatar = ({ color, border, onClick, name, src }: AvatarProps) => {
const shortName = getClientInitials(name); const shortName = getClientInitials(name);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const loadImg = !error && src; const loadImg = !error && src;
const style = loadImg ? undefined : { background: color }; const style = loadImg
? undefined
: { background: color, border: `1px solid ${border}` };
return ( return (
<div className="Avatar" style={style} onClick={onClick}> <div className="Avatar" style={style} onClick={onClick}>
{loadImg ? ( {loadImg ? (

View File

@@ -0,0 +1,20 @@
import React from "react";
import { ActionManager } from "../actions/manager";
import { AppState } from "../types";
export const BackgroundPickerAndDarkModeToggle = ({
appState,
setAppState,
actionManager,
showThemeBtn,
}: {
actionManager: ActionManager;
appState: AppState;
setAppState: React.Component<any, AppState>["setState"];
showThemeBtn: boolean;
}) => (
<div style={{ display: "flex" }}>
{actionManager.renderAction("changeViewBackgroundColor")}
{showThemeBtn && actionManager.renderAction("toggleTheme")}
</div>
);

View File

@@ -64,8 +64,6 @@
color: #{$oc-blue-7}; color: #{$oc-blue-7};
border: 0;
&:focus { &:focus {
box-shadow: 0 0 0 3px #{$oc-blue-7}; box-shadow: 0 0 0 3px #{$oc-blue-7};
} }

View File

@@ -1,9 +1,10 @@
import { useState } from "react"; import { useState } from "react";
import { t } from "../i18n"; import { t } from "../i18n";
import { TrashIcon } from "./icons"; import { useDevice } from "./App";
import { trash } from "./icons";
import { ToolButton } from "./ToolButton";
import ConfirmDialog from "./ConfirmDialog"; import ConfirmDialog from "./ConfirmDialog";
import MenuItem from "./MenuItem";
const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => { const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => {
const [showDialog, setShowDialog] = useState(false); const [showDialog, setShowDialog] = useState(false);
@@ -13,11 +14,14 @@ const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => {
return ( return (
<> <>
<MenuItem <ToolButton
label={t("buttons.clearReset")} type="button"
icon={TrashIcon} icon={trash}
title={t("buttons.clearReset")}
aria-label={t("buttons.clearReset")}
showAriaLabel={useDevice().isMobile}
onClick={toggleDialog} onClick={toggleDialog}
dataTestId="clear-canvas-button" data-testid="clear-canvas-button"
/> />
{showDialog && ( {showDialog && (

View File

@@ -1,51 +1,6 @@
@import "../css/variables.module"; @import "../css/variables.module";
.excalidraw { .excalidraw {
.collab-button {
@include outlineButtonStyles;
width: var(--lg-button-size);
height: var(--lg-button-size);
svg {
width: var(--lg-icon-size);
height: var(--lg-icon-size);
}
background-color: var(--color-primary);
border-color: var(--color-primary);
color: white;
flex-shrink: 0;
&:hover {
background-color: var(--color-primary-darker);
border-color: var(--color-primary-darker);
}
&:active {
background-color: var(--color-primary-darker);
}
&.active {
background-color: #0fb884;
border-color: #0fb884;
svg {
color: #fff;
}
&:hover,
&:active {
background-color: #0fb884;
border-color: #0fb884;
}
}
}
&.theme--dark {
.collab-button {
color: var(--color-gray-90);
}
}
.CollabButton.is-collaborating { .CollabButton.is-collaborating {
background-color: var(--button-special-active-bg-color); background-color: var(--button-special-active-bg-color);
@@ -69,9 +24,9 @@
bottom: -5px; bottom: -5px;
padding: 3px; padding: 3px;
border-radius: 50%; border-radius: 50%;
background-color: $oc-green-2; background-color: $oc-green-6;
color: $oc-green-9; color: $oc-white;
font-size: 0.6rem; font-size: 0.6em;
font-family: "Cascadia"; font-family: "Cascadia";
} }
} }

View File

@@ -1,47 +1,37 @@
import clsx from "clsx";
import { ToolButton } from "./ToolButton";
import { t } from "../i18n"; import { t } from "../i18n";
import { UsersIcon } from "./icons"; import { useDevice } from "../components/App";
import { users } from "./icons";
import "./CollabButton.scss"; import "./CollabButton.scss";
import MenuItem from "./MenuItem";
import clsx from "clsx";
const CollabButton = ({ const CollabButton = ({
isCollaborating, isCollaborating,
collaboratorCount, collaboratorCount,
onClick, onClick,
isInHamburgerMenu = true,
}: { }: {
isCollaborating: boolean; isCollaborating: boolean;
collaboratorCount: number; collaboratorCount: number;
onClick: () => void; onClick: () => void;
isInHamburgerMenu?: boolean;
}) => { }) => {
return ( return (
<> <>
{isInHamburgerMenu ? ( <ToolButton
<MenuItem className={clsx("CollabButton", {
label={t("labels.liveCollaboration")} "is-collaborating": isCollaborating,
dataTestId="collab-button" })}
icon={UsersIcon} onClick={onClick}
onClick={onClick} icon={users}
isCollaborating={isCollaborating} type="button"
/> title={t("labels.liveCollaboration")}
) : ( aria-label={t("labels.liveCollaboration")}
<button showAriaLabel={useDevice().isMobile}
className={clsx("collab-button", { active: isCollaborating })} >
type="button" {isCollaborating && (
onClick={onClick} <div className="CollabButton-collaborators">{collaboratorCount}</div>
style={{ position: "relative" }} )}
title={t("labels.liveCollaboration")} </ToolButton>
>
{UsersIcon}
{collaboratorCount > 0 && (
<div className="CollabButton-collaborators">
{collaboratorCount}
</div>
)}
</button>
)}
</> </>
); );
}; };

View File

@@ -21,23 +21,6 @@
display: grid; display: grid;
grid-template-columns: auto 1fr; grid-template-columns: auto 1fr;
align-items: center; align-items: center;
column-gap: 0.5rem;
}
.color-picker-control-container + .popover {
position: static;
}
.color-picker-popover-container {
margin-top: -0.25rem;
:root[dir="ltr"] & {
margin-left: 0.5rem;
}
:root[dir="rtl"] & {
margin-left: -3rem;
}
} }
.color-picker-triangle { .color-picker-triangle {
@@ -47,29 +30,20 @@
border-width: 0 9px 10px; border-width: 0 9px 10px;
border-color: transparent transparent var(--popup-bg-color); border-color: transparent transparent var(--popup-bg-color);
position: absolute; position: absolute;
top: 10px; top: -10px;
:root[dir="ltr"] & { :root[dir="ltr"] & {
transform: rotate(270deg); left: 12px;
left: -14px;
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
transform: rotate(90deg); right: 12px;
right: -14px;
} }
} }
.color-picker-triangle-shadow { .color-picker-triangle-shadow {
border-color: transparent transparent transparentize($oc-black, 0.9); border-color: transparent transparent transparentize($oc-black, 0.9);
top: -11px;
:root[dir="ltr"] & {
left: -14px;
}
:root[dir="rtl"] & {
right: -16px;
}
} }
.color-picker-content--default { .color-picker-content--default {
@@ -145,21 +119,16 @@
} }
.color-picker-hash { .color-picker-hash {
height: var(--default-button-size); background: var(--input-border-color);
flex-shrink: 0; height: 1.875rem;
padding: 0.5rem 0.5rem 0.5rem 0.75rem; width: 1.875rem;
border: 1px solid var(--default-border-color);
border-right: 0;
box-sizing: border-box;
:root[dir="ltr"] & { :root[dir="ltr"] & {
border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg); border-radius: 4px 0 0 4px;
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0; border-radius: 0 4px 4px 0;
border-right: 1px solid var(--default-border-color);
border-left: 0;
} }
color: var(--input-label-color); color: var(--input-label-color);
@@ -169,64 +138,81 @@
position: relative; position: relative;
} }
.color-input-container { .color-input-container:focus-within .color-picker-hash {
display: flex; box-shadow: 0 0 0 2px var(--focus-highlight-color);
&:focus-within {
box-shadow: 0 0 0 1px var(--color-primary-darkest);
border-radius: var(--border-radius-lg);
}
} }
.color-picker-input { .color-input-container:focus-within .color-picker-hash::before,
box-sizing: border-box; .color-input-container:focus-within .color-picker-hash::after {
width: 100%; content: "";
margin: 0; width: 1px;
font-size: 0.875rem; height: 100%;
background-color: transparent; position: absolute;
color: var(--text-primary-color); top: 0;
border: 0; }
outline: none;
height: var(--default-button-size); .color-input-container:focus-within .color-picker-hash::before {
border: 1px solid var(--default-border-color); background: var(--input-border-color);
border-left: 0;
letter-spacing: 0.4px;
:root[dir="ltr"] & { :root[dir="ltr"] & {
border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0; right: -1px;
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg); left: -1px;
border-left: 1px solid var(--default-border-color);
border-right: 0;
}
padding: 0.5rem;
padding-left: 0.25rem;
appearance: none;
&:focus-visible {
box-shadow: none;
} }
} }
.color-picker-label-swatch-container { .color-input-container:focus-within .color-picker-hash::after {
border: 1px solid var(--default-border-color); background: var(--input-bg-color);
border-radius: var(--border-radius-lg);
width: var(--default-button-size); :root[dir="ltr"] & {
height: var(--default-button-size); right: -2px;
box-sizing: border-box; }
overflow: hidden;
:root[dir="rtl"] & {
left: -2px;
}
}
.color-input-container {
display: flex;
}
.color-picker-input {
width: 11ch; /* length of `transparent` */
margin: 0;
font-size: 1rem;
background-color: var(--input-bg-color);
color: var(--text-primary-color);
border: 0;
outline: none;
height: 1.75em;
box-shadow: var(--input-border-color) 0 0 0 1px inset;
:root[dir="ltr"] & {
border-radius: 0 4px 4px 0;
}
:root[dir="rtl"] & {
border-radius: 4px 0 0 4px;
}
float: left;
padding: 1px;
padding-inline-start: 0.5em;
appearance: none;
} }
.color-picker-label-swatch { .color-picker-label-swatch {
@include outlineButtonStyles; height: 1.875rem;
background-color: var(--swatch-color) !important; width: 1.875rem;
overflow: hidden; margin-inline-end: 0.25rem;
border: 1px solid $oc-gray-3;
position: relative; position: relative;
overflow: hidden;
background-color: transparent !important;
filter: var(--theme-filter); filter: var(--theme-filter);
border: 0 !important;
&:after { &:after {
content: ""; content: "";

View File

@@ -66,13 +66,10 @@ const getColor = (color: string): string | null => {
return color; return color;
} }
// testing for `#` first fixes a bug on Electron (more specfically, an return isValidColor(color)
// Obsidian popout window), where a hex color without `#` is (incorrectly)
// considered valid
return isValidColor(`#${color}`)
? `#${color}`
: isValidColor(color)
? color ? color
: isValidColor(`#${color}`)
? `#${color}`
: null; : null;
}; };
@@ -368,20 +365,17 @@ export const ColorPicker = ({
appState: AppState; appState: AppState;
}) => { }) => {
const pickerButton = React.useRef<HTMLButtonElement>(null); const pickerButton = React.useRef<HTMLButtonElement>(null);
const coords = pickerButton.current?.getBoundingClientRect();
return ( return (
<div> <div>
<div className="color-picker-control-container"> <div className="color-picker-control-container">
<div className="color-picker-label-swatch-container"> <button
<button className="color-picker-label-swatch"
className="color-picker-label-swatch" aria-label={label}
aria-label={label} style={color ? { "--swatch-color": color } : undefined}
style={color ? { "--swatch-color": color } : undefined} onClick={() => setActive(!isActive)}
onClick={() => setActive(!isActive)} ref={pickerButton}
ref={pickerButton} />
/>
</div>
<ColorInput <ColorInput
color={color} color={color}
label={label} label={label}
@@ -392,37 +386,27 @@ export const ColorPicker = ({
</div> </div>
<React.Suspense fallback=""> <React.Suspense fallback="">
{isActive ? ( {isActive ? (
<div <Popover
className="color-picker-popover-container" onCloseRequest={(event) =>
style={{ event.target !== pickerButton.current && setActive(false)
position: "fixed", }
top: coords?.top,
left: coords?.right,
zIndex: 1,
}}
> >
<Popover <Picker
onCloseRequest={(event) => colors={colors[type]}
event.target !== pickerButton.current && setActive(false) color={color || null}
} onChange={(changedColor) => {
> onChange(changedColor);
<Picker }}
colors={colors[type]} onClose={() => {
color={color || null} setActive(false);
onChange={(changedColor) => { pickerButton.current?.focus();
onChange(changedColor); }}
}} label={label}
onClose={() => { showInput={false}
setActive(false); type={type}
pickerButton.current?.focus(); elements={elements}
}} />
label={label} </Popover>
showInput={false}
type={type}
elements={elements}
/>
</Popover>
</div>
) : null} ) : null}
</React.Suspense> </React.Suspense>
</div> </div>

View File

@@ -4,8 +4,34 @@
.confirm-dialog { .confirm-dialog {
&-buttons { &-buttons {
display: flex; display: flex;
column-gap: 0.5rem; 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 {
margin-left: 0.8rem;
padding: 0 0.5rem;
}
&__content {
font-size: 1rem;
}
&--confirm.ToolIcon_type_button {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-8;
}
.ToolIcon__icon {
color: $oc-white;
}
}
} }
} }

View File

@@ -1,11 +1,8 @@
import { t } from "../i18n"; import { t } from "../i18n";
import { Dialog, DialogProps } from "./Dialog"; import { Dialog, DialogProps } from "./Dialog";
import { ToolButton } from "./ToolButton";
import "./ConfirmDialog.scss"; import "./ConfirmDialog.scss";
import DialogActionButton from "./DialogActionButton";
import { isMenuOpenAtom } from "./App";
import { isDropdownOpenAtom } from "./App";
import { useSetAtom } from "jotai";
interface Props extends Omit<DialogProps, "onCloseRequest"> { interface Props extends Omit<DialogProps, "onCloseRequest"> {
onConfirm: () => void; onConfirm: () => void;
@@ -23,10 +20,6 @@ const ConfirmDialog = (props: Props) => {
className = "", className = "",
...rest ...rest
} = props; } = props;
const setIsMenuOpen = useSetAtom(isMenuOpenAtom);
const setIsDropdownOpen = useSetAtom(isDropdownOpenAtom);
return ( return (
<Dialog <Dialog
onCloseRequest={onCancel} onCloseRequest={onCancel}
@@ -36,22 +29,21 @@ const ConfirmDialog = (props: Props) => {
> >
{children} {children}
<div className="confirm-dialog-buttons"> <div className="confirm-dialog-buttons">
<DialogActionButton <ToolButton
type="button"
title={cancelText}
aria-label={cancelText}
label={cancelText} label={cancelText}
onClick={() => { onClick={onCancel}
setIsMenuOpen(false); className="confirm-dialog--cancel"
setIsDropdownOpen(false);
onCancel();
}}
/> />
<DialogActionButton <ToolButton
type="button"
title={confirmText}
aria-label={confirmText}
label={confirmText} label={confirmText}
onClick={() => { onClick={onConfirm}
setIsMenuOpen(false); className="confirm-dialog--confirm"
setIsDropdownOpen(false);
onConfirm();
}}
actionType="danger"
/> />
</div> </div>
</Dialog> </Dialog>

View File

@@ -19,7 +19,7 @@
color: var(--popup-text-color); color: var(--popup-text-color);
} }
.context-menu-item { .context-menu-option {
position: relative; position: relative;
width: 100%; width: 100%;
min-width: 9.5rem; min-width: 9.5rem;
@@ -43,16 +43,16 @@
} }
&.dangerous { &.dangerous {
.context-menu-item__label { .context-menu-option__label {
color: $oc-red-7; color: $oc-red-7;
} }
} }
.context-menu-item__label { .context-menu-option__label {
justify-self: start; justify-self: start;
margin-inline-end: 20px; margin-inline-end: 20px;
} }
.context-menu-item__shortcut { .context-menu-option__shortcut {
justify-self: end; justify-self: end;
opacity: 0.6; opacity: 0.6;
font-family: inherit; font-family: inherit;
@@ -60,37 +60,37 @@
} }
} }
.context-menu-item:hover { .context-menu-option:hover {
color: var(--popup-bg-color); color: var(--popup-bg-color);
background-color: var(--select-highlight-color); background-color: var(--select-highlight-color);
&.dangerous { &.dangerous {
.context-menu-item__label { .context-menu-option__label {
color: var(--popup-bg-color); color: var(--popup-bg-color);
} }
background-color: $oc-red-6; background-color: $oc-red-6;
} }
} }
.context-menu-item:focus { .context-menu-option:focus {
z-index: 1; z-index: 1;
} }
@include isMobile { @include isMobile {
.context-menu-item { .context-menu-option {
display: block; display: block;
.context-menu-item__label { .context-menu-option__label {
margin-inline-end: 0; margin-inline-end: 0;
} }
.context-menu-item__shortcut { .context-menu-option__shortcut {
display: none; display: none;
} }
} }
} }
.context-menu-item-separator { .context-menu-option-separator {
border: none; border: none;
border-top: 1px solid $oc-gray-5; border-top: 1px solid $oc-gray-5;
} }

View File

@@ -1,3 +1,4 @@
import { render, unmountComponentAtNode } from "react-dom";
import clsx from "clsx"; import clsx from "clsx";
import { Popover } from "./Popover"; import { Popover } from "./Popover";
import { t } from "../i18n"; import { t } from "../i18n";
@@ -9,116 +10,140 @@ import {
} from "../actions/shortcuts"; } from "../actions/shortcuts";
import { Action } from "../actions/types"; import { Action } from "../actions/types";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
import { import { AppState } from "../types";
useExcalidrawAppState, import { NonDeletedExcalidrawElement } from "../element/types";
useExcalidrawElements,
useExcalidrawSetAppState,
} from "./App";
import React from "react";
export type ContextMenuItem = typeof CONTEXT_MENU_SEPARATOR | Action; export type ContextMenuOption = "separator" | Action;
export type ContextMenuItems = (ContextMenuItem | false | null | undefined)[];
type ContextMenuProps = { type ContextMenuProps = {
actionManager: ActionManager; options: ContextMenuOption[];
items: ContextMenuItems; onCloseRequest?(): void;
top: number; top: number;
left: number; left: number;
actionManager: ActionManager;
appState: Readonly<AppState>;
elements: readonly NonDeletedExcalidrawElement[];
}; };
export const CONTEXT_MENU_SEPARATOR = "separator"; const ContextMenu = ({
options,
export const ContextMenu = React.memo( onCloseRequest,
({ actionManager, items, top, left }: ContextMenuProps) => { top,
const appState = useExcalidrawAppState(); left,
const setAppState = useExcalidrawSetAppState(); actionManager,
const elements = useExcalidrawElements(); appState,
elements,
const filteredItems = items.reduce((acc: ContextMenuItem[], item) => { }: ContextMenuProps) => {
if ( return (
item && <Popover
(item === CONTEXT_MENU_SEPARATOR || onCloseRequest={onCloseRequest}
!item.contextItemPredicate || top={top}
item.contextItemPredicate( left={left}
elements, fitInViewport={true}
appState, offsetLeft={appState.offsetLeft}
actionManager.app.props, offsetTop={appState.offsetTop}
actionManager.app, viewportWidth={appState.width}
)) viewportHeight={appState.height}
) { >
acc.push(item); <ul
} className="context-menu"
return acc; onContextMenu={(event) => event.preventDefault()}
}, []);
return (
<Popover
onCloseRequest={() => setAppState({ contextMenu: null })}
top={top}
left={left}
fitInViewport={true}
offsetLeft={appState.offsetLeft}
offsetTop={appState.offsetTop}
viewportWidth={appState.width}
viewportHeight={appState.height}
> >
<ul {options.map((option, idx) => {
className="context-menu" if (option === "separator") {
onContextMenu={(event) => event.preventDefault()} return <hr key={idx} className="context-menu-option-separator" />;
> }
{filteredItems.map((item, idx) => {
if (item === CONTEXT_MENU_SEPARATOR) {
if (
!filteredItems[idx - 1] ||
filteredItems[idx - 1] === CONTEXT_MENU_SEPARATOR
) {
return null;
}
return <hr key={idx} className="context-menu-item-separator" />;
}
const actionName = item.name; const actionName = option.name;
let label = ""; let label = "";
if (item.contextItemLabel) { if (option.contextItemLabel) {
if (typeof item.contextItemLabel === "function") { if (typeof option.contextItemLabel === "function") {
label = t(item.contextItemLabel(elements, appState)); label = t(option.contextItemLabel(elements, appState));
} else { } else {
label = t(item.contextItemLabel); label = t(option.contextItemLabel);
}
} }
}
return ( return (
<li <li key={idx} data-testid={actionName} onClick={onCloseRequest}>
key={idx} <button
data-testid={actionName} className={clsx("context-menu-option", {
onClick={() => { dangerous: actionName === "deleteSelectedElements",
// we need update state before executing the action in case checkmark: option.checked?.(appState),
// the action uses the appState it's being passed (that still })}
// contains a defined contextMenu) to return the next state. onClick={() =>
setAppState({ contextMenu: null }, () => { actionManager.executeAction(option, "contextMenu")
actionManager.executeAction(item, "contextMenu"); }
});
}}
> >
<button <div className="context-menu-option__label">{label}</div>
className={clsx("context-menu-item", { <kbd className="context-menu-option__shortcut">
dangerous: actionName === "deleteSelectedElements", {actionName
checkmark: item.checked?.(appState), ? getShortcutFromShortcutName(actionName as ShortcutName)
})} : ""}
> </kbd>
<div className="context-menu-item__label">{label}</div> </button>
<kbd className="context-menu-item__shortcut"> </li>
{actionName );
? getShortcutFromShortcutName(actionName as ShortcutName) })}
: ""} </ul>
</kbd> </Popover>
</button> );
</li> };
);
})} const contextMenuNodeByContainer = new WeakMap<HTMLElement, HTMLDivElement>();
</ul>
</Popover> const getContextMenuNode = (container: HTMLElement): HTMLDivElement => {
); let contextMenuNode = contextMenuNodeByContainer.get(container);
if (contextMenuNode) {
return contextMenuNode;
}
contextMenuNode = document.createElement("div");
container
.querySelector(".excalidraw-contextMenuContainer")!
.appendChild(contextMenuNode);
contextMenuNodeByContainer.set(container, contextMenuNode);
return contextMenuNode;
};
type ContextMenuParams = {
options: (ContextMenuOption | false | null | undefined)[];
top: ContextMenuProps["top"];
left: ContextMenuProps["left"];
actionManager: ContextMenuProps["actionManager"];
appState: Readonly<AppState>;
container: HTMLElement;
elements: readonly NonDeletedExcalidrawElement[];
};
const handleClose = (container: HTMLElement) => {
const contextMenuNode = contextMenuNodeByContainer.get(container);
if (contextMenuNode) {
unmountComponentAtNode(contextMenuNode);
contextMenuNode.remove();
contextMenuNodeByContainer.delete(container);
}
};
export default {
push(params: ContextMenuParams) {
const options = Array.of<ContextMenuOption>();
params.options.forEach((option) => {
if (option) {
options.push(option);
}
});
if (options.length) {
render(
<ContextMenu
top={params.top}
left={params.left}
options={options}
onCloseRequest={() => handleClose(params.container)}
actionManager={params.actionManager}
appState={params.appState}
elements={params.elements}
/>,
getContextMenuNode(params.container),
);
}
}, },
); };

View File

@@ -7,11 +7,68 @@
} }
.Dialog__title { .Dialog__title {
display: grid;
align-items: center;
margin-top: 0;
grid-template-columns: 1fr calc(var(--space-factor) * 7);
grid-gap: var(--metric);
padding: calc(var(--space-factor) * 2);
text-align: center;
font-variant: small-caps;
font-size: 1.2em;
}
.Dialog__titleContent {
flex: 1;
}
.Dialog .Modal__close {
color: var(--icon-fill-color);
margin: 0; margin: 0;
text-align: left; }
font-size: 1.25rem;
border-bottom: 1px solid var(--dialog-border-color); .Dialog__content {
padding: 0 0 0.75rem; padding: 0 16px 16px;
margin-bottom: 1.5rem; }
@include isMobile {
.Dialog {
--metric: calc(var(--space-factor) * 4);
--inset-left: #{"max(var(--metric), var(--sal))"};
--inset-right: #{"max(var(--metric), var(--sar))"};
}
.Dialog__title {
grid-template-columns: calc(var(--space-factor) * 7) 1fr calc(
var(--space-factor) * 7
);
position: sticky;
top: 0;
padding: calc(var(--space-factor) * 2);
background: var(--island-bg-color);
font-size: 1.25em;
box-sizing: border-box;
border-bottom: 1px solid var(--button-gray-2);
z-index: 1;
}
.Dialog__titleContent {
text-align: center;
}
.Dialog .Island {
width: 100vw;
height: 100%;
box-sizing: border-box;
overflow-y: auto;
padding-left: #{"max(calc(var(--padding) * var(--space-factor)), var(--sal))"};
padding-right: #{"max(calc(var(--padding) * var(--space-factor)), var(--sar))"};
padding-bottom: #{"max(calc(var(--padding) * var(--space-factor)), var(--sab))"};
}
.Dialog .Modal__close {
order: -1;
}
} }
} }

View File

@@ -5,13 +5,11 @@ import { t } from "../i18n";
import { useExcalidrawContainer, useDevice } from "../components/App"; import { useExcalidrawContainer, useDevice } from "../components/App";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import "./Dialog.scss"; import "./Dialog.scss";
import { back, CloseIcon } from "./icons"; import { back, close } from "./icons";
import { Island } from "./Island"; import { Island } from "./Island";
import { Modal } from "./Modal"; import { Modal } from "./Modal";
import { AppState } from "../types"; import { AppState } from "../types";
import { queryFocusableElements } from "../utils"; import { queryFocusableElements } from "../utils";
import { isMenuOpenAtom, isDropdownOpenAtom } from "./App";
import { useSetAtom } from "jotai";
export interface DialogProps { export interface DialogProps {
children: React.ReactNode; children: React.ReactNode;
@@ -67,12 +65,7 @@ export const Dialog = (props: DialogProps) => {
return () => islandNode.removeEventListener("keydown", handleKeyDown); return () => islandNode.removeEventListener("keydown", handleKeyDown);
}, [islandNode, props.autofocus]); }, [islandNode, props.autofocus]);
const setIsMenuOpen = useSetAtom(isMenuOpenAtom);
const setIsDropdownOpen = useSetAtom(isDropdownOpenAtom);
const onClose = () => { const onClose = () => {
setIsMenuOpen(false);
setIsDropdownOpen(false);
(lastActiveElement as HTMLElement).focus(); (lastActiveElement as HTMLElement).focus();
props.onCloseRequest(); props.onCloseRequest();
}; };
@@ -95,7 +88,7 @@ export const Dialog = (props: DialogProps) => {
title={t("buttons.close")} title={t("buttons.close")}
aria-label={t("buttons.close")} aria-label={t("buttons.close")}
> >
{useDevice().isMobile ? back : CloseIcon} {useDevice().isMobile ? back : close}
</button> </button>
</h2> </h2>
<div className="Dialog__content">{props.children}</div> <div className="Dialog__content">{props.children}</div>

View File

@@ -1,47 +0,0 @@
.excalidraw {
.Dialog__action-button {
position: relative;
display: flex;
column-gap: 0.5rem;
align-items: center;
padding: 0.5rem 1.5rem;
border: 1px solid var(--default-border-color);
background-color: transparent;
height: 3rem;
border-radius: var(--border-radius-lg);
letter-spacing: 0.4px;
color: inherit;
font-family: inherit;
font-size: 0.875rem;
font-weight: 600;
user-select: none;
svg {
display: block;
width: 1rem;
height: 1rem;
}
&--danger {
background-color: var(--color-danger);
border-color: var(--color-danger);
color: #fff;
}
&--primary {
background-color: var(--color-primary);
border-color: var(--color-primary);
color: #fff;
}
}
&.theme--dark {
.Dialog__action-button--danger {
color: var(--color-gray-100);
}
.Dialog__action-button--primary {
color: var(--color-gray-100);
}
}
}

View File

@@ -1,46 +0,0 @@
import clsx from "clsx";
import { ReactNode } from "react";
import "./DialogActionButton.scss";
import Spinner from "./Spinner";
interface DialogActionButtonProps {
label: string;
children?: ReactNode;
actionType?: "primary" | "danger";
isLoading?: boolean;
}
const DialogActionButton = ({
label,
onClick,
className,
children,
actionType,
type = "button",
isLoading,
...rest
}: DialogActionButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
const cs = actionType ? `Dialog__action-button--${actionType}` : "";
return (
<button
className={clsx("Dialog__action-button", cs, className)}
type={type}
aria-label={label}
onClick={onClick}
{...rest}
>
{children && (
<div style={isLoading ? { visibility: "hidden" } : {}}>{children}</div>
)}
<div style={isLoading ? { visibility: "hidden" } : {}}>{label}</div>
{isLoading && (
<div style={{ position: "absolute", inset: 0 }}>
<Spinner />
</div>
)}
</button>
);
};
export default DialogActionButton;

View File

@@ -91,8 +91,6 @@
} }
button.ExportDialog-imageExportButton { button.ExportDialog-imageExportButton {
border: 0;
width: 5rem; width: 5rem;
height: 5rem; height: 5rem;
margin: 0 0.2em; margin: 0 0.2em;

View File

@@ -9,10 +9,9 @@
} }
.FixedSideContainer_side_top { .FixedSideContainer_side_top {
left: 1rem; left: var(--space-factor);
top: 1rem; top: var(--space-factor);
right: 1rem; right: var(--space-factor);
bottom: 1rem;
z-index: 2; z-index: 2;
} }

View File

@@ -1,37 +1,31 @@
import clsx from "clsx"; import clsx from "clsx";
import { ActionManager } from "../../actions/manager"; import { ActionManager } from "../actions/manager";
import { t } from "../../i18n"; import { AppState, ExcalidrawProps } from "../types";
import { AppState } from "../../types";
import { import {
ExitZenModeAction, ExitZenModeAction,
FinalizeAction, FinalizeAction,
UndoRedoActions, UndoRedoActions,
ZoomActions, ZoomActions,
} from "../Actions"; } from "./Actions";
import { useDevice } from "../App"; import { useDevice } from "./App";
import { WelcomeScreenHelpArrow } from "../icons"; import { Island } from "./Island";
import { Section } from "../Section"; import { Section } from "./Section";
import Stack from "../Stack"; import Stack from "./Stack";
import WelcomeScreenDecor from "../WelcomeScreenDecor";
import FooterCenter from "./FooterCenter";
const Footer = ({ const Footer = ({
appState, appState,
actionManager, actionManager,
renderCustomFooter,
showExitZenModeBtn, showExitZenModeBtn,
renderWelcomeScreen,
children,
}: { }: {
appState: AppState; appState: AppState;
actionManager: ActionManager; actionManager: ActionManager;
renderCustomFooter?: ExcalidrawProps["renderFooter"];
showExitZenModeBtn: boolean; showExitZenModeBtn: boolean;
renderWelcomeScreen: boolean;
children?: React.ReactNode;
}) => { }) => {
const device = useDevice(); const device = useDevice();
const showFinalize = const showFinalize =
!appState.viewModeEnabled && appState.multiElement && device.isTouchScreen; !appState.viewModeEnabled && appState.multiElement && device.isTouchScreen;
return ( return (
<footer <footer
role="contentinfo" role="contentinfo"
@@ -45,19 +39,31 @@ const Footer = ({
> >
<Stack.Col gap={2}> <Stack.Col gap={2}>
<Section heading="canvasActions"> <Section heading="canvasActions">
<ZoomActions <Island padding={1}>
renderAction={actionManager.renderAction} <ZoomActions
zoom={appState.zoom}
/>
{!appState.viewModeEnabled && (
<UndoRedoActions
renderAction={actionManager.renderAction} renderAction={actionManager.renderAction}
className={clsx("zen-mode-transition", { zoom={appState.zoom}
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
})}
/> />
</Island>
{!appState.viewModeEnabled && (
<>
<UndoRedoActions
renderAction={actionManager.renderAction}
className={clsx("zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
})}
/>
<div
className={clsx("eraser-buttons zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-left":
appState.zenModeEnabled,
})}
>
{actionManager.renderAction("eraser", { size: "small" })}
</div>
</>
)} )}
{showFinalize && ( {showFinalize && (
<FinalizeAction <FinalizeAction
@@ -71,24 +77,23 @@ const Footer = ({
</Section> </Section>
</Stack.Col> </Stack.Col>
</div> </div>
<FooterCenter>{children}</FooterCenter> <div
className={clsx(
"layer-ui__wrapper__footer-center zen-mode-transition",
{
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
},
)}
>
{renderCustomFooter?.(false, appState)}
</div>
<div <div
className={clsx("layer-ui__wrapper__footer-right zen-mode-transition", { className={clsx("layer-ui__wrapper__footer-right zen-mode-transition", {
"transition-right disable-pointerEvents": appState.zenModeEnabled, "transition-right disable-pointerEvents": appState.zenModeEnabled,
})} })}
> >
<div style={{ position: "relative" }}> {actionManager.renderAction("toggleShortcuts")}
<WelcomeScreenDecor
shouldRender={renderWelcomeScreen && !appState.isLoading}
>
<div className="virgil WelcomeScreen-decor WelcomeScreen-decor--help-pointer">
<div>{t("welcomeScreen.helpHints")}</div>
{WelcomeScreenHelpArrow}
</div>
</WelcomeScreenDecor>
{actionManager.renderAction("toggleShortcuts")}
</div>
</div> </div>
<ExitZenModeAction <ExitZenModeAction
actionManager={actionManager} actionManager={actionManager}
@@ -99,4 +104,3 @@ const Footer = ({
}; };
export default Footer; export default Footer;
Footer.displayName = "Footer";

View File

@@ -1,115 +1,56 @@
@import "../css/variables.module"; @import "../css/variables.module";
.excalidraw { .excalidraw {
.HelpDialog { .HelpDialog h3 {
.Modal__content { border-bottom: 1px solid var(--button-gray-2);
max-width: 960px; padding-bottom: 4px;
} }
h3 { .HelpDialog--island {
margin: 1.5rem 0; border: 1px solid var(--button-gray-2);
font-weight: bold; margin-bottom: 16px;
font-size: 1.125rem; }
}
&__header { .HelpDialog--island-title {
display: flex; margin: 0;
flex-wrap: wrap; padding: 4px;
gap: 0.75rem; background-color: var(--button-gray-1);
} text-align: center;
}
&__btn { .HelpDialog--shortcut {
display: flex; border-top: 1px solid var(--button-gray-2);
column-gap: 0.5rem; }
align-items: center;
border: 1px solid var(--default-border-color);
padding: 0.625rem 1rem;
border-radius: var(--border-radius-lg);
color: var(--text-primary-color);
font-weight: 600;
font-size: 0.75rem;
letter-spacing: 0.4px;
&:hover { .HelpDialog--key {
text-decoration: none; word-break: keep-all;
} border: 1px solid var(--button-gray-2);
} padding: 2px 8px;
margin: auto 4px;
background-color: var(--button-gray-1);
border-radius: 2px;
font-size: 0.8em;
min-height: 26px;
box-sizing: border-box;
display: flex;
align-items: center;
font-family: inherit;
}
&__link-icon { .HelpDialog--header {
line-height: 0; display: flex;
svg { flex-direction: row;
width: 1rem; justify-content: space-evenly;
height: 1rem; margin-bottom: 32px;
} padding-bottom: 16px;
} }
&__islands-container { .HelpDialog--btn {
display: grid; border: 1px solid var(--link-color);
@media screen and (min-width: 1024px) { padding: 8px 32px;
grid-template-columns: 1fr 1fr; border-radius: 4px;
} }
grid-column-gap: 1.5rem; .HelpDialog--btn:hover {
grid-row-gap: 2rem; text-decoration: none;
}
@media screen and (min-width: 1024px) {
&__island--tools {
grid-area: 1 / 1 / 2 / 2;
}
&__island--view {
grid-area: 2 / 1 / 3 / 2;
}
&__island--editor {
grid-area: 1 / 2 / 3 / 3;
}
}
&__island {
h4 {
font-size: 1rem;
font-weight: bold;
margin: 0;
margin-bottom: 0.625rem;
}
&-content {
border: 1px solid var(--dialog-border-color);
border-radius: var(--border-radius-lg);
}
}
&__shortcut {
border-bottom: 1px solid var(--dialog-border-color);
padding: 0.375rem 0.75rem;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.875rem;
column-gap: 0.5rem;
&:last-child {
border-bottom: none;
}
}
&__key-container {
display: flex;
align-items: center;
column-gap: 0.25rem;
flex-shrink: 0;
}
&__key {
display: flex;
box-sizing: border-box;
font-size: 0.625rem;
background-color: var(--color-primary-light);
border-radius: var(--border-radius-md);
padding: 0.5rem;
word-break: keep-all;
align-items: center;
font-family: inherit;
line-height: 1;
}
} }
} }

View File

@@ -1,39 +1,35 @@
import React from "react"; import React from "react";
import { t } from "../i18n"; import { t } from "../i18n";
import { isDarwin, isWindows, KEYS } from "../keys"; import { isDarwin, isWindows } from "../keys";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import "./HelpDialog.scss"; import "./HelpDialog.scss";
import { ExternalLinkIcon } from "./icons";
const Header = () => ( const Header = () => (
<div className="HelpDialog__header"> <div className="HelpDialog--header">
<a <a
className="HelpDialog__btn" className="HelpDialog--btn"
href="https://github.com/excalidraw/excalidraw#documentation" href="https://github.com/excalidraw/excalidraw#documentation"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.documentation")} {t("helpDialog.documentation")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
<a <a
className="HelpDialog__btn" className="HelpDialog--btn"
href="https://blog.excalidraw.com" href="https://blog.excalidraw.com"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.blog")} {t("helpDialog.blog")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
<a <a
className="HelpDialog__btn" className="HelpDialog--btn"
href="https://github.com/excalidraw/excalidraw/issues" href="https://github.com/excalidraw/excalidraw/issues"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.github")} {t("helpDialog.github")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
</div> </div>
); );
@@ -41,61 +37,88 @@ const Header = () => (
const Section = (props: { title: string; children: React.ReactNode }) => ( const Section = (props: { title: string; children: React.ReactNode }) => (
<> <>
<h3>{props.title}</h3> <h3>{props.title}</h3>
<div className="HelpDialog__islands-container">{props.children}</div> {props.children}
</> </>
); );
const Columns = (props: { children: React.ReactNode }) => (
<div
style={{
display: "flex",
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "space-between",
}}
>
{props.children}
</div>
);
const Column = (props: { children: React.ReactNode }) => (
<div style={{ width: "49%" }}>{props.children}</div>
);
const ShortcutIsland = (props: { const ShortcutIsland = (props: {
caption: string; caption: string;
children: React.ReactNode; children: React.ReactNode;
className?: string;
}) => ( }) => (
<div className={`HelpDialog__island ${props.className}`}> <div className="HelpDialog--island">
<h4 className="HelpDialog__island-title">{props.caption}</h4> <h3 className="HelpDialog--island-title">{props.caption}</h3>
<div className="HelpDialog__island-content">{props.children}</div> {props.children}
</div> </div>
); );
function* intersperse(as: JSX.Element[][], delim: string | null) { const Shortcut = (props: {
let first = true;
for (const x of as) {
if (!first) {
yield delim;
}
first = false;
yield x;
}
}
const Shortcut = ({
label,
shortcuts,
isOr = true,
}: {
label: string; label: string;
shortcuts: string[]; shortcuts: string[];
isOr?: boolean; isOr: boolean;
}) => { }) => {
const splitShortcutKeys = shortcuts.map((shortcut) => {
const keys = shortcut.endsWith("++")
? [...shortcut.slice(0, -2).split("+"), "+"]
: shortcut.split("+");
return keys.map((key) => <ShortcutKey key={key}>{key}</ShortcutKey>);
});
return ( return (
<div className="HelpDialog__shortcut"> <div className="HelpDialog--shortcut">
<div>{label}</div> <div
<div className="HelpDialog__key-container"> style={{
{[...intersperse(splitShortcutKeys, isOr ? t("helpDialog.or") : null)]} display: "flex",
margin: "0",
padding: "4px 8px",
alignItems: "center",
}}
>
<div
style={{
lineHeight: 1.4,
}}
>
{props.label}
</div>
<div
style={{
display: "flex",
flex: "0 0 auto",
justifyContent: "flex-end",
marginInlineStart: "auto",
minWidth: "30%",
}}
>
{props.shortcuts.map((shortcut, index) => (
<React.Fragment key={index}>
<ShortcutKey>{shortcut}</ShortcutKey>
{props.isOr &&
index !== props.shortcuts.length - 1 &&
t("helpDialog.or")}
</React.Fragment>
))}
</div>
</div> </div>
</div> </div>
); );
}; };
Shortcut.defaultProps = {
isOr: true,
};
const ShortcutKey = (props: { children: React.ReactNode }) => ( const ShortcutKey = (props: { children: React.ReactNode }) => (
<kbd className="HelpDialog__key" {...props} /> <kbd className="HelpDialog--key" {...props} />
); );
export const HelpDialog = ({ onClose }: { onClose?: () => void }) => { export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
@@ -114,303 +137,286 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
> >
<Header /> <Header />
<Section title={t("helpDialog.shortcuts")}> <Section title={t("helpDialog.shortcuts")}>
<ShortcutIsland <Columns>
className="HelpDialog__island--tools" <Column>
caption={t("helpDialog.tools")} <ShortcutIsland caption={t("helpDialog.tools")}>
> <Shortcut
<Shortcut label={t("toolBar.selection")}
label={t("toolBar.selection")} shortcuts={["V", "1"]}
shortcuts={[KEYS.V, KEYS["1"]]} />
/> <Shortcut
<Shortcut label={t("toolBar.rectangle")}
label={t("toolBar.rectangle")} shortcuts={["R", "2"]}
shortcuts={[KEYS.R, KEYS["2"]]} />
/> <Shortcut label={t("toolBar.diamond")} shortcuts={["D", "3"]} />
<Shortcut <Shortcut label={t("toolBar.ellipse")} shortcuts={["O", "4"]} />
label={t("toolBar.diamond")} <Shortcut label={t("toolBar.arrow")} shortcuts={["A", "5"]} />
shortcuts={[KEYS.D, KEYS["3"]]} <Shortcut label={t("toolBar.line")} shortcuts={["P", "6"]} />
/> <Shortcut
<Shortcut label={t("toolBar.freedraw")}
label={t("toolBar.ellipse")} shortcuts={["Shift + P", "X", "7"]}
shortcuts={[KEYS.O, KEYS["4"]]} />
/> <Shortcut label={t("toolBar.text")} shortcuts={["T", "8"]} />
<Shortcut <Shortcut label={t("toolBar.image")} shortcuts={["9"]} />
label={t("toolBar.arrow")} <Shortcut label={t("toolBar.library")} shortcuts={["0"]} />
shortcuts={[KEYS.A, KEYS["5"]]} <Shortcut
/> label={t("toolBar.eraser")}
<Shortcut shortcuts={[getShortcutKey("E")]}
label={t("toolBar.line")} />
shortcuts={[KEYS.P, KEYS["6"]]} <Shortcut
/> label={t("helpDialog.editSelectedShape")}
<Shortcut shortcuts={[
label={t("toolBar.freedraw")} getShortcutKey("Enter"),
shortcuts={["Shift + P", KEYS["7"]]} t("helpDialog.doubleClick"),
/> ]}
<Shortcut />
label={t("toolBar.text")} <Shortcut
shortcuts={[KEYS.T, KEYS["8"]]} label={t("helpDialog.textNewLine")}
/> shortcuts={[
<Shortcut label={t("toolBar.image")} shortcuts={[KEYS["9"]]} /> getShortcutKey("Enter"),
<Shortcut getShortcutKey("Shift+Enter"),
label={t("toolBar.eraser")} ]}
shortcuts={[KEYS.E, KEYS["0"]]} />
/> <Shortcut
<Shortcut label={t("helpDialog.textFinish")}
label={t("helpDialog.editSelectedShape")} shortcuts={[
shortcuts={[ getShortcutKey("Esc"),
getShortcutKey("CtrlOrCmd+Enter"), getShortcutKey("CtrlOrCmd+Enter"),
getShortcutKey(`CtrlOrCmd + ${t("helpDialog.doubleClick")}`), ]}
]} />
/> <Shortcut
<Shortcut label={t("helpDialog.curvedArrow")}
label={t("helpDialog.textNewLine")} shortcuts={[
shortcuts={[ "A",
getShortcutKey("Enter"), t("helpDialog.click"),
getShortcutKey("Shift+Enter"), t("helpDialog.click"),
]} t("helpDialog.click"),
/> ]}
<Shortcut isOr={false}
label={t("helpDialog.textFinish")} />
shortcuts={[ <Shortcut
getShortcutKey("Esc"), label={t("helpDialog.curvedLine")}
getShortcutKey("CtrlOrCmd+Enter"), shortcuts={[
]} "L",
/> t("helpDialog.click"),
<Shortcut t("helpDialog.click"),
label={t("helpDialog.curvedArrow")} t("helpDialog.click"),
shortcuts={[ ]}
"A", isOr={false}
t("helpDialog.click"), />
t("helpDialog.click"), <Shortcut label={t("toolBar.lock")} shortcuts={["Q"]} />
t("helpDialog.click"), <Shortcut
]} label={t("helpDialog.preventBinding")}
isOr={false} shortcuts={[getShortcutKey("CtrlOrCmd")]}
/> />
<Shortcut <Shortcut
label={t("helpDialog.curvedLine")} label={t("toolBar.link")}
shortcuts={[ shortcuts={[getShortcutKey("CtrlOrCmd+K")]}
"L", />
t("helpDialog.click"), </ShortcutIsland>
t("helpDialog.click"), <ShortcutIsland caption={t("helpDialog.view")}>
t("helpDialog.click"), <Shortcut
]} label={t("buttons.zoomIn")}
isOr={false} shortcuts={[getShortcutKey("CtrlOrCmd++")]}
/> />
<Shortcut label={t("toolBar.lock")} shortcuts={[KEYS.Q]} /> <Shortcut
<Shortcut label={t("buttons.zoomOut")}
label={t("helpDialog.preventBinding")} shortcuts={[getShortcutKey("CtrlOrCmd+-")]}
shortcuts={[getShortcutKey("CtrlOrCmd")]} />
/> <Shortcut
<Shortcut label={t("buttons.resetZoom")}
label={t("toolBar.link")} shortcuts={[getShortcutKey("CtrlOrCmd+0")]}
shortcuts={[getShortcutKey("CtrlOrCmd+K")]} />
/> <Shortcut
</ShortcutIsland> label={t("helpDialog.zoomToFit")}
<ShortcutIsland shortcuts={["Shift+1"]}
className="HelpDialog__island--view" />
caption={t("helpDialog.view")} <Shortcut
> label={t("helpDialog.zoomToSelection")}
<Shortcut shortcuts={["Shift+2"]}
label={t("buttons.zoomIn")} />
shortcuts={[getShortcutKey("CtrlOrCmd++")]} <Shortcut label={t("buttons.fullScreen")} shortcuts={["F"]} />
/> <Shortcut
<Shortcut label={t("buttons.zenMode")}
label={t("buttons.zoomOut")} shortcuts={[getShortcutKey("Alt+Z")]}
shortcuts={[getShortcutKey("CtrlOrCmd+-")]} />
/> <Shortcut
<Shortcut label={t("labels.showGrid")}
label={t("buttons.resetZoom")} shortcuts={[getShortcutKey("CtrlOrCmd+'")]}
shortcuts={[getShortcutKey("CtrlOrCmd+0")]} />
/> <Shortcut
<Shortcut label={t("labels.viewMode")}
label={t("helpDialog.zoomToFit")} shortcuts={[getShortcutKey("Alt+R")]}
shortcuts={["Shift+1"]} />
/> <Shortcut
<Shortcut label={t("labels.toggleTheme")}
label={t("helpDialog.zoomToSelection")} shortcuts={[getShortcutKey("Alt+Shift+D")]}
shortcuts={["Shift+2"]} />
/> <Shortcut
<Shortcut label={t("buttons.fullScreen")} shortcuts={["F"]} /> label={t("stats.title")}
<Shortcut shortcuts={[getShortcutKey("Alt+/")]}
label={t("buttons.zenMode")} />
shortcuts={[getShortcutKey("Alt+Z")]} </ShortcutIsland>
/> </Column>
<Shortcut <Column>
label={t("labels.showGrid")} <ShortcutIsland caption={t("helpDialog.editor")}>
shortcuts={[getShortcutKey("CtrlOrCmd+'")]} <Shortcut
/> label={t("labels.selectAll")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+A")]}
label={t("labels.viewMode")} />
shortcuts={[getShortcutKey("Alt+R")]} <Shortcut
/> label={t("labels.multiSelect")}
<Shortcut shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]}
label={t("labels.toggleTheme")} />
shortcuts={[getShortcutKey("Alt+Shift+D")]} <Shortcut
/> label={t("helpDialog.deepSelect")}
<Shortcut shortcuts={[
label={t("stats.title")} getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`),
shortcuts={[getShortcutKey("Alt+/")]} ]}
/> />
</ShortcutIsland> <Shortcut
<ShortcutIsland label={t("helpDialog.deepBoxSelect")}
className="HelpDialog__island--editor" shortcuts={[
caption={t("helpDialog.editor")} getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`),
> ]}
<Shortcut />
label={t("labels.selectAll")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+A")]} label={t("labels.moveCanvas")}
/> shortcuts={[
<Shortcut getShortcutKey(`Space+${t("helpDialog.drag")}`),
label={t("labels.multiSelect")} getShortcutKey(`Wheel+${t("helpDialog.drag")}`),
shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]} ]}
/> isOr={true}
<Shortcut />
label={t("helpDialog.deepSelect")} <Shortcut
shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`)]} label={t("labels.cut")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+X")]}
<Shortcut />
label={t("helpDialog.deepBoxSelect")} <Shortcut
shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`)]} label={t("labels.copy")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+C")]}
<Shortcut />
label={t("labels.moveCanvas")} <Shortcut
shortcuts={[ label={t("labels.paste")}
getShortcutKey(`Space+${t("helpDialog.drag")}`), shortcuts={[getShortcutKey("CtrlOrCmd+V")]}
getShortcutKey(`Wheel+${t("helpDialog.drag")}`), />
]} <Shortcut
isOr={true} label={t("labels.copyAsPng")}
/> shortcuts={[getShortcutKey("Shift+Alt+C")]}
<Shortcut />
label={t("labels.cut")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+X")]} label={t("labels.copyStyles")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Alt+C")]}
<Shortcut />
label={t("labels.copy")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+C")]} label={t("labels.pasteStyles")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Alt+V")]}
<Shortcut />
label={t("labels.paste")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+V")]} label={t("labels.delete")}
/> shortcuts={[getShortcutKey("Del")]}
<Shortcut />
label={t("labels.pasteAsPlaintext")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+V")]} label={t("labels.sendToBack")}
/> shortcuts={[
<Shortcut isDarwin
label={t("labels.copyAsPng")} ? getShortcutKey("CtrlOrCmd+Alt+[")
shortcuts={[getShortcutKey("Shift+Alt+C")]} : getShortcutKey("CtrlOrCmd+Shift+["),
/> ]}
<Shortcut />
label={t("labels.copyStyles")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+Alt+C")]} label={t("labels.bringToFront")}
/> shortcuts={[
<Shortcut isDarwin
label={t("labels.pasteStyles")} ? getShortcutKey("CtrlOrCmd+Alt+]")
shortcuts={[getShortcutKey("CtrlOrCmd+Alt+V")]} : getShortcutKey("CtrlOrCmd+Shift+]"),
/> ]}
<Shortcut />
label={t("labels.delete")} <Shortcut
shortcuts={[getShortcutKey("Delete")]} label={t("labels.sendBackward")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+[")]}
<Shortcut />
label={t("labels.sendToBack")} <Shortcut
shortcuts={[ label={t("labels.bringForward")}
isDarwin shortcuts={[getShortcutKey("CtrlOrCmd+]")]}
? getShortcutKey("CtrlOrCmd+Alt+[") />
: getShortcutKey("CtrlOrCmd+Shift+["), <Shortcut
]} label={t("labels.alignTop")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Up")]}
<Shortcut />
label={t("labels.bringToFront")} <Shortcut
shortcuts={[ label={t("labels.alignBottom")}
isDarwin shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Down")]}
? getShortcutKey("CtrlOrCmd+Alt+]") />
: getShortcutKey("CtrlOrCmd+Shift+]"), <Shortcut
]} label={t("labels.alignLeft")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Left")]}
<Shortcut />
label={t("labels.sendBackward")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+[")]} label={t("labels.alignRight")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Right")]}
<Shortcut />
label={t("labels.bringForward")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+]")]} label={t("labels.duplicateSelection")}
/> shortcuts={[
<Shortcut getShortcutKey("CtrlOrCmd+D"),
label={t("labels.alignTop")} getShortcutKey(`Alt+${t("helpDialog.drag")}`),
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Up")]} ]}
/> />
<Shortcut <Shortcut
label={t("labels.alignBottom")} label={t("helpDialog.toggleElementLock")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Down")]} shortcuts={[getShortcutKey("CtrlOrCmd+Shift+L")]}
/> />
<Shortcut <Shortcut
label={t("labels.alignLeft")} label={t("buttons.undo")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Left")]} shortcuts={[getShortcutKey("CtrlOrCmd+Z")]}
/> />
<Shortcut <Shortcut
label={t("labels.alignRight")} label={t("buttons.redo")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Right")]} shortcuts={
/> isWindows
<Shortcut ? [
label={t("labels.duplicateSelection")} getShortcutKey("CtrlOrCmd+Y"),
shortcuts={[ getShortcutKey("CtrlOrCmd+Shift+Z"),
getShortcutKey("CtrlOrCmd+D"), ]
getShortcutKey(`Alt+${t("helpDialog.drag")}`), : [getShortcutKey("CtrlOrCmd+Shift+Z")]
]} }
/> />
<Shortcut <Shortcut
label={t("helpDialog.toggleElementLock")} label={t("labels.group")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+L")]} shortcuts={[getShortcutKey("CtrlOrCmd+G")]}
/> />
<Shortcut <Shortcut
label={t("buttons.undo")} label={t("labels.ungroup")}
shortcuts={[getShortcutKey("CtrlOrCmd+Z")]} shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]}
/> />
<Shortcut <Shortcut
label={t("buttons.redo")} label={t("labels.flipHorizontal")}
shortcuts={ shortcuts={[getShortcutKey("Shift+H")]}
isWindows />
? [ <Shortcut
getShortcutKey("CtrlOrCmd+Y"), label={t("labels.flipVertical")}
getShortcutKey("CtrlOrCmd+Shift+Z"), shortcuts={[getShortcutKey("Shift+V")]}
] />
: [getShortcutKey("CtrlOrCmd+Shift+Z")] <Shortcut
} label={t("labels.showStroke")}
/> shortcuts={[getShortcutKey("S")]}
<Shortcut />
label={t("labels.group")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+G")]} label={t("labels.showBackground")}
/> shortcuts={[getShortcutKey("G")]}
<Shortcut />
label={t("labels.ungroup")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]} label={t("labels.decreaseFontSize")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]}
<Shortcut />
label={t("labels.flipHorizontal")} <Shortcut
shortcuts={[getShortcutKey("Shift+H")]} label={t("labels.increaseFontSize")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]}
<Shortcut />
label={t("labels.flipVertical")} </ShortcutIsland>
shortcuts={[getShortcutKey("Shift+V")]} </Column>
/> </Columns>
<Shortcut
label={t("labels.showStroke")}
shortcuts={[getShortcutKey("S")]}
/>
<Shortcut
label={t("labels.showBackground")}
shortcuts={[getShortcutKey("G")]}
/>
<Shortcut
label={t("labels.decreaseFontSize")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]}
/>
<Shortcut
label={t("labels.increaseFontSize")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]}
/>
</ShortcutIsland>
</Section> </Section>
</Dialog> </Dialog>
</> </>

View File

@@ -1,13 +1,13 @@
import { HelpIcon } from "./icons"; import { questionCircle } from "../components/icons";
type HelpButtonProps = { type HelpIconProps = {
title?: string; title?: string;
name?: string; name?: string;
id?: string; id?: string;
onClick?(): void; onClick?(): void;
}; };
export const HelpButton = (props: HelpButtonProps) => ( export const HelpIcon = (props: HelpIconProps) => (
<button <button
className="help-icon" className="help-icon"
onClick={props.onClick} onClick={props.onClick}
@@ -15,6 +15,6 @@ export const HelpButton = (props: HelpButtonProps) => (
title={`${props.title} — ?`} title={`${props.title} — ?`}
aria-label={props.title} aria-label={props.title}
> >
{HelpIcon} {questionCircle}
</button> </button>
); );

View File

@@ -14,24 +14,20 @@ $wide-viewport-width: 1000px;
top: 100%; top: 100%;
max-width: 100%; max-width: 100%;
width: 100%; width: 100%;
margin-top: 0.5rem; margin-top: 6px;
text-align: center; text-align: center;
color: var(--color-gray-40); color: $oc-gray-6;
font-size: 0.75rem; font-size: 0.8rem;
@include isMobile { @include isMobile {
position: static; position: static;
padding-right: 2rem; padding-right: 2em;
} }
> span { > span {
padding: 0.25rem; padding: 0.2rem 0.4rem;
} background-color: var(--overlay-bg-color);
} border-radius: 4px;
&.theme--dark {
.HintViewer {
color: var(--color-gray-60);
} }
} }
} }

View File

@@ -3,7 +3,7 @@ import { NonDeletedExcalidrawElement } from "../element/types";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
import "./HintViewer.scss"; import "./HintViewer.scss";
import { AppState, Device } from "../types"; import { AppState } from "../types";
import { import {
isImageElement, isImageElement,
isLinearElement, isLinearElement,
@@ -17,19 +17,13 @@ interface HintViewerProps {
appState: AppState; appState: AppState;
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
isMobile: boolean; isMobile: boolean;
device: Device;
} }
const getHints = ({ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => {
appState,
elements,
isMobile,
device,
}: HintViewerProps) => {
const { activeTool, isResizing, isRotating, lastPointerDownWith } = appState; const { activeTool, isResizing, isRotating, lastPointerDownWith } = appState;
const multiMode = appState.multiElement !== null; const multiMode = appState.multiElement !== null;
if (appState.openSidebar === "library" && !device.canDeviceFitSidebar) { if (appState.isLibraryOpen) {
return null; return null;
} }
@@ -117,13 +111,11 @@ export const HintViewer = ({
appState, appState,
elements, elements,
isMobile, isMobile,
device,
}: HintViewerProps) => { }: HintViewerProps) => {
let hint = getHints({ let hint = getHints({
appState, appState,
elements, elements,
isMobile, isMobile,
device,
}); });
if (!hint) { if (!hint) {
return null; return null;

View File

@@ -10,8 +10,7 @@
.picker { .picker {
background: var(--popup-bg-color); background: var(--popup-bg-color);
border: 0 solid transparentize($oc-white, 0.75); border: 0 solid transparentize($oc-white, 0.75);
// ˇˇ yeah, i dunno, open to suggestions here :D box-shadow: transparentize($oc-black, 0.75) 0 1px 4px;
box-shadow: rgb(0 0 0 / 25%) 2px 2px 4px 2px;
border-radius: 4px; border-radius: 4px;
position: absolute; position: absolute;
} }
@@ -47,6 +46,7 @@
margin: 0; margin: 0;
width: 36px; width: 36px;
height: 18px; height: 18px;
opacity: 0.6;
pointer-events: none; pointer-events: none;
} }
} }

View File

@@ -4,7 +4,6 @@ import { Popover } from "./Popover";
import "./IconPicker.scss"; import "./IconPicker.scss";
import { isArrowKey, KEYS } from "../keys"; import { isArrowKey, KEYS } from "../keys";
import { getLanguage } from "../i18n"; import { getLanguage } from "../i18n";
import clsx from "clsx";
function Picker<T>({ function Picker<T>({
options, options,
@@ -103,9 +102,7 @@ function Picker<T>({
<div className="picker-content" ref={rGallery}> <div className="picker-content" ref={rGallery}>
{options.map((option, i) => ( {options.map((option, i) => (
<button <button
className={clsx("picker-option", { className="picker-option"
active: value === option.value,
})}
onClick={(event) => { onClick={(event) => {
(event.currentTarget as HTMLButtonElement).focus(); (event.currentTarget as HTMLButtonElement).focus();
onChange(option.value); onChange(option.value);
@@ -153,7 +150,7 @@ export function IconPicker<T>({
const isRTL = getLanguage().rtl; const isRTL = getLanguage().rtl;
return ( return (
<div> <label className={"picker-container"}>
<button <button
name={group} name={group}
className={isActive ? "active" : ""} className={isActive ? "active" : ""}
@@ -187,6 +184,6 @@ export function IconPicker<T>({
</> </>
) : null} ) : null}
</React.Suspense> </React.Suspense>
</div> </label>
); );
} }

View File

@@ -1,14 +1,18 @@
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { probablySupportsClipboardBlob } from "../clipboard"; import { probablySupportsClipboardBlob } from "../clipboard";
import { canvasToBlob } from "../data/blob"; import { canvasToBlob } from "../data/blob";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { CanvasError } from "../errors";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "./App";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { exportToCanvas } from "../scene/export"; import { exportToCanvas } from "../scene/export";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { clipboard } from "./icons"; import { clipboard, exportImage } from "./icons";
import Stack from "./Stack"; import Stack from "./Stack";
import { ToolButton } from "./ToolButton";
import "./ExportDialog.scss"; import "./ExportDialog.scss";
import OpenColor from "open-color"; import OpenColor from "open-color";
import { CheckboxItem } from "./CheckboxItem"; import { CheckboxItem } from "./CheckboxItem";
@@ -31,6 +35,19 @@ export const ErrorCanvasPreview = () => {
); );
}; };
const renderPreview = (
content: HTMLCanvasElement | Error,
previewNode: HTMLDivElement,
) => {
unmountComponentAtNode(previewNode);
previewNode.innerHTML = "";
if (content instanceof HTMLCanvasElement) {
previewNode.appendChild(content);
} else {
render(<ErrorCanvasPreview />, previewNode);
}
};
export type ExportCB = ( export type ExportCB = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
scale?: number, scale?: number,
@@ -84,7 +101,6 @@ const ImageExportModal = ({
const [exportSelected, setExportSelected] = useState(someElementIsSelected); const [exportSelected, setExportSelected] = useState(someElementIsSelected);
const previewRef = useRef<HTMLDivElement>(null); const previewRef = useRef<HTMLDivElement>(null);
const { exportBackground, viewBackgroundColor } = appState; const { exportBackground, viewBackgroundColor } = appState;
const [renderError, setRenderError] = useState<Error | null>(null);
const exportedElements = exportSelected const exportedElements = exportSelected
? getSelectedElements(elements, appState, true) ? getSelectedElements(elements, appState, true)
@@ -105,16 +121,15 @@ const ImageExportModal = ({
exportPadding, exportPadding,
}) })
.then((canvas) => { .then((canvas) => {
setRenderError(null);
// if converting to blob fails, there's some problem that will // if converting to blob fails, there's some problem that will
// likely prevent preview and export (e.g. canvas too big) // likely prevent preview and export (e.g. canvas too big)
return canvasToBlob(canvas).then(() => { return canvasToBlob(canvas).then(() => {
previewNode.replaceChildren(canvas); renderPreview(canvas, previewNode);
}); });
}) })
.catch((error) => { .catch((error) => {
console.error(error); console.error(error);
setRenderError(error); renderPreview(new CanvasError(), previewNode);
}); });
}, [ }, [
appState, appState,
@@ -127,9 +142,7 @@ const ImageExportModal = ({
return ( return (
<div className="ExportDialog"> <div className="ExportDialog">
<div className="ExportDialog__preview" ref={previewRef}> <div className="ExportDialog__preview" ref={previewRef} />
{renderError && <ErrorCanvasPreview />}
</div>
{supportsContextFilters && {supportsContextFilters &&
actionManager.renderAction("exportWithDarkMode")} actionManager.renderAction("exportWithDarkMode")}
<div style={{ display: "grid", gridTemplateColumns: "1fr" }}> <div style={{ display: "grid", gridTemplateColumns: "1fr" }}>
@@ -208,7 +221,6 @@ const ImageExportModal = ({
export const ImageExportDialog = ({ export const ImageExportDialog = ({
elements, elements,
appState, appState,
setAppState,
files, files,
exportPadding = DEFAULT_EXPORT_PADDING, exportPadding = DEFAULT_EXPORT_PADDING,
actionManager, actionManager,
@@ -217,7 +229,6 @@ export const ImageExportDialog = ({
onExportToClipboard, onExportToClipboard,
}: { }: {
appState: AppState; appState: AppState;
setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles; files: BinaryFiles;
exportPadding?: number; exportPadding?: number;
@@ -226,13 +237,26 @@ export const ImageExportDialog = ({
onExportToSvg: ExportCB; onExportToSvg: ExportCB;
onExportToClipboard: ExportCB; onExportToClipboard: ExportCB;
}) => { }) => {
const [modalIsShown, setModalIsShown] = useState(false);
const handleClose = React.useCallback(() => { const handleClose = React.useCallback(() => {
setAppState({ openDialog: null }); setModalIsShown(false);
}, [setAppState]); }, []);
return ( return (
<> <>
{appState.openDialog === "imageExport" && ( <ToolButton
onClick={() => {
setModalIsShown(true);
}}
data-testid="image-export-button"
icon={exportImage}
type="button"
aria-label={t("buttons.exportImage")}
showAriaLabel={useDevice().isMobile}
title={t("buttons.exportImage")}
/>
{modalIsShown && (
<Dialog onCloseRequest={handleClose} title={t("buttons.exportImage")}> <Dialog onCloseRequest={handleClose} title={t("buttons.exportImage")}>
<ImageExportModal <ImageExportModal
elements={elements} elements={elements}

View File

@@ -2,12 +2,10 @@ import React, { useEffect, useState } from "react";
import { LoadingMessage } from "./LoadingMessage"; import { LoadingMessage } from "./LoadingMessage";
import { defaultLang, Language, languages, setLanguage } from "../i18n"; import { defaultLang, Language, languages, setLanguage } from "../i18n";
import { Theme } from "../element/types";
interface Props { interface Props {
langCode: Language["code"]; langCode: Language["code"];
children: React.ReactElement; children: React.ReactElement;
theme?: Theme;
} }
export const InitializeApp = (props: Props) => { export const InitializeApp = (props: Props) => {
@@ -23,5 +21,5 @@ export const InitializeApp = (props: Props) => {
updateLang(); updateLang();
}, [props.langCode]); }, [props.langCode]);
return loading ? <LoadingMessage theme={props.theme} /> : props.children; return loading ? <LoadingMessage /> : props.children;
}; };

View File

@@ -1,7 +1,6 @@
.excalidraw { .excalidraw {
.Island { .Island {
--padding: 0; --padding: 0;
box-sizing: border-box;
background-color: var(--island-bg-color); background-color: var(--island-bg-color);
box-shadow: var(--shadow-island); box-shadow: var(--shadow-island);
border-radius: var(--border-radius-lg); border-radius: var(--border-radius-lg);

View File

@@ -1,10 +1,10 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "./App";
import { AppState, ExportOpts, BinaryFiles } from "../types"; import { AppState, ExportOpts, BinaryFiles } from "../types";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { ExportIcon, exportToFileIcon, LinkIcon } from "./icons"; import { exportFile, exportToFileIcon, link } from "./icons";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import { actionSaveFileToDisk } from "../actions/actionExport"; import { actionSaveFileToDisk } from "../actions/actionExport";
import { Card } from "./Card"; import { Card } from "./Card";
@@ -14,7 +14,6 @@ import { nativeFileSystemSupported } from "../data/filesystem";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
import { getFrame } from "../utils"; import { getFrame } from "../utils";
import MenuItem from "./MenuItem";
export type ExportCB = ( export type ExportCB = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
@@ -64,7 +63,7 @@ const JSONExportModal = ({
)} )}
{onExportToBackend && ( {onExportToBackend && (
<Card color="pink"> <Card color="pink">
<div className="Card-icon">{LinkIcon}</div> <div className="Card-icon">{link}</div>
<h2>{t("exportDialog.link_title")}</h2> <h2>{t("exportDialog.link_title")}</h2>
<div className="Card-details">{t("exportDialog.link_details")}</div> <div className="Card-details">{t("exportDialog.link_details")}</div>
<ToolButton <ToolButton
@@ -110,13 +109,16 @@ export const JSONExportDialog = ({
return ( return (
<> <>
<MenuItem <ToolButton
icon={ExportIcon}
label={t("buttons.export")}
onClick={() => { onClick={() => {
setModalIsShown(true); setModalIsShown(true);
}} }}
dataTestId="json-export-button" data-testid="json-export-button"
icon={exportFile}
type="button"
aria-label={t("buttons.export")}
showAriaLabel={useDevice().isMobile}
title={t("buttons.export")}
/> />
{modalIsShown && ( {modalIsShown && (
<Dialog onCloseRequest={handleClose} title={t("buttons.export")}> <Dialog onCloseRequest={handleClose} title={t("buttons.export")}>

View File

@@ -1,6 +1,48 @@
@import "open-color/open-color"; @import "open-color/open-color";
@import "../css/variables.module"; @import "../css/variables.module";
.layer-ui__sidebar {
position: absolute;
top: var(--sat);
bottom: var(--sab);
right: var(--sar);
z-index: 5;
box-shadow: var(--shadow-island);
overflow: hidden;
border-radius: var(--border-radius-lg);
margin: var(--space-factor);
width: calc(#{$right-sidebar-width} - var(--space-factor) * 2);
.Island {
box-shadow: none;
}
.ToolIcon__icon {
border-radius: var(--border-radius-md);
}
.ToolIcon__icon__close {
.Modal__close {
width: calc(var(--space-factor) * 7);
height: calc(var(--space-factor) * 7);
display: flex;
justify-content: center;
align-items: center;
color: var(--color-text);
}
}
.Island {
--padding: 0;
background-color: var(--island-bg-color);
border-radius: var(--border-radius-lg);
padding: calc(var(--padding) * var(--space-factor));
position: relative;
transition: box-shadow 0.5s ease-in-out;
}
}
.excalidraw { .excalidraw {
.layer-ui__wrapper.animate { .layer-ui__wrapper.animate {
transition: width 0.1s ease-in-out; transition: width 0.1s ease-in-out;
@@ -16,10 +58,8 @@
height: 100%; height: 100%;
pointer-events: none; pointer-events: none;
z-index: var(--zIndex-layerUI); z-index: var(--zIndex-layerUI);
&__top-right { &__top-right {
display: flex; display: flex;
gap: 0.75rem;
} }
&__footer { &__footer {
@@ -50,6 +90,13 @@
transform: translate(-999px, 0); transform: translate(-999px, 0);
} }
:root[dir="ltr"] &.layer-ui__wrapper__footer-left--transition-left {
transform: translate(-76px, 0);
}
:root[dir="rtl"] &.layer-ui__wrapper__footer-left--transition-left {
transform: translate(76px, 0);
}
&.layer-ui__wrapper__footer-left--transition-bottom { &.layer-ui__wrapper__footer-left--transition-bottom {
transform: translate(0, 92px); transform: translate(0, 92px);
} }
@@ -85,10 +132,6 @@
& > * { & > * {
pointer-events: all; pointer-events: all;
} }
display: flex;
width: 100%;
justify-content: flex-start;
} }
.layer-ui__wrapper__footer-left, .layer-ui__wrapper__footer-left,
.layer-ui__wrapper__footer-right, .layer-ui__wrapper__footer-right,
@@ -96,9 +139,14 @@
pointer-events: all; pointer-events: all;
} }
.layer-ui__wrapper__footer-left {
margin-bottom: 0.2em;
}
.layer-ui__wrapper__footer-right { .layer-ui__wrapper__footer-right {
margin-top: auto; margin-top: auto;
margin-bottom: auto; margin-bottom: auto;
margin-inline-end: 1em;
} }
} }
} }

View File

@@ -1,22 +1,17 @@
import clsx from "clsx"; import clsx from "clsx";
import React from "react"; import React, { useCallback } from "react";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
import { CLASSES, LIBRARY_SIDEBAR_WIDTH } from "../constants"; import { CLASSES, LIBRARY_SIDEBAR_WIDTH } from "../constants";
import { exportCanvas } from "../data"; import { exportCanvas } from "../data";
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 { calculateScrollCenter } from "../scene"; import { calculateScrollCenter, getSelectedElements } from "../scene";
import { ExportType } from "../scene/types"; import { ExportType } from "../scene/types";
import { import { AppProps, AppState, ExcalidrawProps, BinaryFiles } from "../types";
AppProps, import { muteFSAbortError } from "../utils";
AppState,
ExcalidrawProps,
BinaryFiles,
UIChildrenComponents,
} from "../types";
import { muteFSAbortError, ReactChildrenToObject } from "../utils";
import { SelectedShapeActions, ShapesSwitcher } from "./Actions"; import { SelectedShapeActions, ShapesSwitcher } from "./Actions";
import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
import CollabButton from "./CollabButton"; import CollabButton from "./CollabButton";
import { ErrorDialog } from "./ErrorDialog"; import { ErrorDialog } from "./ErrorDialog";
import { ExportCB, ImageExportDialog } from "./ImageExportDialog"; import { ExportCB, ImageExportDialog } from "./ImageExportDialog";
@@ -31,7 +26,7 @@ import { Section } from "./Section";
import { HelpDialog } from "./HelpDialog"; import { HelpDialog } from "./HelpDialog";
import Stack from "./Stack"; import Stack from "./Stack";
import { UserList } from "./UserList"; import { UserList } from "./UserList";
import Library from "../data/library"; import Library, { distributeLibraryItemsOnSquareGrid } 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";
@@ -41,26 +36,10 @@ import "./LayerUI.scss";
import "./Toolbar.scss"; import "./Toolbar.scss";
import { PenModeButton } from "./PenModeButton"; import { PenModeButton } from "./PenModeButton";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { isMenuOpenAtom, useDevice } from "../components/App"; import { useDevice } from "../components/App";
import { Stats } from "./Stats"; import { Stats } from "./Stats";
import { actionToggleStats } from "../actions/actionToggleStats"; import { actionToggleStats } from "../actions/actionToggleStats";
import Footer from "./footer/Footer"; import Footer from "./Footer";
import {
ExportImageIcon,
HamburgerMenuIcon,
WelcomeScreenMenuArrow,
WelcomeScreenTopToolbarArrow,
} from "./icons";
import { MenuLinks, Separator } from "./MenuUtils";
import { useOutsideClickHook } from "../hooks/useOutsideClick";
import WelcomeScreen from "./WelcomeScreen";
import { hostSidebarCountersAtom } from "./Sidebar/Sidebar";
import { jotaiScope } from "../jotai";
import { useAtom } from "jotai";
import { LanguageList } from "../excalidraw-app/components/LanguageList";
import WelcomeScreenDecor from "./WelcomeScreenDecor";
import { getShortcutFromShortcutName } from "../actions/shortcuts";
import MenuItem from "./MenuItem";
interface LayerUIProps { interface LayerUIProps {
actionManager: ActionManager; actionManager: ActionManager;
@@ -74,21 +53,19 @@ interface LayerUIProps {
onPenModeToggle: () => void; onPenModeToggle: () => void;
onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void; onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
showExitZenModeBtn: boolean; showExitZenModeBtn: boolean;
showThemeBtn: boolean;
langCode: Language["code"]; langCode: Language["code"];
isCollaborating: boolean; isCollaborating: boolean;
renderTopRightUI?: ExcalidrawProps["renderTopRightUI"]; renderTopRightUI?: ExcalidrawProps["renderTopRightUI"];
renderCustomFooter?: ExcalidrawProps["renderFooter"];
renderCustomStats?: ExcalidrawProps["renderCustomStats"]; renderCustomStats?: ExcalidrawProps["renderCustomStats"];
renderCustomSidebar?: ExcalidrawProps["renderSidebar"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"]; libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
UIOptions: AppProps["UIOptions"]; UIOptions: AppProps["UIOptions"];
focusContainer: () => void; focusContainer: () => void;
library: Library; library: Library;
id: string; id: string;
onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void; onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void;
renderWelcomeScreen: boolean;
children?: React.ReactNode;
} }
const LayerUI = ({ const LayerUI = ({
actionManager, actionManager,
appState, appState,
@@ -101,25 +78,20 @@ const LayerUI = ({
onPenModeToggle, onPenModeToggle,
onInsertElements, onInsertElements,
showExitZenModeBtn, showExitZenModeBtn,
showThemeBtn,
isCollaborating, isCollaborating,
renderTopRightUI, renderTopRightUI,
renderCustomFooter,
renderCustomStats, renderCustomStats,
renderCustomSidebar,
libraryReturnUrl, libraryReturnUrl,
UIOptions, UIOptions,
focusContainer, focusContainer,
library, library,
id, id,
onImageAction, onImageAction,
renderWelcomeScreen,
children,
}: LayerUIProps) => { }: LayerUIProps) => {
const device = useDevice(); const device = useDevice();
const childrenComponents =
ReactChildrenToObject<UIChildrenComponents>(children);
const renderJSONExportDialog = () => { const renderJSONExportDialog = () => {
if (!UIOptions.canvasActions.export) { if (!UIOptions.canvasActions.export) {
return null; return null;
@@ -176,7 +148,6 @@ const LayerUI = ({
<ImageExportDialog <ImageExportDialog
elements={elements} elements={elements}
appState={appState} appState={appState}
setAppState={setAppState}
files={files} files={files}
actionManager={actionManager} actionManager={actionManager}
onExportToPng={createExporter("png")} onExportToPng={createExporter("png")}
@@ -186,107 +157,76 @@ const LayerUI = ({
); );
}; };
const [isMenuOpen, setIsMenuOpen] = useAtom(isMenuOpenAtom); const Separator = () => {
const menuRef = useOutsideClickHook(() => setIsMenuOpen(false)); return <div style={{ width: ".625em" }} />;
};
const renderCanvasActions = () => ( const renderViewModeCanvasActions = () => {
<div style={{ position: "relative" }}> return (
<WelcomeScreenDecor <Section
shouldRender={renderWelcomeScreen && !appState.isLoading} heading="canvasActions"
> className={clsx("zen-mode-transition", {
<div className="virgil WelcomeScreen-decor WelcomeScreen-decor--menu-pointer">
{WelcomeScreenMenuArrow}
<div>{t("welcomeScreen.menuHints")}</div>
</div>
</WelcomeScreenDecor>
<button
data-prevent-outside-click
className={clsx("menu-button", "zen-mode-transition", {
"transition-left": appState.zenModeEnabled, "transition-left": appState.zenModeEnabled,
})} })}
onClick={() => setIsMenuOpen(!isMenuOpen)}
type="button"
data-testid="menu-button"
> >
{HamburgerMenuIcon} {/* the zIndex ensures this menu has higher stacking order,
</button>
{isMenuOpen && (
<div
ref={menuRef}
style={{ position: "absolute", top: "100%", marginTop: ".25rem" }}
>
<Section heading="canvasActions">
{/* the zIndex ensures this menu has higher stacking order,
see https://github.com/excalidraw/excalidraw/pull/1445 */} see https://github.com/excalidraw/excalidraw/pull/1445 */}
<Island <Island padding={2} style={{ zIndex: 1 }}>
className="menu-container" <Stack.Col gap={4}>
padding={2} <Stack.Row gap={1} justifyContent="space-between">
style={{ zIndex: 1 }}
>
{!appState.viewModeEnabled &&
actionManager.renderAction("loadScene")}
{/* // TODO barnabasmolnar/editor-redesign */}
{/* is this fine here? */}
{appState.fileHandle &&
actionManager.renderAction("saveToActiveFile")}
{renderJSONExportDialog()} {renderJSONExportDialog()}
{UIOptions.canvasActions.saveAsImage && ( {renderImageExportDialog()}
<MenuItem </Stack.Row>
label={t("buttons.exportImage")} </Stack.Col>
icon={ExportImageIcon} </Island>
dataTestId="image-export-button" </Section>
onClick={() => setAppState({ openDialog: "imageExport" })} );
shortcut={getShortcutFromShortcutName("imageExport")} };
/>
)} const renderCanvasActions = () => (
{onCollabButtonClick && ( <Section
<CollabButton heading="canvasActions"
isCollaborating={isCollaborating} className={clsx("zen-mode-transition", {
collaboratorCount={appState.collaborators.size} "transition-left": appState.zenModeEnabled,
onClick={onCollabButtonClick} })}
/> >
)} {/* the zIndex ensures this menu has higher stacking order,
{actionManager.renderAction("toggleShortcuts", undefined, true)} see https://github.com/excalidraw/excalidraw/pull/1445 */}
{!appState.viewModeEnabled && <Island padding={2} style={{ zIndex: 1 }}>
actionManager.renderAction("clearCanvas")} <Stack.Col gap={4}>
<Separator /> <Stack.Row gap={1} justifyContent="space-between">
<MenuLinks /> {actionManager.renderAction("clearCanvas")}
<Separator /> <Separator />
<div {actionManager.renderAction("loadScene")}
style={{ {renderJSONExportDialog()}
display: "flex", {renderImageExportDialog()}
flexDirection: "column", <Separator />
rowGap: ".5rem", {onCollabButtonClick && (
}} <CollabButton
> isCollaborating={isCollaborating}
<div>{actionManager.renderAction("toggleTheme")}</div> collaboratorCount={appState.collaborators.size}
<div style={{ padding: "0 0.625rem" }}> onClick={onCollabButtonClick}
<LanguageList style={{ width: "100%" }} /> />
</div> )}
{!appState.viewModeEnabled && ( </Stack.Row>
<div> <BackgroundPickerAndDarkModeToggle
<div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}> appState={appState}
{t("labels.canvasBackground")} actionManager={actionManager}
</div> setAppState={setAppState}
<div style={{ padding: "0 0.625rem" }}> showThemeBtn={showThemeBtn}
{actionManager.renderAction("changeViewBackgroundColor")} />
</div> {appState.fileHandle && (
</div> <>{actionManager.renderAction("saveToActiveFile")}</>
)} )}
</div> </Stack.Col>
</Island> </Island>
</Section> </Section>
</div>
)}
</div>
); );
const renderSelectedShapeActions = () => ( const renderSelectedShapeActions = () => (
<Section <Section
heading="selectedShapeActions" heading="selectedShapeActions"
className={clsx("selected-shape-actions zen-mode-transition", { className={clsx("zen-mode-transition", {
"transition-left": appState.zenModeEnabled, "transition-left": appState.zenModeEnabled,
})} })}
> >
@@ -294,9 +234,10 @@ const LayerUI = ({
className={CLASSES.SHAPE_ACTIONS_MENU} className={CLASSES.SHAPE_ACTIONS_MENU}
padding={2} padding={2}
style={{ style={{
// we want to make sure this doesn't overflow so subtracting the // we want to make sure this doesn't overflow so subtracting 200
// approximate height of hamburgerMenu + footer // which is approximately height of zoom footer and top left menu items with some buffer
maxHeight: `${appState.height - 166}px`, // if active file name is displayed, subtracting 248 to account for its height
maxHeight: `${appState.height - (appState.fileHandle ? 248 : 200)}px`,
}} }}
> >
<SelectedShapeActions <SelectedShapeActions
@@ -308,6 +249,41 @@ const LayerUI = ({
</Section> </Section>
); );
const closeLibrary = useCallback(() => {
const isDialogOpen = !!document.querySelector(".Dialog");
// Prevent closing if any dialog is open
if (isDialogOpen) {
return;
}
setAppState({ isLibraryOpen: false });
}, [setAppState]);
const deselectItems = useCallback(() => {
setAppState({
selectedElementIds: {},
selectedGroupIds: {},
});
}, [setAppState]);
const libraryMenu = appState.isLibraryOpen ? (
<LibraryMenu
pendingElements={getSelectedElements(elements, appState, true)}
onClose={closeLibrary}
onInsertLibraryItems={(libraryItems) => {
onInsertElements(distributeLibraryItemsOnSquareGrid(libraryItems));
}}
onAddToLibrary={deselectItems}
setAppState={setAppState}
libraryReturnUrl={libraryReturnUrl}
focusContainer={focusContainer}
library={library}
files={files}
id={id}
appState={appState}
/>
) : null;
const renderFixedSideContainer = () => { const renderFixedSideContainer = () => {
const shouldRenderSelectedShapeActions = showSelectedShapeActions( const shouldRenderSelectedShapeActions = showSelectedShapeActions(
appState, appState,
@@ -316,89 +292,73 @@ const LayerUI = ({
return ( return (
<FixedSideContainer side="top"> <FixedSideContainer side="top">
{renderWelcomeScreen && !appState.isLoading && (
<WelcomeScreen appState={appState} actionManager={actionManager} />
)}
<div className="App-menu App-menu_top"> <div className="App-menu App-menu_top">
<Stack.Col <Stack.Col
gap={6} gap={4}
className={clsx("App-menu_top__left", { className={clsx({
"disable-pointerEvents": appState.zenModeEnabled, "disable-pointerEvents": appState.zenModeEnabled,
})} })}
> >
{renderCanvasActions()} {appState.viewModeEnabled
? renderViewModeCanvasActions()
: renderCanvasActions()}
{shouldRenderSelectedShapeActions && renderSelectedShapeActions()} {shouldRenderSelectedShapeActions && renderSelectedShapeActions()}
</Stack.Col> </Stack.Col>
{!appState.viewModeEnabled && ( {!appState.viewModeEnabled && (
<Section heading="shapes" className="shapes-section"> <Section heading="shapes">
{(heading: React.ReactNode) => ( {(heading: React.ReactNode) => (
<div style={{ position: "relative" }}> <Stack.Col gap={4} align="start">
<WelcomeScreenDecor <Stack.Row
shouldRender={renderWelcomeScreen && !appState.isLoading} gap={1}
className={clsx("App-toolbar-container", {
"zen-mode": appState.zenModeEnabled,
})}
> >
<div className="virgil WelcomeScreen-decor WelcomeScreen-decor--top-toolbar-pointer"> <PenModeButton
<div className="WelcomeScreen-decor--top-toolbar-pointer__label"> zenModeEnabled={appState.zenModeEnabled}
{t("welcomeScreen.toolbarHints")} checked={appState.penMode}
</div> onChange={onPenModeToggle}
{WelcomeScreenTopToolbarArrow} title={t("toolBar.penMode")}
</div> penDetected={appState.penDetected}
</WelcomeScreenDecor> />
<LockButton
<Stack.Col gap={4} align="start"> zenModeEnabled={appState.zenModeEnabled}
<Stack.Row checked={appState.activeTool.locked}
gap={1} onChange={() => onLockToggle()}
className={clsx("App-toolbar-container", { title={t("toolBar.lock")}
/>
<Island
padding={1}
className={clsx("App-toolbar", {
"zen-mode": appState.zenModeEnabled, "zen-mode": appState.zenModeEnabled,
})} })}
> >
<Island <HintViewer
padding={1} appState={appState}
className={clsx("App-toolbar", { elements={elements}
"zen-mode": appState.zenModeEnabled, isMobile={device.isMobile}
})} />
> {heading}
<HintViewer <Stack.Row gap={1}>
<ShapesSwitcher
appState={appState} appState={appState}
elements={elements} canvas={canvas}
isMobile={device.isMobile} activeTool={appState.activeTool}
device={device} setAppState={setAppState}
onImageAction={({ pointerType }) => {
onImageAction({
insertOnCanvasDirectly: pointerType !== "mouse",
});
}}
/> />
{heading} </Stack.Row>
<Stack.Row gap={1}> </Island>
<PenModeButton <LibraryButton
zenModeEnabled={appState.zenModeEnabled} appState={appState}
checked={appState.penMode} setAppState={setAppState}
onChange={onPenModeToggle} />
title={t("toolBar.penMode")} </Stack.Row>
penDetected={appState.penDetected} </Stack.Col>
/>
<LockButton
zenModeEnabled={appState.zenModeEnabled}
checked={appState.activeTool.locked}
onChange={() => onLockToggle()}
title={t("toolBar.lock")}
/>
<div className="App-toolbar__divider"></div>
<ShapesSwitcher
appState={appState}
canvas={canvas}
activeTool={appState.activeTool}
setAppState={setAppState}
onImageAction={({ pointerType }) => {
onImageAction({
insertOnCanvasDirectly: pointerType !== "mouse",
});
}}
/>
{/* {actionManager.renderAction("eraser", {
// size: "small",
})} */}
</Stack.Row>
</Island>
</Stack.Row>
</Stack.Col>
</div>
)} )}
</Section> </Section>
)} )}
@@ -414,41 +374,13 @@ const LayerUI = ({
collaborators={appState.collaborators} collaborators={appState.collaborators}
actionManager={actionManager} actionManager={actionManager}
/> />
{onCollabButtonClick && (
<CollabButton
isInHamburgerMenu={false}
isCollaborating={isCollaborating}
collaboratorCount={appState.collaborators.size}
onClick={onCollabButtonClick}
/>
)}
{renderTopRightUI?.(device.isMobile, appState)} {renderTopRightUI?.(device.isMobile, appState)}
{!appState.viewModeEnabled && (
<LibraryButton appState={appState} setAppState={setAppState} />
)}
</div> </div>
</div> </div>
</FixedSideContainer> </FixedSideContainer>
); );
}; };
const renderSidebars = () => {
return appState.openSidebar === "customSidebar" ? (
renderCustomSidebar?.() || null
) : appState.openSidebar === "library" ? (
<LibraryMenu
appState={appState}
onInsertElements={onInsertElements}
libraryReturnUrl={libraryReturnUrl}
focusContainer={focusContainer}
library={library}
id={id}
/>
) : null;
};
const [hostSidebarCounters] = useAtom(hostSidebarCountersAtom, jotaiScope);
return ( return (
<> <>
{appState.isLoading && <LoadingMessage delay={250} />} {appState.isLoading && <LoadingMessage delay={250} />}
@@ -458,14 +390,13 @@ const LayerUI = ({
onClose={() => setAppState({ errorMessage: null })} onClose={() => setAppState({ errorMessage: null })}
/> />
)} )}
{appState.openDialog === "help" && ( {appState.showHelpDialog && (
<HelpDialog <HelpDialog
onClose={() => { onClose={() => {
setAppState({ openDialog: null }); setAppState({ showHelpDialog: false });
}} }}
/> />
)} )}
{renderImageExportDialog()}
{appState.pasteDialog.shown && ( {appState.pasteDialog.shown && (
<PasteChartDialog <PasteChartDialog
setAppState={setAppState} setAppState={setAppState}
@@ -480,10 +411,10 @@ const LayerUI = ({
)} )}
{device.isMobile && ( {device.isMobile && (
<MobileMenu <MobileMenu
renderWelcomeScreen={renderWelcomeScreen}
appState={appState} appState={appState}
elements={elements} elements={elements}
actionManager={actionManager} actionManager={actionManager}
libraryMenu={libraryMenu}
renderJSONExportDialog={renderJSONExportDialog} renderJSONExportDialog={renderJSONExportDialog}
renderImageExportDialog={renderImageExportDialog} renderImageExportDialog={renderImageExportDialog}
setAppState={setAppState} setAppState={setAppState}
@@ -492,11 +423,11 @@ const LayerUI = ({
onPenModeToggle={onPenModeToggle} onPenModeToggle={onPenModeToggle}
canvas={canvas} canvas={canvas}
isCollaborating={isCollaborating} isCollaborating={isCollaborating}
renderCustomFooter={renderCustomFooter}
showThemeBtn={showThemeBtn}
onImageAction={onImageAction} onImageAction={onImageAction}
renderTopRightUI={renderTopRightUI} renderTopRightUI={renderTopRightUI}
renderCustomStats={renderCustomStats} renderCustomStats={renderCustomStats}
renderSidebars={renderSidebars}
device={device}
/> />
)} )}
@@ -511,9 +442,8 @@ const LayerUI = ({
!isTextElement(appState.editingElement)), !isTextElement(appState.editingElement)),
})} })}
style={ style={
((appState.openSidebar === "library" && appState.isLibraryOpen &&
appState.isSidebarDocked) || appState.isLibraryMenuDocked &&
hostSidebarCounters.docked) &&
device.canDeviceFitSidebar device.canDeviceFitSidebar
? { width: `calc(100% - ${LIBRARY_SIDEBAR_WIDTH}px)` } ? { width: `calc(100% - ${LIBRARY_SIDEBAR_WIDTH}px)` }
: {} : {}
@@ -521,14 +451,11 @@ const LayerUI = ({
> >
{renderFixedSideContainer()} {renderFixedSideContainer()}
<Footer <Footer
renderWelcomeScreen={renderWelcomeScreen}
appState={appState} appState={appState}
actionManager={actionManager} actionManager={actionManager}
renderCustomFooter={renderCustomFooter}
showExitZenModeBtn={showExitZenModeBtn} showExitZenModeBtn={showExitZenModeBtn}
> />
{childrenComponents.FooterCenter}
</Footer>
{appState.showStats && ( {appState.showStats && (
<Stats <Stats
appState={appState} appState={appState}
@@ -553,7 +480,9 @@ const LayerUI = ({
</button> </button>
)} )}
</div> </div>
{renderSidebars()} {appState.isLibraryOpen && (
<div className="layer-ui__sidebar">{libraryMenu}</div>
)}
</> </>
)} )}
</> </>
@@ -573,11 +502,8 @@ const areEqual = (prev: LayerUIProps, next: LayerUIProps) => {
const nextAppState = getNecessaryObj(next.appState); const nextAppState = getNecessaryObj(next.appState);
const keys = Object.keys(prevAppState) as (keyof Partial<AppState>)[]; const keys = Object.keys(prevAppState) as (keyof Partial<AppState>)[];
return ( return (
prev.renderTopRightUI === next.renderTopRightUI && prev.renderCustomFooter === next.renderCustomFooter &&
prev.renderCustomStats === next.renderCustomStats &&
prev.renderCustomSidebar === next.renderCustomSidebar &&
prev.langCode === next.langCode && prev.langCode === next.langCode &&
prev.elements === next.elements && prev.elements === next.elements &&
prev.files === next.files && prev.files === next.files &&

View File

@@ -1,32 +0,0 @@
@import "../css/variables.module";
.library-button {
@include outlineButtonStyles;
background-color: var(--island-bg-color);
width: auto;
height: var(--lg-button-size);
display: flex;
align-items: center;
gap: 0.5rem;
line-height: 0;
font-size: 0.75rem;
letter-spacing: 0.4px;
svg {
width: var(--lg-icon-size);
height: var(--lg-icon-size);
}
&__label {
display: none;
@media screen and (min-width: 1024px) {
display: block;
}
}
}

View File

@@ -1,11 +1,19 @@
import React from "react"; import React from "react";
import clsx from "clsx";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppState } from "../types"; import { AppState } from "../types";
import { capitalizeString } from "../utils"; import { capitalizeString } from "../utils";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { useDevice } from "./App"; import { useDevice } from "./App";
import "./LibraryButton.scss";
import { LibraryIcon } from "./icons"; const LIBRARY_ICON = (
<svg viewBox="0 0 576 512">
<path
fill="currentColor"
d="M542.22 32.05c-54.8 3.11-163.72 14.43-230.96 55.59-4.64 2.84-7.27 7.89-7.27 13.17v363.87c0 11.55 12.63 18.85 23.28 13.49 69.18-34.82 169.23-44.32 218.7-46.92 16.89-.89 30.02-14.43 30.02-30.66V62.75c.01-17.71-15.35-31.74-33.77-30.7zM264.73 87.64C197.5 46.48 88.58 35.17 33.78 32.05 15.36 31.01 0 45.04 0 62.75V400.6c0 16.24 13.13 29.78 30.02 30.66 49.49 2.6 149.59 12.11 218.77 46.95 10.62 5.35 23.21-1.94 23.21-13.46V100.63c0-5.29-2.62-10.14-7.27-12.99z"
></path>
</svg>
);
export const LibraryButton: React.FC<{ export const LibraryButton: React.FC<{
appState: AppState; appState: AppState;
@@ -13,16 +21,17 @@ export const LibraryButton: React.FC<{
isMobile?: boolean; isMobile?: boolean;
}> = ({ appState, setAppState, isMobile }) => { }> = ({ appState, setAppState, isMobile }) => {
const device = useDevice(); const device = useDevice();
const showLabel = !isMobile;
// TODO barnabasmolnar/redesign
// not great, toolbar jumps in a jarring manner
if (appState.isSidebarDocked && appState.openSidebar === "library") {
return null;
}
return ( return (
<label title={`${capitalizeString(t("toolBar.library"))}`}> <label
className={clsx(
"ToolIcon ToolIcon_type_floating ToolIcon__library",
`ToolIcon_size_medium`,
{
"is-mobile": isMobile,
},
)}
title={`${capitalizeString(t("toolBar.library"))} — 0`}
>
<input <input
className="ToolIcon_type_checkbox" className="ToolIcon_type_checkbox"
type="checkbox" type="checkbox"
@@ -31,10 +40,10 @@ export const LibraryButton: React.FC<{
document document
.querySelector(".layer-ui__wrapper") .querySelector(".layer-ui__wrapper")
?.classList.remove("animate"); ?.classList.remove("animate");
const isOpen = event.target.checked; const nextState = event.target.checked;
setAppState({ openSidebar: isOpen ? "library" : null }); setAppState({ isLibraryOpen: nextState });
// track only openings // track only openings
if (isOpen) { if (nextState) {
trackEvent( trackEvent(
"library", "library",
"toggleLibrary (open)", "toggleLibrary (open)",
@@ -42,16 +51,11 @@ export const LibraryButton: React.FC<{
); );
} }
}} }}
checked={appState.openSidebar === "library"} checked={appState.isLibraryOpen}
aria-label={capitalizeString(t("toolBar.library"))} aria-label={capitalizeString(t("toolBar.library"))}
aria-keyshortcuts="0" aria-keyshortcuts="0"
/> />
<div className="library-button"> <div className="ToolIcon__icon">{LIBRARY_ICON}</div>
<div>{LibraryIcon}</div>
{showLabel && (
<div className="library-button__label">{t("toolBar.library")}</div>
)}
</div>
</label> </label>
); );
}; };

View File

@@ -1,16 +1,10 @@
@import "open-color/open-color"; @import "open-color/open-color";
.excalidraw { .excalidraw {
.layer-ui__library-sidebar {
display: flex;
flex-direction: column;
}
.layer-ui__library { .layer-ui__library {
display: flex; display: flex;
flex-direction: column; align-items: center;
justify-content: center;
flex: 1 1 auto;
.layer-ui__library-header { .layer-ui__library-header {
display: flex; display: flex;
@@ -29,38 +23,25 @@
} }
.layer-ui__sidebar { .layer-ui__sidebar {
.layer-ui__library {
padding: 0;
height: 100%;
}
.library-menu-items-container { .library-menu-items-container {
height: 100%; height: 100%;
width: 100%; width: 100%;
} }
} }
.library-actions-counter {
background-color: var(--color-primary);
color: var(--color-primary-light);
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
width: 1rem;
height: 1rem;
position: absolute;
bottom: -0.25rem;
right: -0.25rem;
font-size: 0.625rem;
pointer-events: none;
}
.layer-ui__library-message { .layer-ui__library-message {
padding: 2rem; padding: 2em 4em;
min-width: 200px; min-width: 200px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
flex-grow: 1; .Spinner {
justify-content: center; margin-bottom: 1em;
}
span { span {
font-size: 0.8em; font-size: 0.8em;
} }
@@ -88,10 +69,11 @@
} }
.library-menu-browse-button { .library-menu-browse-button {
margin: 1rem auto; width: 80%;
min-height: 22px;
padding: 0.875rem 1rem; margin: 0 auto;
margin-top: 1rem;
padding: 10px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -104,10 +86,6 @@
text-align: center; text-align: center;
white-space: nowrap; white-space: nowrap;
text-decoration: none !important; text-decoration: none !important;
font-weight: 600;
font-size: 0.75rem;
&:hover { &:hover {
background-color: var(--color-primary-darker); background-color: var(--color-primary-darker);
} }
@@ -116,12 +94,6 @@
} }
} }
&.theme--dark {
.library-menu-browse-button {
color: var(--color-gray-100);
}
}
.library-menu-browse-button--mobile { .library-menu-browse-button--mobile {
min-height: 22px; min-height: 22px;
margin-left: auto; margin-left: auto;

View File

@@ -6,13 +6,20 @@ import {
RefObject, RefObject,
forwardRef, forwardRef,
} from "react"; } from "react";
import Library, { import Library, { libraryItemsAtom } from "../data/library";
distributeLibraryItemsOnSquareGrid,
libraryItemsAtom,
} from "../data/library";
import { t } from "../i18n"; import { t } from "../i18n";
import { randomId } from "../random"; import { randomId } from "../random";
import { LibraryItems, LibraryItem, AppState, ExcalidrawProps } from "../types"; 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 "./LibraryMenu.scss";
import LibraryMenuItems from "./LibraryMenuItems"; import LibraryMenuItems from "./LibraryMenuItems";
@@ -22,16 +29,7 @@ import { trackEvent } from "../analytics";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { jotaiScope } from "../jotai"; import { jotaiScope } from "../jotai";
import Spinner from "./Spinner"; import Spinner from "./Spinner";
import { import { useDevice } from "./App";
useDevice,
useExcalidrawElements,
useExcalidrawSetAppState,
} from "./App";
import { Sidebar } from "./Sidebar/Sidebar";
import { getSelectedElements } from "../scene";
import { NonDeletedExcalidrawElement } from "../element/types";
import { LibraryMenuHeader } from "./LibraryMenuHeaderContent";
import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton";
const useOnClickOutside = ( const useOnClickOutside = (
ref: RefObject<HTMLElement>, ref: RefObject<HTMLElement>,
@@ -61,42 +59,110 @@ const useOnClickOutside = (
}, [ref, cb]); }, [ref, cb]);
}; };
const getSelectedItems = (
libraryItems: LibraryItems,
selectedItems: LibraryItem["id"][],
) => libraryItems.filter((item) => selectedItems.includes(item.id));
const LibraryMenuWrapper = forwardRef< const LibraryMenuWrapper = forwardRef<
HTMLDivElement, HTMLDivElement,
{ children: React.ReactNode } { children: React.ReactNode }
>(({ children }, ref) => { >(({ children }, ref) => {
return ( return (
<div ref={ref} className="layer-ui__library"> <Island padding={1} ref={ref} className="layer-ui__library">
{children} {children}
</div> </Island>
); );
}); });
export const LibraryMenuContent = ({ export const LibraryMenu = ({
onClose,
onInsertLibraryItems, onInsertLibraryItems,
pendingElements, pendingElements,
onAddToLibrary, onAddToLibrary,
setAppState, setAppState,
files,
libraryReturnUrl, libraryReturnUrl,
focusContainer,
library, library,
id, id,
appState, appState,
selectedItems,
onSelectItems,
}: { }: {
pendingElements: LibraryItem["elements"]; pendingElements: LibraryItem["elements"];
onClose: () => void;
onInsertLibraryItems: (libraryItems: LibraryItems) => void; onInsertLibraryItems: (libraryItems: LibraryItems) => void;
onAddToLibrary: () => void; onAddToLibrary: () => void;
files: BinaryFiles;
setAppState: React.Component<any, AppState>["setState"]; setAppState: React.Component<any, AppState>["setState"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"]; libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
focusContainer: () => void;
library: Library; library: Library;
id: string; id: string;
appState: AppState; appState: AppState;
selectedItems: LibraryItem["id"][];
onSelectItems: (id: LibraryItem["id"][]) => void;
}) => { }) => {
const ref = useRef<HTMLDivElement | null>(null);
const device = useDevice();
useOnClickOutside(
ref,
useCallback(
(event) => {
// If click on the library icon, do nothing so that LibraryButton
// can toggle library menu
if ((event.target as Element).closest(".ToolIcon__library")) {
return;
}
if (!appState.isLibraryMenuDocked || !device.canDeviceFitSidebar) {
onClose();
}
},
[onClose, appState.isLibraryMenuDocked, device.canDeviceFitSidebar],
),
);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === KEYS.ESCAPE &&
(!appState.isLibraryMenuDocked || !device.canDeviceFitSidebar)
) {
onClose();
}
};
document.addEventListener(EVENT.KEYDOWN, handleKeyDown);
return () => {
document.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
};
}, [onClose, appState.isLibraryMenuDocked, device.canDeviceFitSidebar]);
const [selectedItems, setSelectedItems] = useState<LibraryItem["id"][]>([]);
const [showPublishLibraryDialog, setShowPublishLibraryDialog] =
useState(false);
const [publishLibSuccess, setPublishLibSuccess] = useState<null | {
url: string;
authorName: string;
}>(null);
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope); const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
const removeFromLibrary = useCallback(
async (libraryItems: LibraryItems) => {
const nextItems = libraryItems.filter(
(item) => !selectedItems.includes(item.id),
);
library.setLibrary(nextItems).catch(() => {
setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
});
setSelectedItems([]);
},
[library, setAppState, selectedItems, setSelectedItems],
);
const resetLibrary = useCallback(() => {
library.resetLibrary();
focusContainer();
}, [library, focusContainer]);
const addToLibrary = useCallback( const addToLibrary = useCallback(
async (elements: LibraryItem["elements"], libraryItems: LibraryItems) => { async (elements: LibraryItem["elements"], libraryItems: LibraryItems) => {
trackEvent("element", "addToLibrary", "ui"); trackEvent("element", "addToLibrary", "ui");
@@ -122,188 +188,114 @@ export const LibraryMenuContent = ({
[onAddToLibrary, library, setAppState], [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: { url: string; authorName: string }, libraryItems: LibraryItems) => {
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.setLibrary(nextLibItems);
},
[setShowPublishLibraryDialog, setPublishLibSuccess, selectedItems, library],
);
if ( if (
libraryItemsData.status === "loading" && libraryItemsData.status === "loading" &&
!libraryItemsData.isInitialized !libraryItemsData.isInitialized
) { ) {
return ( return (
<LibraryMenuWrapper> <LibraryMenuWrapper ref={ref}>
<div className="layer-ui__library-message"> <div className="layer-ui__library-message">
<div> <Spinner size="2em" />
<Spinner size="2em" /> <span>{t("labels.libraryLoadingMessage")}</span>
<span>{t("labels.libraryLoadingMessage")}</span>
</div>
</div> </div>
</LibraryMenuWrapper> </LibraryMenuWrapper>
); );
} }
const showBtn =
libraryItemsData.libraryItems.length > 0 || pendingElements.length > 0;
return ( return (
<LibraryMenuWrapper> <LibraryMenuWrapper ref={ref}>
{showPublishLibraryDialog && (
<PublishLibrary
onClose={() => setShowPublishLibraryDialog(false)}
libraryItems={getSelectedItems(
libraryItemsData.libraryItems,
selectedItems,
)}
appState={appState}
onSuccess={(data) =>
onPublishLibSuccess(data, libraryItemsData.libraryItems)
}
onError={(error) => window.alert(error)}
updateItemsInStorage={() =>
library.setLibrary(libraryItemsData.libraryItems)
}
onRemove={(id: string) =>
setSelectedItems(selectedItems.filter((_id) => _id !== id))
}
/>
)}
{publishLibSuccess && renderPublishSuccess()}
<LibraryMenuItems <LibraryMenuItems
isLoading={libraryItemsData.status === "loading"} isLoading={libraryItemsData.status === "loading"}
libraryItems={libraryItemsData.libraryItems} libraryItems={libraryItemsData.libraryItems}
onRemoveFromLibrary={() =>
removeFromLibrary(libraryItemsData.libraryItems)
}
onAddToLibrary={(elements) => onAddToLibrary={(elements) =>
addToLibrary(elements, libraryItemsData.libraryItems) addToLibrary(elements, libraryItemsData.libraryItems)
} }
onInsertLibraryItems={onInsertLibraryItems} onInsertLibraryItems={onInsertLibraryItems}
pendingElements={pendingElements} pendingElements={pendingElements}
selectedItems={selectedItems} setAppState={setAppState}
onSelectItems={onSelectItems} appState={appState}
id={id}
libraryReturnUrl={libraryReturnUrl} libraryReturnUrl={libraryReturnUrl}
library={library}
theme={appState.theme} theme={appState.theme}
files={files}
id={id}
selectedItems={selectedItems}
onSelectItems={(ids) => setSelectedItems(ids)}
onPublish={() => setShowPublishLibraryDialog(true)}
resetLibrary={resetLibrary}
/> />
{showBtn && (
<LibraryMenuBrowseButton
id={id}
libraryReturnUrl={libraryReturnUrl}
theme={appState.theme}
/>
)}
</LibraryMenuWrapper> </LibraryMenuWrapper>
); );
}; };
export const LibraryMenu: React.FC<{
appState: AppState;
onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
focusContainer: () => void;
library: Library;
id: string;
}> = ({
appState,
onInsertElements,
libraryReturnUrl,
focusContainer,
library,
id,
}) => {
const setAppState = useExcalidrawSetAppState();
const elements = useExcalidrawElements();
const device = useDevice();
const [selectedItems, setSelectedItems] = useState<LibraryItem["id"][]>([]);
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
const ref = useRef<HTMLDivElement | null>(null);
const closeLibrary = useCallback(() => {
const isDialogOpen = !!document.querySelector(".Dialog");
// Prevent closing if any dialog is open
if (isDialogOpen) {
return;
}
setAppState({ openSidebar: null });
}, [setAppState]);
useOnClickOutside(
ref,
useCallback(
(event) => {
// If click on the library icon, do nothing so that LibraryButton
// can toggle library menu
if ((event.target as Element).closest(".ToolIcon__library")) {
return;
}
if (!appState.isSidebarDocked || !device.canDeviceFitSidebar) {
closeLibrary();
}
},
[closeLibrary, appState.isSidebarDocked, device.canDeviceFitSidebar],
),
);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === KEYS.ESCAPE &&
(!appState.isSidebarDocked || !device.canDeviceFitSidebar)
) {
closeLibrary();
}
};
document.addEventListener(EVENT.KEYDOWN, handleKeyDown);
return () => {
document.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
};
}, [closeLibrary, appState.isSidebarDocked, device.canDeviceFitSidebar]);
const deselectItems = useCallback(() => {
setAppState({
selectedElementIds: {},
selectedGroupIds: {},
});
}, [setAppState]);
const removeFromLibrary = useCallback(
async (libraryItems: LibraryItems) => {
const nextItems = libraryItems.filter(
(item) => !selectedItems.includes(item.id),
);
library.setLibrary(nextItems).catch(() => {
setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
});
setSelectedItems([]);
},
[library, setAppState, selectedItems, setSelectedItems],
);
const resetLibrary = useCallback(() => {
library.resetLibrary();
focusContainer();
}, [library, focusContainer]);
return (
<Sidebar
__isInternal
// necessary to remount when switching between internal
// and custom (host app) sidebar, so that the `props.onClose`
// is colled correctly
key="library"
className="layer-ui__library-sidebar"
initialDockedState={appState.isSidebarDocked}
onDock={(docked) => {
trackEvent(
"library",
`toggleLibraryDock (${docked ? "dock" : "undock"})`,
`sidebar (${device.isMobile ? "mobile" : "desktop"})`,
);
}}
ref={ref}
>
<Sidebar.Header className="layer-ui__library-header">
<LibraryMenuHeader
appState={appState}
setAppState={setAppState}
selectedItems={selectedItems}
onSelectItems={setSelectedItems}
library={library}
onRemoveFromLibrary={() =>
removeFromLibrary(libraryItemsData.libraryItems)
}
resetLibrary={resetLibrary}
/>
</Sidebar.Header>
<LibraryMenuContent
pendingElements={getSelectedElements(elements, appState, true)}
onInsertLibraryItems={(libraryItems) => {
onInsertElements(distributeLibraryItemsOnSquareGrid(libraryItems));
}}
onAddToLibrary={deselectItems}
setAppState={setAppState}
libraryReturnUrl={libraryReturnUrl}
library={library}
id={id}
appState={appState}
selectedItems={selectedItems}
onSelectItems={setSelectedItems}
/>
</Sidebar>
);
};

View File

@@ -1,31 +0,0 @@
import { VERSIONS } from "../constants";
import { t } from "../i18n";
import { AppState, ExcalidrawProps } from "../types";
const LibraryMenuBrowseButton = ({
theme,
id,
libraryReturnUrl,
}: {
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
theme: AppState["theme"];
id: string;
}) => {
const referrer =
libraryReturnUrl || window.location.origin + window.location.pathname;
return (
<a
className="library-menu-browse-button"
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
window.name || "_blank"
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}&version=${
VERSIONS.excalidrawLibrary
}`}
target="_excalidraw_libraries"
>
{t("labels.libraries")}
</a>
);
};
export default LibraryMenuBrowseButton;

View File

@@ -1,257 +0,0 @@
import React, { useCallback, useState } from "react";
import { saveLibraryAsJSON } from "../data/json";
import Library, { libraryItemsAtom } from "../data/library";
import { t } from "../i18n";
import { AppState, LibraryItem, LibraryItems } from "../types";
import {
DotsIcon,
ExportIcon,
LoadIcon,
publishIcon,
TrashIcon,
} from "./icons";
import { ToolButton } from "./ToolButton";
import { fileOpen } from "../data/filesystem";
import { muteFSAbortError } from "../utils";
import { useAtom } from "jotai";
import { jotaiScope } from "../jotai";
import ConfirmDialog from "./ConfirmDialog";
import PublishLibrary from "./PublishLibrary";
import { Dialog } from "./Dialog";
import { useOutsideClickHook } from "../hooks/useOutsideClick";
import MenuItem from "./MenuItem";
import { isDropdownOpenAtom } from "./App";
const getSelectedItems = (
libraryItems: LibraryItems,
selectedItems: LibraryItem["id"][],
) => libraryItems.filter((item) => selectedItems.includes(item.id));
export const LibraryMenuHeader: React.FC<{
setAppState: React.Component<any, AppState>["setState"];
selectedItems: LibraryItem["id"][];
library: Library;
onRemoveFromLibrary: () => void;
resetLibrary: () => void;
onSelectItems: (items: LibraryItem["id"][]) => void;
appState: AppState;
}> = ({
setAppState,
selectedItems,
library,
onRemoveFromLibrary,
resetLibrary,
onSelectItems,
appState,
}) => {
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
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 itemsSelected = !!selectedItems.length;
const items = itemsSelected
? libraryItemsData.libraryItems.filter((item) =>
selectedItems.includes(item.id),
)
: libraryItemsData.libraryItems;
const resetLabel = itemsSelected
? t("buttons.remove")
: t("buttons.resetLibrary");
const [showPublishLibraryDialog, setShowPublishLibraryDialog] =
useState(false);
const [publishLibSuccess, setPublishLibSuccess] = useState<null | {
url: string;
authorName: string;
}>(null);
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: { url: string; authorName: string }, libraryItems: LibraryItems) => {
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.setLibrary(nextLibItems);
},
[setShowPublishLibraryDialog, setPublishLibSuccess, selectedItems, library],
);
const onLibraryImport = async () => {
try {
await library.updateLibrary({
libraryItems: fileOpen({
description: "Excalidraw library files",
// ToDo: Be over-permissive until https://bugs.webkit.org/show_bug.cgi?id=34442
// gets resolved. Else, iOS users cannot open `.excalidraw` files.
/*
extensions: [".json", ".excalidrawlib"],
*/
}),
merge: true,
openLibraryMenu: true,
});
} catch (error: any) {
if (error?.name === "AbortError") {
console.warn(error);
return;
}
setAppState({ errorMessage: t("errors.importLibraryError") });
}
};
const onLibraryExport = async () => {
const libraryItems = itemsSelected
? items
: await library.getLatestLibrary();
saveLibraryAsJSON(libraryItems)
.catch(muteFSAbortError)
.catch((error) => {
setAppState({ errorMessage: error.message });
});
};
const [isDropdownOpen, setIsDropdownOpen] = useAtom(isDropdownOpenAtom);
const dropdownRef = useOutsideClickHook(() => setIsDropdownOpen(false));
return (
<div style={{ position: "relative" }}>
<button
type="button"
className="Sidebar__dropdown-btn"
data-prevent-outside-click
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
>
{DotsIcon}
</button>
{selectedItems.length > 0 && (
<div className="library-actions-counter">{selectedItems.length}</div>
)}
{isDropdownOpen && (
<div
className="Sidebar__dropdown-content menu-container"
ref={dropdownRef}
>
{!itemsSelected && (
<MenuItem
label={t("buttons.load")}
icon={LoadIcon}
dataTestId="lib-dropdown--load"
onClick={onLibraryImport}
/>
)}
{showRemoveLibAlert && renderRemoveLibAlert()}
{showPublishLibraryDialog && (
<PublishLibrary
onClose={() => setShowPublishLibraryDialog(false)}
libraryItems={getSelectedItems(
libraryItemsData.libraryItems,
selectedItems,
)}
appState={appState}
onSuccess={(data) =>
onPublishLibSuccess(data, libraryItemsData.libraryItems)
}
onError={(error) => window.alert(error)}
updateItemsInStorage={() =>
library.setLibrary(libraryItemsData.libraryItems)
}
onRemove={(id: string) =>
onSelectItems(selectedItems.filter((_id) => _id !== id))
}
/>
)}
{publishLibSuccess && renderPublishSuccess()}
{!!items.length && (
<>
<MenuItem
label={t("buttons.export")}
icon={ExportIcon}
onClick={onLibraryExport}
dataTestId="lib-dropdown--export"
/>
<MenuItem
label={resetLabel}
icon={TrashIcon}
onClick={() => setShowRemoveLibAlert(true)}
dataTestId="lib-dropdown--remove"
/>
</>
)}
{itemsSelected && (
<MenuItem
label={t("buttons.publishLibrary")}
icon={publishIcon}
dataTestId="lib-dropdown--publish"
onClick={() => setShowPublishLibraryDialog(true)}
/>
)}
</div>
)}
</div>
);
};

View File

@@ -1,70 +1,107 @@
@import "open-color/open-color"; @import "open-color/open-color";
.excalidraw { .excalidraw {
--container-padding-y: 1.5rem;
--container-padding-x: 0.75rem;
.library-menu-items__no-items {
text-align: center;
color: var(--color-gray-70);
line-height: 1.5;
font-size: 0.875rem;
width: 100%;
&__label {
color: var(--color-primary);
font-weight: bold;
font-size: 1.125rem;
margin-bottom: 0.75rem;
}
}
&.theme--dark {
.library-menu-items__no-items {
color: var(--color-gray-40);
}
}
.library-menu-items-container { .library-menu-items-container {
display: flex; display: flex;
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
overflow-y: auto;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
justify-content: center; padding: 0.5rem;
margin: 0; box-sizing: border-box;
border-bottom: 1px solid var(--sidebar-border-color);
position: relative; .library-actions {
width: 100%;
display: flex;
margin-right: auto;
align-items: center;
&__row { button .library-actions-counter {
display: grid; position: absolute;
grid-template-columns: repeat(4, 1fr); right: 2px;
gap: 1rem; 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 { &__items {
row-gap: 0.5rem;
padding: var(--container-padding-y) var(--container-padding-x);
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
overflow-x: hidden; overflow-x: hidden;
margin-bottom: 1rem; margin-bottom: 1rem;
} }
&__header {
color: var(--color-primary);
font-size: 1.125rem;
font-weight: bold;
margin-bottom: 0.75rem;
&--excal {
margin-top: 2.5rem;
}
}
.separator { .separator {
width: 100%; width: 100%;
display: flex; display: flex;

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