Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f09e465560 | |||
| 6a891365b9 | |||
| 54fa0c9089 | |||
| dfdd994dbb | |||
| 28691e14b1 | |||
| 60759d314d | |||
| d5e37cda81 | |||
| 6135548534 | |||
| acf54c6f38 | |||
| 84a309d669 | |||
| 3c8e893cab | |||
| 9ba0f5dbc9 | |||
| 60ab14c2f6 | |||
| 0988ecfef4 | |||
| 1f47d61e8c | |||
| 9d760336d1 | |||
| 0443511954 | |||
| 5a73b9a363 | |||
| 24a6941861 | |||
| a0b98a944f | |||
| 6ebf52279d | |||
| 3b97f5a10c | |||
| da59205846 | |||
| b9a255407f | |||
| cc6c29c0b9 | |||
| 87faa5d3da | |||
| c158187f20 | |||
| 63e1148280 | |||
| b5fc873323 | |||
| 6c908553a9 | |||
| 0586fc138c |
+2
-2
@@ -12,7 +12,7 @@ VITE_APP_WS_SERVER_URL=http://localhost:3002
|
|||||||
VITE_APP_PLUS_LP=https://plus.excalidraw.com
|
VITE_APP_PLUS_LP=https://plus.excalidraw.com
|
||||||
VITE_APP_PLUS_APP=http://localhost:3000
|
VITE_APP_PLUS_APP=http://localhost:3000
|
||||||
|
|
||||||
VITE_APP_AI_BACKEND=http://localhost:3015
|
VITE_APP_AI_BACKEND=http://localhost:3016
|
||||||
|
|
||||||
VITE_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyCMkxA60XIW8KbqMYL7edC4qT5l4qHX2h8","authDomain":"excalidraw-oss-dev.firebaseapp.com","projectId":"excalidraw-oss-dev","storageBucket":"excalidraw-oss-dev.appspot.com","messagingSenderId":"664559512677","appId":"1:664559512677:web:a385181f2928d328a7aa8c"}'
|
VITE_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyCMkxA60XIW8KbqMYL7edC4qT5l4qHX2h8","authDomain":"excalidraw-oss-dev.firebaseapp.com","projectId":"excalidraw-oss-dev","storageBucket":"excalidraw-oss-dev.appspot.com","messagingSenderId":"664559512677","appId":"1:664559512677:web:a385181f2928d328a7aa8c"}'
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ VITE_APP_ENABLE_TRACKING=true
|
|||||||
FAST_REFRESH=false
|
FAST_REFRESH=false
|
||||||
|
|
||||||
# The port the run the dev server
|
# The port the run the dev server
|
||||||
VITE_APP_PORT=3000
|
VITE_APP_PORT=3001
|
||||||
|
|
||||||
#Debug flags
|
#Debug flags
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ jobs:
|
|||||||
export SENTRY_RELEASE=$(sentry-cli releases propose-version)
|
export SENTRY_RELEASE=$(sentry-cli releases propose-version)
|
||||||
sentry-cli releases new $SENTRY_RELEASE --project $SENTRY_PROJECT
|
sentry-cli releases new $SENTRY_RELEASE --project $SENTRY_PROJECT
|
||||||
sentry-cli releases set-commits --auto $SENTRY_RELEASE
|
sentry-cli releases set-commits --auto $SENTRY_RELEASE
|
||||||
sentry-cli releases files $SENTRY_RELEASE upload-sourcemaps --no-rewrite ./build/static/js/ --url-prefix "~/static/js"
|
sentry-cli sourcemaps upload --release $SENTRY_RELEASE --no-rewrite ./build/static/js/ --url-prefix "~/static/js"
|
||||||
sentry-cli releases finalize $SENTRY_RELEASE
|
sentry-cli releases finalize $SENTRY_RELEASE
|
||||||
sentry-cli releases deploys $SENTRY_RELEASE new -e production
|
sentry-cli releases deploys $SENTRY_RELEASE new -e production
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
- name: "Install Node"
|
- name: "Install Node"
|
||||||
uses: actions/setup-node@v2
|
uses: actions/setup-node@v2
|
||||||
with:
|
with:
|
||||||
node-version: "18.x"
|
node-version: "20.x"
|
||||||
- name: "Install Deps"
|
- name: "Install Deps"
|
||||||
run: yarn install
|
run: yarn install
|
||||||
- name: "Test Coverage"
|
- name: "Test Coverage"
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Setup Node.js 18.x
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 18.x
|
node-version: 20.x
|
||||||
- name: Install and test
|
- name: Install and test
|
||||||
run: |
|
run: |
|
||||||
yarn install
|
yarn install
|
||||||
|
|||||||
+40
-8
@@ -48,7 +48,11 @@ import {
|
|||||||
youtubeIcon,
|
youtubeIcon,
|
||||||
} from "@excalidraw/excalidraw/components/icons";
|
} from "@excalidraw/excalidraw/components/icons";
|
||||||
import { isElementLink } from "@excalidraw/element";
|
import { isElementLink } from "@excalidraw/element";
|
||||||
import { restore, restoreAppState } from "@excalidraw/excalidraw/data/restore";
|
import {
|
||||||
|
bumpElementVersions,
|
||||||
|
restoreAppState,
|
||||||
|
restoreElements,
|
||||||
|
} from "@excalidraw/excalidraw/data/restore";
|
||||||
import { newElementWith } from "@excalidraw/element";
|
import { newElementWith } from "@excalidraw/element";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
@@ -105,8 +109,8 @@ import { TopErrorBoundary } from "./components/TopErrorBoundary";
|
|||||||
import {
|
import {
|
||||||
exportToBackend,
|
exportToBackend,
|
||||||
getCollaborationLinkData,
|
getCollaborationLinkData,
|
||||||
|
importFromBackend,
|
||||||
isCollaborationLink,
|
isCollaborationLink,
|
||||||
loadScene,
|
|
||||||
} from "./data";
|
} from "./data";
|
||||||
|
|
||||||
import { updateStaleImageStatuses } from "./data/FileManager";
|
import { updateStaleImageStatuses } from "./data/FileManager";
|
||||||
@@ -224,9 +228,20 @@ const initializeScene = async (opts: {
|
|||||||
|
|
||||||
const localDataState = importFromLocalStorage();
|
const localDataState = importFromLocalStorage();
|
||||||
|
|
||||||
let scene: RestoredDataState & {
|
let scene: Omit<
|
||||||
|
RestoredDataState,
|
||||||
|
// we're not storing files in the scene database/localStorage, and instead
|
||||||
|
// fetch them async from a different store
|
||||||
|
"files"
|
||||||
|
> & {
|
||||||
scrollToContent?: boolean;
|
scrollToContent?: boolean;
|
||||||
} = await loadScene(null, null, localDataState);
|
} = {
|
||||||
|
elements: restoreElements(localDataState?.elements, null, {
|
||||||
|
repairBindings: true,
|
||||||
|
deleteInvisibleElements: true,
|
||||||
|
}),
|
||||||
|
appState: restoreAppState(localDataState?.appState, null),
|
||||||
|
};
|
||||||
|
|
||||||
let roomLinkData = getCollaborationLinkData(window.location.href);
|
let roomLinkData = getCollaborationLinkData(window.location.href);
|
||||||
const isExternalScene = !!(id || jsonBackendMatch || roomLinkData);
|
const isExternalScene = !!(id || jsonBackendMatch || roomLinkData);
|
||||||
@@ -240,11 +255,26 @@ const initializeScene = async (opts: {
|
|||||||
(await openConfirmModal(shareableLinkConfirmDialog))
|
(await openConfirmModal(shareableLinkConfirmDialog))
|
||||||
) {
|
) {
|
||||||
if (jsonBackendMatch) {
|
if (jsonBackendMatch) {
|
||||||
scene = await loadScene(
|
const imported = await importFromBackend(
|
||||||
jsonBackendMatch[1],
|
jsonBackendMatch[1],
|
||||||
jsonBackendMatch[2],
|
jsonBackendMatch[2],
|
||||||
localDataState,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
scene = {
|
||||||
|
elements: bumpElementVersions(
|
||||||
|
restoreElements(imported.elements, null, {
|
||||||
|
repairBindings: true,
|
||||||
|
deleteInvisibleElements: true,
|
||||||
|
}),
|
||||||
|
localDataState?.elements,
|
||||||
|
),
|
||||||
|
appState: restoreAppState(
|
||||||
|
imported.appState,
|
||||||
|
// local appState when importing from backend to ensure we restore
|
||||||
|
// localStorage user settings which we do not persist on server.
|
||||||
|
localDataState?.appState,
|
||||||
|
),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
scene.scrollToContent = true;
|
scene.scrollToContent = true;
|
||||||
if (!roomLinkData) {
|
if (!roomLinkData) {
|
||||||
@@ -496,8 +526,10 @@ const ExcalidrawWrapper = () => {
|
|||||||
loadImages(data);
|
loadImages(data);
|
||||||
if (data.scene) {
|
if (data.scene) {
|
||||||
excalidrawAPI.updateScene({
|
excalidrawAPI.updateScene({
|
||||||
...data.scene,
|
elements: restoreElements(data.scene.elements, null, {
|
||||||
...restore(data.scene, null, null, { repairBindings: true }),
|
repairBindings: true,
|
||||||
|
}),
|
||||||
|
appState: restoreAppState(data.scene.appState, null),
|
||||||
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ export const STORAGE_KEYS = {
|
|||||||
VERSION_FILES: "version-files",
|
VERSION_FILES: "version-files",
|
||||||
|
|
||||||
IDB_LIBRARY: "excalidraw-library",
|
IDB_LIBRARY: "excalidraw-library",
|
||||||
|
IDB_TTD_CHATS: "excalidraw-ttd-chats",
|
||||||
|
|
||||||
// do not use apart from migrations
|
// do not use apart from migrations
|
||||||
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
reconcileElements,
|
reconcileElements,
|
||||||
} from "@excalidraw/excalidraw";
|
} from "@excalidraw/excalidraw";
|
||||||
import { ErrorDialog } from "@excalidraw/excalidraw/components/ErrorDialog";
|
import { ErrorDialog } from "@excalidraw/excalidraw/components/ErrorDialog";
|
||||||
import { APP_NAME, EVENT } from "@excalidraw/common";
|
import { APP_NAME, cloneJSON, EVENT, toBrandedType } from "@excalidraw/common";
|
||||||
import {
|
import {
|
||||||
IDLE_THRESHOLD,
|
IDLE_THRESHOLD,
|
||||||
ACTIVE_THRESHOLD,
|
ACTIVE_THRESHOLD,
|
||||||
@@ -29,6 +29,8 @@ import { withBatchedUpdates } from "@excalidraw/excalidraw/reactUtils";
|
|||||||
import throttle from "lodash.throttle";
|
import throttle from "lodash.throttle";
|
||||||
import { PureComponent } from "react";
|
import { PureComponent } from "react";
|
||||||
|
|
||||||
|
import { bumpElementVersions } from "@excalidraw/excalidraw/data/restore";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ReconciledExcalidrawElement,
|
ReconciledExcalidrawElement,
|
||||||
RemoteExcalidrawElement,
|
RemoteExcalidrawElement,
|
||||||
@@ -311,6 +313,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
saveCollabRoomToFirebase = async (
|
saveCollabRoomToFirebase = async (
|
||||||
syncableElements: readonly SyncableExcalidrawElement[],
|
syncableElements: readonly SyncableExcalidrawElement[],
|
||||||
) => {
|
) => {
|
||||||
|
syncableElements = cloneJSON(syncableElements);
|
||||||
try {
|
try {
|
||||||
const storedElements = await saveToFirebase(
|
const storedElements = await saveToFirebase(
|
||||||
this.portal,
|
this.portal,
|
||||||
@@ -579,7 +582,9 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
case WS_SUBTYPES.INIT: {
|
case WS_SUBTYPES.INIT: {
|
||||||
if (!this.portal.socketInitialized) {
|
if (!this.portal.socketInitialized) {
|
||||||
this.initializeRoom({ fetchScene: false });
|
this.initializeRoom({ fetchScene: false });
|
||||||
const remoteElements = decryptedData.payload.elements;
|
const remoteElements = toBrandedType<
|
||||||
|
readonly RemoteExcalidrawElement[]
|
||||||
|
>(decryptedData.payload.elements);
|
||||||
const reconciledElements =
|
const reconciledElements =
|
||||||
this._reconcileElements(remoteElements);
|
this._reconcileElements(remoteElements);
|
||||||
this.handleRemoteSceneUpdate(reconciledElements);
|
this.handleRemoteSceneUpdate(reconciledElements);
|
||||||
@@ -593,7 +598,11 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
}
|
}
|
||||||
case WS_SUBTYPES.UPDATE:
|
case WS_SUBTYPES.UPDATE:
|
||||||
this.handleRemoteSceneUpdate(
|
this.handleRemoteSceneUpdate(
|
||||||
this._reconcileElements(decryptedData.payload.elements),
|
this._reconcileElements(
|
||||||
|
toBrandedType<readonly RemoteExcalidrawElement[]>(
|
||||||
|
decryptedData.payload.elements,
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
case WS_SUBTYPES.MOUSE_LOCATION: {
|
case WS_SUBTYPES.MOUSE_LOCATION: {
|
||||||
@@ -742,20 +751,28 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
private _reconcileElements = (
|
private _reconcileElements = (
|
||||||
remoteElements: readonly ExcalidrawElement[],
|
remoteElements: readonly RemoteExcalidrawElement[],
|
||||||
): ReconciledExcalidrawElement[] => {
|
): ReconciledExcalidrawElement[] => {
|
||||||
const localElements = this.getSceneElementsIncludingDeleted();
|
|
||||||
const appState = this.excalidrawAPI.getAppState();
|
const appState = this.excalidrawAPI.getAppState();
|
||||||
const restoredRemoteElements = restoreElements(
|
|
||||||
|
const existingElements = this.getSceneElementsIncludingDeleted();
|
||||||
|
|
||||||
|
// NOTE ideally we restore _after_ reconciliation but we can't do that
|
||||||
|
// as we'd regenerate even elements such as appState.newElement which would
|
||||||
|
// break the state
|
||||||
|
remoteElements = restoreElements(remoteElements, existingElements);
|
||||||
|
|
||||||
|
let reconciledElements = reconcileElements(
|
||||||
|
existingElements,
|
||||||
remoteElements,
|
remoteElements,
|
||||||
this.excalidrawAPI.getSceneElementsMapIncludingDeleted(),
|
|
||||||
);
|
|
||||||
const reconciledElements = reconcileElements(
|
|
||||||
localElements,
|
|
||||||
restoredRemoteElements as RemoteExcalidrawElement[],
|
|
||||||
appState,
|
appState,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
reconciledElements = bumpElementVersions(
|
||||||
|
reconciledElements,
|
||||||
|
existingElements,
|
||||||
|
);
|
||||||
|
|
||||||
// Avoid broadcasting to the rest of the collaborators the scene
|
// Avoid broadcasting to the rest of the collaborators the scene
|
||||||
// we just received!
|
// we just received!
|
||||||
// Note: this needs to be set before updating the scene as it
|
// Note: this needs to be set before updating the scene as it
|
||||||
|
|||||||
@@ -4,12 +4,15 @@ import {
|
|||||||
getTextFromElements,
|
getTextFromElements,
|
||||||
MIME_TYPES,
|
MIME_TYPES,
|
||||||
TTDDialog,
|
TTDDialog,
|
||||||
|
TTDStreamFetch,
|
||||||
} from "@excalidraw/excalidraw";
|
} from "@excalidraw/excalidraw";
|
||||||
import { getDataURL } from "@excalidraw/excalidraw/data/blob";
|
import { getDataURL } from "@excalidraw/excalidraw/data/blob";
|
||||||
import { safelyParseJSON } from "@excalidraw/common";
|
import { safelyParseJSON } from "@excalidraw/common";
|
||||||
|
|
||||||
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
|
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
|
import { TTDIndexedDBAdapter } from "../data/TTDStorage";
|
||||||
|
|
||||||
export const AIComponents = ({
|
export const AIComponents = ({
|
||||||
excalidrawAPI,
|
excalidrawAPI,
|
||||||
}: {
|
}: {
|
||||||
@@ -99,61 +102,23 @@ export const AIComponents = ({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TTDDialog
|
<TTDDialog
|
||||||
onTextSubmit={async (input) => {
|
onTextSubmit={async (props) => {
|
||||||
try {
|
const { onChunk, onStreamCreated, signal, messages } = props;
|
||||||
const response = await fetch(
|
|
||||||
`${
|
|
||||||
import.meta.env.VITE_APP_AI_BACKEND
|
|
||||||
}/v1/ai/text-to-diagram/generate`,
|
|
||||||
{
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
Accept: "application/json",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ prompt: input }),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const rateLimit = response.headers.has("X-Ratelimit-Limit")
|
const result = await TTDStreamFetch({
|
||||||
? parseInt(response.headers.get("X-Ratelimit-Limit") || "0", 10)
|
url: `${
|
||||||
: undefined;
|
import.meta.env.VITE_APP_AI_BACKEND
|
||||||
|
}/v1/ai/text-to-diagram/chat-streaming`,
|
||||||
|
messages,
|
||||||
|
onChunk,
|
||||||
|
onStreamCreated,
|
||||||
|
extractRateLimits: true,
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
|
||||||
const rateLimitRemaining = response.headers.has(
|
return result;
|
||||||
"X-Ratelimit-Remaining",
|
|
||||||
)
|
|
||||||
? parseInt(
|
|
||||||
response.headers.get("X-Ratelimit-Remaining") || "0",
|
|
||||||
10,
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const json = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
if (response.status === 429) {
|
|
||||||
return {
|
|
||||||
rateLimit,
|
|
||||||
rateLimitRemaining,
|
|
||||||
error: new Error(
|
|
||||||
"Too many requests today, please try again tomorrow!",
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(json.message || "Generation failed...");
|
|
||||||
}
|
|
||||||
|
|
||||||
const generatedResponse = json.generatedResponse;
|
|
||||||
if (!generatedResponse) {
|
|
||||||
throw new Error("Generation failed...");
|
|
||||||
}
|
|
||||||
|
|
||||||
return { generatedResponse, rateLimit, rateLimitRemaining };
|
|
||||||
} catch (err: any) {
|
|
||||||
throw new Error("Request failed");
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
|
persistenceAdapter={TTDIndexedDBAdapter}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,7 +27,10 @@ import { isCurve } from "@excalidraw/math/curve";
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
import type { Curve } from "@excalidraw/math";
|
import type { Curve } from "@excalidraw/math";
|
||||||
import type { DebugElement } from "@excalidraw/common";
|
import type {
|
||||||
|
DebugElement,
|
||||||
|
DebugPolygon,
|
||||||
|
} from "@excalidraw/element/visualdebug";
|
||||||
import type {
|
import type {
|
||||||
ElementsMap,
|
ElementsMap,
|
||||||
ExcalidrawArrowElement,
|
ExcalidrawArrowElement,
|
||||||
@@ -75,6 +78,44 @@ const renderCubicBezier = (
|
|||||||
context.restore();
|
context.restore();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const renderPolygon = (
|
||||||
|
context: CanvasRenderingContext2D,
|
||||||
|
zoom: number,
|
||||||
|
polygon: DebugPolygon,
|
||||||
|
color: string,
|
||||||
|
) => {
|
||||||
|
const { points, fill, close } = polygon;
|
||||||
|
|
||||||
|
if (points.length < 2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.save();
|
||||||
|
context.beginPath();
|
||||||
|
context.moveTo(points[0][0] * zoom, points[0][1] * zoom);
|
||||||
|
for (let i = 1; i < points.length; i += 1) {
|
||||||
|
context.lineTo(points[i][0] * zoom, points[i][1] * zoom);
|
||||||
|
}
|
||||||
|
if (close !== false) {
|
||||||
|
context.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fill) {
|
||||||
|
context.save();
|
||||||
|
context.globalAlpha = 0.15;
|
||||||
|
context.fillStyle = color;
|
||||||
|
context.fill();
|
||||||
|
context.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
context.strokeStyle = color;
|
||||||
|
context.stroke();
|
||||||
|
context.restore();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isDebugPolygon = (data: DebugElement["data"]): data is DebugPolygon =>
|
||||||
|
(data as DebugPolygon).type === "polygon";
|
||||||
|
|
||||||
const renderOrigin = (context: CanvasRenderingContext2D, zoom: number) => {
|
const renderOrigin = (context: CanvasRenderingContext2D, zoom: number) => {
|
||||||
context.strokeStyle = "#888";
|
context.strokeStyle = "#888";
|
||||||
context.save();
|
context.save();
|
||||||
@@ -280,6 +321,9 @@ const render = (
|
|||||||
el.color,
|
el.color,
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
|
case isDebugPolygon(el.data):
|
||||||
|
renderPolygon(context, appState.zoom.value, el.data, el.color);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unknown element type ${JSON.stringify(el)}`);
|
throw new Error(`Unknown element type ${JSON.stringify(el)}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { THEME } from "@excalidraw/common";
|
|
||||||
import oc from "open-color";
|
|
||||||
import React from "react";
|
|
||||||
|
|
||||||
import type { Theme } from "@excalidraw/element/types";
|
|
||||||
|
|
||||||
// https://github.com/tholman/github-corners
|
|
||||||
export const GitHubCorner = React.memo(
|
|
||||||
({ theme, dir }: { theme: Theme; dir: string }) => (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
width="40"
|
|
||||||
height="40"
|
|
||||||
viewBox="0 0 250 250"
|
|
||||||
className="rtl-mirror"
|
|
||||||
style={{
|
|
||||||
marginTop: "calc(var(--space-factor) * -1)",
|
|
||||||
[dir === "rtl" ? "marginLeft" : "marginRight"]:
|
|
||||||
"calc(var(--space-factor) * -1)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<a
|
|
||||||
href="https://github.com/excalidraw/excalidraw"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
aria-label="GitHub repository"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M0 0l115 115h15l12 27 108 108V0z"
|
|
||||||
fill={theme === THEME.LIGHT ? oc.gray[6] : oc.gray[7]}
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
className="octo-arm"
|
|
||||||
d="M128 109c-15-9-9-19-9-19 3-7 2-11 2-11-1-7 3-2 3-2 4 5 2 11 2 11-3 10 5 15 9 16"
|
|
||||||
style={{ transformOrigin: "130px 106px" }}
|
|
||||||
fill={theme === THEME.LIGHT ? oc.white : "var(--default-bg-color)"}
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
className="octo-body"
|
|
||||||
d="M115 115s4 2 5 0l14-14c3-2 6-3 8-3-8-11-15-24 2-41 5-5 10-7 16-7 1-2 3-7 12-11 0 0 5 3 7 16 4 2 8 5 12 9s7 8 9 12c14 3 17 7 17 7-4 8-9 11-11 11 0 6-2 11-7 16-16 16-30 10-41 2 0 3-1 7-5 11l-12 11c-1 1 1 5 1 5z"
|
|
||||||
fill={theme === THEME.LIGHT ? oc.white : "var(--default-bg-color)"}
|
|
||||||
/>
|
|
||||||
</a>
|
|
||||||
</svg>
|
|
||||||
),
|
|
||||||
);
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { createStore, get, set } from "idb-keyval";
|
||||||
|
|
||||||
|
import type { SavedChats } from "@excalidraw/excalidraw/components/TTDDialog/types";
|
||||||
|
|
||||||
|
import { STORAGE_KEYS } from "../app_constants";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IndexedDB adapter for TTD chat storage.
|
||||||
|
* Implements TTDPersistenceAdapter interface.
|
||||||
|
*/
|
||||||
|
export class TTDIndexedDBAdapter {
|
||||||
|
/** IndexedDB database name */
|
||||||
|
private static idb_name = STORAGE_KEYS.IDB_TTD_CHATS;
|
||||||
|
/** Store key for chat data */
|
||||||
|
private static key = "ttdChats";
|
||||||
|
|
||||||
|
private static store = createStore(
|
||||||
|
`${TTDIndexedDBAdapter.idb_name}-db`,
|
||||||
|
`${TTDIndexedDBAdapter.idb_name}-store`,
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load saved chats from IndexedDB.
|
||||||
|
* @returns Promise resolving to saved chats array (empty if none found)
|
||||||
|
*/
|
||||||
|
static async loadChats(): Promise<SavedChats> {
|
||||||
|
try {
|
||||||
|
const data = await get<SavedChats>(
|
||||||
|
TTDIndexedDBAdapter.key,
|
||||||
|
TTDIndexedDBAdapter.store,
|
||||||
|
);
|
||||||
|
return data || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("Failed to load TTD chats from IndexedDB:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save chats to IndexedDB.
|
||||||
|
* @param chats - The chats array to persist
|
||||||
|
*/
|
||||||
|
static async saveChats(chats: SavedChats): Promise<void> {
|
||||||
|
try {
|
||||||
|
await set(TTDIndexedDBAdapter.key, chats, TTDIndexedDBAdapter.store);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("Failed to save TTD chats to IndexedDB:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { reconcileElements } from "@excalidraw/excalidraw";
|
import { reconcileElements } from "@excalidraw/excalidraw";
|
||||||
import { MIME_TYPES } from "@excalidraw/common";
|
import { MIME_TYPES, toBrandedType } from "@excalidraw/common";
|
||||||
import { decompressData } from "@excalidraw/excalidraw/data/encode";
|
import { decompressData } from "@excalidraw/excalidraw/data/encode";
|
||||||
import {
|
import {
|
||||||
encryptData,
|
encryptData,
|
||||||
@@ -243,7 +243,7 @@ export const saveToFirebase = async (
|
|||||||
|
|
||||||
FirebaseSceneVersionCache.set(socket, storedElements);
|
FirebaseSceneVersionCache.set(socket, storedElements);
|
||||||
|
|
||||||
return storedElements;
|
return toBrandedType<RemoteExcalidrawElement[]>(storedElements);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const loadFromFirebase = async (
|
export const loadFromFirebase = async (
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
IV_LENGTH_BYTES,
|
IV_LENGTH_BYTES,
|
||||||
} from "@excalidraw/excalidraw/data/encryption";
|
} from "@excalidraw/excalidraw/data/encryption";
|
||||||
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
||||||
import { restore } from "@excalidraw/excalidraw/data/restore";
|
|
||||||
import { isInvisiblySmallElement } from "@excalidraw/element";
|
import { isInvisiblySmallElement } from "@excalidraw/element";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element";
|
||||||
import { t } from "@excalidraw/excalidraw/i18n";
|
import { t } from "@excalidraw/excalidraw/i18n";
|
||||||
@@ -84,13 +83,13 @@ export type SocketUpdateDataSource = {
|
|||||||
SCENE_INIT: {
|
SCENE_INIT: {
|
||||||
type: WS_SUBTYPES.INIT;
|
type: WS_SUBTYPES.INIT;
|
||||||
payload: {
|
payload: {
|
||||||
elements: readonly ExcalidrawElement[];
|
elements: readonly OrderedExcalidrawElement[];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
SCENE_UPDATE: {
|
SCENE_UPDATE: {
|
||||||
type: WS_SUBTYPES.UPDATE;
|
type: WS_SUBTYPES.UPDATE;
|
||||||
payload: {
|
payload: {
|
||||||
elements: readonly ExcalidrawElement[];
|
elements: readonly OrderedExcalidrawElement[];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
MOUSE_LOCATION: {
|
MOUSE_LOCATION: {
|
||||||
@@ -200,7 +199,7 @@ const legacy_decodeFromBackend = async ({
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const importFromBackend = async (
|
export const importFromBackend = async (
|
||||||
id: string,
|
id: string,
|
||||||
decryptionKey: string,
|
decryptionKey: string,
|
||||||
): Promise<ImportedDataState> => {
|
): Promise<ImportedDataState> => {
|
||||||
@@ -242,45 +241,6 @@ const importFromBackend = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const loadScene = async (
|
|
||||||
id: string | null,
|
|
||||||
privateKey: string | null,
|
|
||||||
// Supply local state even if importing from backend to ensure we restore
|
|
||||||
// localStorage user settings which we do not persist on server.
|
|
||||||
// Non-optional so we don't forget to pass it even if `undefined`.
|
|
||||||
localDataState: ImportedDataState | undefined | null,
|
|
||||||
) => {
|
|
||||||
let data;
|
|
||||||
if (id != null && privateKey != null) {
|
|
||||||
// the private key is used to decrypt the content from the server, take
|
|
||||||
// extra care not to leak it
|
|
||||||
data = restore(
|
|
||||||
await importFromBackend(id, privateKey),
|
|
||||||
localDataState?.appState,
|
|
||||||
localDataState?.elements,
|
|
||||||
{
|
|
||||||
repairBindings: true,
|
|
||||||
refreshDimensions: false,
|
|
||||||
deleteInvisibleElements: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
data = restore(localDataState || null, null, null, {
|
|
||||||
repairBindings: true,
|
|
||||||
deleteInvisibleElements: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
elements: data.elements,
|
|
||||||
appState: data.appState,
|
|
||||||
// note: this will always be empty because we're not storing files
|
|
||||||
// in the scene database/localStorage, and instead fetch them async
|
|
||||||
// from a different database
|
|
||||||
files: data.files,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type ExportToBackendResult =
|
type ExportToBackendResult =
|
||||||
| { url: null; errorMessage: string }
|
| { url: null; errorMessage: string }
|
||||||
| { url: string; errorMessage: null };
|
| { url: string; errorMessage: null };
|
||||||
|
|||||||
+51
-24
@@ -10,8 +10,6 @@ const lessPrecise = (num: number, precision = 5) =>
|
|||||||
const getAvgFrameTime = (times: number[]) =>
|
const getAvgFrameTime = (times: number[]) =>
|
||||||
lessPrecise(times.reduce((a, b) => a + b) / times.length);
|
lessPrecise(times.reduce((a, b) => a + b) / times.length);
|
||||||
|
|
||||||
const getFps = (frametime: number) => lessPrecise(1000 / frametime);
|
|
||||||
|
|
||||||
export class Debug {
|
export class Debug {
|
||||||
public static DEBUG_LOG_TIMES = true;
|
public static DEBUG_LOG_TIMES = true;
|
||||||
|
|
||||||
@@ -24,34 +22,35 @@ export class Debug {
|
|||||||
private static LAST_DEBUG_LOG_CALL = 0;
|
private static LAST_DEBUG_LOG_CALL = 0;
|
||||||
private static DEBUG_LOG_INTERVAL_ID: null | number = null;
|
private static DEBUG_LOG_INTERVAL_ID: null | number = null;
|
||||||
|
|
||||||
|
private static LAST_FRAME_TIMESTAMP = 0;
|
||||||
|
private static FRAME_COUNT = 0;
|
||||||
|
private static ANIMATION_FRAME_ID: null | number = null;
|
||||||
|
|
||||||
|
private static scheduleAnimationFrame = () => {
|
||||||
|
if (Debug.DEBUG_LOG_INTERVAL_ID !== null) {
|
||||||
|
Debug.ANIMATION_FRAME_ID = requestAnimationFrame((timestamp) => {
|
||||||
|
if (Debug.LAST_FRAME_TIMESTAMP !== timestamp) {
|
||||||
|
Debug.LAST_FRAME_TIMESTAMP = timestamp;
|
||||||
|
Debug.FRAME_COUNT++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Debug.DEBUG_LOG_INTERVAL_ID !== null) {
|
||||||
|
Debug.scheduleAnimationFrame();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
private static setupInterval = () => {
|
private static setupInterval = () => {
|
||||||
if (Debug.DEBUG_LOG_INTERVAL_ID === null) {
|
if (Debug.DEBUG_LOG_INTERVAL_ID === null) {
|
||||||
console.info("%c(starting perf recording)", "color: lime");
|
console.info("%c(starting perf recording)", "color: lime");
|
||||||
Debug.DEBUG_LOG_INTERVAL_ID = window.setInterval(Debug.debugLogger, 1000);
|
Debug.DEBUG_LOG_INTERVAL_ID = window.setInterval(Debug.debugLogger, 1000);
|
||||||
|
Debug.scheduleAnimationFrame();
|
||||||
}
|
}
|
||||||
Debug.LAST_DEBUG_LOG_CALL = Date.now();
|
Debug.LAST_DEBUG_LOG_CALL = Date.now();
|
||||||
};
|
};
|
||||||
|
|
||||||
private static debugLogger = () => {
|
private static debugLogger = () => {
|
||||||
if (
|
|
||||||
Date.now() - Debug.LAST_DEBUG_LOG_CALL > 600 &&
|
|
||||||
Debug.DEBUG_LOG_INTERVAL_ID !== null
|
|
||||||
) {
|
|
||||||
window.clearInterval(Debug.DEBUG_LOG_INTERVAL_ID);
|
|
||||||
Debug.DEBUG_LOG_INTERVAL_ID = null;
|
|
||||||
for (const [name, { avg }] of Object.entries(Debug.TIMES_AVG)) {
|
|
||||||
if (avg != null) {
|
|
||||||
console.info(
|
|
||||||
`%c${name} run avg: ${avg}ms (${getFps(avg)} fps)`,
|
|
||||||
"color: blue",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.info("%c(stopping perf recording)", "color: red");
|
|
||||||
Debug.TIMES_AGGR = {};
|
|
||||||
Debug.TIMES_AVG = {};
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (Debug.DEBUG_LOG_TIMES) {
|
if (Debug.DEBUG_LOG_TIMES) {
|
||||||
for (const [name, { t, times }] of Object.entries(Debug.TIMES_AGGR)) {
|
for (const [name, { t, times }] of Object.entries(Debug.TIMES_AGGR)) {
|
||||||
if (times.length) {
|
if (times.length) {
|
||||||
@@ -65,8 +64,18 @@ export class Debug {
|
|||||||
}
|
}
|
||||||
for (const [name, { t, times, avg }] of Object.entries(Debug.TIMES_AVG)) {
|
for (const [name, { t, times, avg }] of Object.entries(Debug.TIMES_AVG)) {
|
||||||
if (times.length) {
|
if (times.length) {
|
||||||
const avgFrameTime = getAvgFrameTime(times);
|
// const avgFrameTime = getAvgFrameTime(times);
|
||||||
console.info(name, `${avgFrameTime}ms (${getFps(avgFrameTime)} fps)`);
|
const totalTime = times.reduce((a, b) => a + b);
|
||||||
|
const avgFrameTime = lessPrecise(totalTime / Debug.FRAME_COUNT);
|
||||||
|
console.info(
|
||||||
|
name,
|
||||||
|
`- ${times.length} calls - ${avgFrameTime}ms/frame across ${
|
||||||
|
Debug.FRAME_COUNT
|
||||||
|
} frames (${lessPrecise(
|
||||||
|
(avgFrameTime / 16.67) * 100,
|
||||||
|
1,
|
||||||
|
)}% of frame budget)`,
|
||||||
|
);
|
||||||
Debug.TIMES_AVG[name] = {
|
Debug.TIMES_AVG[name] = {
|
||||||
t,
|
t,
|
||||||
times: [],
|
times: [],
|
||||||
@@ -76,6 +85,24 @@ export class Debug {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Debug.FRAME_COUNT = 0;
|
||||||
|
|
||||||
|
// Check for stop condition after logging
|
||||||
|
if (
|
||||||
|
Date.now() - Debug.LAST_DEBUG_LOG_CALL > 600 &&
|
||||||
|
Debug.DEBUG_LOG_INTERVAL_ID !== null
|
||||||
|
) {
|
||||||
|
console.info("%c(stopping perf recording)", "color: red");
|
||||||
|
window.clearInterval(Debug.DEBUG_LOG_INTERVAL_ID);
|
||||||
|
window.cancelAnimationFrame(Debug.ANIMATION_FRAME_ID!);
|
||||||
|
Debug.ANIMATION_FRAME_ID = null;
|
||||||
|
Debug.FRAME_COUNT = 0;
|
||||||
|
Debug.LAST_FRAME_TIMESTAMP = 0;
|
||||||
|
|
||||||
|
Debug.DEBUG_LOG_INTERVAL_ID = null;
|
||||||
|
Debug.TIMES_AGGR = {};
|
||||||
|
Debug.TIMES_AVG = {};
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
public static logTime = (time?: number, name = "default") => {
|
public static logTime = (time?: number, name = "default") => {
|
||||||
@@ -109,7 +136,7 @@ export class Debug {
|
|||||||
return (...args: T) => {
|
return (...args: T) => {
|
||||||
const t0 = performance.now();
|
const t0 = performance.now();
|
||||||
const ret = fn(...args);
|
const ret = fn(...args);
|
||||||
Debug.logTime(performance.now() - t0, name);
|
Debug[type](performance.now() - t0, name);
|
||||||
return ret;
|
return ret;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -36,6 +36,7 @@
|
|||||||
"react": "19.0.0",
|
"react": "19.0.0",
|
||||||
"react-dom": "19.0.0",
|
"react-dom": "19.0.0",
|
||||||
"socket.io-client": "4.7.2",
|
"socket.io-client": "4.7.2",
|
||||||
|
"uqr": "0.1.2",
|
||||||
"vite-plugin-html": "3.2.2"
|
"vite-plugin-html": "3.2.2"
|
||||||
},
|
},
|
||||||
"prettier": "@excalidraw/prettier-config",
|
"prettier": "@excalidraw/prettier-config",
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Spinner from "@excalidraw/excalidraw/components/Spinner";
|
||||||
|
|
||||||
|
interface QRCodeProps {
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const QRCode = ({ value }: QRCodeProps) => {
|
||||||
|
const [svgData, setSvgData] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
|
||||||
|
import("./qrcode.chunk")
|
||||||
|
.then(({ generateQRCodeSVG }) => {
|
||||||
|
if (mounted) {
|
||||||
|
try {
|
||||||
|
setSvgData(generateQRCodeSVG(value));
|
||||||
|
} catch {
|
||||||
|
setError(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (mounted) {
|
||||||
|
setError(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
};
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!svgData) {
|
||||||
|
return (
|
||||||
|
<div className="ShareDialog__active__qrcode ShareDialog__active__qrcode--loading">
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="ShareDialog__active__qrcode"
|
||||||
|
role="img"
|
||||||
|
aria-label="QR code for collaboration link"
|
||||||
|
dangerouslySetInnerHTML={{ __html: svgData }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -140,6 +140,31 @@
|
|||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&__qrcode {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
align-self: center;
|
||||||
|
padding: 1rem;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid #e0e0e0;
|
||||||
|
|
||||||
|
$size: 150px;
|
||||||
|
width: $size;
|
||||||
|
height: $size;
|
||||||
|
|
||||||
|
& svg {
|
||||||
|
width: $size;
|
||||||
|
height: $size;
|
||||||
|
}
|
||||||
|
|
||||||
|
&--loading {
|
||||||
|
background: var(--island-bg-color);
|
||||||
|
border: 1px solid var(--dialog-border-color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
&__description {
|
&__description {
|
||||||
border-top: 1px solid var(--color-gray-20);
|
border-top: 1px solid var(--color-gray-20);
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { atom, useAtom, useAtomValue } from "../app-jotai";
|
|||||||
import { activeRoomLinkAtom } from "../collab/Collab";
|
import { activeRoomLinkAtom } from "../collab/Collab";
|
||||||
|
|
||||||
import "./ShareDialog.scss";
|
import "./ShareDialog.scss";
|
||||||
|
import { QRCode } from "./QRCode";
|
||||||
|
|
||||||
import type { CollabAPI } from "../collab/Collab";
|
import type { CollabAPI } from "../collab/Collab";
|
||||||
|
|
||||||
@@ -142,6 +143,7 @@ const ActiveRoomDialog = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<QRCode value={activeRoomLink} />
|
||||||
<div className="ShareDialog__active__description">
|
<div className="ShareDialog__active__description">
|
||||||
<p>
|
<p>
|
||||||
<span
|
<span
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { renderSVG } from "uqr";
|
||||||
|
|
||||||
|
export const generateQRCodeSVG = (text: string): string => {
|
||||||
|
return renderSVG(text);
|
||||||
|
};
|
||||||
@@ -102,6 +102,10 @@ export default defineConfig(({ mode }) => {
|
|||||||
// Taking the substring after "locales/"
|
// Taking the substring after "locales/"
|
||||||
return `locales/${id.substring(index + 8)}`;
|
return `locales/${id.substring(index + 8)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (id.includes("@excalidraw/mermaid-to-excalidraw")) {
|
||||||
|
return "mermaid-to-excalidraw";
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -196,6 +200,7 @@ export default defineConfig(({ mode }) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
maximumFileSizeToCacheInBytes: 2.3 * 1024 ** 2, // 2.3MB
|
||||||
},
|
},
|
||||||
manifest: {
|
manifest: {
|
||||||
short_name: "Excalidraw",
|
short_name: "Excalidraw",
|
||||||
|
|||||||
@@ -55,5 +55,11 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"gen:types": "rimraf types && tsc",
|
"gen:types": "rimraf types && tsc",
|
||||||
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"tinycolor2": "1.6.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/tinycolor2": "1.4.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||||
|
|
||||||
|
exports[`COLOR_PALETTE > color palette doesn't regress 1`] = `
|
||||||
|
{
|
||||||
|
"black": "#1e1e1e",
|
||||||
|
"blue": [
|
||||||
|
"#e7f5ff",
|
||||||
|
"#a5d8ff",
|
||||||
|
"#4dabf7",
|
||||||
|
"#228be6",
|
||||||
|
"#1971c2",
|
||||||
|
],
|
||||||
|
"bronze": [
|
||||||
|
"#f8f1ee",
|
||||||
|
"#eaddd7",
|
||||||
|
"#d2bab0",
|
||||||
|
"#a18072",
|
||||||
|
"#846358",
|
||||||
|
],
|
||||||
|
"cyan": [
|
||||||
|
"#e3fafc",
|
||||||
|
"#99e9f2",
|
||||||
|
"#3bc9db",
|
||||||
|
"#15aabf",
|
||||||
|
"#0c8599",
|
||||||
|
],
|
||||||
|
"grape": [
|
||||||
|
"#f8f0fc",
|
||||||
|
"#eebefa",
|
||||||
|
"#da77f2",
|
||||||
|
"#be4bdb",
|
||||||
|
"#9c36b5",
|
||||||
|
],
|
||||||
|
"gray": [
|
||||||
|
"#f8f9fa",
|
||||||
|
"#e9ecef",
|
||||||
|
"#ced4da",
|
||||||
|
"#868e96",
|
||||||
|
"#343a40",
|
||||||
|
],
|
||||||
|
"green": [
|
||||||
|
"#ebfbee",
|
||||||
|
"#b2f2bb",
|
||||||
|
"#69db7c",
|
||||||
|
"#40c057",
|
||||||
|
"#2f9e44",
|
||||||
|
],
|
||||||
|
"orange": [
|
||||||
|
"#fff4e6",
|
||||||
|
"#ffd8a8",
|
||||||
|
"#ffa94d",
|
||||||
|
"#fd7e14",
|
||||||
|
"#e8590c",
|
||||||
|
],
|
||||||
|
"pink": [
|
||||||
|
"#fff0f6",
|
||||||
|
"#fcc2d7",
|
||||||
|
"#f783ac",
|
||||||
|
"#e64980",
|
||||||
|
"#c2255c",
|
||||||
|
],
|
||||||
|
"red": [
|
||||||
|
"#fff5f5",
|
||||||
|
"#ffc9c9",
|
||||||
|
"#ff8787",
|
||||||
|
"#fa5252",
|
||||||
|
"#e03131",
|
||||||
|
],
|
||||||
|
"teal": [
|
||||||
|
"#e6fcf5",
|
||||||
|
"#96f2d7",
|
||||||
|
"#38d9a9",
|
||||||
|
"#12b886",
|
||||||
|
"#099268",
|
||||||
|
],
|
||||||
|
"transparent": "transparent",
|
||||||
|
"violet": [
|
||||||
|
"#f3f0ff",
|
||||||
|
"#d0bfff",
|
||||||
|
"#9775fa",
|
||||||
|
"#7950f2",
|
||||||
|
"#6741d9",
|
||||||
|
],
|
||||||
|
"white": "#ffffff",
|
||||||
|
"yellow": [
|
||||||
|
"#fff9db",
|
||||||
|
"#ffec99",
|
||||||
|
"#ffd43b",
|
||||||
|
"#fab005",
|
||||||
|
"#f08c00",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
exports[`applyDarkModeFilter > COLOR_PALETTE regression tests > matches snapshot for all palette colors 1`] = `
|
||||||
|
{
|
||||||
|
"black": "#d3d3d3",
|
||||||
|
"blue": [
|
||||||
|
"#121e26",
|
||||||
|
"#154162",
|
||||||
|
"#2273b4",
|
||||||
|
"#3791e0",
|
||||||
|
"#56a2e8",
|
||||||
|
],
|
||||||
|
"bronze": [
|
||||||
|
"#221c1a",
|
||||||
|
"#362b26",
|
||||||
|
"#5a463d",
|
||||||
|
"#917569",
|
||||||
|
"#a98d84",
|
||||||
|
],
|
||||||
|
"cyan": [
|
||||||
|
"#0a1e20",
|
||||||
|
"#004149",
|
||||||
|
"#007281",
|
||||||
|
"#0f8fa1",
|
||||||
|
"#3da5b6",
|
||||||
|
],
|
||||||
|
"grape": [
|
||||||
|
"#211a25",
|
||||||
|
"#5b3165",
|
||||||
|
"#a954be",
|
||||||
|
"#d471ed",
|
||||||
|
"#e28af8",
|
||||||
|
],
|
||||||
|
"gray": [
|
||||||
|
"#161718",
|
||||||
|
"#202325",
|
||||||
|
"#33383d",
|
||||||
|
"#6e757c",
|
||||||
|
"#b7bcc1",
|
||||||
|
],
|
||||||
|
"green": [
|
||||||
|
"#0f1d12",
|
||||||
|
"#043b0c",
|
||||||
|
"#056715",
|
||||||
|
"#16842a",
|
||||||
|
"#39994b",
|
||||||
|
],
|
||||||
|
"orange": [
|
||||||
|
"#22190d",
|
||||||
|
"#4c2b01",
|
||||||
|
"#924800",
|
||||||
|
"#cd6005",
|
||||||
|
"#f17634",
|
||||||
|
],
|
||||||
|
"pink": [
|
||||||
|
"#26191e",
|
||||||
|
"#602e40",
|
||||||
|
"#b04d70",
|
||||||
|
"#f56e9d",
|
||||||
|
"#ff8dbc",
|
||||||
|
],
|
||||||
|
"red": [
|
||||||
|
"#1f1717",
|
||||||
|
"#5a2c2c",
|
||||||
|
"#b44d4d",
|
||||||
|
"#fa6969",
|
||||||
|
"#ff8383",
|
||||||
|
],
|
||||||
|
"teal": [
|
||||||
|
"#0a1d17",
|
||||||
|
"#00422b",
|
||||||
|
"#00744b",
|
||||||
|
"#039267",
|
||||||
|
"#32a783",
|
||||||
|
],
|
||||||
|
"transparent": "#ededed00",
|
||||||
|
"violet": [
|
||||||
|
"#1f1c29",
|
||||||
|
"#4a3b72",
|
||||||
|
"#8a6cdf",
|
||||||
|
"#a885ff",
|
||||||
|
"#b595ff",
|
||||||
|
],
|
||||||
|
"white": "#121212",
|
||||||
|
"yellow": [
|
||||||
|
"#1e1900",
|
||||||
|
"#362600",
|
||||||
|
"#5f3a00",
|
||||||
|
"#905000",
|
||||||
|
"#b86200",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
`;
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import {
|
||||||
|
applyDarkModeFilter,
|
||||||
|
COLOR_PALETTE,
|
||||||
|
rgbToHex,
|
||||||
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
|
describe("COLOR_PALETTE", () => {
|
||||||
|
it("color palette doesn't regress", () => {
|
||||||
|
expect(COLOR_PALETTE).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("applyDarkModeFilter", () => {
|
||||||
|
describe("basic transformations", () => {
|
||||||
|
it("transforms black to near-white", () => {
|
||||||
|
const result = applyDarkModeFilter("#000000");
|
||||||
|
// Black inverted 93% + hue rotate should be near white/light gray
|
||||||
|
expect(result).toBe("#ededed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms white to near-black", () => {
|
||||||
|
const result = applyDarkModeFilter("#ffffff");
|
||||||
|
// White inverted 93% should be near black/dark gray
|
||||||
|
expect(result).toBe("#121212");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms pure red", () => {
|
||||||
|
const result = applyDarkModeFilter("#ff0000");
|
||||||
|
// Invert 93% + hue rotate 180deg produces a cyan-ish tint
|
||||||
|
expect(result).toBe("#ff9090");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms pure green", () => {
|
||||||
|
const result = applyDarkModeFilter("#00ff00");
|
||||||
|
// Invert 93% + hue rotate 180deg
|
||||||
|
expect(result).toBe("#008f00");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms pure blue", () => {
|
||||||
|
const result = applyDarkModeFilter("#0000ff");
|
||||||
|
// Invert 93% + hue rotate 180deg produces a light purple
|
||||||
|
expect(result).toBe("#cdcdff");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("color formats", () => {
|
||||||
|
it("handles hex with hash", () => {
|
||||||
|
const result = applyDarkModeFilter("#ff0000");
|
||||||
|
// Fully opaque colors return 6-char hex
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles named colors", () => {
|
||||||
|
const result = applyDarkModeFilter("red");
|
||||||
|
// "red" = #ff0000, fully opaque
|
||||||
|
expect(result).toBe("#ff9090");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles rgb format", () => {
|
||||||
|
const result = applyDarkModeFilter("rgb(255, 0, 0)");
|
||||||
|
expect(result).toBe("#ff9090");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles rgba format and preserves alpha", () => {
|
||||||
|
const result = applyDarkModeFilter("rgba(255, 0, 0, 0.5)");
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{8}$/);
|
||||||
|
// Alpha 0.5 = 128 in hex = 80
|
||||||
|
expect(result).toBe("#ff909080");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles transparent", () => {
|
||||||
|
const result = applyDarkModeFilter("transparent");
|
||||||
|
// transparent = rgba(0,0,0,0), inverted should still have 0 alpha
|
||||||
|
expect(result).toBe("#ededed00");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles shorthand hex", () => {
|
||||||
|
const result = applyDarkModeFilter("#f00");
|
||||||
|
expect(result).toBe("#ff9090");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("alpha preservation", () => {
|
||||||
|
it("omits alpha for full opacity", () => {
|
||||||
|
const result = applyDarkModeFilter("#ff0000ff");
|
||||||
|
// Full opacity returns 6-char hex (no alpha suffix)
|
||||||
|
expect(result).toBe("#ff9090");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves 50% opacity", () => {
|
||||||
|
const result = applyDarkModeFilter("#ff000080");
|
||||||
|
expect(result.slice(-2)).toBe("80");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves 0% opacity", () => {
|
||||||
|
const result = applyDarkModeFilter("#ff000000");
|
||||||
|
expect(result.slice(-2)).toBe("00");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("COLOR_PALETTE regression tests", () => {
|
||||||
|
it("transforms black from palette", () => {
|
||||||
|
// COLOR_PALETTE.black is #1e1e1e (not pure black)
|
||||||
|
const result = applyDarkModeFilter(COLOR_PALETTE.black);
|
||||||
|
expect(result).toBe("#d3d3d3");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms white from palette", () => {
|
||||||
|
const result = applyDarkModeFilter(COLOR_PALETTE.white);
|
||||||
|
expect(result).toBe("#121212");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transforms transparent from palette", () => {
|
||||||
|
const result = applyDarkModeFilter(COLOR_PALETTE.transparent);
|
||||||
|
expect(result).toBe("#ededed00");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test each color family from the palette (all opaque, so 6-char hex)
|
||||||
|
describe("red shades", () => {
|
||||||
|
const redShades = COLOR_PALETTE.red;
|
||||||
|
it.each(redShades.map((color, i) => [color, i]))(
|
||||||
|
"transforms red shade %s (index %d)",
|
||||||
|
(color) => {
|
||||||
|
const result = applyDarkModeFilter(color as string);
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("blue shades", () => {
|
||||||
|
const blueShades = COLOR_PALETTE.blue;
|
||||||
|
it.each(blueShades.map((color, i) => [color, i]))(
|
||||||
|
"transforms blue shade %s (index %d)",
|
||||||
|
(color) => {
|
||||||
|
const result = applyDarkModeFilter(color as string);
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("green shades", () => {
|
||||||
|
const greenShades = COLOR_PALETTE.green;
|
||||||
|
it.each(greenShades.map((color, i) => [color, i]))(
|
||||||
|
"transforms green shade %s (index %d)",
|
||||||
|
(color) => {
|
||||||
|
const result = applyDarkModeFilter(color as string);
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("gray shades", () => {
|
||||||
|
const grayShades = COLOR_PALETTE.gray;
|
||||||
|
it.each(grayShades.map((color, i) => [color, i]))(
|
||||||
|
"transforms gray shade %s (index %d)",
|
||||||
|
(color) => {
|
||||||
|
const result = applyDarkModeFilter(color as string);
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("bronze shades", () => {
|
||||||
|
const bronzeShades = COLOR_PALETTE.bronze;
|
||||||
|
it.each(bronzeShades.map((color, i) => [color, i]))(
|
||||||
|
"transforms bronze shade %s (index %d)",
|
||||||
|
(color) => {
|
||||||
|
const result = applyDarkModeFilter(color as string);
|
||||||
|
expect(result).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Snapshot test for full palette to catch any regressions
|
||||||
|
it("matches snapshot for all palette colors", () => {
|
||||||
|
const transformedPalette: Record<string, string | string[]> = {};
|
||||||
|
|
||||||
|
transformedPalette.black = applyDarkModeFilter(COLOR_PALETTE.black);
|
||||||
|
transformedPalette.white = applyDarkModeFilter(COLOR_PALETTE.white);
|
||||||
|
transformedPalette.transparent = applyDarkModeFilter(
|
||||||
|
COLOR_PALETTE.transparent,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Transform color arrays
|
||||||
|
for (const colorName of [
|
||||||
|
"gray",
|
||||||
|
"red",
|
||||||
|
"pink",
|
||||||
|
"grape",
|
||||||
|
"violet",
|
||||||
|
"blue",
|
||||||
|
"cyan",
|
||||||
|
"teal",
|
||||||
|
"green",
|
||||||
|
"yellow",
|
||||||
|
"orange",
|
||||||
|
"bronze",
|
||||||
|
] as const) {
|
||||||
|
const shades = COLOR_PALETTE[colorName];
|
||||||
|
transformedPalette[colorName] = shades.map((shade) =>
|
||||||
|
applyDarkModeFilter(shade),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(transformedPalette).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("caching", () => {
|
||||||
|
it("returns same result for same input (cached)", () => {
|
||||||
|
const result1 = applyDarkModeFilter("#ff0000");
|
||||||
|
const result2 = applyDarkModeFilter("#ff0000");
|
||||||
|
expect(result1).toBe(result2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rgbToHex", () => {
|
||||||
|
describe("basic RGB conversion", () => {
|
||||||
|
it("converts black (0,0,0)", () => {
|
||||||
|
expect(rgbToHex(0, 0, 0)).toBe("#000000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts white (255,255,255)", () => {
|
||||||
|
expect(rgbToHex(255, 255, 255)).toBe("#ffffff");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts red (255,0,0)", () => {
|
||||||
|
expect(rgbToHex(255, 0, 0)).toBe("#ff0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts green (0,255,0)", () => {
|
||||||
|
expect(rgbToHex(0, 255, 0)).toBe("#00ff00");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts blue (0,0,255)", () => {
|
||||||
|
expect(rgbToHex(0, 0, 255)).toBe("#0000ff");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts arbitrary color", () => {
|
||||||
|
expect(rgbToHex(30, 30, 30)).toBe("#1e1e1e");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("leading zeros preservation", () => {
|
||||||
|
it("preserves leading zeros for low values", () => {
|
||||||
|
expect(rgbToHex(0, 0, 1)).toBe("#000001");
|
||||||
|
expect(rgbToHex(0, 1, 0)).toBe("#000100");
|
||||||
|
expect(rgbToHex(1, 0, 0)).toBe("#010000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves zeros for single-digit hex values", () => {
|
||||||
|
expect(rgbToHex(15, 15, 15)).toBe("#0f0f0f");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("alpha handling", () => {
|
||||||
|
it("omits alpha when undefined", () => {
|
||||||
|
expect(rgbToHex(255, 0, 0)).toBe("#ff0000");
|
||||||
|
expect(rgbToHex(255, 0, 0, undefined)).toBe("#ff0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits alpha when fully opaque (1)", () => {
|
||||||
|
expect(rgbToHex(255, 0, 0, 1)).toBe("#ff0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes alpha for semi-transparent (0.5)", () => {
|
||||||
|
// 0.5 * 255 = 127.5 -> rounds to 128 = 0x80
|
||||||
|
expect(rgbToHex(255, 0, 0, 0.5)).toBe("#ff000080");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes alpha for fully transparent (0)", () => {
|
||||||
|
expect(rgbToHex(255, 0, 0, 0)).toBe("#ff000000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes alpha for near-opaque (0.99)", () => {
|
||||||
|
// 0.99 * 255 = 252.45 -> rounds to 252 = 0xfc
|
||||||
|
expect(rgbToHex(255, 0, 0, 0.99)).toBe("#ff0000fc");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pads alpha with leading zero when needed", () => {
|
||||||
|
// 0.05 * 255 = 12.75 -> rounds to 13 = 0x0d
|
||||||
|
expect(rgbToHex(255, 0, 0, 0.05)).toBe("#ff00000d");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
+226
-43
@@ -1,8 +1,117 @@
|
|||||||
import oc from "open-color";
|
import tinycolor from "tinycolor2";
|
||||||
|
|
||||||
import type { Merge } from "./utility-types";
|
import { clamp } from "@excalidraw/math";
|
||||||
|
import { degreesToRadians } from "@excalidraw/math";
|
||||||
|
|
||||||
export const COLOR_OUTLINE_CONTRAST_THRESHOLD = 240;
|
import type { Degrees } from "@excalidraw/math";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Dark mode color transformation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Browser-only cache to avoid memory leaks on server
|
||||||
|
const DARK_MODE_COLORS_CACHE: Map<string, string> | null =
|
||||||
|
typeof window !== "undefined" ? new Map() : null;
|
||||||
|
|
||||||
|
function cssHueRotate(
|
||||||
|
red: number,
|
||||||
|
green: number,
|
||||||
|
blue: number,
|
||||||
|
degrees: Degrees,
|
||||||
|
): { r: number; g: number; b: number } {
|
||||||
|
// normalize
|
||||||
|
const r = red / 255;
|
||||||
|
const g = green / 255;
|
||||||
|
const b = blue / 255;
|
||||||
|
|
||||||
|
// Convert degrees to radians
|
||||||
|
const a = degreesToRadians(degrees);
|
||||||
|
|
||||||
|
const c = Math.cos(a);
|
||||||
|
const s = Math.sin(a);
|
||||||
|
|
||||||
|
// rotation matrix
|
||||||
|
const matrix = [
|
||||||
|
0.213 + c * 0.787 - s * 0.213,
|
||||||
|
0.715 - c * 0.715 - s * 0.715,
|
||||||
|
0.072 - c * 0.072 + s * 0.928,
|
||||||
|
0.213 - c * 0.213 + s * 0.143,
|
||||||
|
0.715 + c * 0.285 + s * 0.14,
|
||||||
|
0.072 - c * 0.072 - s * 0.283,
|
||||||
|
0.213 - c * 0.213 - s * 0.787,
|
||||||
|
0.715 - c * 0.715 + s * 0.715,
|
||||||
|
0.072 + c * 0.928 + s * 0.072,
|
||||||
|
];
|
||||||
|
|
||||||
|
// transform
|
||||||
|
const newR = r * matrix[0] + g * matrix[1] + b * matrix[2];
|
||||||
|
const newG = r * matrix[3] + g * matrix[4] + b * matrix[5];
|
||||||
|
const newB = r * matrix[6] + g * matrix[7] + b * matrix[8];
|
||||||
|
|
||||||
|
// clamp the values to [0, 1] range and convert back to [0, 255]
|
||||||
|
return {
|
||||||
|
r: Math.round(Math.max(0, Math.min(1, newR)) * 255),
|
||||||
|
g: Math.round(Math.max(0, Math.min(1, newG)) * 255),
|
||||||
|
b: Math.round(Math.max(0, Math.min(1, newB)) * 255),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const cssInvert = (
|
||||||
|
r: number,
|
||||||
|
g: number,
|
||||||
|
b: number,
|
||||||
|
percent: number,
|
||||||
|
): { r: number; g: number; b: number } => {
|
||||||
|
const p = clamp(percent, 0, 100) / 100;
|
||||||
|
|
||||||
|
// Function to invert a single color component
|
||||||
|
const invertComponent = (color: number): number => {
|
||||||
|
// Apply the invert formula
|
||||||
|
const inverted = color * (1 - p) + (255 - color) * p;
|
||||||
|
// Round to the nearest integer and clamp to [0, 255]
|
||||||
|
return Math.round(clamp(inverted, 0, 255));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calculate the inverted RGB components
|
||||||
|
const invertedR = invertComponent(r);
|
||||||
|
const invertedG = invertComponent(g);
|
||||||
|
const invertedB = invertComponent(b);
|
||||||
|
|
||||||
|
return { r: invertedR, g: invertedG, b: invertedB };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const applyDarkModeFilter = (color: string): string => {
|
||||||
|
const cached = DARK_MODE_COLORS_CACHE?.get(color);
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tc = tinycolor(color);
|
||||||
|
const alpha = tc.getAlpha();
|
||||||
|
|
||||||
|
// order of operations matters
|
||||||
|
// (corresponds to "filter: invert(invertPercent) hue-rotate(hueDegrees)" in css)
|
||||||
|
const rgb = tc.toRgb();
|
||||||
|
const inverted = cssInvert(rgb.r, rgb.g, rgb.b, 93);
|
||||||
|
const rotated = cssHueRotate(
|
||||||
|
inverted.r,
|
||||||
|
inverted.g,
|
||||||
|
inverted.b,
|
||||||
|
180 as Degrees,
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = rgbToHex(rotated.r, rotated.g, rotated.b, alpha);
|
||||||
|
|
||||||
|
if (DARK_MODE_COLORS_CACHE) {
|
||||||
|
DARK_MODE_COLORS_CACHE.set(color, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Color palette
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// FIXME can't put to utils.ts rn because of circular dependency
|
// FIXME can't put to utils.ts rn because of circular dependency
|
||||||
const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
|
const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
|
||||||
@@ -17,15 +126,7 @@ const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
|
|||||||
}, {} as Pick<R, K[number]>) as Pick<R, K[number]>;
|
}, {} as Pick<R, K[number]>) as Pick<R, K[number]>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ColorPickerColor =
|
|
||||||
| Exclude<keyof oc, "indigo" | "lime">
|
|
||||||
| "transparent"
|
|
||||||
| "bronze";
|
|
||||||
export type ColorTuple = readonly [string, string, string, string, string];
|
export type ColorTuple = readonly [string, string, string, string, string];
|
||||||
export type ColorPalette = Merge<
|
|
||||||
Record<ColorPickerColor, ColorTuple>,
|
|
||||||
{ black: "#1e1e1e"; white: "#ffffff"; transparent: "transparent" }
|
|
||||||
>;
|
|
||||||
|
|
||||||
// used general type instead of specific type (ColorPalette) to support custom colors
|
// used general type instead of specific type (ColorPalette) to support custom colors
|
||||||
export type ColorPaletteCustom = { [key: string]: ColorTuple | string };
|
export type ColorPaletteCustom = { [key: string]: ColorTuple | string };
|
||||||
@@ -38,38 +139,30 @@ export const DEFAULT_CHART_COLOR_INDEX = 4;
|
|||||||
|
|
||||||
export const DEFAULT_ELEMENT_STROKE_COLOR_INDEX = 4;
|
export const DEFAULT_ELEMENT_STROKE_COLOR_INDEX = 4;
|
||||||
export const DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX = 1;
|
export const DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX = 1;
|
||||||
export const ELEMENTS_PALETTE_SHADE_INDEXES = [0, 2, 4, 6, 8] as const;
|
|
||||||
export const CANVAS_PALETTE_SHADE_INDEXES = [0, 1, 2, 3, 4] as const;
|
|
||||||
|
|
||||||
export const getSpecificColorShades = (
|
|
||||||
color: Exclude<
|
|
||||||
ColorPickerColor,
|
|
||||||
"transparent" | "white" | "black" | "bronze"
|
|
||||||
>,
|
|
||||||
indexArr: Readonly<ColorShadesIndexes>,
|
|
||||||
) => {
|
|
||||||
return indexArr.map((index) => oc[color][index]) as any as ColorTuple;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const COLOR_PALETTE = {
|
export const COLOR_PALETTE = {
|
||||||
transparent: "transparent",
|
transparent: "transparent",
|
||||||
black: "#1e1e1e",
|
black: "#1e1e1e",
|
||||||
white: "#ffffff",
|
white: "#ffffff",
|
||||||
// open-colors
|
// open-color from https://github.com/yeun/open-color/blob/master/open-color.js
|
||||||
gray: getSpecificColorShades("gray", ELEMENTS_PALETTE_SHADE_INDEXES),
|
// corresponds to indexes [0,2,4,6,8] (weights: 50, 200, 400, 600, 800)
|
||||||
red: getSpecificColorShades("red", ELEMENTS_PALETTE_SHADE_INDEXES),
|
gray: ["#f8f9fa", "#e9ecef", "#ced4da", "#868e96", "#343a40"],
|
||||||
pink: getSpecificColorShades("pink", ELEMENTS_PALETTE_SHADE_INDEXES),
|
red: ["#fff5f5", "#ffc9c9", "#ff8787", "#fa5252", "#e03131"],
|
||||||
grape: getSpecificColorShades("grape", ELEMENTS_PALETTE_SHADE_INDEXES),
|
pink: ["#fff0f6", "#fcc2d7", "#f783ac", "#e64980", "#c2255c"],
|
||||||
violet: getSpecificColorShades("violet", ELEMENTS_PALETTE_SHADE_INDEXES),
|
grape: ["#f8f0fc", "#eebefa", "#da77f2", "#be4bdb", "#9c36b5"],
|
||||||
blue: getSpecificColorShades("blue", ELEMENTS_PALETTE_SHADE_INDEXES),
|
violet: ["#f3f0ff", "#d0bfff", "#9775fa", "#7950f2", "#6741d9"],
|
||||||
cyan: getSpecificColorShades("cyan", ELEMENTS_PALETTE_SHADE_INDEXES),
|
blue: ["#e7f5ff", "#a5d8ff", "#4dabf7", "#228be6", "#1971c2"],
|
||||||
teal: getSpecificColorShades("teal", ELEMENTS_PALETTE_SHADE_INDEXES),
|
cyan: ["#e3fafc", "#99e9f2", "#3bc9db", "#15aabf", "#0c8599"],
|
||||||
green: getSpecificColorShades("green", ELEMENTS_PALETTE_SHADE_INDEXES),
|
teal: ["#e6fcf5", "#96f2d7", "#38d9a9", "#12b886", "#099268"],
|
||||||
yellow: getSpecificColorShades("yellow", ELEMENTS_PALETTE_SHADE_INDEXES),
|
green: ["#ebfbee", "#b2f2bb", "#69db7c", "#40c057", "#2f9e44"],
|
||||||
orange: getSpecificColorShades("orange", ELEMENTS_PALETTE_SHADE_INDEXES),
|
yellow: ["#fff9db", "#ffec99", "#ffd43b", "#fab005", "#f08c00"],
|
||||||
// radix bronze shades 3,5,7,9,11
|
orange: ["#fff4e6", "#ffd8a8", "#ffa94d", "#fd7e14", "#e8590c"],
|
||||||
|
// radix bronze shades [3,5,7,9,11]
|
||||||
bronze: ["#f8f1ee", "#eaddd7", "#d2bab0", "#a18072", "#846358"],
|
bronze: ["#f8f1ee", "#eaddd7", "#d2bab0", "#a18072", "#846358"],
|
||||||
} as ColorPalette;
|
} as const;
|
||||||
|
|
||||||
|
export type ColorPalette = typeof COLOR_PALETTE;
|
||||||
|
export type ColorPickerColor = keyof typeof COLOR_PALETTE;
|
||||||
|
|
||||||
const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
|
const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
|
||||||
"cyan",
|
"cyan",
|
||||||
@@ -84,7 +177,6 @@ const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
|
|||||||
"red",
|
"red",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// quick picks defaults
|
// quick picks defaults
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
@@ -119,7 +211,6 @@ export const DEFAULT_CANVAS_BACKGROUND_PICKS = [
|
|||||||
"#fdf8f6",
|
"#fdf8f6",
|
||||||
] as ColorTuple;
|
] as ColorTuple;
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// palette defaults
|
// palette defaults
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
@@ -145,8 +236,7 @@ export const DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE = {
|
|||||||
...COMMON_ELEMENT_SHADES,
|
...COMMON_ELEMENT_SHADES,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// color palette helpers
|
||||||
// helpers
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
// !!!MUST BE WITHOUT GRAY, TRANSPARENT AND BLACK!!!
|
// !!!MUST BE WITHOUT GRAY, TRANSPARENT AND BLACK!!!
|
||||||
@@ -167,7 +257,100 @@ export const getAllColorsSpecificShade = (index: 0 | 1 | 2 | 3 | 4) =>
|
|||||||
COLOR_PALETTE.red[index],
|
COLOR_PALETTE.red[index],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const rgbToHex = (r: number, g: number, b: number) =>
|
// -----------------------------------------------------------------------------
|
||||||
`#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
|
// other helpers
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const rgbToHex = (r: number, g: number, b: number, a?: number) => {
|
||||||
|
// (1 << 24) adds 0x1000000 to ensure the hex string is always 7 chars,
|
||||||
|
// then slice(1) removes the leading "1" to get exactly 6 hex digits
|
||||||
|
// e.g. rgb(0,0,0) -> 0x1000000 -> "1000000" -> "000000"
|
||||||
|
const hex6 = `#${((1 << 24) + (r << 16) + (g << 8) + b)
|
||||||
|
.toString(16)
|
||||||
|
.slice(1)}`;
|
||||||
|
if (a !== undefined && a < 1) {
|
||||||
|
// convert alpha from 0-1 float to 0-255 int, then to 2-digit hex
|
||||||
|
// e.g. 0.5 -> 128 -> "80"
|
||||||
|
const alphaHex = Math.round(a * 255)
|
||||||
|
.toString(16)
|
||||||
|
.padStart(2, "0");
|
||||||
|
return `${hex6}${alphaHex}`;
|
||||||
|
}
|
||||||
|
return hex6;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns #RRGGBB or #RRGGBBAA based on color containing non-opaque alpha,
|
||||||
|
* null if not valid color
|
||||||
|
*/
|
||||||
|
export const colorToHex = (color: string): string | null => {
|
||||||
|
const tc = tinycolor(color);
|
||||||
|
if (!tc.isValid()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const { r, g, b, a } = tc.toRgb();
|
||||||
|
return rgbToHex(r, g, b, a);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isTransparent = (color: string) => {
|
||||||
|
return tinycolor(color).getAlpha() === 0;
|
||||||
|
};
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
// color contract helpers
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const COLOR_OUTLINE_CONTRAST_THRESHOLD = 240;
|
||||||
|
|
||||||
|
const calculateContrast = (r: number, g: number, b: number): number => {
|
||||||
|
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
|
||||||
|
return yiq;
|
||||||
|
};
|
||||||
|
|
||||||
|
// YIQ algo, inspiration from https://stackoverflow.com/a/11868398
|
||||||
|
export const isColorDark = (color: string, threshold = 160): boolean => {
|
||||||
|
// no color ("") -> assume it default to black
|
||||||
|
if (!color) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTransparent(color)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tc = tinycolor(color);
|
||||||
|
if (!tc.isValid()) {
|
||||||
|
// invalid color -> assume it defaults to black
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { r, g, b } = tc.toRgb();
|
||||||
|
return calculateContrast(r, g, b) < threshold;
|
||||||
|
};
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// normalization
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* tries to keep the input color as-is if it's valid, making minimal adjustments
|
||||||
|
* (trimming whitespace or adding `#` to hex colors)
|
||||||
|
*/
|
||||||
|
export const normalizeInputColor = (color: string): string | null => {
|
||||||
|
color = color.trim();
|
||||||
|
if (isTransparent(color)) {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tc = tinycolor(color);
|
||||||
|
if (tc.isValid()) {
|
||||||
|
// testing for `#` first fixes a bug on Electron (more specfically, an
|
||||||
|
// Obsidian popout window), where a hex color without `#` is considered valid
|
||||||
|
if (tc.getFormat() === "hex" && !color.startsWith("#")) {
|
||||||
|
return `#${color}`;
|
||||||
|
}
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|||||||
@@ -190,6 +190,8 @@ export const THEME = {
|
|||||||
DARK: "dark",
|
DARK: "dark",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
export const DARK_THEME_FILTER = "invert(93%) hue-rotate(180deg)";
|
||||||
|
|
||||||
export const FRAME_STYLE = {
|
export const FRAME_STYLE = {
|
||||||
strokeColor: "#bbb" as ExcalidrawElement["strokeColor"],
|
strokeColor: "#bbb" as ExcalidrawElement["strokeColor"],
|
||||||
strokeWidth: 2 as ExcalidrawElement["strokeWidth"],
|
strokeWidth: 2 as ExcalidrawElement["strokeWidth"],
|
||||||
@@ -305,9 +307,6 @@ export const IDLE_THRESHOLD = 60_000;
|
|||||||
// Report a user active each ACTIVE_THRESHOLD milliseconds
|
// Report a user active each ACTIVE_THRESHOLD milliseconds
|
||||||
export const ACTIVE_THRESHOLD = 3_000;
|
export const ACTIVE_THRESHOLD = 3_000;
|
||||||
|
|
||||||
// duplicates --theme-filter, should be removed soon
|
|
||||||
export const THEME_FILTER = "invert(93%) hue-rotate(180deg)";
|
|
||||||
|
|
||||||
export const URL_QUERY_KEYS = {
|
export const URL_QUERY_KEYS = {
|
||||||
addLibrary: "addLibrary",
|
addLibrary: "addLibrary",
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export type EditorInterface = Readonly<{
|
|||||||
const DESKTOP_UI_MODE_STORAGE_KEY = "excalidraw.desktopUIMode";
|
const DESKTOP_UI_MODE_STORAGE_KEY = "excalidraw.desktopUIMode";
|
||||||
|
|
||||||
// breakpoints
|
// breakpoints
|
||||||
// mobile: up to 699px
|
|
||||||
export const MQ_MAX_MOBILE = 599;
|
export const MQ_MAX_MOBILE = 599;
|
||||||
|
|
||||||
export const MQ_MAX_WIDTH_LANDSCAPE = 1000;
|
export const MQ_MAX_WIDTH_LANDSCAPE = 1000;
|
||||||
@@ -24,9 +23,9 @@ export const MQ_MAX_HEIGHT_LANDSCAPE = 500;
|
|||||||
|
|
||||||
// tablets
|
// tablets
|
||||||
export const MQ_MIN_TABLET = MQ_MAX_MOBILE + 1; // lower bound (excludes phones)
|
export const MQ_MIN_TABLET = MQ_MAX_MOBILE + 1; // lower bound (excludes phones)
|
||||||
export const MQ_MAX_TABLET = 1400; // upper bound (excludes laptops/desktops)
|
export const MQ_MAX_TABLET = 1180; // ipad air
|
||||||
|
|
||||||
// desktop/laptop
|
// desktop/laptop (NOTE: not used for form factor detection)
|
||||||
export const MQ_MIN_WIDTH_DESKTOP = 1440;
|
export const MQ_MIN_WIDTH_DESKTOP = 1440;
|
||||||
|
|
||||||
// sidebar
|
// sidebar
|
||||||
|
|||||||
@@ -11,5 +11,4 @@ export * from "./random";
|
|||||||
export * from "./url";
|
export * from "./url";
|
||||||
export * from "./utils";
|
export * from "./utils";
|
||||||
export * from "./emitter";
|
export * from "./emitter";
|
||||||
export * from "./visualdebug";
|
|
||||||
export * from "./editorInterface";
|
export * from "./editorInterface";
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import type {
|
|||||||
Zoom,
|
Zoom,
|
||||||
} from "@excalidraw/excalidraw/types";
|
} from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
import { COLOR_PALETTE } from "./colors";
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_VERSION,
|
DEFAULT_VERSION,
|
||||||
ENV,
|
ENV,
|
||||||
@@ -548,16 +547,6 @@ export const mapFind = <T, K>(
|
|||||||
return undefined;
|
return undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const isTransparent = (color: string) => {
|
|
||||||
const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
|
|
||||||
const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
|
|
||||||
return (
|
|
||||||
isRGBTransparent ||
|
|
||||||
isRRGGBBTransparent ||
|
|
||||||
color === COLOR_PALETTE.transparent
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ResolvablePromise<T> = Promise<T> & {
|
export type ResolvablePromise<T> = Promise<T> & {
|
||||||
resolve: [T] extends [undefined]
|
resolve: [T] extends [undefined]
|
||||||
? (value?: MaybePromise<Awaited<T>>) => void
|
? (value?: MaybePromise<Awaited<T>>) => void
|
||||||
@@ -1157,39 +1146,69 @@ export const normalizeEOL = (str: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
type HasBrand<T> = {
|
export type HasBrand<T> = {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
[K in keyof T]: K extends `~brand${infer _}` ? true : never;
|
[K in keyof T]: K extends `~brand${infer _}` | "_brand" ? true : never;
|
||||||
}[keyof T];
|
}[keyof T];
|
||||||
|
|
||||||
type RemoveAllBrands<T> = HasBrand<T> extends true
|
type RemoveAllBrands<T> = HasBrand<T> extends true
|
||||||
? {
|
? {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
[K in keyof T as K extends `~brand~${infer _}` ? never : K]: T[K];
|
[K in keyof T as K extends `~brand~${infer _}` | "_brand"
|
||||||
|
? never
|
||||||
|
: K]: T[K];
|
||||||
}
|
}
|
||||||
: never;
|
: T;
|
||||||
|
|
||||||
// adapted from https://github.com/colinhacks/zod/discussions/1994#discussioncomment-6068940
|
// For accepting values - uses loose matching for branded types
|
||||||
// currently does not cover all types (e.g. tuples, promises...)
|
// Preserves readonly modifier: mutable array requires mutable input
|
||||||
type Unbrand<T> = T extends Map<infer E, infer F>
|
type UnbrandForValue<T> = T extends Map<infer E, infer F>
|
||||||
? Map<E, F>
|
? Map<UnbrandForValue<E>, UnbrandForValue<F>>
|
||||||
: T extends Set<infer E>
|
: T extends Set<infer E>
|
||||||
? Set<E>
|
? Set<UnbrandForValue<E>>
|
||||||
: T extends Array<infer E>
|
: T extends readonly any[]
|
||||||
? Array<E>
|
? T extends any[]
|
||||||
|
? unknown[] // mutable array - require mutable input
|
||||||
|
: readonly unknown[] // readonly array - accept readonly input
|
||||||
: RemoveAllBrands<T>;
|
: RemoveAllBrands<T>;
|
||||||
|
|
||||||
|
// For return types - preserves array element unbranding
|
||||||
|
export type Unbrand<T> = T extends Map<infer E, infer F>
|
||||||
|
? Map<Unbrand<E>, Unbrand<F>>
|
||||||
|
: T extends Set<infer E>
|
||||||
|
? Set<Unbrand<E>>
|
||||||
|
: T extends readonly (infer E)[]
|
||||||
|
? Array<Unbrand<E>>
|
||||||
|
: RemoveAllBrands<T>;
|
||||||
|
|
||||||
|
export type CombineBrands<BrandedType, CurrentType> =
|
||||||
|
BrandedType extends readonly (infer BE)[]
|
||||||
|
? CurrentType extends readonly (infer CE)[]
|
||||||
|
? Array<CE & BE>
|
||||||
|
: CurrentType & BrandedType
|
||||||
|
: CurrentType & BrandedType;
|
||||||
|
|
||||||
|
export type CombineBrandsIfNeeded<T, Required> = [T] extends [Required]
|
||||||
|
? T[]
|
||||||
|
: HasBrand<T> extends true
|
||||||
|
? CombineBrands<T, Required>[]
|
||||||
|
: Required[];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Makes type into a branded type, ensuring that value is assignable to
|
* Makes type into a branded type, ensuring that value is assignable to
|
||||||
* the base ubranded type. Optionally you can explicitly supply current value
|
* the base unbranded type. Optionally you can explicitly supply current value
|
||||||
* type to combine both (useful for composite branded types. Make sure you
|
* type to combine both (useful for composite branded types. Make sure you
|
||||||
* compose branded types which are not composite themselves.)
|
* compose branded types which are not composite themselves.)
|
||||||
*/
|
*/
|
||||||
export const toBrandedType = <BrandedType, CurrentType = BrandedType>(
|
export function toBrandedType<BrandedType>(
|
||||||
value: Unbrand<BrandedType>,
|
value: UnbrandForValue<BrandedType>,
|
||||||
) => {
|
): BrandedType;
|
||||||
return value as CurrentType & BrandedType;
|
export function toBrandedType<BrandedType, CurrentType>(
|
||||||
};
|
value: CurrentType,
|
||||||
|
): CombineBrands<BrandedType, CurrentType>;
|
||||||
|
export function toBrandedType(value: unknown) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,12 @@
|
|||||||
"development": "./dist/dev/index.js",
|
"development": "./dist/dev/index.js",
|
||||||
"production": "./dist/prod/index.js",
|
"production": "./dist/prod/index.js",
|
||||||
"default": "./dist/prod/index.js"
|
"default": "./dist/prod/index.js"
|
||||||
|
},
|
||||||
|
"./visualdebug": {
|
||||||
|
"types": "./dist/types/element/src/visualdebug.d.ts",
|
||||||
|
"development": "./dist/dev/visualdebug.js",
|
||||||
|
"production": "./dist/prod/visualdebug.js",
|
||||||
|
"default": "./dist/prod/visualdebug.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
pointFrom,
|
pointFrom,
|
||||||
pointFromVector,
|
pointFromVector,
|
||||||
pointRotateRads,
|
pointRotateRads,
|
||||||
|
pointsEqual,
|
||||||
vectorFromPoint,
|
vectorFromPoint,
|
||||||
vectorNormalize,
|
vectorNormalize,
|
||||||
vectorScale,
|
vectorScale,
|
||||||
@@ -1602,7 +1603,12 @@ export const updateBoundPoint = (
|
|||||||
if (
|
if (
|
||||||
binding == null ||
|
binding == null ||
|
||||||
// We only need to update the other end if this is a 2 point line element
|
// We only need to update the other end if this is a 2 point line element
|
||||||
(binding.elementId !== bindableElement.id && arrow.points.length > 2)
|
(binding.elementId !== bindableElement.id && arrow.points.length > 2) ||
|
||||||
|
// Initial arrow created on pointer down needs to not update the points
|
||||||
|
pointsEqual(
|
||||||
|
arrow.points[arrow.points.length - 1],
|
||||||
|
pointFrom<LocalPoint>(0, 0),
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -897,6 +897,7 @@ export const getArrowheadPoints = (
|
|||||||
return [x2, y2, x3, y3, x4, y4];
|
return [x2, y2, x3, y3, x4, y4];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO reuse shape.ts
|
||||||
const generateLinearElementShape = (
|
const generateLinearElementShape = (
|
||||||
element: ExcalidrawLinearElement,
|
element: ExcalidrawLinearElement,
|
||||||
): Drawable => {
|
): Drawable => {
|
||||||
@@ -954,7 +955,7 @@ const getLinearElementRotatedBounds = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// first element is always the curve
|
// first element is always the curve
|
||||||
const cachedShape = ShapeCache.get(element)?.[0];
|
const cachedShape = ShapeCache.get(element, null)?.[0];
|
||||||
const shape = cachedShape ?? generateLinearElementShape(element);
|
const shape = cachedShape ?? generateLinearElementShape(element);
|
||||||
const ops = getCurvePathOps(shape);
|
const ops = getCurvePathOps(shape);
|
||||||
const transformXY = ([x, y]: GlobalPoint) =>
|
const transformXY = ([x, y]: GlobalPoint) =>
|
||||||
|
|||||||
@@ -105,6 +105,12 @@ export type HitTestArgs = {
|
|||||||
overrideShouldTestInside?: boolean;
|
overrideShouldTestInside?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let cachedPoint: GlobalPoint | null = null;
|
||||||
|
let cachedElement: WeakRef<ExcalidrawElement> | null = null;
|
||||||
|
let cachedThreshold: number = Infinity;
|
||||||
|
let cachedHit: boolean = false;
|
||||||
|
let cachedOverrideShouldTestInside = false;
|
||||||
|
|
||||||
export const hitElementItself = ({
|
export const hitElementItself = ({
|
||||||
point,
|
point,
|
||||||
element,
|
element,
|
||||||
@@ -113,6 +119,24 @@ export const hitElementItself = ({
|
|||||||
frameNameBound = null,
|
frameNameBound = null,
|
||||||
overrideShouldTestInside = false,
|
overrideShouldTestInside = false,
|
||||||
}: HitTestArgs) => {
|
}: HitTestArgs) => {
|
||||||
|
// Return cached result if the same point and element version is tested again
|
||||||
|
if (
|
||||||
|
cachedPoint &&
|
||||||
|
pointsEqual(point, cachedPoint) &&
|
||||||
|
cachedThreshold <= threshold &&
|
||||||
|
overrideShouldTestInside === cachedOverrideShouldTestInside
|
||||||
|
) {
|
||||||
|
const derefElement = cachedElement?.deref();
|
||||||
|
if (
|
||||||
|
derefElement &&
|
||||||
|
derefElement.id === element.id &&
|
||||||
|
derefElement.version === element.version &&
|
||||||
|
derefElement.versionNonce === element.versionNonce
|
||||||
|
) {
|
||||||
|
return cachedHit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Hit test against a frame's name
|
// Hit test against a frame's name
|
||||||
const hitFrameName = frameNameBound
|
const hitFrameName = frameNameBound
|
||||||
? isPointWithinBounds(
|
? isPointWithinBounds(
|
||||||
@@ -153,7 +177,16 @@ export const hitElementItself = ({
|
|||||||
isPointOnElementOutline(point, element, elementsMap, threshold)
|
isPointOnElementOutline(point, element, elementsMap, threshold)
|
||||||
: isPointOnElementOutline(point, element, elementsMap, threshold);
|
: isPointOnElementOutline(point, element, elementsMap, threshold);
|
||||||
|
|
||||||
return hitElement || hitFrameName;
|
const result = hitElement || hitFrameName;
|
||||||
|
|
||||||
|
// Cache end result
|
||||||
|
cachedPoint = point;
|
||||||
|
cachedElement = new WeakRef(element);
|
||||||
|
cachedThreshold = threshold;
|
||||||
|
cachedOverrideShouldTestInside = overrideShouldTestInside;
|
||||||
|
cachedHit = result;
|
||||||
|
|
||||||
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const hitElementBoundingBox = (
|
export const hitElementBoundingBox = (
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import type { AppState } from "@excalidraw/excalidraw/types";
|
import type { AppState } from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
|
import { updateBoundElements } from "./binding";
|
||||||
import { getCommonBoundingBox } from "./bounds";
|
import { getCommonBoundingBox } from "./bounds";
|
||||||
import { newElementWith } from "./mutateElement";
|
|
||||||
|
|
||||||
import { getSelectedElementsByGroup } from "./groups";
|
import { getSelectedElementsByGroup } from "./groups";
|
||||||
|
|
||||||
|
import type { Scene } from "./Scene";
|
||||||
|
|
||||||
import type { ElementsMap, ExcalidrawElement } from "./types";
|
import type { ElementsMap, ExcalidrawElement } from "./types";
|
||||||
|
|
||||||
export interface Distribution {
|
export interface Distribution {
|
||||||
@@ -17,6 +19,7 @@ export const distributeElements = (
|
|||||||
elementsMap: ElementsMap,
|
elementsMap: ElementsMap,
|
||||||
distribution: Distribution,
|
distribution: Distribution,
|
||||||
appState: Readonly<AppState>,
|
appState: Readonly<AppState>,
|
||||||
|
scene: Scene,
|
||||||
): ExcalidrawElement[] => {
|
): ExcalidrawElement[] => {
|
||||||
const [start, mid, end, extent] =
|
const [start, mid, end, extent] =
|
||||||
distribution.axis === "x"
|
distribution.axis === "x"
|
||||||
@@ -66,12 +69,16 @@ export const distributeElements = (
|
|||||||
translation[distribution.axis] = pos - box[mid];
|
translation[distribution.axis] = pos - box[mid];
|
||||||
}
|
}
|
||||||
|
|
||||||
return group.map((element) =>
|
return group.map((element) => {
|
||||||
newElementWith(element, {
|
const updatedElement = scene.mutateElement(element, {
|
||||||
x: element.x + translation.x,
|
x: element.x + translation.x,
|
||||||
y: element.y + translation.y,
|
y: element.y + translation.y,
|
||||||
}),
|
});
|
||||||
);
|
updateBoundElements(element, scene, {
|
||||||
|
simultaneouslyUpdated: group,
|
||||||
|
});
|
||||||
|
return updatedElement;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,11 +97,15 @@ export const distributeElements = (
|
|||||||
pos += step;
|
pos += step;
|
||||||
pos += box[extent];
|
pos += box[extent];
|
||||||
|
|
||||||
return group.map((element) =>
|
return group.map((element) => {
|
||||||
newElementWith(element, {
|
const updatedElement = scene.mutateElement(element, {
|
||||||
x: element.x + translation.x,
|
x: element.x + translation.x,
|
||||||
y: element.y + translation.y,
|
y: element.y + translation.y,
|
||||||
}),
|
});
|
||||||
);
|
updateBoundElements(element, scene, {
|
||||||
|
simultaneouslyUpdated: group,
|
||||||
|
});
|
||||||
|
return updatedElement;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -724,7 +724,6 @@ export class LinearElementEditor {
|
|||||||
? [pointerDownState.lastClickedPoint]
|
? [pointerDownState.lastClickedPoint]
|
||||||
: selectedPointsIndices,
|
: selectedPointsIndices,
|
||||||
isDragging: false,
|
isDragging: false,
|
||||||
pointerOffset: { x: 0, y: 0 },
|
|
||||||
customLineAngle: null,
|
customLineAngle: null,
|
||||||
initialState: {
|
initialState: {
|
||||||
...editingLinearElement.initialState,
|
...editingLinearElement.initialState,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import rough from "roughjs/bin/rough";
|
import rough from "roughjs/bin/rough";
|
||||||
import { getStroke } from "perfect-freehand";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type GlobalPoint,
|
type GlobalPoint,
|
||||||
@@ -15,6 +14,7 @@ import {
|
|||||||
DEFAULT_REDUCED_GLOBAL_ALPHA,
|
DEFAULT_REDUCED_GLOBAL_ALPHA,
|
||||||
ELEMENT_READY_TO_ERASE_OPACITY,
|
ELEMENT_READY_TO_ERASE_OPACITY,
|
||||||
FRAME_STYLE,
|
FRAME_STYLE,
|
||||||
|
DARK_THEME_FILTER,
|
||||||
MIME_TYPES,
|
MIME_TYPES,
|
||||||
THEME,
|
THEME,
|
||||||
distance,
|
distance,
|
||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
isRTL,
|
isRTL,
|
||||||
getVerticalOffset,
|
getVerticalOffset,
|
||||||
invariant,
|
invariant,
|
||||||
|
applyDarkModeFilter,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -78,16 +79,8 @@ import type {
|
|||||||
ElementsMap,
|
ElementsMap,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
import type { StrokeOptions } from "perfect-freehand";
|
|
||||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||||
|
|
||||||
// using a stronger invert (100% vs our regular 93%) and saturate
|
|
||||||
// as a temp hack to make images in dark theme look closer to original
|
|
||||||
// color scheme (it's still not quite there and the colors look slightly
|
|
||||||
// desatured, alas...)
|
|
||||||
export const IMAGE_INVERT_FILTER =
|
|
||||||
"invert(100%) hue-rotate(180deg) saturate(1.25)";
|
|
||||||
|
|
||||||
const isPendingImageElement = (
|
const isPendingImageElement = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
@@ -95,19 +88,6 @@ const isPendingImageElement = (
|
|||||||
isInitializedImageElement(element) &&
|
isInitializedImageElement(element) &&
|
||||||
!renderConfig.imageCache.has(element.fileId);
|
!renderConfig.imageCache.has(element.fileId);
|
||||||
|
|
||||||
const shouldResetImageFilter = (
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
|
||||||
) => {
|
|
||||||
return (
|
|
||||||
appState.theme === THEME.DARK &&
|
|
||||||
isInitializedImageElement(element) &&
|
|
||||||
!isPendingImageElement(element, renderConfig) &&
|
|
||||||
renderConfig.imageCache.get(element.fileId)?.mimeType !== MIME_TYPES.svg
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getCanvasPadding = (element: ExcalidrawElement) => {
|
const getCanvasPadding = (element: ExcalidrawElement) => {
|
||||||
switch (element.type) {
|
switch (element.type) {
|
||||||
case "freedraw":
|
case "freedraw":
|
||||||
@@ -272,11 +252,6 @@ const generateElementCanvas = (
|
|||||||
|
|
||||||
const rc = rough.canvas(canvas);
|
const rc = rough.canvas(canvas);
|
||||||
|
|
||||||
// in dark theme, revert the image color filter
|
|
||||||
if (shouldResetImageFilter(element, renderConfig, appState)) {
|
|
||||||
context.filter = IMAGE_INVERT_FILTER;
|
|
||||||
}
|
|
||||||
|
|
||||||
drawElementOnCanvas(element, rc, context, renderConfig);
|
drawElementOnCanvas(element, rc, context, renderConfig);
|
||||||
|
|
||||||
context.restore();
|
context.restore();
|
||||||
@@ -421,7 +396,8 @@ const drawElementOnCanvas = (
|
|||||||
case "ellipse": {
|
case "ellipse": {
|
||||||
context.lineJoin = "round";
|
context.lineJoin = "round";
|
||||||
context.lineCap = "round";
|
context.lineCap = "round";
|
||||||
rc.draw(ShapeCache.get(element)!);
|
|
||||||
|
rc.draw(ShapeCache.generateElementShape(element, renderConfig));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "arrow":
|
case "arrow":
|
||||||
@@ -429,33 +405,51 @@ const drawElementOnCanvas = (
|
|||||||
context.lineJoin = "round";
|
context.lineJoin = "round";
|
||||||
context.lineCap = "round";
|
context.lineCap = "round";
|
||||||
|
|
||||||
ShapeCache.get(element)!.forEach((shape) => {
|
ShapeCache.generateElementShape(element, renderConfig).forEach(
|
||||||
rc.draw(shape);
|
(shape) => {
|
||||||
});
|
rc.draw(shape);
|
||||||
|
},
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "freedraw": {
|
case "freedraw": {
|
||||||
// Draw directly to canvas
|
// Draw directly to canvas
|
||||||
context.save();
|
context.save();
|
||||||
context.fillStyle = element.strokeColor;
|
|
||||||
|
|
||||||
const path = getFreeDrawPath2D(element) as Path2D;
|
const shapes = ShapeCache.generateElementShape(element, renderConfig);
|
||||||
const fillShape = ShapeCache.get(element);
|
|
||||||
|
|
||||||
if (fillShape) {
|
for (const shape of shapes) {
|
||||||
rc.draw(fillShape);
|
if (typeof shape === "string") {
|
||||||
|
context.fillStyle =
|
||||||
|
renderConfig.theme === THEME.DARK
|
||||||
|
? applyDarkModeFilter(element.strokeColor)
|
||||||
|
: element.strokeColor;
|
||||||
|
context.fill(new Path2D(shape));
|
||||||
|
} else {
|
||||||
|
rc.draw(shape);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
context.fillStyle = element.strokeColor;
|
|
||||||
context.fill(path);
|
|
||||||
|
|
||||||
context.restore();
|
context.restore();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "image": {
|
case "image": {
|
||||||
|
context.save();
|
||||||
|
const cacheEntry =
|
||||||
|
element.fileId !== null
|
||||||
|
? renderConfig.imageCache.get(element.fileId)
|
||||||
|
: null;
|
||||||
const img = isInitializedImageElement(element)
|
const img = isInitializedImageElement(element)
|
||||||
? renderConfig.imageCache.get(element.fileId)?.image
|
? cacheEntry?.image
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
const shouldInvertImage =
|
||||||
|
renderConfig.theme === THEME.DARK &&
|
||||||
|
cacheEntry?.mimeType === MIME_TYPES.svg;
|
||||||
|
|
||||||
|
if (shouldInvertImage) {
|
||||||
|
context.filter = DARK_THEME_FILTER;
|
||||||
|
}
|
||||||
if (img != null && !(img instanceof Promise)) {
|
if (img != null && !(img instanceof Promise)) {
|
||||||
if (element.roundness && context.roundRect) {
|
if (element.roundness && context.roundRect) {
|
||||||
context.beginPath();
|
context.beginPath();
|
||||||
@@ -492,6 +486,7 @@ const drawElementOnCanvas = (
|
|||||||
} else {
|
} else {
|
||||||
drawImagePlaceholder(element, context);
|
drawImagePlaceholder(element, context);
|
||||||
}
|
}
|
||||||
|
context.restore();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
@@ -506,7 +501,10 @@ const drawElementOnCanvas = (
|
|||||||
context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
|
context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
|
||||||
context.save();
|
context.save();
|
||||||
context.font = getFontString(element);
|
context.font = getFontString(element);
|
||||||
context.fillStyle = element.strokeColor;
|
context.fillStyle =
|
||||||
|
renderConfig.theme === THEME.DARK
|
||||||
|
? applyDarkModeFilter(element.strokeColor)
|
||||||
|
: element.strokeColor;
|
||||||
context.textAlign = element.textAlign as CanvasTextAlign;
|
context.textAlign = element.textAlign as CanvasTextAlign;
|
||||||
|
|
||||||
// Canvas does not support multiline text by default
|
// Canvas does not support multiline text by default
|
||||||
@@ -759,12 +757,17 @@ export const renderElement = (
|
|||||||
context.fillStyle = "rgba(0, 0, 200, 0.04)";
|
context.fillStyle = "rgba(0, 0, 200, 0.04)";
|
||||||
|
|
||||||
context.lineWidth = FRAME_STYLE.strokeWidth / appState.zoom.value;
|
context.lineWidth = FRAME_STYLE.strokeWidth / appState.zoom.value;
|
||||||
context.strokeStyle = FRAME_STYLE.strokeColor;
|
context.strokeStyle =
|
||||||
|
appState.theme === THEME.DARK
|
||||||
|
? applyDarkModeFilter(FRAME_STYLE.strokeColor)
|
||||||
|
: FRAME_STYLE.strokeColor;
|
||||||
|
|
||||||
// TODO change later to only affect AI frames
|
// TODO change later to only affect AI frames
|
||||||
if (isMagicFrameElement(element)) {
|
if (isMagicFrameElement(element)) {
|
||||||
context.strokeStyle =
|
context.strokeStyle =
|
||||||
appState.theme === THEME.LIGHT ? "#7affd7" : "#1d8264";
|
appState.theme === THEME.LIGHT
|
||||||
|
? "#7affd7"
|
||||||
|
: applyDarkModeFilter("#1d8264");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (FRAME_STYLE.radius && context.roundRect) {
|
if (FRAME_STYLE.radius && context.roundRect) {
|
||||||
@@ -787,11 +790,6 @@ export const renderElement = (
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "freedraw": {
|
case "freedraw": {
|
||||||
// TODO investigate if we can do this in situ. Right now we need to call
|
|
||||||
// beforehand because math helpers (such as getElementAbsoluteCoords)
|
|
||||||
// rely on existing shapes
|
|
||||||
ShapeCache.generateElementShape(element, null);
|
|
||||||
|
|
||||||
if (renderConfig.isExporting) {
|
if (renderConfig.isExporting) {
|
||||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||||
const cx = (x1 + x2) / 2 + appState.scrollX;
|
const cx = (x1 + x2) / 2 + appState.scrollX;
|
||||||
@@ -835,10 +833,6 @@ export const renderElement = (
|
|||||||
case "text":
|
case "text":
|
||||||
case "iframe":
|
case "iframe":
|
||||||
case "embeddable": {
|
case "embeddable": {
|
||||||
// TODO investigate if we can do this in situ. Right now we need to call
|
|
||||||
// beforehand because math helpers (such as getElementAbsoluteCoords)
|
|
||||||
// rely on existing shapes
|
|
||||||
ShapeCache.generateElementShape(element, renderConfig);
|
|
||||||
if (renderConfig.isExporting) {
|
if (renderConfig.isExporting) {
|
||||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||||
const cx = (x1 + x2) / 2 + appState.scrollX;
|
const cx = (x1 + x2) / 2 + appState.scrollX;
|
||||||
@@ -861,9 +855,6 @@ export const renderElement = (
|
|||||||
context.save();
|
context.save();
|
||||||
context.translate(cx, cy);
|
context.translate(cx, cy);
|
||||||
|
|
||||||
if (shouldResetImageFilter(element, renderConfig, appState)) {
|
|
||||||
context.filter = "none";
|
|
||||||
}
|
|
||||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
const boundTextElement = getBoundTextElement(element, elementsMap);
|
||||||
|
|
||||||
if (isArrowElement(element) && boundTextElement) {
|
if (isArrowElement(element) && boundTextElement) {
|
||||||
@@ -1026,23 +1017,6 @@ export const renderElement = (
|
|||||||
context.globalAlpha = 1;
|
context.globalAlpha = 1;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const pathsCache = new WeakMap<ExcalidrawFreeDrawElement, Path2D>([]);
|
|
||||||
|
|
||||||
export function generateFreeDrawShape(element: ExcalidrawFreeDrawElement) {
|
|
||||||
const svgPathData = getFreeDrawSvgPath(element);
|
|
||||||
const path = new Path2D(svgPathData);
|
|
||||||
pathsCache.set(element, path);
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFreeDrawPath2D(element: ExcalidrawFreeDrawElement) {
|
|
||||||
return pathsCache.get(element);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFreeDrawSvgPath(element: ExcalidrawFreeDrawElement) {
|
|
||||||
return getSvgPathFromStroke(getFreedrawOutlinePoints(element));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFreedrawOutlineAsSegments(
|
export function getFreedrawOutlineAsSegments(
|
||||||
element: ExcalidrawFreeDrawElement,
|
element: ExcalidrawFreeDrawElement,
|
||||||
points: [number, number][],
|
points: [number, number][],
|
||||||
@@ -1098,57 +1072,3 @@ export function getFreedrawOutlineAsSegments(
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getFreedrawOutlinePoints(element: ExcalidrawFreeDrawElement) {
|
|
||||||
// If input points are empty (should they ever be?) return a dot
|
|
||||||
const inputPoints = element.simulatePressure
|
|
||||||
? element.points
|
|
||||||
: element.points.length
|
|
||||||
? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
|
|
||||||
: [[0, 0, 0.5]];
|
|
||||||
|
|
||||||
// Consider changing the options for simulated pressure vs real pressure
|
|
||||||
const options: StrokeOptions = {
|
|
||||||
simulatePressure: element.simulatePressure,
|
|
||||||
size: element.strokeWidth * 4.25,
|
|
||||||
thinning: 0.6,
|
|
||||||
smoothing: 0.5,
|
|
||||||
streamline: 0.5,
|
|
||||||
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
|
|
||||||
last: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
return getStroke(inputPoints as number[][], options) as [number, number][];
|
|
||||||
}
|
|
||||||
|
|
||||||
function med(A: number[], B: number[]) {
|
|
||||||
return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Trim SVG path data so number are each two decimal points. This
|
|
||||||
// improves SVG exports, and prevents rendering errors on points
|
|
||||||
// with long decimals.
|
|
||||||
const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g;
|
|
||||||
|
|
||||||
function getSvgPathFromStroke(points: number[][]): string {
|
|
||||||
if (!points.length) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
const max = points.length - 1;
|
|
||||||
|
|
||||||
return points
|
|
||||||
.reduce(
|
|
||||||
(acc, point, i, arr) => {
|
|
||||||
if (i === max) {
|
|
||||||
acc.push(point, med(point, arr[0]), "L", arr[0], "Z");
|
|
||||||
} else {
|
|
||||||
acc.push(point, med(point, arr[i + 1]));
|
|
||||||
}
|
|
||||||
return acc;
|
|
||||||
},
|
|
||||||
["M", points[0], "Q"],
|
|
||||||
)
|
|
||||||
.join(" ")
|
|
||||||
.replace(TO_FIXED_PRECISION, "$1");
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -318,7 +318,18 @@ export const resizeSingleTextElement = (
|
|||||||
) => {
|
) => {
|
||||||
const elementsMap = scene.getNonDeletedElementsMap();
|
const elementsMap = scene.getNonDeletedElementsMap();
|
||||||
|
|
||||||
const metricsWidth = element.width * (nextHeight / element.height);
|
const isCornerHandle = transformHandleType.length === 2;
|
||||||
|
let metricsWidth = element.width * (nextHeight / element.height);
|
||||||
|
let metricsHeight = nextHeight;
|
||||||
|
|
||||||
|
if (isCornerHandle) {
|
||||||
|
const widthRatio = Math.abs(nextWidth) / element.width;
|
||||||
|
const heightRatio = Math.abs(nextHeight) / element.height;
|
||||||
|
const ratio = Math.max(widthRatio, heightRatio);
|
||||||
|
const sign = Math.sign(nextHeight) || 1;
|
||||||
|
metricsWidth = element.width * ratio * sign;
|
||||||
|
metricsHeight = element.height * ratio * sign;
|
||||||
|
}
|
||||||
|
|
||||||
const metrics = measureFontSizeFromWidth(element, elementsMap, metricsWidth);
|
const metrics = measureFontSizeFromWidth(element, elementsMap, metricsWidth);
|
||||||
if (metrics === null) {
|
if (metrics === null) {
|
||||||
@@ -333,7 +344,7 @@ export const resizeSingleTextElement = (
|
|||||||
origElement.width,
|
origElement.width,
|
||||||
origElement.height,
|
origElement.height,
|
||||||
metricsWidth,
|
metricsWidth,
|
||||||
nextHeight,
|
metricsHeight,
|
||||||
origElement.angle,
|
origElement.angle,
|
||||||
transformHandleType,
|
transformHandleType,
|
||||||
false,
|
false,
|
||||||
@@ -343,7 +354,7 @@ export const resizeSingleTextElement = (
|
|||||||
scene.mutateElement(element, {
|
scene.mutateElement(element, {
|
||||||
fontSize: metrics.size,
|
fontSize: metrics.size,
|
||||||
width: metricsWidth,
|
width: metricsWidth,
|
||||||
height: nextHeight,
|
height: metricsHeight,
|
||||||
x: newOrigin.x,
|
x: newOrigin.x,
|
||||||
y: newOrigin.y,
|
y: newOrigin.y,
|
||||||
});
|
});
|
||||||
|
|||||||
+144
-43
@@ -1,4 +1,5 @@
|
|||||||
import { simplify } from "points-on-curve";
|
import { simplify } from "points-on-curve";
|
||||||
|
import { getStroke } from "perfect-freehand";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type GeometricShape,
|
type GeometricShape,
|
||||||
@@ -17,10 +18,12 @@ import {
|
|||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
import {
|
import {
|
||||||
ROUGHNESS,
|
ROUGHNESS,
|
||||||
|
THEME,
|
||||||
isTransparent,
|
isTransparent,
|
||||||
assertNever,
|
assertNever,
|
||||||
COLOR_PALETTE,
|
COLOR_PALETTE,
|
||||||
LINE_POLYGON_POINT_MERGE_DISTANCE,
|
LINE_POLYGON_POINT_MERGE_DISTANCE,
|
||||||
|
applyDarkModeFilter,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import { RoughGenerator } from "roughjs/bin/generator";
|
import { RoughGenerator } from "roughjs/bin/generator";
|
||||||
@@ -36,6 +39,7 @@ import type {
|
|||||||
import type {
|
import type {
|
||||||
ElementShape,
|
ElementShape,
|
||||||
ElementShapes,
|
ElementShapes,
|
||||||
|
SVGPathString,
|
||||||
} from "@excalidraw/excalidraw/scene/types";
|
} from "@excalidraw/excalidraw/scene/types";
|
||||||
|
|
||||||
import { elementWithCanvasCache } from "./renderElement";
|
import { elementWithCanvasCache } from "./renderElement";
|
||||||
@@ -52,7 +56,6 @@ import { getCornerRadius, isPathALoop } from "./utils";
|
|||||||
import { headingForPointIsHorizontal } from "./heading";
|
import { headingForPointIsHorizontal } from "./heading";
|
||||||
|
|
||||||
import { canChangeRoundness } from "./comparisons";
|
import { canChangeRoundness } from "./comparisons";
|
||||||
import { generateFreeDrawShape } from "./renderElement";
|
|
||||||
import {
|
import {
|
||||||
getArrowheadPoints,
|
getArrowheadPoints,
|
||||||
getCenterForBounds,
|
getCenterForBounds,
|
||||||
@@ -77,29 +80,32 @@ import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
|||||||
|
|
||||||
export class ShapeCache {
|
export class ShapeCache {
|
||||||
private static rg = new RoughGenerator();
|
private static rg = new RoughGenerator();
|
||||||
private static cache = new WeakMap<ExcalidrawElement, ElementShape>();
|
private static cache = new WeakMap<
|
||||||
|
ExcalidrawElement,
|
||||||
|
{ shape: ElementShape; theme: AppState["theme"] }
|
||||||
|
>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves shape from cache if available. Use this only if shape
|
* Retrieves shape from cache if available. Use this only if shape
|
||||||
* is optional and you have a fallback in case it's not cached.
|
* is optional and you have a fallback in case it's not cached.
|
||||||
*/
|
*/
|
||||||
public static get = <T extends ExcalidrawElement>(element: T) => {
|
public static get = <T extends ExcalidrawElement>(
|
||||||
return ShapeCache.cache.get(
|
element: T,
|
||||||
element,
|
theme: AppState["theme"] | null,
|
||||||
) as T["type"] extends keyof ElementShapes
|
) => {
|
||||||
? ElementShapes[T["type"]] | undefined
|
const cached = ShapeCache.cache.get(element);
|
||||||
: ElementShape | undefined;
|
if (cached && (theme === null || cached.theme === theme)) {
|
||||||
|
return cached.shape as T["type"] extends keyof ElementShapes
|
||||||
|
? ElementShapes[T["type"]] | undefined
|
||||||
|
: ElementShape | undefined;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
public static set = <T extends ExcalidrawElement>(
|
public static delete = (element: ExcalidrawElement) => {
|
||||||
element: T,
|
|
||||||
shape: T["type"] extends keyof ElementShapes
|
|
||||||
? ElementShapes[T["type"]]
|
|
||||||
: Drawable,
|
|
||||||
) => ShapeCache.cache.set(element, shape);
|
|
||||||
|
|
||||||
public static delete = (element: ExcalidrawElement) =>
|
|
||||||
ShapeCache.cache.delete(element);
|
ShapeCache.cache.delete(element);
|
||||||
|
elementWithCanvasCache.delete(element);
|
||||||
|
};
|
||||||
|
|
||||||
public static destroy = () => {
|
public static destroy = () => {
|
||||||
ShapeCache.cache = new WeakMap();
|
ShapeCache.cache = new WeakMap();
|
||||||
@@ -117,12 +123,13 @@ export class ShapeCache {
|
|||||||
isExporting: boolean;
|
isExporting: boolean;
|
||||||
canvasBackgroundColor: AppState["viewBackgroundColor"];
|
canvasBackgroundColor: AppState["viewBackgroundColor"];
|
||||||
embedsValidationStatus: EmbedsValidationStatus;
|
embedsValidationStatus: EmbedsValidationStatus;
|
||||||
|
theme: AppState["theme"];
|
||||||
} | null,
|
} | null,
|
||||||
) => {
|
) => {
|
||||||
// when exporting, always regenerated to guarantee the latest shape
|
// when exporting, always regenerated to guarantee the latest shape
|
||||||
const cachedShape = renderConfig?.isExporting
|
const cachedShape = renderConfig?.isExporting
|
||||||
? undefined
|
? undefined
|
||||||
: ShapeCache.get(element);
|
: ShapeCache.get(element, renderConfig ? renderConfig.theme : null);
|
||||||
|
|
||||||
// `null` indicates no rc shape applicable for this element type,
|
// `null` indicates no rc shape applicable for this element type,
|
||||||
// but it's considered a valid cache value (= do not regenerate)
|
// but it's considered a valid cache value (= do not regenerate)
|
||||||
@@ -132,19 +139,25 @@ export class ShapeCache {
|
|||||||
|
|
||||||
elementWithCanvasCache.delete(element);
|
elementWithCanvasCache.delete(element);
|
||||||
|
|
||||||
const shape = generateElementShape(
|
const shape = _generateElementShape(
|
||||||
element,
|
element,
|
||||||
ShapeCache.rg,
|
ShapeCache.rg,
|
||||||
renderConfig || {
|
renderConfig || {
|
||||||
isExporting: false,
|
isExporting: false,
|
||||||
canvasBackgroundColor: COLOR_PALETTE.white,
|
canvasBackgroundColor: COLOR_PALETTE.white,
|
||||||
embedsValidationStatus: null,
|
embedsValidationStatus: null,
|
||||||
|
theme: THEME.LIGHT,
|
||||||
},
|
},
|
||||||
) as T["type"] extends keyof ElementShapes
|
) as T["type"] extends keyof ElementShapes
|
||||||
? ElementShapes[T["type"]]
|
? ElementShapes[T["type"]]
|
||||||
: Drawable | null;
|
: Drawable | null;
|
||||||
|
|
||||||
ShapeCache.cache.set(element, shape);
|
if (!renderConfig?.isExporting) {
|
||||||
|
ShapeCache.cache.set(element, {
|
||||||
|
shape,
|
||||||
|
theme: renderConfig?.theme || THEME.LIGHT,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return shape;
|
return shape;
|
||||||
};
|
};
|
||||||
@@ -180,6 +193,7 @@ function adjustRoughness(element: ExcalidrawElement): number {
|
|||||||
export const generateRoughOptions = (
|
export const generateRoughOptions = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
continuousPath = false,
|
continuousPath = false,
|
||||||
|
isDarkMode: boolean = false,
|
||||||
): Options => {
|
): Options => {
|
||||||
const options: Options = {
|
const options: Options = {
|
||||||
seed: element.seed,
|
seed: element.seed,
|
||||||
@@ -204,7 +218,9 @@ export const generateRoughOptions = (
|
|||||||
fillWeight: element.strokeWidth / 2,
|
fillWeight: element.strokeWidth / 2,
|
||||||
hachureGap: element.strokeWidth * 4,
|
hachureGap: element.strokeWidth * 4,
|
||||||
roughness: adjustRoughness(element),
|
roughness: adjustRoughness(element),
|
||||||
stroke: element.strokeColor,
|
stroke: isDarkMode
|
||||||
|
? applyDarkModeFilter(element.strokeColor)
|
||||||
|
: element.strokeColor,
|
||||||
preserveVertices:
|
preserveVertices:
|
||||||
continuousPath || element.roughness < ROUGHNESS.cartoonist,
|
continuousPath || element.roughness < ROUGHNESS.cartoonist,
|
||||||
};
|
};
|
||||||
@@ -218,6 +234,8 @@ export const generateRoughOptions = (
|
|||||||
options.fillStyle = element.fillStyle;
|
options.fillStyle = element.fillStyle;
|
||||||
options.fill = isTransparent(element.backgroundColor)
|
options.fill = isTransparent(element.backgroundColor)
|
||||||
? undefined
|
? undefined
|
||||||
|
: isDarkMode
|
||||||
|
? applyDarkModeFilter(element.backgroundColor)
|
||||||
: element.backgroundColor;
|
: element.backgroundColor;
|
||||||
if (element.type === "ellipse") {
|
if (element.type === "ellipse") {
|
||||||
options.curveFitting = 1;
|
options.curveFitting = 1;
|
||||||
@@ -231,6 +249,8 @@ export const generateRoughOptions = (
|
|||||||
options.fill =
|
options.fill =
|
||||||
element.backgroundColor === "transparent"
|
element.backgroundColor === "transparent"
|
||||||
? undefined
|
? undefined
|
||||||
|
: isDarkMode
|
||||||
|
? applyDarkModeFilter(element.backgroundColor)
|
||||||
: element.backgroundColor;
|
: element.backgroundColor;
|
||||||
}
|
}
|
||||||
return options;
|
return options;
|
||||||
@@ -284,6 +304,7 @@ const getArrowheadShapes = (
|
|||||||
generator: RoughGenerator,
|
generator: RoughGenerator,
|
||||||
options: Options,
|
options: Options,
|
||||||
canvasBackgroundColor: string,
|
canvasBackgroundColor: string,
|
||||||
|
isDarkMode: boolean,
|
||||||
) => {
|
) => {
|
||||||
const arrowheadPoints = getArrowheadPoints(
|
const arrowheadPoints = getArrowheadPoints(
|
||||||
element,
|
element,
|
||||||
@@ -309,6 +330,10 @@ const getArrowheadShapes = (
|
|||||||
return [generator.line(x3, y3, x4, y4, options)];
|
return [generator.line(x3, y3, x4, y4, options)];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const strokeColor = isDarkMode
|
||||||
|
? applyDarkModeFilter(element.strokeColor)
|
||||||
|
: element.strokeColor;
|
||||||
|
|
||||||
switch (arrowhead) {
|
switch (arrowhead) {
|
||||||
case "dot":
|
case "dot":
|
||||||
case "circle":
|
case "circle":
|
||||||
@@ -324,10 +349,10 @@ const getArrowheadShapes = (
|
|||||||
fill:
|
fill:
|
||||||
arrowhead === "circle_outline"
|
arrowhead === "circle_outline"
|
||||||
? canvasBackgroundColor
|
? canvasBackgroundColor
|
||||||
: element.strokeColor,
|
: strokeColor,
|
||||||
|
|
||||||
fillStyle: "solid",
|
fillStyle: "solid",
|
||||||
stroke: element.strokeColor,
|
stroke: strokeColor,
|
||||||
roughness: Math.min(0.5, options.roughness || 0),
|
roughness: Math.min(0.5, options.roughness || 0),
|
||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
@@ -352,7 +377,7 @@ const getArrowheadShapes = (
|
|||||||
fill:
|
fill:
|
||||||
arrowhead === "triangle_outline"
|
arrowhead === "triangle_outline"
|
||||||
? canvasBackgroundColor
|
? canvasBackgroundColor
|
||||||
: element.strokeColor,
|
: strokeColor,
|
||||||
fillStyle: "solid",
|
fillStyle: "solid",
|
||||||
roughness: Math.min(1, options.roughness || 0),
|
roughness: Math.min(1, options.roughness || 0),
|
||||||
},
|
},
|
||||||
@@ -380,7 +405,7 @@ const getArrowheadShapes = (
|
|||||||
fill:
|
fill:
|
||||||
arrowhead === "diamond_outline"
|
arrowhead === "diamond_outline"
|
||||||
? canvasBackgroundColor
|
? canvasBackgroundColor
|
||||||
: element.strokeColor,
|
: strokeColor,
|
||||||
fillStyle: "solid",
|
fillStyle: "solid",
|
||||||
roughness: Math.min(1, options.roughness || 0),
|
roughness: Math.min(1, options.roughness || 0),
|
||||||
},
|
},
|
||||||
@@ -602,19 +627,22 @@ export const generateLinearCollisionShape = (
|
|||||||
*
|
*
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
const generateElementShape = (
|
const _generateElementShape = (
|
||||||
element: Exclude<NonDeletedExcalidrawElement, ExcalidrawSelectionElement>,
|
element: Exclude<NonDeletedExcalidrawElement, ExcalidrawSelectionElement>,
|
||||||
generator: RoughGenerator,
|
generator: RoughGenerator,
|
||||||
{
|
{
|
||||||
isExporting,
|
isExporting,
|
||||||
canvasBackgroundColor,
|
canvasBackgroundColor,
|
||||||
embedsValidationStatus,
|
embedsValidationStatus,
|
||||||
|
theme,
|
||||||
}: {
|
}: {
|
||||||
isExporting: boolean;
|
isExporting: boolean;
|
||||||
canvasBackgroundColor: string;
|
canvasBackgroundColor: string;
|
||||||
embedsValidationStatus: EmbedsValidationStatus | null;
|
embedsValidationStatus: EmbedsValidationStatus | null;
|
||||||
|
theme?: AppState["theme"];
|
||||||
},
|
},
|
||||||
): Drawable | Drawable[] | null => {
|
): ElementShape => {
|
||||||
|
const isDarkMode = theme === THEME.DARK;
|
||||||
switch (element.type) {
|
switch (element.type) {
|
||||||
case "rectangle":
|
case "rectangle":
|
||||||
case "iframe":
|
case "iframe":
|
||||||
@@ -640,6 +668,7 @@ const generateElementShape = (
|
|||||||
embedsValidationStatus,
|
embedsValidationStatus,
|
||||||
),
|
),
|
||||||
true,
|
true,
|
||||||
|
isDarkMode,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -655,6 +684,7 @@ const generateElementShape = (
|
|||||||
embedsValidationStatus,
|
embedsValidationStatus,
|
||||||
),
|
),
|
||||||
false,
|
false,
|
||||||
|
isDarkMode,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -692,7 +722,7 @@ const generateElementShape = (
|
|||||||
C ${topX} ${topY}, ${topX} ${topY}, ${topX + verticalRadius} ${
|
C ${topX} ${topY}, ${topX} ${topY}, ${topX + verticalRadius} ${
|
||||||
topY + horizontalRadius
|
topY + horizontalRadius
|
||||||
}`,
|
}`,
|
||||||
generateRoughOptions(element, true),
|
generateRoughOptions(element, true, isDarkMode),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
shape = generator.polygon(
|
shape = generator.polygon(
|
||||||
@@ -702,7 +732,7 @@ const generateElementShape = (
|
|||||||
[bottomX, bottomY],
|
[bottomX, bottomY],
|
||||||
[leftX, leftY],
|
[leftX, leftY],
|
||||||
],
|
],
|
||||||
generateRoughOptions(element),
|
generateRoughOptions(element, false, isDarkMode),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return shape;
|
return shape;
|
||||||
@@ -713,14 +743,14 @@ const generateElementShape = (
|
|||||||
element.height / 2,
|
element.height / 2,
|
||||||
element.width,
|
element.width,
|
||||||
element.height,
|
element.height,
|
||||||
generateRoughOptions(element),
|
generateRoughOptions(element, false, isDarkMode),
|
||||||
);
|
);
|
||||||
return shape;
|
return shape;
|
||||||
}
|
}
|
||||||
case "line":
|
case "line":
|
||||||
case "arrow": {
|
case "arrow": {
|
||||||
let shape: ElementShapes[typeof element.type];
|
let shape: ElementShapes[typeof element.type];
|
||||||
const options = generateRoughOptions(element);
|
const options = generateRoughOptions(element, false, isDarkMode);
|
||||||
|
|
||||||
// points array can be empty in the beginning, so it is important to add
|
// points array can be empty in the beginning, so it is important to add
|
||||||
// initial position to it
|
// initial position to it
|
||||||
@@ -745,7 +775,7 @@ const generateElementShape = (
|
|||||||
shape = [
|
shape = [
|
||||||
generator.path(
|
generator.path(
|
||||||
generateElbowArrowShape(points, 16),
|
generateElbowArrowShape(points, 16),
|
||||||
generateRoughOptions(element, true),
|
generateRoughOptions(element, true, isDarkMode),
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -778,6 +808,7 @@ const generateElementShape = (
|
|||||||
generator,
|
generator,
|
||||||
options,
|
options,
|
||||||
canvasBackgroundColor,
|
canvasBackgroundColor,
|
||||||
|
isDarkMode,
|
||||||
);
|
);
|
||||||
shape.push(...shapes);
|
shape.push(...shapes);
|
||||||
}
|
}
|
||||||
@@ -795,6 +826,7 @@ const generateElementShape = (
|
|||||||
generator,
|
generator,
|
||||||
options,
|
options,
|
||||||
canvasBackgroundColor,
|
canvasBackgroundColor,
|
||||||
|
isDarkMode,
|
||||||
);
|
);
|
||||||
shape.push(...shapes);
|
shape.push(...shapes);
|
||||||
}
|
}
|
||||||
@@ -802,23 +834,28 @@ const generateElementShape = (
|
|||||||
return shape;
|
return shape;
|
||||||
}
|
}
|
||||||
case "freedraw": {
|
case "freedraw": {
|
||||||
let shape: ElementShapes[typeof element.type];
|
// oredered in terms of z-index [background, stroke]
|
||||||
generateFreeDrawShape(element);
|
const shapes: ElementShapes[typeof element.type] = [];
|
||||||
|
|
||||||
|
// (1) background fill (rc shape), optional
|
||||||
if (isPathALoop(element.points)) {
|
if (isPathALoop(element.points)) {
|
||||||
// generate rough polygon to fill freedraw shape
|
// generate rough polygon to fill freedraw shape
|
||||||
const simplifiedPoints = simplify(
|
const simplifiedPoints = simplify(
|
||||||
element.points as Mutable<LocalPoint[]>,
|
element.points as Mutable<LocalPoint[]>,
|
||||||
0.75,
|
0.75,
|
||||||
);
|
);
|
||||||
shape = generator.curve(simplifiedPoints as [number, number][], {
|
shapes.push(
|
||||||
...generateRoughOptions(element),
|
generator.curve(simplifiedPoints as [number, number][], {
|
||||||
stroke: "none",
|
...generateRoughOptions(element, false, isDarkMode),
|
||||||
});
|
stroke: "none",
|
||||||
} else {
|
}),
|
||||||
shape = null;
|
);
|
||||||
}
|
}
|
||||||
return shape;
|
|
||||||
|
// (2) stroke
|
||||||
|
shapes.push(getFreeDrawSvgPath(element));
|
||||||
|
|
||||||
|
return shapes;
|
||||||
}
|
}
|
||||||
case "frame":
|
case "frame":
|
||||||
case "magicframe":
|
case "magicframe":
|
||||||
@@ -925,9 +962,7 @@ export const getElementShape = <Point extends GlobalPoint | LocalPoint>(
|
|||||||
return getPolygonShape(element);
|
return getPolygonShape(element);
|
||||||
case "arrow":
|
case "arrow":
|
||||||
case "line": {
|
case "line": {
|
||||||
const roughShape =
|
const roughShape = ShapeCache.generateElementShape(element, null)[0];
|
||||||
ShapeCache.get(element)?.[0] ??
|
|
||||||
ShapeCache.generateElementShape(element, null)[0];
|
|
||||||
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
||||||
|
|
||||||
return shouldTestInside(element)
|
return shouldTestInside(element)
|
||||||
@@ -1003,3 +1038,69 @@ export const toggleLinePolygonState = (
|
|||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// freedraw shape helper
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// NOTE not cached (-> for SVG export)
|
||||||
|
const getFreeDrawSvgPath = (element: ExcalidrawFreeDrawElement) => {
|
||||||
|
return getSvgPathFromStroke(
|
||||||
|
getFreedrawOutlinePoints(element),
|
||||||
|
) as SVGPathString;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getFreedrawOutlinePoints = (
|
||||||
|
element: ExcalidrawFreeDrawElement,
|
||||||
|
) => {
|
||||||
|
// If input points are empty (should they ever be?) return a dot
|
||||||
|
const inputPoints = element.simulatePressure
|
||||||
|
? element.points
|
||||||
|
: element.points.length
|
||||||
|
? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
|
||||||
|
: [[0, 0, 0.5]];
|
||||||
|
|
||||||
|
return getStroke(inputPoints as number[][], {
|
||||||
|
simulatePressure: element.simulatePressure,
|
||||||
|
size: element.strokeWidth * 4.25,
|
||||||
|
thinning: 0.6,
|
||||||
|
smoothing: 0.5,
|
||||||
|
streamline: 0.5,
|
||||||
|
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
|
||||||
|
last: true,
|
||||||
|
}) as [number, number][];
|
||||||
|
};
|
||||||
|
|
||||||
|
const med = (A: number[], B: number[]) => {
|
||||||
|
return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Trim SVG path data so number are each two decimal points. This
|
||||||
|
// improves SVG exports, and prevents rendering errors on points
|
||||||
|
// with long decimals.
|
||||||
|
const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g;
|
||||||
|
|
||||||
|
const getSvgPathFromStroke = (points: number[][]): string => {
|
||||||
|
if (!points.length) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const max = points.length - 1;
|
||||||
|
|
||||||
|
return points
|
||||||
|
.reduce(
|
||||||
|
(acc, point, i, arr) => {
|
||||||
|
if (i === max) {
|
||||||
|
acc.push(point, med(point, arr[0]), "L", arr[0], "Z");
|
||||||
|
} else {
|
||||||
|
acc.push(point, med(point, arr[i + 1]));
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
["M", points[0], "Q"],
|
||||||
|
)
|
||||||
|
.join(" ")
|
||||||
|
.replace(TO_FIXED_PRECISION, "$1");
|
||||||
|
};
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import {
|
import {
|
||||||
isLineSegment,
|
isLineSegment,
|
||||||
lineSegment,
|
lineSegment,
|
||||||
|
pointDistanceSq,
|
||||||
pointFrom,
|
pointFrom,
|
||||||
type GlobalPoint,
|
type GlobalPoint,
|
||||||
type LocalPoint,
|
type LocalPoint,
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
|
import { type Bounds, isBounds } from "@excalidraw/common";
|
||||||
|
import {
|
||||||
|
getElementBounds,
|
||||||
|
intersectElementWithLineSegment,
|
||||||
|
isFreeDrawElement,
|
||||||
|
isLinearElement,
|
||||||
|
isPathALoop,
|
||||||
|
} from "@excalidraw/element";
|
||||||
|
|
||||||
|
import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
|
||||||
import type { Curve } from "@excalidraw/math";
|
import type { Curve } from "@excalidraw/math";
|
||||||
import type { LineSegment } from "@excalidraw/utils";
|
import type { LineSegment } from "@excalidraw/utils";
|
||||||
|
|
||||||
import { type Bounds, isBounds } from "./bounds";
|
|
||||||
|
|
||||||
// The global data holder to collect the debug operations
|
// The global data holder to collect the debug operations
|
||||||
declare global {
|
declare global {
|
||||||
interface Window {
|
interface Window {
|
||||||
@@ -23,10 +31,69 @@ declare global {
|
|||||||
|
|
||||||
export type DebugElement = {
|
export type DebugElement = {
|
||||||
color: string;
|
color: string;
|
||||||
data: LineSegment<GlobalPoint> | Curve<GlobalPoint>;
|
data: LineSegment<GlobalPoint> | Curve<GlobalPoint> | DebugPolygon;
|
||||||
permanent: boolean;
|
permanent: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type DebugPolygon = {
|
||||||
|
type: "polygon";
|
||||||
|
points: GlobalPoint[];
|
||||||
|
fill?: boolean;
|
||||||
|
close?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const debugDrawHitVolume = (
|
||||||
|
element: ExcalidrawElement,
|
||||||
|
elementsMap: ElementsMap,
|
||||||
|
options?: {
|
||||||
|
rays?: number;
|
||||||
|
color?: string;
|
||||||
|
fill?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
if (
|
||||||
|
(isLinearElement(element) || isFreeDrawElement(element)) &&
|
||||||
|
!isPathALoop(element.points)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
|
||||||
|
const center = pointFrom<GlobalPoint>((x1 + x2) / 2, (y1 + y2) / 2);
|
||||||
|
const rays = options?.rays ?? 100;
|
||||||
|
const radius = Math.max(x2 - x1, y2 - y1) * 2;
|
||||||
|
const points: GlobalPoint[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < rays; i += 1) {
|
||||||
|
const angle = (i / rays) * Math.PI * 2;
|
||||||
|
const end = pointFrom<GlobalPoint>(
|
||||||
|
center[0] + Math.cos(angle) * radius,
|
||||||
|
center[1] + Math.sin(angle) * radius,
|
||||||
|
);
|
||||||
|
const hits = intersectElementWithLineSegment(
|
||||||
|
element,
|
||||||
|
elementsMap,
|
||||||
|
lineSegment(center, end),
|
||||||
|
);
|
||||||
|
if (hits.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
hits.sort(pointDistanceSq);
|
||||||
|
points.push(hits[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (points.length >= 3) {
|
||||||
|
debugDrawPolygon(points, {
|
||||||
|
color: options?.color ?? "orange",
|
||||||
|
fill: options?.fill ?? true,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.warn(
|
||||||
|
`debugDrawHitVolume: could not compute hit volume for element ${element.id}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const debugDrawCubicBezier = (
|
export const debugDrawCubicBezier = (
|
||||||
c: Curve<GlobalPoint>,
|
c: Curve<GlobalPoint>,
|
||||||
opts?: {
|
opts?: {
|
||||||
@@ -61,6 +128,31 @@ export const debugDrawLine = (
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const debugDrawPolygon = (
|
||||||
|
points: GlobalPoint[],
|
||||||
|
opts?: {
|
||||||
|
color?: string;
|
||||||
|
permanent?: boolean;
|
||||||
|
fill?: boolean;
|
||||||
|
close?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
if (points.length < 2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
addToCurrentFrame({
|
||||||
|
color: opts?.color ?? "orange",
|
||||||
|
permanent: !!opts?.permanent,
|
||||||
|
data: {
|
||||||
|
type: "polygon",
|
||||||
|
points,
|
||||||
|
fill: opts?.fill,
|
||||||
|
close: opts?.close,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export const debugDrawPoint = (
|
export const debugDrawPoint = (
|
||||||
p: GlobalPoint,
|
p: GlobalPoint,
|
||||||
opts?: {
|
opts?: {
|
||||||
@@ -101,7 +193,7 @@ export const debugDrawBounds = (
|
|||||||
permanent?: boolean;
|
permanent?: boolean;
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
(isBounds(box) ? [box] : box).forEach((bbox) =>
|
(isBounds(box) ? [box] : box).forEach((bbox: Bounds) =>
|
||||||
debugDrawLine(
|
debugDrawLine(
|
||||||
[
|
[
|
||||||
lineSegment(
|
lineSegment(
|
||||||
@@ -17,7 +17,7 @@ exports[`Test Linear Elements > Test bound text element > should match styles fo
|
|||||||
class="excalidraw-wysiwyg"
|
class="excalidraw-wysiwyg"
|
||||||
data-type="wysiwyg"
|
data-type="wysiwyg"
|
||||||
dir="auto"
|
dir="auto"
|
||||||
style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; filter: var(--theme-filter); max-height: 992.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"
|
style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; max-height: 992.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
wrap="off"
|
wrap="off"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
|
import { arrayToMap } from "@excalidraw/common";
|
||||||
import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math";
|
import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math";
|
||||||
import { Excalidraw } from "@excalidraw/excalidraw";
|
import { Excalidraw } from "@excalidraw/excalidraw";
|
||||||
|
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
|
||||||
import { UI } from "@excalidraw/excalidraw/tests/helpers/ui";
|
import { UI } from "@excalidraw/excalidraw/tests/helpers/ui";
|
||||||
import "@excalidraw/utils/test-utils";
|
import "@excalidraw/utils/test-utils";
|
||||||
import { render } from "@excalidraw/excalidraw/tests/test-utils";
|
import { render } from "@excalidraw/excalidraw/tests/test-utils";
|
||||||
|
|
||||||
|
import * as distance from "../src/distance";
|
||||||
import { hitElementItself } from "../src/collision";
|
import { hitElementItself } from "../src/collision";
|
||||||
|
|
||||||
describe("check rotated elements can be hit:", () => {
|
describe("check rotated elements can be hit:", () => {
|
||||||
@@ -25,8 +28,6 @@ describe("check rotated elements can be hit:", () => {
|
|||||||
[-4, -302],
|
[-4, -302],
|
||||||
] as LocalPoint[],
|
] as LocalPoint[],
|
||||||
});
|
});
|
||||||
//const p = [120, -211];
|
|
||||||
//const p = [0, 13];
|
|
||||||
const hit = hitElementItself({
|
const hit = hitElementItself({
|
||||||
point: pointFrom<GlobalPoint>(88, -68),
|
point: pointFrom<GlobalPoint>(88, -68),
|
||||||
element: window.h.elements[0],
|
element: window.h.elements[0],
|
||||||
@@ -36,3 +37,182 @@ describe("check rotated elements can be hit:", () => {
|
|||||||
expect(hit).toBe(true);
|
expect(hit).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("hitElementItself cache", () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
// reset cache
|
||||||
|
hitElementItself({
|
||||||
|
point: pointFrom<GlobalPoint>(50, 50),
|
||||||
|
element: API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
backgroundColor: "#ffffff",
|
||||||
|
}),
|
||||||
|
threshold: Infinity,
|
||||||
|
elementsMap: new Map([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
localStorage.clear();
|
||||||
|
await render(<Excalidraw handleKeyboardGlobally={true} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reuses cached result when threshold increases", () => {
|
||||||
|
const element = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
backgroundColor: "#ffffff",
|
||||||
|
});
|
||||||
|
const elementsMap = arrayToMap([element]);
|
||||||
|
const point = pointFrom<GlobalPoint>(100.5, 50);
|
||||||
|
|
||||||
|
const distanceSpy = jest.spyOn(distance, "distanceToElement");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 1,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 10,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
distanceSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not reuse cache when threshold decreases", () => {
|
||||||
|
const element = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
});
|
||||||
|
const elementsMap = arrayToMap([element]);
|
||||||
|
const point = pointFrom<GlobalPoint>(105, 50);
|
||||||
|
|
||||||
|
const distanceSpy = jest.spyOn(distance, "distanceToElement");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 10,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 6,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(2);
|
||||||
|
distanceSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("invalidates cache when element version changes", () => {
|
||||||
|
const element = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
backgroundColor: "#ffffff",
|
||||||
|
});
|
||||||
|
const elementsMap = arrayToMap([element]);
|
||||||
|
const point = pointFrom<GlobalPoint>(100.5, 50);
|
||||||
|
|
||||||
|
const distanceSpy = jest.spyOn(distance, "distanceToElement");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 1,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const movedElement = {
|
||||||
|
...element,
|
||||||
|
version: element.version + 1,
|
||||||
|
versionNonce: element.versionNonce + 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element: movedElement,
|
||||||
|
threshold: 1,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(2);
|
||||||
|
distanceSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("override does not affect caching", () => {
|
||||||
|
const element = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
});
|
||||||
|
const elementsMap = arrayToMap([element]);
|
||||||
|
const point = pointFrom<GlobalPoint>(50, 50);
|
||||||
|
|
||||||
|
const distanceSpy = jest.spyOn(distance, "distanceToElement");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 10,
|
||||||
|
elementsMap,
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
|
||||||
|
expect(distanceSpy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
hitElementItself({
|
||||||
|
point,
|
||||||
|
element,
|
||||||
|
threshold: 10,
|
||||||
|
elementsMap,
|
||||||
|
overrideShouldTestInside: true,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ describe("Test Linear Elements", () => {
|
|||||||
// drag line from midpoint
|
// drag line from midpoint
|
||||||
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
|
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
|
||||||
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`8`);
|
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`8`);
|
||||||
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
|
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`6`);
|
||||||
expect(line.points.length).toEqual(3);
|
expect(line.points.length).toEqual(3);
|
||||||
expect(line.points).toMatchInlineSnapshot(`
|
expect(line.points).toMatchInlineSnapshot(`
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -563,6 +563,24 @@ describe("text element", () => {
|
|||||||
expect(text.fontSize).toBeCloseTo(fontSize * scale);
|
expect(text.fontSize).toBeCloseTo(fontSize * scale);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("resizes proportionally using horizontal delta from corner handles", async () => {
|
||||||
|
const text = UI.createElement("text");
|
||||||
|
await UI.editText(text, "hello\nworld");
|
||||||
|
const { x, y, width, height, fontSize } = text;
|
||||||
|
const deltaX = width;
|
||||||
|
const deltaY = 0;
|
||||||
|
const scale = (width + deltaX) / width;
|
||||||
|
|
||||||
|
UI.resize(text, "se", [deltaX, deltaY]);
|
||||||
|
|
||||||
|
expect(text.x).toBeCloseTo(x);
|
||||||
|
expect(text.y).toBeCloseTo(y);
|
||||||
|
expect(text.width).toBeCloseTo(width * scale);
|
||||||
|
expect(text.height).toBeCloseTo(height * scale);
|
||||||
|
expect(text.angle).toBeCloseTo(0);
|
||||||
|
expect(text.fontSize).toBeCloseTo(fontSize * scale);
|
||||||
|
});
|
||||||
|
|
||||||
// TODO enable this test after adding single text element flipping
|
// TODO enable this test after adding single text element flipping
|
||||||
it.skip("flips while resizing", async () => {
|
it.skip("flips while resizing", async () => {
|
||||||
const text = UI.createElement("text");
|
const text = UI.createElement("text");
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ const distributeSelectedElements = (
|
|||||||
app.scene.getNonDeletedElementsMap(),
|
app.scene.getNonDeletedElementsMap(),
|
||||||
distribution,
|
distribution,
|
||||||
appState,
|
appState,
|
||||||
|
app.scene,
|
||||||
);
|
);
|
||||||
|
|
||||||
const updatedElementsMap = arrayToMap(updatedElements);
|
const updatedElementsMap = arrayToMap(updatedElements);
|
||||||
|
|||||||
@@ -82,7 +82,10 @@ export const actionFinalize = register<FormData>({
|
|||||||
app.scene,
|
app.scene,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isBindingElement(element)) {
|
if (
|
||||||
|
isBindingElement(element) &&
|
||||||
|
!appState.selectedLinearElement.segmentMidPointHoveredCoords
|
||||||
|
) {
|
||||||
const newArrow = !!appState.newElement;
|
const newArrow = !!appState.newElement;
|
||||||
|
|
||||||
const selectedPointsIndices =
|
const selectedPointsIndices =
|
||||||
@@ -95,7 +98,10 @@ export const actionFinalize = register<FormData>({
|
|||||||
map.set(index, {
|
map.set(index, {
|
||||||
point: LinearElementEditor.pointFromAbsoluteCoords(
|
point: LinearElementEditor.pointFromAbsoluteCoords(
|
||||||
element,
|
element,
|
||||||
pointFrom<GlobalPoint>(sceneCoords.x, sceneCoords.y),
|
pointFrom<GlobalPoint>(
|
||||||
|
sceneCoords.x - linearElementEditor.pointerOffset.x,
|
||||||
|
sceneCoords.y - linearElementEditor.pointerOffset.y,
|
||||||
|
),
|
||||||
elementsMap,
|
elementsMap,
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
@@ -106,8 +112,8 @@ export const actionFinalize = register<FormData>({
|
|||||||
bindOrUnbindBindingElement(
|
bindOrUnbindBindingElement(
|
||||||
element,
|
element,
|
||||||
draggedPoints,
|
draggedPoints,
|
||||||
sceneCoords.x,
|
sceneCoords.x - linearElementEditor.pointerOffset.x,
|
||||||
sceneCoords.y,
|
sceneCoords.y - linearElementEditor.pointerOffset.y,
|
||||||
scene,
|
scene,
|
||||||
appState,
|
appState,
|
||||||
{
|
{
|
||||||
@@ -170,6 +176,7 @@ export const actionFinalize = register<FormData>({
|
|||||||
...linearElementEditor.initialState,
|
...linearElementEditor.initialState,
|
||||||
lastClickedPoint: -1,
|
lastClickedPoint: -1,
|
||||||
},
|
},
|
||||||
|
pointerOffset: { x: 0, y: 0 },
|
||||||
},
|
},
|
||||||
selectionElement: null,
|
selectionElement: null,
|
||||||
suggestedBinding: null,
|
suggestedBinding: null,
|
||||||
|
|||||||
@@ -1263,9 +1263,9 @@ export const ShapesSwitcher = ({
|
|||||||
onSelect={() => app.onMagicframeToolSelect()}
|
onSelect={() => app.onMagicframeToolSelect()}
|
||||||
icon={MagicIcon}
|
icon={MagicIcon}
|
||||||
data-testid="toolbar-magicframe"
|
data-testid="toolbar-magicframe"
|
||||||
|
badge={<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>}
|
||||||
>
|
>
|
||||||
{t("toolBar.magicframe")}
|
{t("toolBar.magicframe")}
|
||||||
<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>
|
|
||||||
</DropdownMenu.Item>
|
</DropdownMenu.Item>
|
||||||
)}
|
)}
|
||||||
</DropdownMenu.Content>
|
</DropdownMenu.Content>
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ import {
|
|||||||
TAP_TWICE_TIMEOUT,
|
TAP_TWICE_TIMEOUT,
|
||||||
TEXT_TO_CENTER_SNAP_THRESHOLD,
|
TEXT_TO_CENTER_SNAP_THRESHOLD,
|
||||||
THEME,
|
THEME,
|
||||||
THEME_FILTER,
|
|
||||||
TOUCH_CTX_MENU_TIMEOUT,
|
TOUCH_CTX_MENU_TIMEOUT,
|
||||||
VERTICAL_ALIGN,
|
VERTICAL_ALIGN,
|
||||||
YOUTUBE_STATES,
|
YOUTUBE_STATES,
|
||||||
@@ -89,6 +88,7 @@ import {
|
|||||||
getDateTime,
|
getDateTime,
|
||||||
isShallowEqual,
|
isShallowEqual,
|
||||||
arrayToMap,
|
arrayToMap,
|
||||||
|
applyDarkModeFilter,
|
||||||
type EXPORT_IMAGE_TYPES,
|
type EXPORT_IMAGE_TYPES,
|
||||||
randomInteger,
|
randomInteger,
|
||||||
CLASSES,
|
CLASSES,
|
||||||
@@ -346,7 +346,7 @@ import {
|
|||||||
|
|
||||||
import { exportCanvas, loadFromBlob } from "../data";
|
import { exportCanvas, loadFromBlob } from "../data";
|
||||||
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
|
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
|
||||||
import { restore, restoreElements } from "../data/restore";
|
import { restoreAppState, restoreElements } from "../data/restore";
|
||||||
import { getCenter, getDistance } from "../gesture";
|
import { getCenter, getDistance } from "../gesture";
|
||||||
import { History } from "../history";
|
import { History } from "../history";
|
||||||
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
|
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
|
||||||
@@ -1770,8 +1770,9 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
style={{
|
style={{
|
||||||
background: this.state.viewBackgroundColor,
|
background: isDarkTheme
|
||||||
filter: isDarkTheme ? THEME_FILTER : "none",
|
? applyDarkModeFilter(this.state.viewBackgroundColor)
|
||||||
|
: this.state.viewBackgroundColor,
|
||||||
zIndex: 2,
|
zIndex: 2,
|
||||||
border: "none",
|
border: "none",
|
||||||
display: "block",
|
display: "block",
|
||||||
@@ -1781,7 +1782,9 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
fontFamily: "Assistant",
|
fontFamily: "Assistant",
|
||||||
fontSize: `${FRAME_STYLE.nameFontSize}px`,
|
fontSize: `${FRAME_STYLE.nameFontSize}px`,
|
||||||
transform: `translate(-${FRAME_NAME_EDIT_PADDING}px, ${FRAME_NAME_EDIT_PADDING}px)`,
|
transform: `translate(-${FRAME_NAME_EDIT_PADDING}px, ${FRAME_NAME_EDIT_PADDING}px)`,
|
||||||
color: "var(--color-gray-80)",
|
color: isDarkTheme
|
||||||
|
? FRAME_STYLE.nameColorDarkTheme
|
||||||
|
: FRAME_STYLE.nameColorLightTheme,
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
maxWidth: `${
|
maxWidth: `${
|
||||||
document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING
|
document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING
|
||||||
@@ -2116,6 +2119,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
elementsPendingErasure: this.elementsPendingErasure,
|
elementsPendingErasure: this.elementsPendingErasure,
|
||||||
pendingFlowchartNodes:
|
pendingFlowchartNodes:
|
||||||
this.flowChartCreator.pendingNodes,
|
this.flowChartCreator.pendingNodes,
|
||||||
|
theme: this.state.theme,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{this.state.newElement && (
|
{this.state.newElement && (
|
||||||
@@ -2136,6 +2140,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
elementsPendingErasure:
|
elementsPendingErasure:
|
||||||
this.elementsPendingErasure,
|
this.elementsPendingErasure,
|
||||||
pendingFlowchartNodes: null,
|
pendingFlowchartNodes: null,
|
||||||
|
theme: this.state.theme,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -2701,46 +2706,47 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const scene = restore(initialData, null, null, {
|
const restoredElements = restoreElements(initialData?.elements, null, {
|
||||||
repairBindings: true,
|
repairBindings: true,
|
||||||
deleteInvisibleElements: true,
|
deleteInvisibleElements: true,
|
||||||
});
|
});
|
||||||
const activeTool = scene.appState.activeTool;
|
let restoredAppState = restoreAppState(initialData?.appState, null);
|
||||||
|
const activeTool = restoredAppState.activeTool;
|
||||||
|
|
||||||
if (!scene.appState.preferredSelectionTool.initialized) {
|
if (!restoredAppState.preferredSelectionTool.initialized) {
|
||||||
scene.appState.preferredSelectionTool = {
|
restoredAppState.preferredSelectionTool = {
|
||||||
type:
|
type:
|
||||||
this.editorInterface.formFactor === "phone" ? "lasso" : "selection",
|
this.editorInterface.formFactor === "phone" ? "lasso" : "selection",
|
||||||
initialized: true,
|
initialized: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
scene.appState = {
|
restoredAppState = {
|
||||||
...scene.appState,
|
...restoredAppState,
|
||||||
theme: this.props.theme || scene.appState.theme,
|
theme: this.props.theme || restoredAppState.theme,
|
||||||
// we're falling back to current (pre-init) state when deciding
|
// we're falling back to current (pre-init) state when deciding
|
||||||
// whether to open the library, to handle a case where we
|
// whether to open the library, to handle a case where we
|
||||||
// update the state outside of initialData (e.g. when loading the app
|
// update the state outside of initialData (e.g. when loading the app
|
||||||
// with a library install link, which should auto-open the library)
|
// with a library install link, which should auto-open the library)
|
||||||
openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
|
openSidebar: restoredAppState?.openSidebar || this.state.openSidebar,
|
||||||
activeTool:
|
activeTool:
|
||||||
activeTool.type === "image" ||
|
activeTool.type === "image" ||
|
||||||
activeTool.type === "lasso" ||
|
activeTool.type === "lasso" ||
|
||||||
activeTool.type === "selection"
|
activeTool.type === "selection"
|
||||||
? {
|
? {
|
||||||
...activeTool,
|
...activeTool,
|
||||||
type: scene.appState.preferredSelectionTool.type,
|
type: restoredAppState.preferredSelectionTool.type,
|
||||||
}
|
}
|
||||||
: scene.appState.activeTool,
|
: restoredAppState.activeTool,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
toast: this.state.toast,
|
toast: this.state.toast,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (initialData?.scrollToContent) {
|
if (initialData?.scrollToContent) {
|
||||||
scene.appState = {
|
restoredAppState = {
|
||||||
...scene.appState,
|
...restoredAppState,
|
||||||
...calculateScrollCenter(scene.elements, {
|
...calculateScrollCenter(restoredElements, {
|
||||||
...scene.appState,
|
...restoredAppState,
|
||||||
width: this.state.width,
|
width: this.state.width,
|
||||||
height: this.state.height,
|
height: this.state.height,
|
||||||
offsetTop: this.state.offsetTop,
|
offsetTop: this.state.offsetTop,
|
||||||
@@ -2752,7 +2758,9 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
this.resetStore();
|
this.resetStore();
|
||||||
this.resetHistory();
|
this.resetHistory();
|
||||||
this.syncActionResult({
|
this.syncActionResult({
|
||||||
...scene,
|
elements: restoredElements,
|
||||||
|
appState: restoredAppState,
|
||||||
|
files: initialData?.files,
|
||||||
captureUpdate: CaptureUpdateAction.NEVER,
|
captureUpdate: CaptureUpdateAction.NEVER,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2772,7 +2780,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
|
|
||||||
private getFormFactor = (editorWidth: number, editorHeight: number) => {
|
private getFormFactor = (editorWidth: number, editorHeight: number) => {
|
||||||
return (
|
return (
|
||||||
this.props.UIOptions.formFactor ??
|
this.props.UIOptions.getFormFactor?.(editorWidth, editorHeight) ??
|
||||||
getFormFactor(editorWidth, editorHeight)
|
getFormFactor(editorWidth, editorHeight)
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -2796,10 +2804,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
? this.props.UIOptions.dockedSidebarBreakpoint
|
? this.props.UIOptions.dockedSidebarBreakpoint
|
||||||
: MQ_RIGHT_SIDEBAR_MIN_WIDTH;
|
: MQ_RIGHT_SIDEBAR_MIN_WIDTH;
|
||||||
const nextEditorInterface = updateObject(this.editorInterface, {
|
const nextEditorInterface = updateObject(this.editorInterface, {
|
||||||
desktopUIMode:
|
desktopUIMode: storedDesktopUIMode ?? this.editorInterface.desktopUIMode,
|
||||||
this.props.UIOptions.desktopUIMode ??
|
|
||||||
storedDesktopUIMode ??
|
|
||||||
this.editorInterface.desktopUIMode,
|
|
||||||
formFactor: this.getFormFactor(editorWidth, editorHeight),
|
formFactor: this.getFormFactor(editorWidth, editorHeight),
|
||||||
userAgent: userAgentDescriptor,
|
userAgent: userAgentDescriptor,
|
||||||
canFitSidebar: editorWidth > sidebarBreakpoint,
|
canFitSidebar: editorWidth > sidebarBreakpoint,
|
||||||
@@ -3178,6 +3183,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
) {
|
) {
|
||||||
setEraserCursor(this.interactiveCanvas, this.state.theme);
|
setEraserCursor(this.interactiveCanvas, this.state.theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hide hyperlink popup if shown when element type is not selection
|
// Hide hyperlink popup if shown when element type is not selection
|
||||||
if (
|
if (
|
||||||
prevState.activeTool.type === "selection" &&
|
prevState.activeTool.type === "selection" &&
|
||||||
@@ -10046,7 +10052,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (pointerDownState.drag.hasOccurred && !multiElement) {
|
} else if (pointerDownState.drag.hasOccurred && !multiElement) {
|
||||||
if (isBindingElement(newElement, false)) {
|
if (isLinearElement(newElement)) {
|
||||||
this.actionManager.executeAction(actionFinalize, "ui", {
|
this.actionManager.executeAction(actionFinalize, "ui", {
|
||||||
event: childEvent,
|
event: childEvent,
|
||||||
sceneCoords,
|
sceneCoords,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.Avatar {
|
.Avatar {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/theme";
|
@use "../css/theme" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.excalidraw-button {
|
.excalidraw-button {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/theme";
|
@use "../css/theme" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
button.standalone {
|
button.standalone {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module.scss" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.Card {
|
.Card {
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
padding: 1.4rem;
|
padding: 1.4rem;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
background: var(--card-color);
|
background: var(--card-color);
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
|
|
||||||
svg {
|
svg {
|
||||||
width: 2.8rem;
|
width: 2.8rem;
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
background-color: var(--card-color-darkest);
|
background-color: var(--card-color-darkest);
|
||||||
}
|
}
|
||||||
.ToolIcon__label {
|
.ToolIcon__label {
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.Spinner {
|
.Spinner {
|
||||||
|
|||||||
@@ -1,25 +1,35 @@
|
|||||||
import OpenColor from "open-color";
|
|
||||||
|
|
||||||
import "./Card.scss";
|
import "./Card.scss";
|
||||||
|
|
||||||
|
// for open-color see https://github.com/yeun/open-color/blob/master/open-color.scss
|
||||||
|
const COLOR_MAP = {
|
||||||
|
primary: {
|
||||||
|
base: "var(--color-primary)",
|
||||||
|
darker: "var(--color-primary-darker)",
|
||||||
|
darkest: "var(--color-primary-darkest)",
|
||||||
|
},
|
||||||
|
lime: {
|
||||||
|
base: "#74b816", // open-color lime[7]
|
||||||
|
darker: "#66a80f", // open-color lime[8]
|
||||||
|
darkest: "#5c940d", // open-color lime[9]
|
||||||
|
},
|
||||||
|
pink: {
|
||||||
|
base: "#d6336c", // open-color pink[7]
|
||||||
|
darker: "#c2255c", // open-color pink[8]
|
||||||
|
darkest: "#a61e4d", // open-color pink[9]
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
export const Card: React.FC<{
|
export const Card: React.FC<{
|
||||||
color: keyof OpenColor | "primary";
|
color: "primary" | "lime" | "pink";
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
}> = ({ children, color }) => {
|
}> = ({ children, color }) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="Card"
|
className="Card"
|
||||||
style={{
|
style={{
|
||||||
["--card-color" as any]:
|
["--card-color" as any]: COLOR_MAP[color].base,
|
||||||
color === "primary" ? "var(--color-primary)" : OpenColor[color][7],
|
["--card-color-darker" as any]: COLOR_MAP[color].darker,
|
||||||
["--card-color-darker" as any]:
|
["--card-color-darkest" as any]: COLOR_MAP[color].darkest,
|
||||||
color === "primary"
|
|
||||||
? "var(--color-primary-darker)"
|
|
||||||
: OpenColor[color][8],
|
|
||||||
["--card-color-darkest" as any]:
|
|
||||||
color === "primary"
|
|
||||||
? "var(--color-primary-darkest)"
|
|
||||||
: OpenColor[color][9],
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "sass:color";
|
||||||
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.Checkbox {
|
.Checkbox {
|
||||||
@@ -12,7 +13,7 @@
|
|||||||
-webkit-tap-highlight-color: transparent;
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
|
||||||
&:hover:not(.is-checked) .Checkbox-box:not(:focus) {
|
&:hover:not(.is-checked) .Checkbox-box:not(:focus) {
|
||||||
box-shadow: 0 0 0 2px #{$oc-blue-4};
|
box-shadow: 0 0 0 2px #{$color-blue-4};
|
||||||
}
|
}
|
||||||
|
|
||||||
&:hover:not(.is-checked) .Checkbox-box:not(:focus) {
|
&:hover:not(.is-checked) .Checkbox-box:not(:focus) {
|
||||||
@@ -24,25 +25,25 @@
|
|||||||
|
|
||||||
&:active {
|
&:active {
|
||||||
.Checkbox-box {
|
.Checkbox-box {
|
||||||
box-shadow: 0 0 2px 1px inset #{$oc-blue-7} !important;
|
box-shadow: 0 0 2px 1px inset #{$color-blue-7} !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
.Checkbox-box {
|
.Checkbox-box {
|
||||||
background-color: fade-out($oc-blue-1, 0.8);
|
background-color: color.adjust($color-blue-1, $alpha: -0.8);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&.is-checked {
|
&.is-checked {
|
||||||
.Checkbox-box {
|
.Checkbox-box {
|
||||||
background-color: #{$oc-blue-1};
|
background-color: #{$color-blue-1};
|
||||||
svg {
|
svg {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&:hover .Checkbox-box {
|
&:hover .Checkbox-box {
|
||||||
background-color: #{$oc-blue-2};
|
background-color: #{$color-blue-2};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,16 +59,16 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
|
||||||
box-shadow: 0 0 0 2px #{$oc-blue-7};
|
box-shadow: 0 0 0 2px #{$color-blue-7};
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
|
|
||||||
color: #{$oc-blue-7};
|
color: #{$color-blue-7};
|
||||||
|
|
||||||
border: 0;
|
border: 0;
|
||||||
|
|
||||||
&:focus {
|
&:focus {
|
||||||
box-shadow: 0 0 0 3px #{$oc-blue-7};
|
box-shadow: 0 0 0 3px #{$color-blue-7};
|
||||||
}
|
}
|
||||||
|
|
||||||
svg {
|
svg {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { KEYS } from "@excalidraw/common";
|
import { KEYS, normalizeInputColor } from "@excalidraw/common";
|
||||||
|
|
||||||
import { getShortcutKey } from "../..//shortcut";
|
import { getShortcutKey } from "../..//shortcut";
|
||||||
import { useAtom } from "../../editor-jotai";
|
import { useAtom } from "../../editor-jotai";
|
||||||
@@ -10,26 +10,23 @@ import { useEditorInterface } from "../App";
|
|||||||
import { activeEyeDropperAtom } from "../EyeDropper";
|
import { activeEyeDropperAtom } from "../EyeDropper";
|
||||||
import { eyeDropperIcon } from "../icons";
|
import { eyeDropperIcon } from "../icons";
|
||||||
|
|
||||||
import { getColor } from "./ColorPicker";
|
|
||||||
import { activeColorPickerSectionAtom } from "./colorPickerUtils";
|
import { activeColorPickerSectionAtom } from "./colorPickerUtils";
|
||||||
|
|
||||||
import type { ColorPickerType } from "./colorPickerUtils";
|
import type { ColorPickerType } from "./colorPickerUtils";
|
||||||
|
|
||||||
interface ColorInputProps {
|
|
||||||
color: string;
|
|
||||||
onChange: (color: string) => void;
|
|
||||||
label: string;
|
|
||||||
colorPickerType: ColorPickerType;
|
|
||||||
placeholder?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ColorInput = ({
|
export const ColorInput = ({
|
||||||
color,
|
color,
|
||||||
onChange,
|
onChange,
|
||||||
label,
|
label,
|
||||||
colorPickerType,
|
colorPickerType,
|
||||||
placeholder,
|
placeholder,
|
||||||
}: ColorInputProps) => {
|
}: {
|
||||||
|
color: string;
|
||||||
|
onChange: (color: string) => void;
|
||||||
|
label: string;
|
||||||
|
colorPickerType: ColorPickerType;
|
||||||
|
placeholder?: string;
|
||||||
|
}) => {
|
||||||
const editorInterface = useEditorInterface();
|
const editorInterface = useEditorInterface();
|
||||||
const [innerValue, setInnerValue] = useState(color);
|
const [innerValue, setInnerValue] = useState(color);
|
||||||
const [activeSection, setActiveColorPickerSection] = useAtom(
|
const [activeSection, setActiveColorPickerSection] = useAtom(
|
||||||
@@ -43,7 +40,7 @@ export const ColorInput = ({
|
|||||||
const changeColor = useCallback(
|
const changeColor = useCallback(
|
||||||
(inputValue: string) => {
|
(inputValue: string) => {
|
||||||
const value = inputValue.toLowerCase();
|
const value = inputValue.toLowerCase();
|
||||||
const color = getColor(value);
|
const color = normalizeInputColor(value);
|
||||||
|
|
||||||
if (color) {
|
if (color) {
|
||||||
onChange(color);
|
onChange(color);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
@import "../../css/variables.module.scss";
|
@use "sass:color";
|
||||||
|
@use "../../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.focus-visible-none {
|
.focus-visible-none {
|
||||||
@@ -185,8 +186,8 @@
|
|||||||
|
|
||||||
.color-picker {
|
.color-picker {
|
||||||
background: var(--popup-bg-color);
|
background: var(--popup-bg-color);
|
||||||
border: 0 solid transparentize($oc-white, 0.75);
|
border: 0 solid color.adjust(#fff, $alpha: -0.75);
|
||||||
box-shadow: transparentize($oc-black, 0.75) 0 1px 4px;
|
box-shadow: color.adjust(#000, $alpha: -0.75) 0 1px 4px;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|
||||||
@@ -243,7 +244,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.color-picker-triangle-shadow {
|
.color-picker-triangle-shadow {
|
||||||
border-color: transparent transparent transparentize($oc-black, 0.9);
|
border-color: transparent transparent color.adjust(#000, $alpha: -0.9);
|
||||||
|
|
||||||
:root[dir="ltr"] & {
|
:root[dir="ltr"] & {
|
||||||
left: -14px;
|
left: -14px;
|
||||||
@@ -280,7 +281,7 @@
|
|||||||
padding: 0.25rem;
|
padding: 0.25rem;
|
||||||
|
|
||||||
&-title {
|
&-title {
|
||||||
color: $oc-gray-6;
|
color: $color-gray-6;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
padding: 0 0.25rem;
|
padding: 0 0.25rem;
|
||||||
}
|
}
|
||||||
@@ -319,7 +320,7 @@
|
|||||||
|
|
||||||
.color-picker-transparent {
|
.color-picker-transparent {
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
box-shadow: transparentize($oc-black, 0.9) 0 0 0 1px inset;
|
box-shadow: color.adjust(#000, $alpha: -0.9) 0 0 0 1px inset;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0;
|
top: 0;
|
||||||
right: 0;
|
right: 0;
|
||||||
@@ -473,7 +474,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.color-picker-type-elementBackground .color-picker-keybinding {
|
.color-picker-type-elementBackground .color-picker-keybinding {
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
|
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
|
||||||
@@ -486,10 +487,10 @@
|
|||||||
|
|
||||||
&.theme--dark {
|
&.theme--dark {
|
||||||
.color-picker-type-elementBackground .color-picker-keybinding {
|
.color-picker-type-elementBackground .color-picker-keybinding {
|
||||||
color: $oc-black;
|
color: #000;
|
||||||
}
|
}
|
||||||
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
|
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
|
||||||
color: $oc-black;
|
color: #000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { useRef, useEffect } from "react";
|
|||||||
import {
|
import {
|
||||||
COLOR_OUTLINE_CONTRAST_THRESHOLD,
|
COLOR_OUTLINE_CONTRAST_THRESHOLD,
|
||||||
COLOR_PALETTE,
|
COLOR_PALETTE,
|
||||||
isTransparent,
|
isColorDark,
|
||||||
isWritableElement,
|
isWritableElement,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ import { ColorInput } from "./ColorInput";
|
|||||||
import { Picker } from "./Picker";
|
import { Picker } from "./Picker";
|
||||||
import PickerHeading from "./PickerHeading";
|
import PickerHeading from "./PickerHeading";
|
||||||
import { TopPicks } from "./TopPicks";
|
import { TopPicks } from "./TopPicks";
|
||||||
import { activeColorPickerSectionAtom, isColorDark } from "./colorPickerUtils";
|
import { activeColorPickerSectionAtom } from "./colorPickerUtils";
|
||||||
|
|
||||||
import "./ColorPicker.scss";
|
import "./ColorPicker.scss";
|
||||||
|
|
||||||
@@ -38,27 +38,6 @@ import type { ColorPickerType } from "./colorPickerUtils";
|
|||||||
|
|
||||||
import type { AppState } from "../../types";
|
import type { AppState } from "../../types";
|
||||||
|
|
||||||
const isValidColor = (color: string) => {
|
|
||||||
const style = new Option().style;
|
|
||||||
style.color = color;
|
|
||||||
return !!style.color;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getColor = (color: string): string | null => {
|
|
||||||
if (isTransparent(color)) {
|
|
||||||
return color;
|
|
||||||
}
|
|
||||||
|
|
||||||
// testing for `#` first fixes a bug on Electron (more specfically, an
|
|
||||||
// Obsidian popout window), where a hex color without `#` is (incorrectly)
|
|
||||||
// considered valid
|
|
||||||
return isValidColor(`#${color}`)
|
|
||||||
? `#${color}`
|
|
||||||
: isValidColor(color)
|
|
||||||
? color
|
|
||||||
: null;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface ColorPickerProps {
|
interface ColorPickerProps {
|
||||||
type: ColorPickerType;
|
type: ColorPickerType;
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { isColorDark } from "@excalidraw/common";
|
||||||
import { isColorDark } from "./colorPickerUtils";
|
|
||||||
|
|
||||||
interface HotkeyLabelProps {
|
interface HotkeyLabelProps {
|
||||||
color: string;
|
color: string;
|
||||||
|
|||||||
@@ -5,10 +5,9 @@ import {
|
|||||||
DEFAULT_CANVAS_BACKGROUND_PICKS,
|
DEFAULT_CANVAS_BACKGROUND_PICKS,
|
||||||
DEFAULT_ELEMENT_BACKGROUND_PICKS,
|
DEFAULT_ELEMENT_BACKGROUND_PICKS,
|
||||||
DEFAULT_ELEMENT_STROKE_PICKS,
|
DEFAULT_ELEMENT_STROKE_PICKS,
|
||||||
|
isColorDark,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import { isColorDark } from "./colorPickerUtils";
|
|
||||||
|
|
||||||
import type { ColorPickerType } from "./colorPickerUtils";
|
import type { ColorPickerType } from "./colorPickerUtils";
|
||||||
|
|
||||||
interface TopPicksProps {
|
interface TopPicksProps {
|
||||||
|
|||||||
@@ -96,63 +96,6 @@ export type ActiveColorPickerSectionAtomType =
|
|||||||
export const activeColorPickerSectionAtom =
|
export const activeColorPickerSectionAtom =
|
||||||
atom<ActiveColorPickerSectionAtomType>(null);
|
atom<ActiveColorPickerSectionAtomType>(null);
|
||||||
|
|
||||||
const calculateContrast = (r: number, g: number, b: number): number => {
|
|
||||||
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
|
|
||||||
return yiq;
|
|
||||||
};
|
|
||||||
|
|
||||||
// YIQ algo, inspiration from https://stackoverflow.com/a/11868398
|
|
||||||
export const isColorDark = (color: string, threshold = 160): boolean => {
|
|
||||||
// no color ("") -> assume it default to black
|
|
||||||
if (!color) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (color === "transparent") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// a string color (white etc) or any other format -> convert to rgb by way
|
|
||||||
// of creating a DOM node and retrieving the computeStyle
|
|
||||||
if (!color.startsWith("#")) {
|
|
||||||
const node = document.createElement("div");
|
|
||||||
node.style.color = color;
|
|
||||||
|
|
||||||
if (node.style.color) {
|
|
||||||
// making invisible so document doesn't reflow (hopefully).
|
|
||||||
// display=none works too, but supposedly not in all browsers
|
|
||||||
node.style.position = "absolute";
|
|
||||||
node.style.visibility = "hidden";
|
|
||||||
node.style.width = "0";
|
|
||||||
node.style.height = "0";
|
|
||||||
|
|
||||||
// needs to be in DOM else browser won't compute the style
|
|
||||||
document.body.appendChild(node);
|
|
||||||
const computedColor = getComputedStyle(node).color;
|
|
||||||
document.body.removeChild(node);
|
|
||||||
// computed style is in rgb() format
|
|
||||||
const rgb = computedColor
|
|
||||||
.replace(/^(rgb|rgba)\(/, "")
|
|
||||||
.replace(/\)$/, "")
|
|
||||||
.replace(/\s/g, "")
|
|
||||||
.split(",");
|
|
||||||
const r = parseInt(rgb[0]);
|
|
||||||
const g = parseInt(rgb[1]);
|
|
||||||
const b = parseInt(rgb[2]);
|
|
||||||
|
|
||||||
return calculateContrast(r, g, b) < threshold;
|
|
||||||
}
|
|
||||||
// invalid color -> assume it default to black
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const r = parseInt(color.slice(1, 3), 16);
|
|
||||||
const g = parseInt(color.slice(3, 5), 16);
|
|
||||||
const b = parseInt(color.slice(5, 7), 16);
|
|
||||||
|
|
||||||
return calculateContrast(r, g, b) < threshold;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ColorPickerType =
|
export type ColorPickerType =
|
||||||
| "canvasBackground"
|
| "canvasBackground"
|
||||||
| "elementBackground"
|
| "elementBackground"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../../css/variables.module.scss";
|
@use "../../css/variables.module" as *;
|
||||||
|
|
||||||
$verticalBreakpoint: 861px;
|
$verticalBreakpoint: 861px;
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,6 @@ import { getSelectedElements } from "../../scene";
|
|||||||
import {
|
import {
|
||||||
LockedIcon,
|
LockedIcon,
|
||||||
UnlockedIcon,
|
UnlockedIcon,
|
||||||
clockIcon,
|
|
||||||
searchIcon,
|
searchIcon,
|
||||||
boltIcon,
|
boltIcon,
|
||||||
bucketFillIcon,
|
bucketFillIcon,
|
||||||
@@ -52,6 +51,7 @@ import {
|
|||||||
mermaidLogoIcon,
|
mermaidLogoIcon,
|
||||||
brainIconThin,
|
brainIconThin,
|
||||||
LibraryIcon,
|
LibraryIcon,
|
||||||
|
historyCommandIcon,
|
||||||
} from "../icons";
|
} from "../icons";
|
||||||
|
|
||||||
import { SHAPES } from "../shapes";
|
import { SHAPES } from "../shapes";
|
||||||
@@ -928,7 +928,7 @@ function CommandPaletteInner({
|
|||||||
marginLeft: "6px",
|
marginLeft: "6px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{clockIcon}
|
{historyCommandIcon}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<CommandItem
|
<CommandItem
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.confirm-dialog {
|
.confirm-dialog {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "sass:color";
|
||||||
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.context-menu-popover {
|
.context-menu-popover {
|
||||||
@@ -8,7 +9,7 @@
|
|||||||
.context-menu {
|
.context-menu {
|
||||||
position: relative;
|
position: relative;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
box-shadow: 0 3px 10px transparentize($oc-black, 0.8);
|
box-shadow: 0 3px 10px color.adjust(#000, $alpha: -0.8);
|
||||||
padding: 0;
|
padding: 0;
|
||||||
list-style: none;
|
list-style: none;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
@@ -49,7 +50,7 @@
|
|||||||
|
|
||||||
&.dangerous {
|
&.dangerous {
|
||||||
.context-menu-item__label {
|
.context-menu-item__label {
|
||||||
color: $oc-red-7;
|
color: $color-red-7;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +74,7 @@
|
|||||||
.context-menu-item__label {
|
.context-menu-item__label {
|
||||||
color: var(--popup-bg-color);
|
color: var(--popup-bg-color);
|
||||||
}
|
}
|
||||||
background-color: $oc-red-6;
|
background-color: $color-red-6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,6 +98,6 @@
|
|||||||
|
|
||||||
.context-menu-item-separator {
|
.context-menu-item-separator {
|
||||||
border: none;
|
border: none;
|
||||||
border-top: 1px solid $oc-gray-5;
|
border-top: 1px solid $color-gray-5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css//variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.ConvertElementTypePopup {
|
.ConvertElementTypePopup {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.Dialog {
|
.Dialog {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.ElementLinkDialog {
|
.ElementLinkDialog {
|
||||||
@@ -59,7 +59,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.ElementLinkDialog__remove {
|
.ElementLinkDialog__remove {
|
||||||
color: $oc-red-9;
|
color: $color-red-9;
|
||||||
margin-left: 1rem;
|
margin-left: 1rem;
|
||||||
|
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
@@ -68,7 +68,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon__icon svg {
|
.ToolIcon__icon svg {
|
||||||
color: $oc-red-6;
|
color: $color-red-6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.ExportDialog__preview {
|
.ExportDialog__preview {
|
||||||
@@ -112,7 +112,7 @@
|
|||||||
|
|
||||||
font-family: Cascadia;
|
font-family: Cascadia;
|
||||||
font-size: 1.8em;
|
font-size: 1.8em;
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: var(--button-color-darker);
|
background-color: var(--button-color-darker);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
@keyframes successStatusAnimation {
|
@keyframes successStatusAnimation {
|
||||||
0% {
|
0% {
|
||||||
@@ -24,6 +24,14 @@
|
|||||||
background-color: var(--back-color);
|
background-color: var(--back-color);
|
||||||
border-color: var(--border-color);
|
border-color: var(--border-color);
|
||||||
|
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border-width: 1px;
|
||||||
|
border-style: solid;
|
||||||
|
|
||||||
|
font-family: var(--font-family);
|
||||||
|
|
||||||
|
user-select: none;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
transition: all 150ms ease-out;
|
transition: all 150ms ease-out;
|
||||||
}
|
}
|
||||||
@@ -52,7 +60,19 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&[disabled] {
|
&[disabled] {
|
||||||
pointer-events: none;
|
cursor: not-allowed;
|
||||||
|
|
||||||
|
&.ExcButton--variant-filled,
|
||||||
|
&:hover {
|
||||||
|
--back-color: var(--color-surface-low) !important;
|
||||||
|
--text-color: var(--color-on-surface-variant) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.ExcButton--variant-outlined,
|
||||||
|
&.ExcButton--variant-icon {
|
||||||
|
--text-color: var(--color-on-surface-variant);
|
||||||
|
--border-color: var(--color-surface-high);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&,
|
&,
|
||||||
@@ -266,14 +286,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
border-width: 1px;
|
|
||||||
border-style: solid;
|
|
||||||
|
|
||||||
font-family: var(--font-family);
|
|
||||||
|
|
||||||
user-select: none;
|
|
||||||
|
|
||||||
&--size-large {
|
&--size-large {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export type FilledButtonProps = {
|
|||||||
fullWidth?: boolean;
|
fullWidth?: boolean;
|
||||||
|
|
||||||
icon?: React.ReactNode;
|
icon?: React.ReactNode;
|
||||||
|
disabled?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
|
export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
|
||||||
@@ -48,6 +49,7 @@ export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
|
|||||||
fullWidth,
|
fullWidth,
|
||||||
className,
|
className,
|
||||||
status,
|
status,
|
||||||
|
disabled,
|
||||||
},
|
},
|
||||||
ref,
|
ref,
|
||||||
) => {
|
) => {
|
||||||
@@ -94,7 +96,7 @@ export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
|
|||||||
type="button"
|
type="button"
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
disabled={_status === "loading" || _status === "success"}
|
disabled={disabled || _status === "loading" || _status === "success"}
|
||||||
>
|
>
|
||||||
<div className="ExcButton__contents">
|
<div className="ExcButton__contents">
|
||||||
{_status === "loading" ? (
|
{_status === "loading" ? (
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.FixedSideContainer {
|
.FixedSideContainer {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../../css/variables.module.scss";
|
@use "../../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.FontPicker__container {
|
.FontPicker__container {
|
||||||
|
|||||||
@@ -290,13 +290,15 @@ export const FontPickerList = React.memo(
|
|||||||
onHover(font.value);
|
onHover(font.value);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
badge={
|
||||||
|
font.badge && (
|
||||||
|
<DropDownMenuItemBadge type={font.badge.type}>
|
||||||
|
{font.badge.placeholder}
|
||||||
|
</DropDownMenuItemBadge>
|
||||||
|
)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{font.text}
|
{font.text}
|
||||||
{font.badge && (
|
|
||||||
<DropDownMenuItemBadge type={font.badge.type}>
|
|
||||||
{font.badge.placeholder}
|
|
||||||
</DropDownMenuItemBadge>
|
|
||||||
)}
|
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.HelpDialog {
|
.HelpDialog {
|
||||||
@@ -60,11 +60,12 @@
|
|||||||
|
|
||||||
&__islands-container {
|
&__islands-container {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
grid-column-gap: 1.5rem;
|
||||||
|
grid-row-gap: 2rem;
|
||||||
|
|
||||||
@media screen and (min-width: 1024px) {
|
@media screen and (min-width: 1024px) {
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: 1fr 1fr;
|
||||||
}
|
}
|
||||||
grid-column-gap: 1.5rem;
|
|
||||||
grid-row-gap: 2rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (min-width: 1024px) {
|
@media screen and (min-width: 1024px) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
// this is loosely based on the longest hint text
|
// this is loosely based on the longest hint text
|
||||||
$wide-viewport-width: 1000px;
|
$wide-viewport-width: 1000px;
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "sass:color";
|
||||||
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.picker {
|
.picker {
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
background: var(--popup-bg-color);
|
background: var(--popup-bg-color);
|
||||||
border: 0 solid transparentize($oc-white, 0.75);
|
border: 0 solid color.adjust(#fff, $alpha: -0.75);
|
||||||
box-shadow: var(--shadow-island);
|
box-shadow: var(--shadow-island);
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
@@ -87,7 +88,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.picker-type-elementBackground .picker-keybinding {
|
.picker-type-elementBackground .picker-keybinding {
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.picker-swatch[aria-label="transparent"] .picker-keybinding {
|
.picker-swatch[aria-label="transparent"] .picker-keybinding {
|
||||||
@@ -100,10 +101,10 @@
|
|||||||
|
|
||||||
&.theme--dark {
|
&.theme--dark {
|
||||||
.picker-type-elementBackground .picker-keybinding {
|
.picker-type-elementBackground .picker-keybinding {
|
||||||
color: $oc-black;
|
color: #000;
|
||||||
}
|
}
|
||||||
.picker-swatch[aria-label="transparent"] .picker-keybinding {
|
.picker-swatch[aria-label="transparent"] .picker-keybinding {
|
||||||
color: $oc-black;
|
color: #000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--ImageExportModal-preview-border: #d6d6d6;
|
--ImageExportModal-preview-border: #d6d6d6;
|
||||||
|
|||||||
@@ -40,9 +40,6 @@ import type { ActionManager } from "../actions/manager";
|
|||||||
|
|
||||||
import type { AppClassProperties, BinaryFiles, UIAppState } from "../types";
|
import type { AppClassProperties, BinaryFiles, UIAppState } from "../types";
|
||||||
|
|
||||||
const supportsContextFilters =
|
|
||||||
"filter" in document.createElement("canvas").getContext("2d")!;
|
|
||||||
|
|
||||||
export const ErrorCanvasPreview = () => {
|
export const ErrorCanvasPreview = () => {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -230,25 +227,23 @@ const ImageExportModal = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</ExportSetting>
|
</ExportSetting>
|
||||||
{supportsContextFilters && (
|
<ExportSetting
|
||||||
<ExportSetting
|
label={t("imageExportDialog.label.darkMode")}
|
||||||
label={t("imageExportDialog.label.darkMode")}
|
name="exportDarkModeSwitch"
|
||||||
|
>
|
||||||
|
<Switch
|
||||||
name="exportDarkModeSwitch"
|
name="exportDarkModeSwitch"
|
||||||
>
|
checked={exportDarkMode}
|
||||||
<Switch
|
onChange={(checked) => {
|
||||||
name="exportDarkModeSwitch"
|
setExportDarkMode(checked);
|
||||||
checked={exportDarkMode}
|
actionManager.executeAction(
|
||||||
onChange={(checked) => {
|
actionExportWithDarkMode,
|
||||||
setExportDarkMode(checked);
|
"ui",
|
||||||
actionManager.executeAction(
|
checked,
|
||||||
actionExportWithDarkMode,
|
);
|
||||||
"ui",
|
}}
|
||||||
checked,
|
/>
|
||||||
);
|
</ExportSetting>
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</ExportSetting>
|
|
||||||
)}
|
|
||||||
<ExportSetting
|
<ExportSetting
|
||||||
label={t("imageExportDialog.label.embedScene")}
|
label={t("imageExportDialog.label.embedScene")}
|
||||||
tooltip={t("imageExportDialog.tooltip.embedScene")}
|
tooltip={t("imageExportDialog.tooltip.embedScene")}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@import "open-color/open-color";
|
@use "../css/variables.module" as *;
|
||||||
@import "../css/variables.module.scss";
|
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.layer-ui__wrapper.animate {
|
.layer-ui__wrapper.animate {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "open-color/open-color";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.layer-ui__library {
|
.layer-ui__library {
|
||||||
@@ -46,15 +46,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&-close.ToolIcon_type_button {
|
&-close.ToolIcon_type_button {
|
||||||
background-color: $oc-blue-6;
|
background-color: $color-blue-6;
|
||||||
align-self: flex-end;
|
align-self: flex-end;
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: $oc-blue-8;
|
background-color: $color-blue-8;
|
||||||
}
|
}
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
width: auto;
|
width: auto;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
padding: 0 0.5rem;
|
padding: 0 0.5rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
|
|
||||||
border-radius: var(--border-radius-lg);
|
border-radius: var(--border-radius-lg);
|
||||||
background-color: var(--color-primary);
|
background-color: var(--color-primary);
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
text-decoration: none !important;
|
text-decoration: none !important;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "open-color/open-color";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--container-padding-y: 1rem;
|
--container-padding-y: 1rem;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.library-unit {
|
.library-unit {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@import "open-color/open-color.scss";
|
@use "../css/variables.module" as *;
|
||||||
@import "../css/variables.module.scss";
|
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.mobile-toolbar {
|
.mobile-toolbar {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
&.excalidraw-modal-container {
|
&.excalidraw-modal-container {
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ export const Modal: React.FC<{
|
|||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
onKeyDown={handleKeydown}
|
onKeyDown={handleKeydown}
|
||||||
aria-labelledby={props.labelledBy}
|
aria-labelledby={props.labelledBy}
|
||||||
data-prevent-outside-click
|
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="Modal__background"
|
className="Modal__background"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../../css/variables.module.scss";
|
@use "../../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.OverwriteConfirm {
|
.OverwriteConfirm {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.PasteChartDialog {
|
.PasteChartDialog {
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
height: 128px;
|
height: 128px;
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
padding: 1px;
|
padding: 1px;
|
||||||
border: 1px solid $oc-gray-4;
|
border: 1px solid $color-gray-4;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
}
|
}
|
||||||
&:hover {
|
&:hover {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
border: 2px solid $oc-blue-5;
|
border: 2px solid $color-blue-5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import oc from "open-color";
|
|
||||||
import React, { useLayoutEffect, useRef, useState } from "react";
|
import React, { useLayoutEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import type { ChartType } from "@excalidraw/element/types";
|
import type { ChartType } from "@excalidraw/element/types";
|
||||||
@@ -49,7 +48,7 @@ const ChartPreviewBtn = (props: {
|
|||||||
elements,
|
elements,
|
||||||
{
|
{
|
||||||
exportBackground: false,
|
exportBackground: false,
|
||||||
viewBackgroundColor: oc.white,
|
viewBackgroundColor: "#fff",
|
||||||
},
|
},
|
||||||
null, // files
|
null, // files
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.publish-library {
|
.publish-library {
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
span {
|
span {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
color: $oc-gray-6;
|
color: $color-gray-6;
|
||||||
}
|
}
|
||||||
input,
|
input,
|
||||||
textarea {
|
textarea {
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.required {
|
.required {
|
||||||
color: $oc-red-8;
|
color: $color-red-8;
|
||||||
margin: 0.2rem;
|
margin: 0.2rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,22 +48,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&--confirm.ToolIcon_type_button {
|
&--confirm.ToolIcon_type_button {
|
||||||
background-color: $oc-blue-6;
|
background-color: $color-blue-6;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: $oc-blue-8;
|
background-color: $color-blue-8;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&--cancel.ToolIcon_type_button {
|
&--cancel.ToolIcon_type_button {
|
||||||
background-color: $oc-gray-5;
|
background-color: $color-gray-5;
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: $oc-gray-6;
|
background-color: $color-gray-6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
.Spinner {
|
.Spinner {
|
||||||
--spinner-color: #fff;
|
--spinner-color: #fff;
|
||||||
svg {
|
svg {
|
||||||
@@ -83,7 +83,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&-warning {
|
&-warning {
|
||||||
color: $oc-red-6;
|
color: $color-red-6;
|
||||||
}
|
}
|
||||||
|
|
||||||
&-note {
|
&-note {
|
||||||
@@ -102,14 +102,14 @@
|
|||||||
top: 0.3rem;
|
top: 0.3rem;
|
||||||
left: 0.3rem;
|
left: 0.3rem;
|
||||||
font-size: 0.7rem;
|
font-size: 0.7rem;
|
||||||
color: $oc-red-7;
|
color: $color-red-7;
|
||||||
background: rgba(255, 255, 255, 0.9);
|
background: rgba(255, 255, 255, 0.9);
|
||||||
padding: 0.1rem 0.2rem;
|
padding: 0.1rem 0.2rem;
|
||||||
border-radius: 0.2rem;
|
border-radius: 0.2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__svg {
|
&__svg {
|
||||||
background-color: $oc-white;
|
background-color: #fff;
|
||||||
padding: 0.3rem;
|
padding: 0.3rem;
|
||||||
width: 7.5rem;
|
width: 7.5rem;
|
||||||
height: 7.5rem;
|
height: 7.5rem;
|
||||||
@@ -121,7 +121,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
background-color: $oc-white;
|
background-color: #fff;
|
||||||
width: auto;
|
width: auto;
|
||||||
height: auto;
|
height: auto;
|
||||||
margin: 0 0.5rem;
|
margin: 0 0.5rem;
|
||||||
@@ -132,7 +132,7 @@
|
|||||||
}
|
}
|
||||||
.required,
|
.required,
|
||||||
.error {
|
.error {
|
||||||
color: $oc-red-8;
|
color: $color-red-8;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
margin: 0.2rem;
|
margin: 0.2rem;
|
||||||
@@ -152,16 +152,16 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
background-color: $oc-red-6;
|
background-color: $color-red-6;
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: $oc-red-7;
|
background-color: $color-red-7;
|
||||||
}
|
}
|
||||||
&:active {
|
&:active {
|
||||||
background-color: $oc-red-8;
|
background-color: $color-red-8;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
svg {
|
svg {
|
||||||
color: $oc-white;
|
color: #fff;
|
||||||
padding: 0.26rem;
|
padding: 0.26rem;
|
||||||
border-radius: 0.3em;
|
border-radius: 0.3em;
|
||||||
width: 1rem;
|
width: 1rem;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";
|
import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";
|
||||||
import OpenColor from "open-color";
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -57,7 +56,7 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
|||||||
|
|
||||||
const ctx = canvas.getContext("2d")!;
|
const ctx = canvas.getContext("2d")!;
|
||||||
|
|
||||||
ctx.fillStyle = OpenColor.white;
|
ctx.fillStyle = "#fff";
|
||||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
// draw items
|
// draw items
|
||||||
@@ -87,7 +86,7 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
|||||||
// draw item border
|
// draw item border
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
ctx.lineWidth = BORDER_WIDTH;
|
ctx.lineWidth = BORDER_WIDTH;
|
||||||
ctx.strokeStyle = OpenColor.gray[4];
|
ctx.strokeStyle = "#ced4da";
|
||||||
ctx.strokeRect(
|
ctx.strokeRect(
|
||||||
colOffset + BOX_PADDING / 2,
|
colOffset + BOX_PADDING / 2,
|
||||||
rowOffset + BOX_PADDING / 2,
|
rowOffset + BOX_PADDING / 2,
|
||||||
@@ -131,7 +130,7 @@ const SingleLibraryItem = ({
|
|||||||
elements: libItem.elements,
|
elements: libItem.elements,
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
viewBackgroundColor: OpenColor.white,
|
viewBackgroundColor: "#fff",
|
||||||
exportBackground: true,
|
exportBackground: true,
|
||||||
},
|
},
|
||||||
files: null,
|
files: null,
|
||||||
@@ -175,7 +174,7 @@ const SingleLibraryItem = ({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ padding: "0.5em 0" }}>
|
<div style={{ padding: "0.5em 0" }}>
|
||||||
<span style={{ fontWeight: 500, color: OpenColor.gray[6] }}>
|
<span style={{ fontWeight: 500, color: "#868e96" }}>
|
||||||
{t("publishDialog.itemName")}
|
{t("publishDialog.itemName")}
|
||||||
</span>
|
</span>
|
||||||
<span aria-hidden="true" className="required">
|
<span aria-hidden="true" className="required">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--RadioGroup-background: var(--island-bg-color);
|
--RadioGroup-background: var(--island-bg-color);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--slider-thumb-size: 16px;
|
--slider-thumb-size: 16px;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.SVGLayer {
|
.SVGLayer {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@import "open-color/open-color";
|
@use "../css/variables.module" as *;
|
||||||
@import "../css//variables.module.scss";
|
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.layer-ui__search {
|
.layer-ui__search {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.ShareableLinkDialog {
|
.ShareableLinkDialog {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@import "open-color/open-color";
|
@use "../../css/variables.module" as *;
|
||||||
@import "../../css/variables.module.scss";
|
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.sidebar {
|
.sidebar {
|
||||||
@@ -19,6 +18,12 @@
|
|||||||
|
|
||||||
pointer-events: var(--ui-pointerEvents);
|
pointer-events: var(--ui-pointerEvents);
|
||||||
|
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 0;
|
||||||
|
width: calc(var(--right-sidebar-width) - var(--space-factor) * 2);
|
||||||
|
|
||||||
|
border-left: 1px solid var(--sidebar-border-color);
|
||||||
|
|
||||||
:root[dir="rtl"] & {
|
:root[dir="rtl"] & {
|
||||||
left: 0;
|
left: 0;
|
||||||
right: auto;
|
right: auto;
|
||||||
@@ -28,12 +33,6 @@
|
|||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
overflow: hidden;
|
|
||||||
border-radius: 0;
|
|
||||||
width: calc(var(--right-sidebar-width) - var(--space-factor) * 2);
|
|
||||||
|
|
||||||
border-left: 1px solid var(--sidebar-border-color);
|
|
||||||
|
|
||||||
:root[dir="rtl"] & {
|
:root[dir="rtl"] & {
|
||||||
border-right: 1px solid var(--sidebar-border-color);
|
border-right: 1px solid var(--sidebar-border-color);
|
||||||
border-left: 0;
|
border-left: 0;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../../css/variables.module.scss";
|
@use "../../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
.sidebar-trigger {
|
.sidebar-trigger {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "open-color/open-color.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
$duration: 1.6s;
|
$duration: 1.6s;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@import "../css/variables.module.scss";
|
@use "../css/variables.module" as *;
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--Switch-disabled-color: var(--color-border-outline);
|
--Switch-disabled-color: var(--color-border-outline);
|
||||||
|
|||||||
@@ -0,0 +1,403 @@
|
|||||||
|
@import "../../../css/variables.module.scss";
|
||||||
|
|
||||||
|
$verticalBreakpoint: 861px;
|
||||||
|
|
||||||
|
.excalidraw {
|
||||||
|
&.theme--dark {
|
||||||
|
.chat-message {
|
||||||
|
&--assistant {
|
||||||
|
.chat-message__content {
|
||||||
|
background: var(--color-surface-lowest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&--system {
|
||||||
|
.chat-message__content {
|
||||||
|
color: var(--color-surface-low);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-interface {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
position: relative;
|
||||||
|
|
||||||
|
@media screen and (max-width: $verticalBreakpoint) {
|
||||||
|
min-height: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__messages {
|
||||||
|
flex: 1 1 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
padding: 1rem 0.5rem 0 0.5rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2rem;
|
||||||
|
min-height: 0;
|
||||||
|
border-top-left-radius: var(--border-radius-lg);
|
||||||
|
border-top-right-radius: var(--border-radius-lg);
|
||||||
|
|
||||||
|
@media screen and (max-width: $verticalBreakpoint) {
|
||||||
|
min-height: 100px;
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__empty-state {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 200px;
|
||||||
|
|
||||||
|
&-content {
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 0 0 0.2rem 0;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media screen and (max-width: $verticalBreakpoint) {
|
||||||
|
min-height: 100px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__input-outer {
|
||||||
|
position: relative;
|
||||||
|
min-height: 71px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__input-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__input-wrapper {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 0.5rem;
|
||||||
|
|
||||||
|
border: 1px solid var(--dialog-border-color);
|
||||||
|
border-radius: var(--border-radius-lg);
|
||||||
|
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: var(--color-surface-lowest);
|
||||||
|
transition: border-color 0.2s ease;
|
||||||
|
|
||||||
|
&:focus-within {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media screen and (max-width: $verticalBreakpoint) {
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__input {
|
||||||
|
flex: 1;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
min-height: 24px;
|
||||||
|
max-height: 120px;
|
||||||
|
overflow-x: hidden;
|
||||||
|
border: none !important;
|
||||||
|
background: transparent !important;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
|
||||||
|
&::placeholder {
|
||||||
|
color: var(--color-gray-40);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media screen and (max-width: $verticalBreakpoint) {
|
||||||
|
line-height: 1.4;
|
||||||
|
min-height: 20px;
|
||||||
|
max-height: 100px;
|
||||||
|
resize: none;
|
||||||
|
padding: 0;
|
||||||
|
|
||||||
|
&::placeholder {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__send-button {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-surface-lowest);
|
||||||
|
cursor: pointer;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background-color: var(--color-primary-darker);
|
||||||
|
}
|
||||||
|
|
||||||
|
svg {
|
||||||
|
transform: rotate(-90deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-message {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
|
||||||
|
&--user {
|
||||||
|
justify-content: flex-end;
|
||||||
|
|
||||||
|
.chat-message__content {
|
||||||
|
background: var(--color-primary-light);
|
||||||
|
color: var(--text-primary-color);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
min-width: 6rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&--assistant {
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: flex-start;
|
||||||
|
align-items: flex-start;
|
||||||
|
|
||||||
|
.chat-message__content {
|
||||||
|
background: var(--color-surface-low);
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
min-width: 6rem;
|
||||||
|
|
||||||
|
.chat-message__body {
|
||||||
|
font-family: monospace;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&--system {
|
||||||
|
justify-content: flex-start;
|
||||||
|
margin-bottom: 0;
|
||||||
|
|
||||||
|
.chat-message__content {
|
||||||
|
background: var(--color-warning);
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
min-width: 6rem;
|
||||||
|
|
||||||
|
.chat-message__body {
|
||||||
|
font-family: monospace;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__content {
|
||||||
|
max-width: 80%;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
box-shadow: var(--chat-msg-shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
&__header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__role {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__timestamp {
|
||||||
|
font-size: 0.625rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__action {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.25rem 0;
|
||||||
|
color: var(--color-gray-60);
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
flex-shrink: 0;
|
||||||
|
|
||||||
|
&.invisible {
|
||||||
|
visibility: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
svg {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__action--danger {
|
||||||
|
&:hover {
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__body {
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__text {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__cursor {
|
||||||
|
display: inline-block;
|
||||||
|
margin-left: 2px;
|
||||||
|
color: currentColor;
|
||||||
|
animation: blink 1s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__loading {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__typing-indicator {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.25rem;
|
||||||
|
|
||||||
|
span {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: currentColor;
|
||||||
|
opacity: 0.4;
|
||||||
|
animation: typing 1.4s infinite ease-in-out;
|
||||||
|
|
||||||
|
&:nth-child(1) {
|
||||||
|
animation-delay: -0.32s;
|
||||||
|
}
|
||||||
|
&:nth-child(2) {
|
||||||
|
animation-delay: -0.16s;
|
||||||
|
}
|
||||||
|
&:nth-child(3) {
|
||||||
|
animation-delay: 0s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__error {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-weight: 500;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-wrap: break-word;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__error_message {
|
||||||
|
background: var(--color-warning-background);
|
||||||
|
color: var(--color-warning-color);
|
||||||
|
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
margin-top: 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__error-link {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 500;
|
||||||
|
padding: 0;
|
||||||
|
margin-top: 1rem;
|
||||||
|
text-decoration: underline;
|
||||||
|
font-family: inherit;
|
||||||
|
color: var(--link-color);
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--link-color-hover);
|
||||||
|
}
|
||||||
|
&:active {
|
||||||
|
color: var(--link-color-active);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes typing {
|
||||||
|
0%,
|
||||||
|
80%,
|
||||||
|
100% {
|
||||||
|
transform: scale(0.8);
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
40% {
|
||||||
|
transform: scale(1);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes blink {
|
||||||
|
0%,
|
||||||
|
50% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
51%,
|
||||||
|
100% {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import clsx from "clsx";
|
||||||
|
|
||||||
|
import { t } from "../../../i18n";
|
||||||
|
import { historyIcon, TrashIcon } from "../../icons";
|
||||||
|
import DropdownMenu from "../../dropdownMenu/DropdownMenu";
|
||||||
|
|
||||||
|
import { FilledButton } from "../../FilledButton";
|
||||||
|
|
||||||
|
import type { SavedChat } from "../types";
|
||||||
|
|
||||||
|
interface ChatHistoryMenuProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onToggle: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onNewChat: () => void;
|
||||||
|
onRestoreChat: (chat: SavedChat) => void;
|
||||||
|
onDeleteChat: (chatId: string, event: React.MouseEvent) => void;
|
||||||
|
savedChats: SavedChat[];
|
||||||
|
activeSessionId: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
isNewChatBtnVisible?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ChatHistoryMenu = ({
|
||||||
|
isOpen,
|
||||||
|
onToggle,
|
||||||
|
onClose,
|
||||||
|
onNewChat,
|
||||||
|
onRestoreChat,
|
||||||
|
onDeleteChat,
|
||||||
|
isNewChatBtnVisible,
|
||||||
|
savedChats,
|
||||||
|
activeSessionId,
|
||||||
|
disabled,
|
||||||
|
}: ChatHistoryMenuProps) => {
|
||||||
|
return (
|
||||||
|
<div className="ttd-chat-history-menu">
|
||||||
|
{isNewChatBtnVisible && (
|
||||||
|
<FilledButton onClick={onNewChat} disabled={disabled}>
|
||||||
|
{t("chat.newChat")}
|
||||||
|
</FilledButton>
|
||||||
|
)}
|
||||||
|
{savedChats.length > 0 && (
|
||||||
|
<div className="ttd-dialog-panel__menu-wrapper">
|
||||||
|
<DropdownMenu open={isOpen}>
|
||||||
|
<DropdownMenu.Trigger
|
||||||
|
onToggle={onToggle}
|
||||||
|
className="ttd-dialog-menu-trigger"
|
||||||
|
disabled={disabled}
|
||||||
|
title={t("chat.menu")}
|
||||||
|
aria-label={t("chat.menu")}
|
||||||
|
>
|
||||||
|
{historyIcon}
|
||||||
|
</DropdownMenu.Trigger>
|
||||||
|
<DropdownMenu.Content
|
||||||
|
onClickOutside={onClose}
|
||||||
|
onSelect={onClose}
|
||||||
|
placement="bottom"
|
||||||
|
>
|
||||||
|
<>
|
||||||
|
{savedChats.map((chat) => (
|
||||||
|
<DropdownMenu.ItemCustom
|
||||||
|
key={chat.id}
|
||||||
|
className={clsx("ttd-chat-menu-item", {
|
||||||
|
"ttd-chat-menu-item--active": chat.id === activeSessionId,
|
||||||
|
})}
|
||||||
|
onClick={() => {
|
||||||
|
onRestoreChat(chat);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="ttd-chat-menu-item__title">
|
||||||
|
{chat.title}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
className="ttd-chat-menu-item__delete"
|
||||||
|
onClick={(e) => onDeleteChat(chat.id, e)}
|
||||||
|
title={t("chat.deleteChat")}
|
||||||
|
aria-label={t("chat.deleteChat")}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{TrashIcon}
|
||||||
|
</button>
|
||||||
|
</DropdownMenu.ItemCustom>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
</DropdownMenu.Content>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import React, { useRef, useEffect, useLayoutEffect } from "react";
|
||||||
|
import { KEYS } from "@excalidraw/common";
|
||||||
|
|
||||||
|
import { ArrowRightIcon, stop as StopIcon } from "../../icons";
|
||||||
|
import { InlineIcon } from "../../InlineIcon";
|
||||||
|
|
||||||
|
import { t } from "../../../i18n";
|
||||||
|
|
||||||
|
import { ChatMessage } from "./ChatMessage";
|
||||||
|
|
||||||
|
import type { TChat, TTTDDialog } from "../types";
|
||||||
|
|
||||||
|
import type { FormEventHandler } from "react";
|
||||||
|
|
||||||
|
export const ChatInterface = ({
|
||||||
|
chatId,
|
||||||
|
messages,
|
||||||
|
currentPrompt,
|
||||||
|
onPromptChange,
|
||||||
|
onGenerate,
|
||||||
|
isGenerating,
|
||||||
|
rateLimits,
|
||||||
|
placeholder,
|
||||||
|
onAbort,
|
||||||
|
onMermaidTabClick,
|
||||||
|
onAiRepairClick,
|
||||||
|
onDeleteMessage,
|
||||||
|
onInsertMessage,
|
||||||
|
onRetry,
|
||||||
|
renderWarning,
|
||||||
|
}: {
|
||||||
|
chatId: string;
|
||||||
|
messages: TChat.ChatMessage[];
|
||||||
|
currentPrompt: string;
|
||||||
|
onPromptChange: (prompt: string) => void;
|
||||||
|
onGenerate: TTTDDialog.OnGenerate;
|
||||||
|
isGenerating: boolean;
|
||||||
|
rateLimits?: {
|
||||||
|
rateLimit: number;
|
||||||
|
rateLimitRemaining: number;
|
||||||
|
} | null;
|
||||||
|
onViewAsMermaid?: () => void;
|
||||||
|
generatedResponse?: string | null;
|
||||||
|
placeholder: {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
hint: string;
|
||||||
|
};
|
||||||
|
onAbort?: () => void;
|
||||||
|
onMermaidTabClick?: (message: TChat.ChatMessage) => void;
|
||||||
|
onAiRepairClick?: (message: TChat.ChatMessage) => void;
|
||||||
|
onDeleteMessage?: (messageId: string) => void;
|
||||||
|
onInsertMessage?: (message: TChat.ChatMessage) => void;
|
||||||
|
onRetry?: (message: TChat.ChatMessage) => void;
|
||||||
|
renderWarning?: TTTDDialog.renderWarning;
|
||||||
|
}) => {
|
||||||
|
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
messagesEndRef.current?.scrollIntoView();
|
||||||
|
}, [messages]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (textareaRef.current) {
|
||||||
|
textareaRef.current.focus();
|
||||||
|
}
|
||||||
|
}, [chatId]);
|
||||||
|
|
||||||
|
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
|
const value = event.target.value;
|
||||||
|
onPromptChange(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (isGenerating && onAbort) {
|
||||||
|
onAbort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmedPrompt = currentPrompt.trim();
|
||||||
|
if (!trimmedPrompt) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onGenerate({ prompt: trimmedPrompt });
|
||||||
|
onPromptChange("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||||
|
if (event.key === KEYS.ENTER && !event.shiftKey) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!isGenerating) {
|
||||||
|
handleSubmit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const canSend =
|
||||||
|
currentPrompt.trim().length > 3 &&
|
||||||
|
!isGenerating &&
|
||||||
|
(rateLimits?.rateLimitRemaining ?? 1) > 0;
|
||||||
|
|
||||||
|
const canStop = isGenerating && !!onAbort;
|
||||||
|
|
||||||
|
const onInput: FormEventHandler<HTMLTextAreaElement> = (ev) => {
|
||||||
|
const target = ev.target as HTMLTextAreaElement;
|
||||||
|
target.style.height = "auto";
|
||||||
|
target.style.height = `${Math.min(target.scrollHeight, 120)}px`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="chat-interface">
|
||||||
|
<div className="chat-interface__messages">
|
||||||
|
{messages.length === 0 ? (
|
||||||
|
<div className="chat-interface__empty-state">
|
||||||
|
<div className="chat-interface__empty-state-content">
|
||||||
|
<h3>{placeholder.title}</h3>
|
||||||
|
<p>{placeholder.description}</p>
|
||||||
|
<p>{placeholder.hint}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
messages.map((message, index) => (
|
||||||
|
<ChatMessage
|
||||||
|
key={message.id}
|
||||||
|
message={message}
|
||||||
|
onMermaidTabClick={onMermaidTabClick}
|
||||||
|
onAiRepairClick={onAiRepairClick}
|
||||||
|
onDeleteMessage={onDeleteMessage}
|
||||||
|
onInsertMessage={onInsertMessage}
|
||||||
|
onRetry={onRetry}
|
||||||
|
rateLimitRemaining={rateLimits?.rateLimitRemaining}
|
||||||
|
isLastMessage={index === messages.length - 1}
|
||||||
|
renderWarning={renderWarning}
|
||||||
|
// so we don't allow to repair parse errors which aren't the last message
|
||||||
|
allowFixingParseError={
|
||||||
|
message.errorType === "parse" && index === messages.length - 1
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
<div ref={messagesEndRef} id="messages-end" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="chat-interface__input-container">
|
||||||
|
<div className="chat-interface__input-outer">
|
||||||
|
<div
|
||||||
|
className="chat-interface__input-wrapper"
|
||||||
|
style={{
|
||||||
|
borderColor: isGenerating
|
||||||
|
? "var(--dialog-border-color)"
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
autoFocus
|
||||||
|
className="chat-interface__input"
|
||||||
|
value={currentPrompt}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder={
|
||||||
|
isGenerating
|
||||||
|
? t("chat.generating")
|
||||||
|
: rateLimits?.rateLimitRemaining === 0
|
||||||
|
? t("chat.rateLimit.messageLimitInputPlaceholder")
|
||||||
|
: messages.length > 0
|
||||||
|
? t("chat.inputPlaceholderWithMessages")
|
||||||
|
: t("chat.inputPlaceholder", { shortcut: "Shift + Enter" })
|
||||||
|
}
|
||||||
|
disabled={rateLimits?.rateLimitRemaining === 0}
|
||||||
|
rows={1}
|
||||||
|
cols={30}
|
||||||
|
onInput={onInput}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="chat-interface__send-button"
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!canSend && !canStop}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<InlineIcon
|
||||||
|
size="1.5em"
|
||||||
|
icon={isGenerating ? StopIcon : ArrowRightIcon}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user