Compare commits

...

26 Commits

Author SHA1 Message Date
Ryan Di f09e465560 fix: text corner resizing only takes delta y 2026-01-28 11:58:06 +11:00
Márk Tolmács 6a891365b9 fix: Arrow endpoint offset (#10706)
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-26 20:55:08 +01:00
Márk Tolmács 54fa0c9089 fix: Increase iteration on curve intersection calc (#10707)
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-26 20:52:13 +01:00
Márk Tolmács dfdd994dbb perf: Cache hits in collision detection (#10648)
* feat: Cache hits and scene lookups

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Remove debug

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Consider hit threshold and inside override too

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Remove Map caching

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: incorrect threshold

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: threshold setting

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Hit caching

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: cache override

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-26 20:50:44 +01:00
Christopher Tangonan 28691e14b1 fix: Bound arrow elements for distribute and wyswig updates (#10702)
* fix: update distributeElements to updateBoundElements

Co-authored-by: Anvi Kudaraya <anvikudaraya417@gmail.com>

* fix: apply updateBoundElements when bound text extends past container height

Co-authored-by: Anvi Kudaraya <anvikudaraya417@gmail.com>

---------

Co-authored-by: Anvi Kudaraya <anvikudaraya417@gmail.com>
2026-01-26 18:52:13 +01:00
zsviczian 60759d314d fix: Regression - invert SVGs in Dark Mode (#10695)
* initial implementation

* lint

* removed separate getThemeFilterValue function from renderElement

* removed BinaryFileData changes

* filter instead of css filter
2026-01-24 13:00:14 +01:00
zsviczian d5e37cda81 fix: set link icon opacity based on element opacity (#10693)
* Set global alpha for drawing elements

* Adjust opacity calculation for canvas rendering

* lint
2026-01-24 12:16:48 +01:00
David Luzar 6135548534 fix: rerender TTD preview on message remove (#10681) 2026-01-21 14:07:48 +01:00
David Luzar acf54c6f38 fix: dropdownMenu item badge position (#10682) 2026-01-21 14:07:36 +01:00
David Luzar 84a309d669 fix: ttd 429 error handling (#10680) 2026-01-21 14:07:23 +01:00
David Luzar 3c8e893cab fix: keep input focus during generation (#10679) 2026-01-20 20:14:28 +01:00
Márk Tolmács 9ba0f5dbc9 fix: Arrow drag start in bindable area jumps across bindable (#10676)
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-20 12:38:40 +01:00
David Luzar 60ab14c2f6 fix: fail gracefully during restore (#10673)
* fix: fail gracefully during restore

* tests
2026-01-20 12:33:22 +01:00
Márk Tolmács 0988ecfef4 fix: Angle-locked line history (#10677)
* fix: Line history

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: More conservative condition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-20 12:11:58 +01:00
David Luzar 1f47d61e8c chore: bump node in tests.yml (#10670) 2026-01-19 09:23:50 +01:00
David Luzar 9d760336d1 feat: reduce max tablet MQ size (#10669)
* feat: reduce max tablet MQ size

* replace UIOptions.formFactor with getFormFactor
2026-01-18 21:55:14 +01:00
David Luzar 0443511954 fix: tweak error display in ttd (#10668)
fix: better error handling for ttd
2026-01-17 18:17:04 +01:00
David Luzar 5a73b9a363 refactor: change TTD persistence to iDB (#10662)
refactor: change ttd persistence to iDB
2026-01-16 15:10:00 +01:00
David Luzar 24a6941861 fix: retries and related UX fixes (#10657)
* fix: retries and related UX fixes

* bump

* fix package version

* yarn.lock

* naming and clearer type

* ignore test flake
2026-01-16 09:52:18 +01:00
Tamas L a0b98a944f feat: TextToDiagram v2 (#10530)
* feat: introducing TextToDiagram v2 feature

* fix: eslint issue

* debug mermaid bundle size

* tests: covering the utils

* fix: import mock chunks dynamically to shrink the bundle size

* fix: removing replay feature

* fix: removing unused prop

* fix: bumping workbox cache limit

* snapshots + yarn.lock

* bump mermaid-to-excalidraw@2 and split into its own chunk

* bump node@20

* css tweaks

* move files around & rewrite stream chunk schema

* random naming & file structure refactor + some tweaks

* fix preview theme

* support custom warning renderer

* label and css fix

* fix and rwrite 429 handling

* fix label

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-01-15 19:15:41 +01:00
Márk Tolmács 6ebf52279d fix: Elbow end point disconnect (#10646)
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-15 15:27:00 +01:00
Márk Tolmács 3b97f5a10c feat: move visualdebug to utils and introduce volume bindable visualization (#10617)
* feat: Move visualdebug to utils and introduce volume bindable volume visualization

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Move visualdebug to elements

Due to dep circles

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-01-12 15:24:50 +01:00
Márk Tolmács da59205846 fix: Curve endpoint intersection (#10640)
* fix: Curve endpoint intersection

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix debug

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-01-12 15:02:56 +01:00
David Luzar b9a255407f refactor: update SCSS syntax & remove open-color dep (#10633) 2026-01-10 18:15:14 +01:00
David Luzar cc6c29c0b9 fix: update wysiwyg color on theme change (#10618) 2026-01-07 12:55:33 +01:00
David Luzar 87faa5d3da fix: sentry CI worfklow (#10610) 2026-01-06 11:39:45 +01:00
157 changed files with 6874 additions and 1652 deletions
+2 -2
View File
@@ -12,7 +12,7 @@ VITE_APP_WS_SERVER_URL=http://localhost:3002
VITE_APP_PLUS_LP=https://plus.excalidraw.com
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"}'
@@ -27,7 +27,7 @@ VITE_APP_ENABLE_TRACKING=true
FAST_REFRESH=false
# The port the run the dev server
VITE_APP_PORT=3000
VITE_APP_PORT=3001
#Debug flags
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
export SENTRY_RELEASE=$(sentry-cli releases propose-version)
sentry-cli releases new $SENTRY_RELEASE --project $SENTRY_PROJECT
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 deploys $SENTRY_RELEASE new -e production
env:
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
- name: "Install Node"
uses: actions/setup-node@v2
with:
node-version: "18.x"
node-version: "20.x"
- name: "Install Deps"
run: yarn install
- name: "Test Coverage"
+2 -2
View File
@@ -9,10 +9,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js 18.x
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 18.x
node-version: 20.x
- name: Install and test
run: |
yarn install
+1
View File
@@ -46,6 +46,7 @@ export const STORAGE_KEYS = {
VERSION_FILES: "version-files",
IDB_LIBRARY: "excalidraw-library",
IDB_TTD_CHATS: "excalidraw-ttd-chats",
// do not use apart from migrations
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
+17 -52
View File
@@ -4,12 +4,15 @@ import {
getTextFromElements,
MIME_TYPES,
TTDDialog,
TTDStreamFetch,
} from "@excalidraw/excalidraw";
import { getDataURL } from "@excalidraw/excalidraw/data/blob";
import { safelyParseJSON } from "@excalidraw/common";
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
import { TTDIndexedDBAdapter } from "../data/TTDStorage";
export const AIComponents = ({
excalidrawAPI,
}: {
@@ -99,61 +102,23 @@ export const AIComponents = ({
/>
<TTDDialog
onTextSubmit={async (input) => {
try {
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 }),
},
);
onTextSubmit={async (props) => {
const { onChunk, onStreamCreated, signal, messages } = props;
const rateLimit = response.headers.has("X-Ratelimit-Limit")
? parseInt(response.headers.get("X-Ratelimit-Limit") || "0", 10)
: undefined;
const result = await TTDStreamFetch({
url: `${
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(
"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");
}
return result;
}}
persistenceAdapter={TTDIndexedDBAdapter}
/>
</>
);
+45 -1
View File
@@ -27,7 +27,10 @@ import { isCurve } from "@excalidraw/math/curve";
import React from "react";
import type { Curve } from "@excalidraw/math";
import type { DebugElement } from "@excalidraw/common";
import type {
DebugElement,
DebugPolygon,
} from "@excalidraw/element/visualdebug";
import type {
ElementsMap,
ExcalidrawArrowElement,
@@ -75,6 +78,44 @@ const renderCubicBezier = (
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) => {
context.strokeStyle = "#888";
context.save();
@@ -280,6 +321,9 @@ const render = (
el.color,
);
break;
case isDebugPolygon(el.data):
renderPolygon(context, appState.zoom.value, el.data, el.color);
break;
default:
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>
),
);
+51
View File
@@ -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;
}
}
}
+6 -6
View File
@@ -10,8 +10,6 @@ const lessPrecise = (num: number, precision = 5) =>
const getAvgFrameTime = (times: number[]) =>
lessPrecise(times.reduce((a, b) => a + b) / times.length);
const getFps = (frametime: number) => lessPrecise(1000 / frametime);
export class Debug {
public static DEBUG_LOG_TIMES = true;
@@ -66,12 +64,14 @@ export class Debug {
}
for (const [name, { t, times, avg }] of Object.entries(Debug.TIMES_AVG)) {
if (times.length) {
const avgFrameTime = getAvgFrameTime(times);
// const avgFrameTime = getAvgFrameTime(times);
const totalTime = times.reduce((a, b) => a + b);
const avgFrameTime = lessPrecise(totalTime / Debug.FRAME_COUNT);
console.info(
name,
`${times.length} runs: ${avgFrameTime}ms across ${
`- ${times.length} calls - ${avgFrameTime}ms/frame across ${
Debug.FRAME_COUNT
} frames (${getFps(avgFrameTime)} fps ~ ${lessPrecise(
} frames (${lessPrecise(
(avgFrameTime / 16.67) * 100,
1,
)}% of frame budget)`,
@@ -136,7 +136,7 @@ export class Debug {
return (...args: T) => {
const t0 = performance.now();
const ret = fn(...args);
Debug.logTime(performance.now() - t0, name);
Debug[type](performance.now() - t0, name);
return ret;
};
};
+5
View File
@@ -102,6 +102,10 @@ export default defineConfig(({ mode }) => {
// Taking the substring after "locales/"
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: {
short_name: "Excalidraw",
@@ -1,5 +1,97 @@
// 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",
+6
View File
@@ -4,6 +4,12 @@ import {
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", () => {
+102 -48
View File
@@ -1,4 +1,3 @@
import oc from "open-color";
import tinycolor from "tinycolor2";
import { clamp } from "@excalidraw/math";
@@ -6,18 +5,14 @@ import { degreesToRadians } from "@excalidraw/math";
import type { Degrees } from "@excalidraw/math";
import type { Merge } from "./utility-types";
export { tinycolor };
// ---------------------------------------------------------------------------
// 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;
// ---------------------------------------------------------------------------
// Dark mode color transformation
// ---------------------------------------------------------------------------
function cssHueRotate(
red: number,
green: number,
@@ -115,8 +110,8 @@ export const applyDarkModeFilter = (color: string): string => {
};
// ---------------------------------------------------------------------------
export const COLOR_OUTLINE_CONTRAST_THRESHOLD = 240;
// Color palette
// ---------------------------------------------------------------------------
// FIXME can't put to utils.ts rn because of circular dependency
const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
@@ -131,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]>;
};
export type ColorPickerColor =
| Exclude<keyof oc, "indigo" | "lime">
| "transparent"
| "bronze";
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
export type ColorPaletteCustom = { [key: string]: ColorTuple | string };
@@ -152,38 +139,30 @@ export const DEFAULT_CHART_COLOR_INDEX = 4;
export const DEFAULT_ELEMENT_STROKE_COLOR_INDEX = 4;
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 = {
transparent: "transparent",
black: "#1e1e1e",
white: "#ffffff",
// open-colors
gray: getSpecificColorShades("gray", ELEMENTS_PALETTE_SHADE_INDEXES),
red: getSpecificColorShades("red", ELEMENTS_PALETTE_SHADE_INDEXES),
pink: getSpecificColorShades("pink", ELEMENTS_PALETTE_SHADE_INDEXES),
grape: getSpecificColorShades("grape", ELEMENTS_PALETTE_SHADE_INDEXES),
violet: getSpecificColorShades("violet", ELEMENTS_PALETTE_SHADE_INDEXES),
blue: getSpecificColorShades("blue", ELEMENTS_PALETTE_SHADE_INDEXES),
cyan: getSpecificColorShades("cyan", ELEMENTS_PALETTE_SHADE_INDEXES),
teal: getSpecificColorShades("teal", ELEMENTS_PALETTE_SHADE_INDEXES),
green: getSpecificColorShades("green", ELEMENTS_PALETTE_SHADE_INDEXES),
yellow: getSpecificColorShades("yellow", ELEMENTS_PALETTE_SHADE_INDEXES),
orange: getSpecificColorShades("orange", ELEMENTS_PALETTE_SHADE_INDEXES),
// radix bronze shades 3,5,7,9,11
// open-color from https://github.com/yeun/open-color/blob/master/open-color.js
// corresponds to indexes [0,2,4,6,8] (weights: 50, 200, 400, 600, 800)
gray: ["#f8f9fa", "#e9ecef", "#ced4da", "#868e96", "#343a40"],
red: ["#fff5f5", "#ffc9c9", "#ff8787", "#fa5252", "#e03131"],
pink: ["#fff0f6", "#fcc2d7", "#f783ac", "#e64980", "#c2255c"],
grape: ["#f8f0fc", "#eebefa", "#da77f2", "#be4bdb", "#9c36b5"],
violet: ["#f3f0ff", "#d0bfff", "#9775fa", "#7950f2", "#6741d9"],
blue: ["#e7f5ff", "#a5d8ff", "#4dabf7", "#228be6", "#1971c2"],
cyan: ["#e3fafc", "#99e9f2", "#3bc9db", "#15aabf", "#0c8599"],
teal: ["#e6fcf5", "#96f2d7", "#38d9a9", "#12b886", "#099268"],
green: ["#ebfbee", "#b2f2bb", "#69db7c", "#40c057", "#2f9e44"],
yellow: ["#fff9db", "#ffec99", "#ffd43b", "#fab005", "#f08c00"],
orange: ["#fff4e6", "#ffd8a8", "#ffa94d", "#fd7e14", "#e8590c"],
// radix bronze shades [3,5,7,9,11]
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, [
"cyan",
@@ -198,7 +177,6 @@ const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
"red",
]);
// -----------------------------------------------------------------------------
// quick picks defaults
// -----------------------------------------------------------------------------
@@ -233,7 +211,6 @@ export const DEFAULT_CANVAS_BACKGROUND_PICKS = [
"#fdf8f6",
] as ColorTuple;
// -----------------------------------------------------------------------------
// palette defaults
// -----------------------------------------------------------------------------
@@ -259,8 +236,7 @@ export const DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE = {
...COMMON_ELEMENT_SHADES,
} as const;
// -----------------------------------------------------------------------------
// helpers
// color palette helpers
// -----------------------------------------------------------------------------
// !!!MUST BE WITHOUT GRAY, TRANSPARENT AND BLACK!!!
@@ -281,6 +257,10 @@ export const getAllColorsSpecificShade = (index: 0 | 1 | 2 | 3 | 4) =>
COLOR_PALETTE.red[index],
] as const;
// -----------------------------------------------------------------------------
// 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
@@ -299,4 +279,78 @@ export const rgbToHex = (r: number, g: number, b: number, a?: number) => {
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;
};
+2
View File
@@ -190,6 +190,8 @@ export const THEME = {
DARK: "dark",
} as const;
export const DARK_THEME_FILTER = "invert(93%) hue-rotate(180deg)";
export const FRAME_STYLE = {
strokeColor: "#bbb" as ExcalidrawElement["strokeColor"],
strokeWidth: 2 as ExcalidrawElement["strokeWidth"],
+2 -3
View File
@@ -16,7 +16,6 @@ export type EditorInterface = Readonly<{
const DESKTOP_UI_MODE_STORAGE_KEY = "excalidraw.desktopUIMode";
// breakpoints
// mobile: up to 699px
export const MQ_MAX_MOBILE = 599;
export const MQ_MAX_WIDTH_LANDSCAPE = 1000;
@@ -24,9 +23,9 @@ export const MQ_MAX_HEIGHT_LANDSCAPE = 500;
// tablets
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;
// sidebar
-1
View File
@@ -11,5 +11,4 @@ export * from "./random";
export * from "./url";
export * from "./utils";
export * from "./emitter";
export * from "./visualdebug";
export * from "./editorInterface";
-5
View File
@@ -10,7 +10,6 @@ import type {
Zoom,
} from "@excalidraw/excalidraw/types";
import { tinycolor } from "./colors";
import {
DEFAULT_VERSION,
ENV,
@@ -548,10 +547,6 @@ export const mapFind = <T, K>(
return undefined;
};
export const isTransparent = (color: string) => {
return tinycolor(color).getAlpha() === 0;
};
export type ResolvablePromise<T> = Promise<T> & {
resolve: [T] extends [undefined]
? (value?: MaybePromise<Awaited<T>>) => void
+6
View File
@@ -17,6 +17,12 @@
"development": "./dist/dev/index.js",
"production": "./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": [
+7 -1
View File
@@ -15,6 +15,7 @@ import {
pointFrom,
pointFromVector,
pointRotateRads,
pointsEqual,
vectorFromPoint,
vectorNormalize,
vectorScale,
@@ -1602,7 +1603,12 @@ export const updateBoundPoint = (
if (
binding == null ||
// 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;
}
+34 -1
View File
@@ -105,6 +105,12 @@ export type HitTestArgs = {
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 = ({
point,
element,
@@ -113,6 +119,24 @@ export const hitElementItself = ({
frameNameBound = null,
overrideShouldTestInside = false,
}: 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
const hitFrameName = frameNameBound
? isPointWithinBounds(
@@ -153,7 +177,16 @@ export const hitElementItself = ({
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 = (
+20 -9
View File
@@ -1,10 +1,12 @@
import type { AppState } from "@excalidraw/excalidraw/types";
import { updateBoundElements } from "./binding";
import { getCommonBoundingBox } from "./bounds";
import { newElementWith } from "./mutateElement";
import { getSelectedElementsByGroup } from "./groups";
import type { Scene } from "./Scene";
import type { ElementsMap, ExcalidrawElement } from "./types";
export interface Distribution {
@@ -17,6 +19,7 @@ export const distributeElements = (
elementsMap: ElementsMap,
distribution: Distribution,
appState: Readonly<AppState>,
scene: Scene,
): ExcalidrawElement[] => {
const [start, mid, end, extent] =
distribution.axis === "x"
@@ -66,12 +69,16 @@ export const distributeElements = (
translation[distribution.axis] = pos - box[mid];
}
return group.map((element) =>
newElementWith(element, {
return group.map((element) => {
const updatedElement = scene.mutateElement(element, {
x: element.x + translation.x,
y: element.y + translation.y,
}),
);
});
updateBoundElements(element, scene, {
simultaneouslyUpdated: group,
});
return updatedElement;
});
});
}
@@ -90,11 +97,15 @@ export const distributeElements = (
pos += step;
pos += box[extent];
return group.map((element) =>
newElementWith(element, {
return group.map((element) => {
const updatedElement = scene.mutateElement(element, {
x: element.x + translation.x,
y: element.y + translation.y,
}),
);
});
updateBoundElements(element, scene, {
simultaneouslyUpdated: group,
});
return updatedElement;
});
});
};
@@ -724,7 +724,6 @@ export class LinearElementEditor {
? [pointerDownState.lastClickedPoint]
: selectedPointsIndices,
isDragging: false,
pointerOffset: { x: 0, y: 0 },
customLineAngle: null,
initialState: {
...editingLinearElement.initialState,
+16 -1
View File
@@ -14,6 +14,7 @@ import {
DEFAULT_REDUCED_GLOBAL_ALPHA,
ELEMENT_READY_TO_ERASE_OPACITY,
FRAME_STYLE,
DARK_THEME_FILTER,
MIME_TYPES,
THEME,
distance,
@@ -433,9 +434,22 @@ const drawElementOnCanvas = (
break;
}
case "image": {
context.save();
const cacheEntry =
element.fileId !== null
? renderConfig.imageCache.get(element.fileId)
: null;
const img = isInitializedImageElement(element)
? renderConfig.imageCache.get(element.fileId)?.image
? cacheEntry?.image
: 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 (element.roundness && context.roundRect) {
context.beginPath();
@@ -472,6 +486,7 @@ const drawElementOnCanvas = (
} else {
drawImagePlaceholder(element, context);
}
context.restore();
break;
}
default: {
+14 -3
View File
@@ -318,7 +318,18 @@ export const resizeSingleTextElement = (
) => {
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);
if (metrics === null) {
@@ -333,7 +344,7 @@ export const resizeSingleTextElement = (
origElement.width,
origElement.height,
metricsWidth,
nextHeight,
metricsHeight,
origElement.angle,
transformHandleType,
false,
@@ -343,7 +354,7 @@ export const resizeSingleTextElement = (
scene.mutateElement(element, {
fontSize: metrics.size,
width: metricsWidth,
height: nextHeight,
height: metricsHeight,
x: newOrigin.x,
y: newOrigin.y,
});
@@ -1,16 +1,24 @@
import {
isLineSegment,
lineSegment,
pointDistanceSq,
pointFrom,
type GlobalPoint,
type LocalPoint,
} 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 { LineSegment } from "@excalidraw/utils";
import { type Bounds, isBounds } from "./bounds";
// The global data holder to collect the debug operations
declare global {
interface Window {
@@ -23,10 +31,69 @@ declare global {
export type DebugElement = {
color: string;
data: LineSegment<GlobalPoint> | Curve<GlobalPoint>;
data: LineSegment<GlobalPoint> | Curve<GlobalPoint> | DebugPolygon;
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 = (
c: Curve<GlobalPoint>,
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 = (
p: GlobalPoint,
opts?: {
@@ -101,7 +193,7 @@ export const debugDrawBounds = (
permanent?: boolean;
},
) => {
(isBounds(box) ? [box] : box).forEach((bbox) =>
(isBounds(box) ? [box] : box).forEach((bbox: Bounds) =>
debugDrawLine(
[
lineSegment(
+182 -2
View File
@@ -1,9 +1,12 @@
import { arrayToMap } from "@excalidraw/common";
import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { UI } from "@excalidraw/excalidraw/tests/helpers/ui";
import "@excalidraw/utils/test-utils";
import { render } from "@excalidraw/excalidraw/tests/test-utils";
import * as distance from "../src/distance";
import { hitElementItself } from "../src/collision";
describe("check rotated elements can be hit:", () => {
@@ -25,8 +28,6 @@ describe("check rotated elements can be hit:", () => {
[-4, -302],
] as LocalPoint[],
});
//const p = [120, -211];
//const p = [0, 13];
const hit = hitElementItself({
point: pointFrom<GlobalPoint>(88, -68),
element: window.h.elements[0],
@@ -36,3 +37,182 @@ describe("check rotated elements can be hit:", () => {
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(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
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).toMatchInlineSnapshot(`
[
+18
View File
@@ -563,6 +563,24 @@ describe("text element", () => {
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
it.skip("flips while resizing", async () => {
const text = UI.createElement("text");
@@ -58,6 +58,7 @@ const distributeSelectedElements = (
app.scene.getNonDeletedElementsMap(),
distribution,
appState,
app.scene,
);
const updatedElementsMap = arrayToMap(updatedElements);
+11 -4
View File
@@ -82,7 +82,10 @@ export const actionFinalize = register<FormData>({
app.scene,
);
if (isBindingElement(element)) {
if (
isBindingElement(element) &&
!appState.selectedLinearElement.segmentMidPointHoveredCoords
) {
const newArrow = !!appState.newElement;
const selectedPointsIndices =
@@ -95,7 +98,10 @@ export const actionFinalize = register<FormData>({
map.set(index, {
point: LinearElementEditor.pointFromAbsoluteCoords(
element,
pointFrom<GlobalPoint>(sceneCoords.x, sceneCoords.y),
pointFrom<GlobalPoint>(
sceneCoords.x - linearElementEditor.pointerOffset.x,
sceneCoords.y - linearElementEditor.pointerOffset.y,
),
elementsMap,
),
});
@@ -106,8 +112,8 @@ export const actionFinalize = register<FormData>({
bindOrUnbindBindingElement(
element,
draggedPoints,
sceneCoords.x,
sceneCoords.y,
sceneCoords.x - linearElementEditor.pointerOffset.x,
sceneCoords.y - linearElementEditor.pointerOffset.y,
scene,
appState,
{
@@ -170,6 +176,7 @@ export const actionFinalize = register<FormData>({
...linearElementEditor.initialState,
lastClickedPoint: -1,
},
pointerOffset: { x: 0, y: 0 },
},
selectionElement: null,
suggestedBinding: null,
+1 -1
View File
@@ -1263,9 +1263,9 @@ export const ShapesSwitcher = ({
onSelect={() => app.onMagicframeToolSelect()}
icon={MagicIcon}
data-testid="toolbar-magicframe"
badge={<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>}
>
{t("toolBar.magicframe")}
<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>
</DropdownMenu.Item>
)}
</DropdownMenu.Content>
+3 -6
View File
@@ -2780,7 +2780,7 @@ class App extends React.Component<AppProps, AppState> {
private getFormFactor = (editorWidth: number, editorHeight: number) => {
return (
this.props.UIOptions.formFactor ??
this.props.UIOptions.getFormFactor?.(editorWidth, editorHeight) ??
getFormFactor(editorWidth, editorHeight)
);
};
@@ -2804,10 +2804,7 @@ class App extends React.Component<AppProps, AppState> {
? this.props.UIOptions.dockedSidebarBreakpoint
: MQ_RIGHT_SIDEBAR_MIN_WIDTH;
const nextEditorInterface = updateObject(this.editorInterface, {
desktopUIMode:
this.props.UIOptions.desktopUIMode ??
storedDesktopUIMode ??
this.editorInterface.desktopUIMode,
desktopUIMode: storedDesktopUIMode ?? this.editorInterface.desktopUIMode,
formFactor: this.getFormFactor(editorWidth, editorHeight),
userAgent: userAgentDescriptor,
canFitSidebar: editorWidth > sidebarBreakpoint,
@@ -10055,7 +10052,7 @@ class App extends React.Component<AppProps, AppState> {
});
}
} else if (pointerDownState.drag.hasOccurred && !multiElement) {
if (isBindingElement(newElement, false)) {
if (isLinearElement(newElement)) {
this.actionManager.executeAction(actionFinalize, "ui", {
event: childEvent,
sceneCoords,
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.Avatar {
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/theme";
@use "../css/theme" as *;
.excalidraw {
.excalidraw-button {
@@ -1,4 +1,4 @@
@import "../css/theme";
@use "../css/theme" as *;
.excalidraw {
button.standalone {
+3 -3
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module.scss" as *;
.excalidraw {
.Card {
@@ -19,7 +19,7 @@
padding: 1.4rem;
border-radius: 50%;
background: var(--card-color);
color: $oc-white;
color: #fff;
svg {
width: 2.8rem;
@@ -46,7 +46,7 @@
background-color: var(--card-color-darkest);
}
.ToolIcon__label {
color: $oc-white;
color: #fff;
}
.Spinner {
+23 -13
View File
@@ -1,25 +1,35 @@
import OpenColor from "open-color";
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<{
color: keyof OpenColor | "primary";
color: "primary" | "lime" | "pink";
children?: React.ReactNode;
}> = ({ children, color }) => {
return (
<div
className="Card"
style={{
["--card-color" as any]:
color === "primary" ? "var(--color-primary)" : OpenColor[color][7],
["--card-color-darker" as any]:
color === "primary"
? "var(--color-primary-darker)"
: OpenColor[color][8],
["--card-color-darkest" as any]:
color === "primary"
? "var(--color-primary-darkest)"
: OpenColor[color][9],
["--card-color" as any]: COLOR_MAP[color].base,
["--card-color-darker" as any]: COLOR_MAP[color].darker,
["--card-color-darkest" as any]: COLOR_MAP[color].darkest,
}}
>
{children}
@@ -1,4 +1,5 @@
@import "../css/variables.module.scss";
@use "sass:color";
@use "../css/variables.module" as *;
.excalidraw {
.Checkbox {
@@ -12,7 +13,7 @@
-webkit-tap-highlight-color: transparent;
&: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) {
@@ -24,25 +25,25 @@
&:active {
.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 {
.Checkbox-box {
background-color: fade-out($oc-blue-1, 0.8);
background-color: color.adjust($color-blue-1, $alpha: -0.8);
}
}
&.is-checked {
.Checkbox-box {
background-color: #{$oc-blue-1};
background-color: #{$color-blue-1};
svg {
display: block;
}
}
&:hover .Checkbox-box {
background-color: #{$oc-blue-2};
background-color: #{$color-blue-2};
}
}
@@ -58,16 +59,16 @@
align-items: 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;
border-radius: 4px;
color: #{$oc-blue-7};
color: #{$color-blue-7};
border: 0;
&:focus {
box-shadow: 0 0 0 3px #{$oc-blue-7};
box-shadow: 0 0 0 3px #{$color-blue-7};
}
svg {
@@ -1,9 +1,7 @@
import clsx from "clsx";
import { useCallback, useEffect, useRef, useState } from "react";
import { isTransparent, KEYS } from "@excalidraw/common";
import tinycolor from "tinycolor2";
import { KEYS, normalizeInputColor } from "@excalidraw/common";
import { getShortcutKey } from "../..//shortcut";
import { useAtom } from "../../editor-jotai";
@@ -16,29 +14,6 @@ import { activeColorPickerSectionAtom } from "./colorPickerUtils";
import type { ColorPickerType } from "./colorPickerUtils";
/**
* 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;
};
export const ColorInput = ({
color,
onChange,
@@ -1,4 +1,5 @@
@import "../../css/variables.module.scss";
@use "sass:color";
@use "../../css/variables.module" as *;
.excalidraw {
.focus-visible-none {
@@ -185,8 +186,8 @@
.color-picker {
background: var(--popup-bg-color);
border: 0 solid transparentize($oc-white, 0.75);
box-shadow: transparentize($oc-black, 0.75) 0 1px 4px;
border: 0 solid color.adjust(#fff, $alpha: -0.75);
box-shadow: color.adjust(#000, $alpha: -0.75) 0 1px 4px;
border-radius: 4px;
position: absolute;
@@ -243,7 +244,7 @@
}
.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"] & {
left: -14px;
@@ -280,7 +281,7 @@
padding: 0.25rem;
&-title {
color: $oc-gray-6;
color: $color-gray-6;
font-size: 12px;
padding: 0 0.25rem;
}
@@ -319,7 +320,7 @@
.color-picker-transparent {
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;
top: 0;
right: 0;
@@ -473,7 +474,7 @@
}
.color-picker-type-elementBackground .color-picker-keybinding {
color: $oc-white;
color: #fff;
}
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
@@ -486,10 +487,10 @@
&.theme--dark {
.color-picker-type-elementBackground .color-picker-keybinding {
color: $oc-black;
color: #000;
}
.color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
color: $oc-black;
color: #000;
}
}
}
@@ -5,6 +5,7 @@ import { useRef, useEffect } from "react";
import {
COLOR_OUTLINE_CONTRAST_THRESHOLD,
COLOR_PALETTE,
isColorDark,
isWritableElement,
} from "@excalidraw/common";
@@ -29,7 +30,7 @@ import { ColorInput } from "./ColorInput";
import { Picker } from "./Picker";
import PickerHeading from "./PickerHeading";
import { TopPicks } from "./TopPicks";
import { activeColorPickerSectionAtom, isColorDark } from "./colorPickerUtils";
import { activeColorPickerSectionAtom } from "./colorPickerUtils";
import "./ColorPicker.scss";
@@ -1,6 +1,5 @@
import React from "react";
import { isColorDark } from "./colorPickerUtils";
import { isColorDark } from "@excalidraw/common";
interface HotkeyLabelProps {
color: string;
@@ -5,10 +5,9 @@ import {
DEFAULT_CANVAS_BACKGROUND_PICKS,
DEFAULT_ELEMENT_BACKGROUND_PICKS,
DEFAULT_ELEMENT_STROKE_PICKS,
isColorDark,
} from "@excalidraw/common";
import { isColorDark } from "./colorPickerUtils";
import type { ColorPickerType } from "./colorPickerUtils";
interface TopPicksProps {
@@ -1,8 +1,4 @@
import {
isTransparent,
MAX_CUSTOM_COLORS_USED_IN_CANVAS,
tinycolor,
} from "@excalidraw/common";
import { MAX_CUSTOM_COLORS_USED_IN_CANVAS } from "@excalidraw/common";
import type { ExcalidrawElement } from "@excalidraw/element/types";
@@ -100,32 +96,6 @@ export type ActiveColorPickerSectionAtomType =
export const activeColorPickerSectionAtom =
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 (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;
};
export type ColorPickerType =
| "canvasBackground"
| "elementBackground"
@@ -1,4 +1,4 @@
@import "../../css/variables.module.scss";
@use "../../css/variables.module" as *;
$verticalBreakpoint: 861px;
@@ -44,7 +44,6 @@ import { getSelectedElements } from "../../scene";
import {
LockedIcon,
UnlockedIcon,
clockIcon,
searchIcon,
boltIcon,
bucketFillIcon,
@@ -52,6 +51,7 @@ import {
mermaidLogoIcon,
brainIconThin,
LibraryIcon,
historyCommandIcon,
} from "../icons";
import { SHAPES } from "../shapes";
@@ -928,7 +928,7 @@ function CommandPaletteInner({
marginLeft: "6px",
}}
>
{clockIcon}
{historyCommandIcon}
</div>
</div>
<CommandItem
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.confirm-dialog {
@@ -1,4 +1,5 @@
@import "../css/variables.module.scss";
@use "sass:color";
@use "../css/variables.module" as *;
.excalidraw {
.context-menu-popover {
@@ -8,7 +9,7 @@
.context-menu {
position: relative;
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;
list-style: none;
user-select: none;
@@ -49,7 +50,7 @@
&.dangerous {
.context-menu-item__label {
color: $oc-red-7;
color: $color-red-7;
}
}
@@ -73,7 +74,7 @@
.context-menu-item__label {
color: var(--popup-bg-color);
}
background-color: $oc-red-6;
background-color: $color-red-6;
}
}
@@ -97,6 +98,6 @@
.context-menu-item-separator {
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 {
.ConvertElementTypePopup {
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.Dialog {
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.ElementLinkDialog {
@@ -59,7 +59,7 @@
}
.ElementLinkDialog__remove {
color: $oc-red-9;
color: $color-red-9;
margin-left: 1rem;
.ToolIcon__icon {
@@ -68,7 +68,7 @@
}
.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 {
.ExportDialog__preview {
@@ -112,7 +112,7 @@
font-family: Cascadia;
font-size: 1.8em;
color: $oc-white;
color: #fff;
&:hover {
background-color: var(--button-color-darker);
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
@keyframes successStatusAnimation {
0% {
@@ -24,6 +24,14 @@
background-color: var(--back-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 {
transition: all 150ms ease-out;
}
@@ -52,7 +60,19 @@
}
&[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 {
font-weight: 600;
font-size: 0.875rem;
@@ -33,6 +33,7 @@ export type FilledButtonProps = {
fullWidth?: boolean;
icon?: React.ReactNode;
disabled?: boolean;
};
export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
@@ -48,6 +49,7 @@ export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
fullWidth,
className,
status,
disabled,
},
ref,
) => {
@@ -94,7 +96,7 @@ export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
type="button"
aria-label={label}
ref={ref}
disabled={_status === "loading" || _status === "success"}
disabled={disabled || _status === "loading" || _status === "success"}
>
<div className="ExcButton__contents">
{_status === "loading" ? (
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.FixedSideContainer {
@@ -1,4 +1,4 @@
@import "../../css/variables.module.scss";
@use "../../css/variables.module" as *;
.excalidraw {
.FontPicker__container {
@@ -290,13 +290,15 @@ export const FontPickerList = React.memo(
onHover(font.value);
}
}}
badge={
font.badge && (
<DropDownMenuItemBadge type={font.badge.type}>
{font.badge.placeholder}
</DropDownMenuItemBadge>
)
}
>
{font.text}
{font.badge && (
<DropDownMenuItemBadge type={font.badge.type}>
{font.badge.placeholder}
</DropDownMenuItemBadge>
)}
</DropdownMenuItem>
);
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.HelpDialog {
@@ -60,11 +60,12 @@
&__islands-container {
display: grid;
grid-column-gap: 1.5rem;
grid-row-gap: 2rem;
@media screen and (min-width: 1024px) {
grid-template-columns: 1fr 1fr;
}
grid-column-gap: 1.5rem;
grid-row-gap: 2rem;
}
@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
$wide-viewport-width: 1000px;
@@ -1,10 +1,11 @@
@import "../css/variables.module.scss";
@use "sass:color";
@use "../css/variables.module" as *;
.excalidraw {
.picker {
padding: 0.5rem;
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);
border-radius: 4px;
position: absolute;
@@ -87,7 +88,7 @@
}
.picker-type-elementBackground .picker-keybinding {
color: $oc-white;
color: #fff;
}
.picker-swatch[aria-label="transparent"] .picker-keybinding {
@@ -100,10 +101,10 @@
&.theme--dark {
.picker-type-elementBackground .picker-keybinding {
color: $oc-black;
color: #000;
}
.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 {
--ImageExportModal-preview-border: #d6d6d6;
+1 -2
View File
@@ -1,5 +1,4 @@
@import "open-color/open-color";
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.layer-ui__wrapper.animate {
@@ -1,4 +1,4 @@
@import "open-color/open-color";
@use "../css/variables.module" as *;
.excalidraw {
.layer-ui__library {
@@ -46,15 +46,15 @@
}
&-close.ToolIcon_type_button {
background-color: $oc-blue-6;
background-color: $color-blue-6;
align-self: flex-end;
&:hover {
background-color: $oc-blue-8;
background-color: $color-blue-8;
}
.ToolIcon__icon {
width: auto;
font-size: 1rem;
color: $oc-white;
color: #fff;
padding: 0 0.5rem;
}
}
@@ -90,7 +90,7 @@
border-radius: var(--border-radius-lg);
background-color: var(--color-primary);
color: $oc-white;
color: #fff;
text-align: center;
white-space: nowrap;
text-decoration: none !important;
@@ -1,4 +1,4 @@
@import "open-color/open-color";
@use "../css/variables.module" as *;
.excalidraw {
--container-padding-y: 1rem;
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.library-unit {
@@ -1,5 +1,4 @@
@import "open-color/open-color.scss";
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.mobile-toolbar {
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
&.excalidraw-modal-container {
-1
View File
@@ -49,7 +49,6 @@ export const Modal: React.FC<{
aria-modal="true"
onKeyDown={handleKeydown}
aria-labelledby={props.labelledBy}
data-prevent-outside-click
>
<div
className="Modal__background"
@@ -1,4 +1,4 @@
@import "../../css/variables.module.scss";
@use "../../css/variables.module" as *;
.excalidraw {
.OverwriteConfirm {
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.PasteChartDialog {
@@ -25,7 +25,7 @@
height: 128px;
border-radius: 2px;
padding: 1px;
border: 1px solid $oc-gray-4;
border: 1px solid $color-gray-4;
display: flex;
align-items: center;
justify-content: center;
@@ -39,7 +39,7 @@
}
&:hover {
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 type { ChartType } from "@excalidraw/element/types";
@@ -49,7 +48,7 @@ const ChartPreviewBtn = (props: {
elements,
{
exportBackground: false,
viewBackgroundColor: oc.white,
viewBackgroundColor: "#fff",
},
null, // files
{
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.publish-library {
@@ -14,7 +14,7 @@
span {
font-weight: 500;
font-size: 1rem;
color: $oc-gray-6;
color: $color-gray-6;
}
input,
textarea {
@@ -24,7 +24,7 @@
}
.required {
color: $oc-red-8;
color: $color-red-8;
margin: 0.2rem;
}
}
@@ -48,22 +48,22 @@
}
&--confirm.ToolIcon_type_button {
background-color: $oc-blue-6;
background-color: $color-blue-6;
&:hover {
background-color: $oc-blue-8;
background-color: $color-blue-8;
}
}
&--cancel.ToolIcon_type_button {
background-color: $oc-gray-5;
background-color: $color-gray-5;
&:hover {
background-color: $oc-gray-6;
background-color: $color-gray-6;
}
}
.ToolIcon__icon {
color: $oc-white;
color: #fff;
.Spinner {
--spinner-color: #fff;
svg {
@@ -83,7 +83,7 @@
}
&-warning {
color: $oc-red-6;
color: $color-red-6;
}
&-note {
@@ -102,14 +102,14 @@
top: 0.3rem;
left: 0.3rem;
font-size: 0.7rem;
color: $oc-red-7;
color: $color-red-7;
background: rgba(255, 255, 255, 0.9);
padding: 0.1rem 0.2rem;
border-radius: 0.2rem;
}
&__svg {
background-color: $oc-white;
background-color: #fff;
padding: 0.3rem;
width: 7.5rem;
height: 7.5rem;
@@ -121,7 +121,7 @@
}
.ToolIcon__icon {
background-color: $oc-white;
background-color: #fff;
width: auto;
height: auto;
margin: 0 0.5rem;
@@ -132,7 +132,7 @@
}
.required,
.error {
color: $oc-red-8;
color: $color-red-8;
font-weight: 700;
font-size: 1rem;
margin: 0.2rem;
@@ -152,16 +152,16 @@
margin: 0;
}
.ToolIcon__icon {
background-color: $oc-red-6;
background-color: $color-red-6;
&:hover {
background-color: $oc-red-7;
background-color: $color-red-7;
}
&:active {
background-color: $oc-red-8;
background-color: $color-red-8;
}
}
svg {
color: $oc-white;
color: #fff;
padding: 0.26rem;
border-radius: 0.3em;
width: 1rem;
@@ -1,5 +1,4 @@
import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";
import OpenColor from "open-color";
import { useCallback, useEffect, useRef, useState } from "react";
import {
@@ -57,7 +56,7 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
const ctx = canvas.getContext("2d")!;
ctx.fillStyle = OpenColor.white;
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw items
@@ -87,7 +86,7 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
// draw item border
// -------------------------------------------------------------------------
ctx.lineWidth = BORDER_WIDTH;
ctx.strokeStyle = OpenColor.gray[4];
ctx.strokeStyle = "#ced4da";
ctx.strokeRect(
colOffset + BOX_PADDING / 2,
rowOffset + BOX_PADDING / 2,
@@ -131,7 +130,7 @@ const SingleLibraryItem = ({
elements: libItem.elements,
appState: {
...appState,
viewBackgroundColor: OpenColor.white,
viewBackgroundColor: "#fff",
exportBackground: true,
},
files: null,
@@ -175,7 +174,7 @@ const SingleLibraryItem = ({
}}
>
<div style={{ padding: "0.5em 0" }}>
<span style={{ fontWeight: 500, color: OpenColor.gray[6] }}>
<span style={{ fontWeight: 500, color: "#868e96" }}>
{t("publishDialog.itemName")}
</span>
<span aria-hidden="true" className="required">
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
--RadioGroup-background: var(--island-bg-color);
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
--slider-thumb-size: 16px;
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.SVGLayer {
@@ -1,5 +1,4 @@
@import "open-color/open-color";
@import "../css//variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.layer-ui__search {
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
.ShareableLinkDialog {
@@ -1,5 +1,4 @@
@import "open-color/open-color";
@import "../../css/variables.module.scss";
@use "../../css/variables.module" as *;
.excalidraw {
.sidebar {
@@ -19,6 +18,12 @@
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"] & {
left: 0;
right: auto;
@@ -28,12 +33,6 @@
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"] & {
border-right: 1px solid var(--sidebar-border-color);
border-left: 0;
@@ -1,4 +1,4 @@
@import "../../css/variables.module.scss";
@use "../../css/variables.module" as *;
.excalidraw {
.sidebar-trigger {
+1 -1
View File
@@ -1,4 +1,4 @@
@import "open-color/open-color.scss";
@use "../css/variables.module" as *;
$duration: 1.6s;
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../css/variables.module.scss";
@use "../css/variables.module" as *;
.excalidraw {
--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>
);
};
@@ -0,0 +1,218 @@
import clsx from "clsx";
import React, { useState, useEffect } from "react";
import { t } from "../../../i18n";
import { FilledButton } from "../../FilledButton";
import { TrashIcon, codeIcon, stackPushIcon, RetryIcon } from "../../icons";
import type { TChat, TTTDDialog } from "../types";
export const ChatMessage: React.FC<{
message: TChat.ChatMessage;
onMermaidTabClick?: (message: TChat.ChatMessage) => void;
onAiRepairClick?: (message: TChat.ChatMessage) => void;
onDeleteMessage?: (messageId: string) => void;
onInsertMessage?: (message: TChat.ChatMessage) => void;
onRetry?: (message: TChat.ChatMessage) => void;
rateLimitRemaining?: number;
isLastMessage?: boolean;
renderWarning?: TTTDDialog.renderWarning;
allowFixingParseError?: boolean;
}> = ({
message,
onMermaidTabClick,
onAiRepairClick,
onDeleteMessage,
onInsertMessage,
onRetry,
rateLimitRemaining,
isLastMessage,
renderWarning,
allowFixingParseError,
}) => {
const [canRetry, setCanRetry] = useState(false);
useEffect(() => {
if (!message.error || !isLastMessage) {
return;
}
if (message.error && !message.lastAttemptAt) {
setCanRetry(true);
return;
}
const timeSinceLastAttempt = Date.now() - message.lastAttemptAt!;
const remainingTime = Math.max(0, 5000 - timeSinceLastAttempt);
if (remainingTime === 0) {
setCanRetry(true);
return;
}
setCanRetry(false);
const timer = setTimeout(() => {
setCanRetry(true);
}, remainingTime);
return () => clearTimeout(timer);
}, [message.error, message.lastAttemptAt, isLastMessage]);
const formatTime = (date: Date) => {
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
};
if (message.type === "warning") {
const customOverride = renderWarning?.(message);
return (
<div className="chat-message chat-message--system">
<div className="chat-message__content">
<div className="chat-message__header">
<span className="chat-message__role">{t("chat.role.system")}</span>
<span className="chat-message__timestamp">
{formatTime(message.timestamp)}
</span>
</div>
<div className="chat-message__body">
<div className="chat-message__text">
{customOverride ? (
customOverride
) : message.warningType === "messageLimitExceeded" ? (
<>
{t("chat.rateLimit.messageLimit")}
<div style={{ marginTop: "10px" }}>
<FilledButton
onClick={() => {
window.open(
`${
import.meta.env.VITE_APP_PLUS_LP
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=ttdChatBanner#excalidraw-redirect`,
"_blank",
"noopener",
);
}}
>
{t("chat.upsellBtnLabel")}
</FilledButton>
</div>
</>
) : (
t("chat.rateLimit.generalRateLimit")
)}
</div>
</div>
</div>
</div>
);
}
return (
<div className={`chat-message chat-message--${message.type}`}>
<div className="chat-message__content">
<div className="chat-message__header">
<span className="chat-message__role">
{message.type === "user"
? t("chat.role.user")
: t("chat.role.assistant")}
</span>
<span className="chat-message__timestamp">
{formatTime(message.timestamp)}
</span>
</div>
<div className="chat-message__body">
{message.error ? (
<>
<div className="chat-message__error">{message.content}</div>
{message.errorType !== "parse" && (
<div className="chat-message__error_message">
Error: {message.error || t("chat.errors.generationFailed")}
</div>
)}
{message.errorType === "parse" && allowFixingParseError && (
<div className="chat-message__error_message">
<p>{t("chat.errors.invalidDiagram")}</p>
<div className="chat-message__error-actions">
{onMermaidTabClick && (
<button
className="chat-message__error-link"
onClick={() => onMermaidTabClick(message)}
type="button"
>
{t("chat.errors.fixInMermaid")}
</button>
)}
{onAiRepairClick && (
<button
className="chat-message__error-link"
onClick={() => onAiRepairClick(message)}
disabled={rateLimitRemaining === 0}
type="button"
>
{t("chat.errors.aiRepair")}
</button>
)}
</div>
</div>
)}
</>
) : (
<div className="chat-message__text">
{message.content}
{message.isGenerating && (
<span className="chat-message__cursor"></span>
)}
</div>
)}
</div>
</div>
{message.type === "assistant" && !message.isGenerating && (
<div className="chat-message__actions">
{!message.error && onInsertMessage && (
<button
className="chat-message__action"
onClick={() => onInsertMessage(message)}
type="button"
aria-label={t("chat.insert")}
title={t("chat.insert")}
>
{stackPushIcon}
</button>
)}
{onMermaidTabClick && message.content && (
<button
className="chat-message__action"
onClick={() => onMermaidTabClick(message)}
type="button"
aria-label={t("chat.viewAsMermaid")}
title={t("chat.viewAsMermaid")}
>
{codeIcon}
</button>
)}
{onDeleteMessage && message.errorType !== "network" && (
<button
className="chat-message__action chat-message__action--danger"
onClick={() => onDeleteMessage(message.id)}
type="button"
aria-label={t("chat.deleteMessage")}
title={t("chat.deleteMessage")}
>
{TrashIcon}
</button>
)}
{message.errorType === "network" && onRetry && isLastMessage && (
<button
className={clsx("chat-message__action", { invisible: !canRetry })}
onClick={() => onRetry(message)}
type="button"
aria-label={t("chat.retry")}
title={t("chat.retry")}
>
{RetryIcon}
</button>
)}
</div>
)}
</div>
);
};
@@ -0,0 +1,163 @@
import { t } from "../../../i18n";
import { ArrowRightIcon } from "../../icons";
import { InlineIcon } from "../../InlineIcon";
import { TTDDialogPanel } from "../TTDDialogPanel";
import { useAtom } from "../../../editor-jotai";
import { rateLimitsAtom } from "../TTDContext";
import { ChatHistoryMenu } from "./ChatHistoryMenu";
import { ChatInterface } from ".";
import type { TTDPanelAction } from "../TTDDialogPanel";
import type { SavedChat, TChat, TTTDDialog } from "../types";
export const TTDChatPanel = ({
chatId,
messages,
currentPrompt,
onPromptChange,
onGenerate,
isGenerating,
generatedResponse,
isMenuOpen,
onMenuToggle,
onMenuClose,
onNewChat,
onRestoreChat,
onDeleteChat,
savedChats,
activeSessionId,
onAbort,
onMermaidTabClick,
onAiRepairClick,
onDeleteMessage,
onInsertMessage,
onRetry,
onViewAsMermaid,
renderWarning,
}: {
chatId: string;
messages: TChat.ChatMessage[];
currentPrompt: string;
onPromptChange: (prompt: string) => void;
onGenerate: TTTDDialog.OnGenerate;
isGenerating: boolean;
generatedResponse: string | null | undefined;
isMenuOpen: boolean;
onMenuToggle: () => void;
onMenuClose: () => void;
onNewChat: () => void;
onRestoreChat: (chat: SavedChat) => void;
onDeleteChat: (chatId: string, event: React.MouseEvent) => void;
savedChats: SavedChat[];
activeSessionId: 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;
onViewAsMermaid: () => void;
renderWarning?: TTTDDialog.renderWarning;
}) => {
const [rateLimits] = useAtom(rateLimitsAtom);
const getPanelActions = () => {
const actions: TTDPanelAction[] = [];
if (rateLimits) {
actions.push({
label: t("chat.rateLimitRemaining", {
count: rateLimits.rateLimitRemaining,
}),
variant: "rateLimit",
className:
rateLimits.rateLimitRemaining < 5
? "ttd-dialog-panel__rate-limit--danger"
: "",
});
}
if (generatedResponse) {
actions.push({
action: onViewAsMermaid,
label: t("chat.viewAsMermaid"),
icon: <InlineIcon icon={ArrowRightIcon} />,
variant: "link",
});
}
return actions;
};
const actions = getPanelActions();
const getPanelActionFlexProp = () => {
if (actions.length === 2) {
return "space-between";
}
if (actions.length === 1 && actions[0].variant === "rateLimit") {
return "flex-start";
}
return "flex-end";
};
return (
<TTDDialogPanel
label={
<div className="ttd-dialog-panel__label-wrapper">
<div className="ttd-dialog-panel__label-group"></div>
<div className="ttd-dialog-panel__header-right">
<ChatHistoryMenu
isNewChatBtnVisible={!!messages.length}
isOpen={isMenuOpen}
onToggle={onMenuToggle}
onClose={onMenuClose}
onNewChat={onNewChat}
onRestoreChat={onRestoreChat}
onDeleteChat={onDeleteChat}
savedChats={savedChats}
activeSessionId={activeSessionId}
disabled={isGenerating}
/>
</div>
</div>
}
className="ttd-dialog-chat-panel"
panelActionJustifyContent={getPanelActionFlexProp()}
panelActions={actions}
>
<ChatInterface
chatId={chatId}
messages={messages}
currentPrompt={currentPrompt}
onPromptChange={onPromptChange}
onGenerate={onGenerate}
isGenerating={isGenerating}
generatedResponse={generatedResponse}
onAbort={onAbort}
onMermaidTabClick={onMermaidTabClick}
onAiRepairClick={onAiRepairClick}
onDeleteMessage={onDeleteMessage}
onInsertMessage={onInsertMessage}
onRetry={onRetry}
rateLimits={rateLimits}
placeholder={{
title: t("chat.placeholder.title"),
description: t("chat.placeholder.description"),
hint: t("chat.placeholder.hint"),
}}
renderWarning={renderWarning}
/>
</TTDDialogPanel>
);
};
@@ -0,0 +1,3 @@
export { ChatInterface } from "./ChatInterface";
export { ChatMessage } from "./ChatMessage";
export { useChatAgent } from "./useChatAgent";
@@ -0,0 +1,76 @@
import { useAtom } from "../../../editor-jotai";
import { chatHistoryAtom } from "../../TTDDialog/TTDContext";
import {
addMessages,
updateAssistantContent,
} from "../../TTDDialog/utils/chat";
export const useChatAgent = () => {
const [chatHistory, setChatHistory] = useAtom(chatHistoryAtom);
const addUserMessage = (content: string) => {
setChatHistory((prev) =>
addMessages(prev, [
{
type: "user",
content,
},
]),
);
};
const addAssistantMessage = () => {
setChatHistory((prev) =>
addMessages(prev, [
{
type: "assistant",
content: "",
isGenerating: true,
},
]),
);
};
const setLastRetryAttempt = () => {
setChatHistory((prev) =>
updateAssistantContent(prev, {
lastAttemptAt: Date.now(),
}),
);
};
const setAssistantError = (
errorMessage: string,
errorType: "parse" | "network" | "other" = "other",
errorDetails?: Error | unknown,
) => {
const serializedErrorDetails = errorDetails
? JSON.stringify({
name: errorDetails instanceof Error ? errorDetails.name : "Error",
message:
errorDetails instanceof Error
? errorDetails.message
: String(errorDetails),
stack: errorDetails instanceof Error ? errorDetails.stack : undefined,
})
: undefined;
setChatHistory((prev) =>
updateAssistantContent(prev, {
isGenerating: false,
error: errorMessage,
errorType,
errorDetails: serializedErrorDetails,
}),
);
};
return {
addUserMessage,
addAssistantMessage,
setAssistantError,
chatHistory,
setChatHistory,
setLastRetryAttempt,
};
};
@@ -10,6 +10,8 @@ import { EditorLocalStorage } from "../../data/EditorLocalStorage";
import { t } from "../../i18n";
import Trans from "../Trans";
import { useUIAppState } from "../../context/ui-appState";
import { TTDDialogInput } from "./TTDDialogInput";
import { TTDDialogOutput } from "./TTDDialogOutput";
import { TTDDialogPanel } from "./TTDDialogPanel";
@@ -19,12 +21,13 @@ import {
convertMermaidToExcalidraw,
insertToEditor,
saveMermaidDataToStorage,
resetPreview,
} from "./common";
import "./MermaidToExcalidraw.scss";
import type { BinaryFiles } from "../../types";
import type { MermaidToExcalidrawLibProps } from "./common";
import type { MermaidToExcalidrawLibProps } from "./types";
const MERMAID_EXAMPLE =
"flowchart TD\n A[Christmas] -->|Get money| B(Go shopping)\n B --> C{Let me think}\n C -->|One| D[Laptop]\n C -->|Two| E[iPhone]\n C -->|Three| F[Car]";
@@ -33,8 +36,10 @@ const debouncedSaveMermaidDefinition = debounce(saveMermaidDataToStorage, 300);
const MermaidToExcalidraw = ({
mermaidToExcalidrawLib,
isActive,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
isActive?: boolean;
}) => {
const [text, setText] = useState(
() =>
@@ -51,22 +56,40 @@ const MermaidToExcalidraw = ({
}>({ elements: [], files: null });
const app = useApp();
const { theme } = useUIAppState();
useEffect(() => {
convertMermaidToExcalidraw({
canvasRef,
data,
mermaidToExcalidrawLib,
setError,
mermaidDefinition: deferredText,
}).catch((err) => {
if (isDevEnv()) {
console.error("Failed to parse mermaid definition", err);
}
});
const doRender = async () => {
try {
if (!deferredText) {
resetPreview({ canvasRef, setError });
return;
}
const result = await convertMermaidToExcalidraw({
canvasRef,
data,
mermaidToExcalidrawLib,
setError,
mermaidDefinition: deferredText,
theme,
});
debouncedSaveMermaidDefinition(deferredText);
}, [deferredText, mermaidToExcalidrawLib]);
if (!result.success) {
const err = result.error ?? new Error("Invalid mermaid definition");
setError(err);
}
} catch (err) {
if (isDevEnv()) {
console.error("Failed to parse mermaid definition", err);
}
}
};
if (isActive) {
doRender();
debouncedSaveMermaidDefinition(deferredText);
}
}, [deferredText, mermaidToExcalidrawLib, isActive, theme]);
useEffect(
() => () => {
@@ -103,10 +126,10 @@ const MermaidToExcalidraw = ({
/>
</div>
<TTDDialogPanels>
<TTDDialogPanel label={t("mermaid.syntax")}>
<TTDDialogPanel>
<TTDDialogInput
input={text}
placeholder={"Write Mermaid diagram defintion here..."}
placeholder={t("mermaid.inputPlaceholder")}
onChange={(event) => setText(event.target.value)}
onKeyboardSubmit={() => {
onInsertToEditor();
@@ -114,14 +137,16 @@ const MermaidToExcalidraw = ({
/>
</TTDDialogPanel>
<TTDDialogPanel
label={t("mermaid.preview")}
panelAction={{
action: () => {
onInsertToEditor();
panelActions={[
{
action: () => {
onInsertToEditor();
},
label: t("mermaid.button"),
icon: ArrowRightIcon,
variant: "button",
},
label: t("mermaid.button"),
icon: ArrowRightIcon,
}}
]}
renderSubmitShortcut={() => <TTDDialogSubmitShortcut />}
>
<TTDDialogOutput
@@ -0,0 +1,17 @@
import { randomId } from "@excalidraw/common";
import { atom } from "../../editor-jotai";
import type { RateLimits, TChat } from "./types";
export const rateLimitsAtom = atom<RateLimits | null>(null);
export const showPreviewAtom = atom<boolean>(false);
export const errorAtom = atom<Error | null>(null);
export const chatHistoryAtom = atom<TChat.ChatHistory>({
id: randomId(),
messages: [],
currentPrompt: "",
});
@@ -1,6 +1,8 @@
@import "../../css/variables.module.scss";
@use "../../css/variables.module.scss" as *;
@use "./Chat/Chat.scss";
$verticalBreakpoint: 861px;
$fullScreenModalBreakpoint: 600px;
.excalidraw {
.Modal.Dialog.ttd-dialog {
@@ -16,21 +18,26 @@ $verticalBreakpoint: 861px;
display: flex;
flex-direction: column;
flex: 1 1 auto;
box-shadow: none;
}
.Modal__content {
height: auto;
max-height: 100%;
min-height: 95vh;
height: 100%;
@media screen and (min-width: $verticalBreakpoint) {
max-height: 750px;
max-height: min(950px, calc(100vh - 4rem));
height: 100%;
min-height: unset;
}
}
.Dialog__content {
flex: 1 1 auto;
@media screen and (max-width: $verticalBreakpoint) {
margin-top: 0 !important;
}
}
}
@@ -38,7 +45,7 @@ $verticalBreakpoint: 861px;
font-size: 15px;
font-style: italic;
font-weight: 500;
margin-bottom: 1.5rem;
margin: 0.5rem 0 1.5rem 0;
}
.ttd-dialog-tabs-root {
@@ -63,12 +70,33 @@ $verticalBreakpoint: 861px;
&[data-state="active"] {
border-bottom: 2px solid var(--color-primary);
}
&__content {
display: flex;
align-items: center;
}
&__badge {
display: flex;
align-items: center;
justify-content: center;
padding: 1px 6px;
margin-left: 10px;
font-size: 10px;
border-radius: 12px;
background: var(--color-promo);
color: var(--color-surface-lowest);
}
}
.ttd-dialog-triggers {
border-bottom: 1px solid var(--color-surface-high);
margin-bottom: 1.5rem;
margin-bottom: 1rem;
padding-inline: 2.5rem;
@media screen and (max-width: $verticalBreakpoint) {
margin-bottom: 1rem;
}
}
.ttd-dialog-content {
@@ -76,10 +104,102 @@ $verticalBreakpoint: 861px;
height: 100%;
display: flex;
flex-direction: column;
overflow: visible;
outline: none;
&[hidden] {
display: none;
}
@media screen and (max-width: $verticalBreakpoint) {
padding-inline: 1rem;
flex-grow: 1;
}
}
.ttd-dialog-panel__header .dropdown-menu {
z-index: 2;
margin: 0;
right: 0;
left: auto;
min-width: 280px;
.dropdown-menu-container.dropdown-menu-container {
padding-inline: 0.5rem !important;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
max-height: min(400px, 70vh);
height: fit-content;
overflow-y: auto;
box-shadow: var(--shadow-island);
border-radius: var(--border-radius-lg);
background-color: var(--island-bg-color-alt);
}
}
.ttd-dialog-layout {
display: grid;
grid-template-columns: 1fr 1fr;
height: 100%;
&--split {
gap: 2rem;
min-width: 0;
@media screen and (max-width: $verticalBreakpoint) {
grid-template-columns: 1fr;
grid-template-rows: 1fr auto;
grid-row-gap: 0;
}
.ttd-dialog-chat-panel {
min-width: 0;
@media screen and (max-width: $verticalBreakpoint) {
width: 100%;
flex: 0 0 auto;
height: auto;
min-height: 250px;
}
}
.ttd-dialog-preview-panel {
min-width: 0;
overflow: hidden;
@media screen and (max-width: $verticalBreakpoint) {
width: 100%;
flex: 0 0 auto;
max-width: 100%;
min-height: 280px;
height: unset;
}
}
}
&--chat-only {
grid-template-columns: 1fr;
.invisible {
display: none;
}
.ttd-dialog-chat-panel {
@media screen and (max-width: $verticalBreakpoint) {
height: unset;
}
}
@media screen and (max-width: $verticalBreakpoint) {
.chat-interface {
max-height: 100%;
&__messages {
max-height: unset;
}
}
}
}
}
.ttd-dialog-input {
@@ -101,12 +221,15 @@ $verticalBreakpoint: 861px;
.ttd-dialog-output-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0.85rem;
box-sizing: border-box;
flex-grow: 1;
position: relative;
overflow: hidden;
max-width: 100%;
max-height: 100%;
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
left center;
@@ -115,16 +238,29 @@ $verticalBreakpoint: 861px;
height: 400px;
width: auto;
max-width: 100%;
@media screen and (min-width: $verticalBreakpoint) {
width: 100%;
// acts as min-height
@media screen and (max-width: $fullScreenModalBreakpoint) {
height: 200px;
}
@media screen and (max-width: $verticalBreakpoint) {
width: 100%;
max-width: 100%;
}
&--error {
background: none;
border: 1px solid var(--dialog-border-color);
border-radius: var(--border-radius-lg);
}
canvas {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
}
}
@@ -135,28 +271,74 @@ $verticalBreakpoint: 861px;
align-items: center;
justify-content: center;
flex-grow: 1;
position: relative;
user-select: none;
&.invisible {
visibility: hidden;
pointer-events: none;
}
}
.ttd-dialog-output-canvas-content {
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
flex-grow: 1;
canvas {
image-rendering: auto;
}
}
.ttd-dialog-output-error {
color: red;
font-weight: 700;
font-size: 30px;
word-break: break-word;
overflow: auto;
max-height: 100%;
height: 100%;
width: 100%;
text-align: center;
position: absolute;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
p {
font-weight: 500;
font-family: Cascadia;
.ttd-dialog-output-error-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
padding: 2.5rem 2rem;
background: var(--color-surface-primary);
}
.ttd-dialog-output-error-icon {
color: var(--color-danger);
display: flex;
align-items: center;
justify-content: center;
svg {
width: 52px;
height: 52px;
stroke-width: 1.5;
}
}
.ttd-dialog-output-error-title {
font-size: 1.25rem;
font-weight: 600;
color: var(--color-danger);
text-align: center;
margin-top: 0.25rem;
}
.ttd-dialog-output-error-message {
text-align: left;
font-weight: 400;
color: var(--color-gray-50);
word-break: break-word;
white-space: pre-wrap;
font-size: 0.875rem;
padding: 0 10px;
max-width: 100%;
font-family: monospace;
}
}
@@ -166,37 +348,86 @@ $verticalBreakpoint: 861px;
@media screen and (min-width: $verticalBreakpoint) {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4rem;
gap: 2rem;
}
}
.ttd-dialog-chat-panel,
.ttd-dialog-preview-panel {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
align-items: stretch;
}
.ttd-dialog-panel {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
@media screen and (max-width: $verticalBreakpoint) {
height: 50%;
}
&__header {
display: flex;
margin: 0px 4px 4px 4px;
align-items: center;
gap: 1rem;
gap: 0.3rem;
height: 36px;
margin-top: 0.2rem;
margin-bottom: 0.5rem;
flex-shrink: 0;
label {
font-size: 14px;
line-height: 22px;
font-style: normal;
font-weight: 600;
}
}
&:first-child {
.ttd-dialog-panel-button-container:not(.invisible) {
margin-bottom: 4rem;
&__label-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
&__label-group {
display: flex;
gap: 5px;
}
&__header-right {
display: flex;
align-items: center;
gap: 0.75rem;
}
&__rate-limit {
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
&--danger {
color: var(--color-danger);
}
}
@media screen and (min-width: $verticalBreakpoint) {
.ttd-dialog-panel-button-container:not(.invisible) {
margin-bottom: 0.5rem !important;
&__menu-wrapper {
position: relative;
.ttd-dialog-menu-trigger {
height: 40px;
width: 40px;
}
.dropdown-menu {
margin-top: 0.375rem;
right: 0;
}
}
@@ -213,23 +444,28 @@ $verticalBreakpoint: 861px;
@media screen and (max-width: $verticalBreakpoint) {
width: auto;
height: 10rem;
}
}
}
.ttd-dialog-panel-button-container {
display: flex;
align-items: center;
flex-grow: 0;
height: 40px;
flex-shrink: 0;
margin-top: 1rem;
margin-bottom: 0.5rem;
&.invisible {
.ttd-dialog-panel-button {
display: none;
@media screen and (max-width: $verticalBreakpoint) {
margin-top: 0.5rem;
}
@media screen and (min-width: $verticalBreakpoint) {
display: block;
visibility: hidden;
}
&.invisible {
visibility: hidden;
@media screen and (max-width: $verticalBreakpoint) {
display: none;
}
}
}
@@ -241,7 +477,7 @@ $verticalBreakpoint: 861px;
height: 2.5rem;
font-size: 12px;
color: $oc-white;
color: #fff;
background-color: var(--color-primary);
width: 100%;
@@ -271,7 +507,9 @@ $verticalBreakpoint: 861px;
}
}
position: relative;
& {
position: relative;
}
div {
display: contents;
@@ -312,4 +550,109 @@ $verticalBreakpoint: 861px;
border-radius: 4px;
}
}
.ttd-dialog-panel-action-link {
display: flex;
align-items: center;
gap: 0.25rem;
background: none;
border: none;
color: var(--color-primary);
font-weight: 500;
font-family: inherit;
height: 40px;
&__icon {
display: inline-flex;
align-items: center;
svg {
width: 12px;
height: 12px;
}
}
@media screen and (max-width: $verticalBreakpoint) {
height: unset;
}
}
.dropdown-menu-item-custom.ttd-chat-menu-item {
display: flex;
width: unset;
align-items: center;
justify-content: space-between;
padding: 0.25rem 0.5rem;
cursor: pointer;
position: relative;
border: 1px solid transparent;
border-radius: var(--border-radius-md);
margin-top: 1px;
&:hover {
background-color: var(--button-hover-bg);
}
&:active {
border: 1px solid var(--button-active-border);
}
&--active {
background-color: var(--color-surface-primary-container);
}
.ttd-chat-menu-item__title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&:hover {
.ttd-chat-menu-item__delete {
visibility: visible;
}
}
.ttd-chat-menu-item__delete {
border: none;
padding: 0.25rem;
cursor: pointer;
flex-shrink: 0;
margin-left: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
visibility: hidden;
&:hover {
color: var(--color-danger);
}
@at-root .excalidraw.theme--dark#{&} {
svg {
color: var(--color-on-surface);
}
&:hover svg {
color: var(--color-danger);
}
}
svg {
width: 16px;
height: 16px;
}
}
}
.ttd-dialog-preview-panel--hidden {
display: none;
}
.ttd-chat-history-menu {
display: flex;
gap: 1rem;
align-items: center;
}
}
@@ -1,71 +1,32 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import { isFiniteNumber } from "@excalidraw/math";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { trackEvent } from "../../analytics";
import { useUIAppState } from "../../context/ui-appState";
import { atom, useAtom } from "../../editor-jotai";
import { t } from "../../i18n";
import { useApp, useExcalidrawSetAppState } from "../App";
import { useApp } from "../App";
import { Dialog } from "../Dialog";
import { InlineIcon } from "../InlineIcon";
import { withInternalFallback } from "../hoc/withInternalFallback";
import { ArrowRightIcon } from "../icons";
import MermaidToExcalidraw from "./MermaidToExcalidraw";
import TextToDiagram from "./TextToDiagram";
import TTDDialogTabs from "./TTDDialogTabs";
import { TTDDialogTabTriggers } from "./TTDDialogTabTriggers";
import { TTDDialogTabTrigger } from "./TTDDialogTabTrigger";
import { TTDDialogTab } from "./TTDDialogTab";
import { TTDDialogInput } from "./TTDDialogInput";
import { TTDDialogOutput } from "./TTDDialogOutput";
import { TTDDialogPanel } from "./TTDDialogPanel";
import { TTDDialogPanels } from "./TTDDialogPanels";
import {
convertMermaidToExcalidraw,
insertToEditor,
saveMermaidDataToStorage,
} from "./common";
import { TTDDialogSubmitShortcut } from "./TTDDialogSubmitShortcut";
import "./TTDDialog.scss";
import type { ChangeEventHandler } from "react";
import type { MermaidToExcalidrawLibProps } from "./common";
import type { BinaryFiles } from "../../types";
const MIN_PROMPT_LENGTH = 3;
const MAX_PROMPT_LENGTH = 1000;
const rateLimitsAtom = atom<{
rateLimit: number;
rateLimitRemaining: number;
} | null>(null);
const ttdGenerationAtom = atom<{
generatedResponse: string | null;
prompt: string | null;
} | null>(null);
type OnTestSubmitRetValue = {
rateLimit?: number | null;
rateLimitRemaining?: number | null;
} & (
| { generatedResponse: string | undefined; error?: null | undefined }
| {
error: Error;
generatedResponse?: null | undefined;
}
);
import type {
MermaidToExcalidrawLibProps,
TTDPersistenceAdapter,
TTTDDialog,
} from "./types";
export const TTDDialog = (
props:
| {
onTextSubmit(value: string): Promise<OnTestSubmitRetValue>;
onTextSubmit: TTTDDialog.onTextSubmit;
renderWarning?: TTTDDialog.renderWarning;
persistenceAdapter: TTDPersistenceAdapter;
}
| { __fallback: true },
) => {
@@ -81,7 +42,7 @@ export const TTDDialog = (
/**
* Text to diagram (TTD) dialog
*/
export const TTDDialogBase = withInternalFallback(
const TTDDialogBase = withInternalFallback(
"TTDDialogBase",
({
tab,
@@ -90,127 +51,15 @@ export const TTDDialogBase = withInternalFallback(
tab: "text-to-diagram" | "mermaid";
} & (
| {
onTextSubmit(value: string): Promise<OnTestSubmitRetValue>;
onTextSubmit(
props: TTTDDialog.OnTextSubmitProps,
): Promise<TTTDDialog.OnTextSubmitRetValue>;
renderWarning?: TTTDDialog.renderWarning;
persistenceAdapter: TTDPersistenceAdapter;
}
| { __fallback: true }
)) => {
const app = useApp();
const setAppState = useExcalidrawSetAppState();
const someRandomDivRef = useRef<HTMLDivElement>(null);
const [ttdGeneration, setTtdGeneration] = useAtom(ttdGenerationAtom);
const [text, setText] = useState(ttdGeneration?.prompt ?? "");
const prompt = text.trim();
const handleTextChange: ChangeEventHandler<HTMLTextAreaElement> = (
event,
) => {
setText(event.target.value);
setTtdGeneration((s) => ({
generatedResponse: s?.generatedResponse ?? null,
prompt: event.target.value,
}));
};
const [onTextSubmitInProgess, setOnTextSubmitInProgess] = useState(false);
const [rateLimits, setRateLimits] = useAtom(rateLimitsAtom);
const onGenerate = async () => {
if (
prompt.length > MAX_PROMPT_LENGTH ||
prompt.length < MIN_PROMPT_LENGTH ||
onTextSubmitInProgess ||
rateLimits?.rateLimitRemaining === 0 ||
// means this is not a text-to-diagram dialog (needed for TS only)
"__fallback" in rest
) {
if (prompt.length < MIN_PROMPT_LENGTH) {
setError(
new Error(
`Prompt is too short (min ${MIN_PROMPT_LENGTH} characters)`,
),
);
}
if (prompt.length > MAX_PROMPT_LENGTH) {
setError(
new Error(
`Prompt is too long (max ${MAX_PROMPT_LENGTH} characters)`,
),
);
}
return;
}
try {
setOnTextSubmitInProgess(true);
trackEvent("ai", "generate", "ttd");
const { generatedResponse, error, rateLimit, rateLimitRemaining } =
await rest.onTextSubmit(prompt);
if (typeof generatedResponse === "string") {
setTtdGeneration((s) => ({
generatedResponse,
prompt: s?.prompt ?? null,
}));
}
if (isFiniteNumber(rateLimit) && isFiniteNumber(rateLimitRemaining)) {
setRateLimits({ rateLimit, rateLimitRemaining });
}
if (error) {
setError(error);
return;
}
if (!generatedResponse) {
setError(new Error("Generation failed"));
return;
}
try {
await convertMermaidToExcalidraw({
canvasRef: someRandomDivRef,
data,
mermaidToExcalidrawLib,
setError,
mermaidDefinition: generatedResponse,
});
trackEvent("ai", "mermaid parse success", "ttd");
} catch (error: any) {
console.info(
`%cTTD mermaid render errror: ${error.message}`,
"color: red",
);
console.info(
`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nTTD mermaid definition render errror: ${error.message}`,
"color: yellow",
);
trackEvent("ai", "mermaid parse failed", "ttd");
setError(
new Error(
"Generated an invalid diagram :(. You may also try a different prompt.",
),
);
}
} catch (error: any) {
let message: string | undefined = error.message;
if (!message || message === "Failed to fetch") {
message = "Request failed";
}
setError(new Error(message));
} finally {
setOnTextSubmitInProgess(false);
}
};
const refOnGenerate = useRef(onGenerate);
refOnGenerate.current = onGenerate;
const [mermaidToExcalidrawLib, setMermaidToExcalidrawLib] =
useState<MermaidToExcalidrawLibProps>({
@@ -226,20 +75,13 @@ export const TTDDialogBase = withInternalFallback(
fn();
}, [mermaidToExcalidrawLib.api]);
const data = useRef<{
elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles | null;
}>({ elements: [], files: null });
const [error, setError] = useState<Error | null>(null);
return (
<Dialog
className="ttd-dialog"
onCloseRequest={() => {
app.setOpenDialog(null);
}}
size={1200}
size={1520}
title={false}
{...rest}
autofocus={false}
@@ -250,150 +92,35 @@ export const TTDDialogBase = withInternalFallback(
) : (
<TTDDialogTabTriggers>
<TTDDialogTabTrigger tab="text-to-diagram">
<div style={{ display: "flex", alignItems: "center" }}>
<div className="ttd-dialog-tab-trigger__content">
{t("labels.textToDiagram")}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "1px 6px",
marginLeft: "10px",
fontSize: 10,
borderRadius: "12px",
background: "var(--color-promo)",
color: "var(--color-surface-lowest)",
}}
>
AI Beta
<div className="ttd-dialog-tab-trigger__badge">
{t("chat.aiBeta")}
</div>
</div>
</TTDDialogTabTrigger>
<TTDDialogTabTrigger tab="mermaid">Mermaid</TTDDialogTabTrigger>
<TTDDialogTabTrigger tab="mermaid">
{t("mermaid.label")}
</TTDDialogTabTrigger>
</TTDDialogTabTriggers>
)}
{!("__fallback" in rest) && (
<TTDDialogTab className="ttd-dialog-content" tab="text-to-diagram">
<TextToDiagram
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
onTextSubmit={rest.onTextSubmit}
renderWarning={rest.renderWarning}
persistenceAdapter={rest.persistenceAdapter}
/>
</TTDDialogTab>
)}
<TTDDialogTab className="ttd-dialog-content" tab="mermaid">
<MermaidToExcalidraw
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
isActive={tab === "mermaid"}
/>
</TTDDialogTab>
{!("__fallback" in rest) && (
<TTDDialogTab className="ttd-dialog-content" tab="text-to-diagram">
<div className="ttd-dialog-desc">
Currently we use Mermaid as a middle step, so you'll get best
results if you describe a diagram, workflow, flow chart, and
similar.
</div>
<TTDDialogPanels>
<TTDDialogPanel
label={t("labels.prompt")}
panelAction={{
action: onGenerate,
label: "Generate",
icon: ArrowRightIcon,
}}
onTextSubmitInProgess={onTextSubmitInProgess}
panelActionDisabled={
prompt.length > MAX_PROMPT_LENGTH ||
rateLimits?.rateLimitRemaining === 0
}
renderTopRight={() => {
if (!rateLimits) {
return null;
}
return (
<div
className="ttd-dialog-rate-limit"
style={{
fontSize: 12,
marginLeft: "auto",
color:
rateLimits.rateLimitRemaining === 0
? "var(--color-danger)"
: undefined,
}}
>
{rateLimits.rateLimitRemaining} requests left today
</div>
);
}}
renderSubmitShortcut={() => <TTDDialogSubmitShortcut />}
renderBottomRight={() => {
if (typeof ttdGeneration?.generatedResponse === "string") {
return (
<div
className="excalidraw-link"
style={{ marginLeft: "auto", fontSize: 14 }}
onClick={() => {
if (
typeof ttdGeneration?.generatedResponse ===
"string"
) {
saveMermaidDataToStorage(
ttdGeneration.generatedResponse,
);
setAppState({
openDialog: { name: "ttd", tab: "mermaid" },
});
}
}}
>
View as Mermaid
<InlineIcon icon={ArrowRightIcon} />
</div>
);
}
const ratio = prompt.length / MAX_PROMPT_LENGTH;
if (ratio > 0.8) {
return (
<div
style={{
marginLeft: "auto",
fontSize: 12,
fontFamily: "monospace",
color:
ratio > 1 ? "var(--color-danger)" : undefined,
}}
>
Length: {prompt.length}/{MAX_PROMPT_LENGTH}
</div>
);
}
return null;
}}
>
<TTDDialogInput
onChange={handleTextChange}
input={text}
placeholder={"Describe what you want to see..."}
onKeyboardSubmit={() => {
refOnGenerate.current();
}}
/>
</TTDDialogPanel>
<TTDDialogPanel
label="Preview"
panelAction={{
action: () => {
console.info("Panel action clicked");
insertToEditor({ app, data });
},
label: "Insert",
icon: ArrowRightIcon,
}}
>
<TTDDialogOutput
canvasRef={someRandomDivRef}
error={error}
loaded={mermaidToExcalidrawLib.loaded}
/>
</TTDDialogPanel>
</TTDDialogPanels>
</TTDDialogTab>
)}
</TTDDialogTabs>
</Dialog>
);
@@ -1,36 +1,58 @@
import Spinner from "../Spinner";
import clsx from "clsx";
const ErrorComp = ({ error }: { error: string }) => {
return (
<div
data-testid="ttd-dialog-output-error"
className="ttd-dialog-output-error"
>
Error! <p>{error}</p>
</div>
);
};
import Spinner from "../Spinner";
import { t } from "../../i18n";
import { alertTriangleIcon } from "../icons";
interface TTDDialogOutputProps {
error: Error | null;
canvasRef: React.RefObject<HTMLDivElement | null>;
loaded: boolean;
hideErrorDetails?: boolean;
}
export const TTDDialogOutput = ({
error,
canvasRef,
loaded,
hideErrorDetails,
}: TTDDialogOutputProps) => {
return (
<div className="ttd-dialog-output-wrapper">
{error && <ErrorComp error={error.message} />}
<div
className={`ttd-dialog-output-wrapper ${
error ? "ttd-dialog-output-wrapper--error" : ""
}`}
>
{error && (
<div
key="error"
data-testid="ttd-dialog-output-error"
className="ttd-dialog-output-error"
>
<div className="ttd-dialog-output-error-content">
<div className="ttd-dialog-output-error-icon">
{alertTriangleIcon}
</div>
<div className="ttd-dialog-output-error-title">
{t("ttd.error")}
</div>
<div className="ttd-dialog-output-error-message">
{hideErrorDetails
? t("chat.errors.mermaidParseError")
: error.message}
</div>
</div>
</div>
)}
{loaded ? (
<div
ref={canvasRef}
style={{ opacity: error ? "0.15" : 1 }}
className="ttd-dialog-output-canvas-container"
/>
key="canvas"
className={clsx("ttd-dialog-output-canvas-container", {
invisible: !!error,
})}
>
<div ref={canvasRef} className="ttd-dialog-output-canvas-content" />
</div>
) : (
<Spinner size="2rem" />
)}
@@ -1,53 +1,76 @@
import clsx from "clsx";
import { Fragment } from "react";
import { Button } from "../Button";
import Spinner from "../Spinner";
import type { ReactNode } from "react";
interface TTDDialogPanelProps {
export type TTDPanelAction = {
label: string;
action?: () => void;
icon?: ReactNode;
variant: "button" | "link" | "rateLimit";
disabled?: boolean;
className?: string;
};
interface TTDDialogPanelProps {
label?: string | ReactNode;
children: ReactNode;
panelAction?: {
label: string;
action: () => void;
icon?: ReactNode;
};
panelActionDisabled?: boolean;
panelActions?: TTDPanelAction[];
onTextSubmitInProgess?: boolean;
renderTopRight?: () => ReactNode;
renderSubmitShortcut?: () => ReactNode;
renderBottomRight?: () => ReactNode;
className?: string;
panelActionJustifyContent?:
| "flex-start"
| "flex-end"
| "center"
| "space-between"
| "space-around"
| "space-evenly";
}
export const TTDDialogPanel = ({
label,
children,
panelAction,
panelActionDisabled = false,
panelActions = [],
onTextSubmitInProgess,
renderTopRight,
renderSubmitShortcut,
renderBottomRight,
className,
panelActionJustifyContent = "flex-start",
}: TTDDialogPanelProps) => {
return (
<div className="ttd-dialog-panel">
<div className="ttd-dialog-panel__header">
<label>{label}</label>
{renderTopRight?.()}
</div>
const renderPanelAction = (panelAction: TTDPanelAction) => {
if (panelAction?.variant === "link") {
return (
<button
className={clsx(
"ttd-dialog-panel-action-link",
panelAction.className,
)}
onClick={panelAction.action}
disabled={panelAction?.disabled || onTextSubmitInProgess}
type="button"
>
{panelAction.label}
{panelAction.icon && (
<span className="ttd-dialog-panel-action-link__icon">
{panelAction.icon}
</span>
)}
</button>
);
}
{children}
<div
className={clsx("ttd-dialog-panel-button-container", {
invisible: !panelAction,
})}
style={{ display: "flex", alignItems: "center" }}
>
if (panelAction?.variant === "button") {
return (
<Button
className="ttd-dialog-panel-button"
onSelect={panelAction ? panelAction.action : () => {}}
disabled={panelActionDisabled || onTextSubmitInProgess}
className={clsx("ttd-dialog-panel-button", panelAction.className)}
onSelect={panelAction.action ? panelAction.action : () => {}}
disabled={panelAction?.disabled || onTextSubmitInProgess}
>
<div className={clsx({ invisible: onTextSubmitInProgess })}>
{panelAction?.label}
@@ -55,10 +78,46 @@ export const TTDDialogPanel = ({
</div>
{onTextSubmitInProgess && <Spinner />}
</Button>
{!panelActionDisabled &&
!onTextSubmitInProgess &&
renderSubmitShortcut?.()}
{renderBottomRight?.()}
);
}
if (panelAction?.variant === "rateLimit") {
return (
<div
className={clsx(
"ttd-dialog-panel__rate-limit",
panelAction.className,
)}
>
{panelAction.label}
</div>
);
}
};
return (
<div className={clsx("ttd-dialog-panel", className)}>
{(label || renderTopRight) && (
<div className="ttd-dialog-panel__header">
{typeof label === "string" ? <label>{label}</label> : label}
{renderTopRight?.()}
</div>
)}
{children}
<div
className={clsx("ttd-dialog-panel-button-container", {
invisible: !panelActions.length,
})}
style={{
justifyContent: panelActionJustifyContent,
}}
>
{panelActions.filter(Boolean).map((panelAction) => (
<Fragment key={panelAction.label}>
{renderPanelAction(panelAction)}
</Fragment>
))}
{!onTextSubmitInProgess && renderSubmitShortcut?.()}
</div>
</div>
);
@@ -26,9 +26,9 @@ export const TTDDialogTrigger = ({
setAppState({ openDialog: { name: "ttd", tab: "text-to-diagram" } });
}}
icon={icon ?? brainIcon}
badge={<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>}
>
{children ?? t("labels.textToDiagram")}
<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>
</DropdownMenu.Item>
</TTDDialogTriggerTunnel.In>
);
@@ -0,0 +1,47 @@
import { t } from "../../i18n";
import { ArrowRightIcon } from "../icons";
import { TTDDialogPanel } from "./TTDDialogPanel";
import { TTDDialogOutput } from "./TTDDialogOutput";
import type { TTDPanelAction } from "./TTDDialogPanel";
interface TTDPreviewPanelProps {
canvasRef: React.RefObject<HTMLDivElement | null>;
error: Error | null;
loaded: boolean;
onInsert: () => void;
hideErrorDetails?: boolean;
}
export const TTDPreviewPanel = ({
canvasRef,
error,
loaded,
onInsert,
hideErrorDetails,
}: TTDPreviewPanelProps) => {
const actions: TTDPanelAction[] = [
{
action: onInsert,
label: t("chat.insert"),
icon: ArrowRightIcon,
variant: "button",
},
];
return (
<TTDDialogPanel
panelActionJustifyContent="flex-end"
panelActions={actions}
className="ttd-dialog-preview-panel"
>
<TTDDialogOutput
canvasRef={canvasRef}
error={error}
loaded={loaded}
hideErrorDetails={hideErrorDetails}
/>
</TTDDialogPanel>
);
};
@@ -0,0 +1,260 @@
import { useRef } from "react";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { useAtom, useAtomValue } from "../../editor-jotai";
import { useApp, useExcalidrawSetAppState } from "../App";
import { useChatAgent } from "./Chat";
import {
convertMermaidToExcalidraw,
insertToEditor,
saveMermaidDataToStorage,
} from "./common";
import { errorAtom, chatHistoryAtom, showPreviewAtom } from "./TTDContext";
import { useTTDChatStorage } from "./useTTDChatStorage";
import { useMermaidRenderer } from "./hooks/useMermaidRenderer";
import { useTextGeneration } from "./hooks/useTextGeneration";
import { useChatManagement } from "./hooks/useChatManagement";
import { TTDChatPanel } from "./Chat/TTDChatPanel";
import { TTDPreviewPanel } from "./TTDPreviewPanel";
import { getLastAssistantMessage } from "./utils/chat";
import type { BinaryFiles } from "../../types";
import type {
MermaidToExcalidrawLibProps,
TChat,
TTDPersistenceAdapter,
TTTDDialog,
} from "./types";
const TextToDiagramContent = ({
mermaidToExcalidrawLib,
onTextSubmit,
renderWarning,
persistenceAdapter,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
onTextSubmit: (
props: TTTDDialog.OnTextSubmitProps,
) => Promise<TTTDDialog.OnTextSubmitRetValue>;
renderWarning?: TTTDDialog.renderWarning;
persistenceAdapter: TTDPersistenceAdapter;
}) => {
const app = useApp();
const setAppState = useExcalidrawSetAppState();
const canvasRef = useRef<HTMLDivElement | null>(null);
const [error, setError] = useAtom(errorAtom);
const [chatHistory, setChatHistory] = useAtom(chatHistoryAtom);
const showPreview = useAtomValue(showPreviewAtom);
const { savedChats } = useTTDChatStorage({ persistenceAdapter });
const lastAssistantMessage = getLastAssistantMessage(chatHistory);
const { setLastRetryAttempt } = useChatAgent();
const { data } = useMermaidRenderer({
canvasRef,
mermaidToExcalidrawLib,
});
const { onGenerate, handleAbort } = useTextGeneration({
onTextSubmit,
});
const {
isMenuOpen,
onRestoreChat,
handleDeleteChat,
handleNewChat,
handleMenuToggle,
handleMenuClose,
} = useChatManagement({ persistenceAdapter });
const onViewAsMermaid = () => {
if (typeof lastAssistantMessage?.content === "string") {
saveMermaidDataToStorage(lastAssistantMessage.content);
setAppState({
openDialog: { name: "ttd", tab: "mermaid" },
});
}
};
const handleMermaidTabClick = (message: TChat.ChatMessage) => {
const mermaidContent = message.content || "";
if (mermaidContent) {
saveMermaidDataToStorage(mermaidContent);
setAppState({
openDialog: { name: "ttd", tab: "mermaid" },
});
}
};
const handleInsertMessage = async (message: TChat.ChatMessage) => {
const mermaidContent = message.content || "";
if (!mermaidContent.trim() || !mermaidToExcalidrawLib.loaded) {
return;
}
const tempDataRef = {
current: {
elements: [] as readonly NonDeletedExcalidrawElement[],
files: null as BinaryFiles | null,
},
};
const result = await convertMermaidToExcalidraw({
canvasRef,
data: tempDataRef,
mermaidToExcalidrawLib,
setError,
mermaidDefinition: mermaidContent,
theme: app.state.theme,
});
if (result.success) {
insertToEditor({
app,
data: tempDataRef,
text: mermaidContent,
shouldSaveMermaidDataToStorage: true,
});
}
};
const handleAiRepairClick = async (message: TChat.ChatMessage) => {
const mermaidContent = message.content || "";
const errorMessage = message.error || "";
if (!mermaidContent) {
return;
}
const repairPrompt = `Fix the error in this Mermaid diagram. The diagram is:\n\n\`\`\`mermaid\n${mermaidContent}\n\`\`\`\n\nThe exception/error is: ${errorMessage}\n\nPlease fix the Mermaid syntax and regenerate a valid diagram.`;
await onGenerate({ prompt: repairPrompt, isRepairFlow: true });
};
const handleRetry = async (message: TChat.ChatMessage) => {
const messageIndex = chatHistory.messages.findIndex(
(msg) => msg.id === message.id,
);
if (messageIndex > 0) {
const previousMessage = chatHistory.messages[messageIndex - 1];
if (
previousMessage.type === "user" &&
typeof previousMessage.content === "string"
) {
setLastRetryAttempt();
await onGenerate({
prompt: previousMessage.content,
isRepairFlow: true,
});
}
}
};
const handleInsertToEditor = () => {
insertToEditor({ app, data });
};
const handleDeleteMessage = (messageId: string) => {
const assistantMessageIndex = chatHistory.messages.findIndex(
(msg) => msg.id === messageId && msg.type === "assistant",
);
const remainingMessages = chatHistory.messages.slice(
0,
assistantMessageIndex - 1,
);
setChatHistory({
...chatHistory,
messages: remainingMessages,
});
};
const handlePromptChange = (newPrompt: string) => {
setChatHistory((prev) => ({
...prev,
currentPrompt: newPrompt,
}));
};
return (
<div
className={`ttd-dialog-layout ${
showPreview
? "ttd-dialog-layout--split"
: "ttd-dialog-layout--chat-only"
}`}
>
<TTDChatPanel
chatId={chatHistory.id}
messages={chatHistory.messages}
currentPrompt={chatHistory.currentPrompt}
onPromptChange={handlePromptChange}
onGenerate={onGenerate}
isGenerating={lastAssistantMessage?.isGenerating ?? false}
generatedResponse={lastAssistantMessage?.content}
isMenuOpen={isMenuOpen}
onMenuToggle={handleMenuToggle}
onMenuClose={handleMenuClose}
onNewChat={handleNewChat}
onRestoreChat={onRestoreChat}
onDeleteChat={handleDeleteChat}
savedChats={savedChats}
activeSessionId={chatHistory.id}
onAbort={handleAbort}
onMermaidTabClick={handleMermaidTabClick}
onAiRepairClick={handleAiRepairClick}
onDeleteMessage={handleDeleteMessage}
onInsertMessage={handleInsertMessage}
onRetry={handleRetry}
onViewAsMermaid={onViewAsMermaid}
renderWarning={renderWarning}
/>
{showPreview && (
<TTDPreviewPanel
canvasRef={canvasRef}
hideErrorDetails={lastAssistantMessage?.errorType === "parse"}
error={error}
loaded={mermaidToExcalidrawLib.loaded}
onInsert={handleInsertToEditor}
/>
)}
</div>
);
};
export const TextToDiagram = ({
mermaidToExcalidrawLib,
onTextSubmit,
renderWarning,
persistenceAdapter,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
onTextSubmit(
props: TTTDDialog.OnTextSubmitProps,
): Promise<TTTDDialog.OnTextSubmitRetValue>;
renderWarning?: TTTDDialog.renderWarning;
persistenceAdapter: TTDPersistenceAdapter;
}) => {
return (
<TextToDiagramContent
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
onTextSubmit={onTextSubmit}
renderWarning={renderWarning}
persistenceAdapter={persistenceAdapter}
/>
);
};
export default TextToDiagram;
@@ -1,18 +1,22 @@
import { DEFAULT_EXPORT_PADDING, EDITOR_LS_KEYS } from "@excalidraw/common";
import type { MermaidConfig } from "@excalidraw/mermaid-to-excalidraw";
import type { MermaidToExcalidrawResult } from "@excalidraw/mermaid-to-excalidraw/dist/interfaces";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import type {
NonDeletedExcalidrawElement,
Theme,
} from "@excalidraw/element/types";
import { EditorLocalStorage } from "../../data/EditorLocalStorage";
import { canvasToBlob } from "../../data/blob";
import { t } from "../../i18n";
import { convertToExcalidrawElements, exportToCanvas } from "../../index";
import {
convertToExcalidrawElements,
exportToCanvas,
THEME,
} from "../../index";
import type { MermaidToExcalidrawLibProps } from "./types";
import type { AppClassProperties, BinaryFiles } from "../../types";
const resetPreview = ({
export const resetPreview = ({
canvasRef,
setError,
}: {
@@ -33,17 +37,14 @@ const resetPreview = ({
canvasNode.replaceChildren();
};
export interface MermaidToExcalidrawLibProps {
loaded: boolean;
api: Promise<{
parseMermaidToExcalidraw: (
definition: string,
config?: MermaidConfig,
) => Promise<MermaidToExcalidrawResult>;
}>;
}
interface ConvertMermaidToExcalidrawFormatProps {
export const convertMermaidToExcalidraw = async ({
canvasRef,
mermaidToExcalidrawLib,
mermaidDefinition,
setError,
data,
theme,
}: {
canvasRef: React.RefObject<HTMLDivElement | null>;
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
mermaidDefinition: string;
@@ -52,38 +53,36 @@ interface ConvertMermaidToExcalidrawFormatProps {
elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles | null;
}>;
}
export const convertMermaidToExcalidraw = async ({
canvasRef,
mermaidToExcalidrawLib,
mermaidDefinition,
setError,
data,
}: ConvertMermaidToExcalidrawFormatProps) => {
theme: Theme;
}): Promise<{ success: true } | { success: false; error?: Error }> => {
const canvasNode = canvasRef.current;
const parent = canvasNode?.parentElement;
if (!canvasNode || !parent) {
return;
return { success: false };
}
if (!mermaidDefinition) {
resetPreview({ canvasRef, setError });
return;
return { success: false };
}
let ret;
try {
const api = await mermaidToExcalidrawLib.api;
let ret;
try {
ret = await api.parseMermaidToExcalidraw(mermaidDefinition);
} catch (err: any) {
ret = await api.parseMermaidToExcalidraw(
mermaidDefinition.replace(/"/g, "'"),
);
try {
ret = await api.parseMermaidToExcalidraw(mermaidDefinition);
} catch (err: unknown) {
ret = await api.parseMermaidToExcalidraw(
mermaidDefinition.replace(/"/g, "'"),
);
}
} catch (err: unknown) {
return { success: false, error: err as Error };
}
const { elements, files } = ret;
setError(null);
@@ -102,34 +101,23 @@ export const convertMermaidToExcalidraw = async ({
Math.max(parent.offsetWidth, parent.offsetHeight) *
window.devicePixelRatio,
appState: {
// TODO hack (will be refactored in TTD v2)
exportWithDarkMode: document
.querySelector(".excalidraw-container")
?.classList.contains("theme--dark"),
exportWithDarkMode: theme === THEME.DARK,
},
});
// if converting to blob fails, there's some problem that will
// likely prevent preview and export (e.g. canvas too big)
try {
await canvasToBlob(canvas);
} catch (e: any) {
if (e.name === "CANVAS_POSSIBLY_TOO_BIG") {
throw new Error(t("canvasError.canvasTooBig"));
}
throw e;
}
parent.style.background = "var(--default-bg-color)";
canvasNode.replaceChildren(canvas);
return { success: true };
} catch (err: any) {
parent.style.background = "var(--default-bg-color)";
if (mermaidDefinition) {
setError(err);
}
throw err;
// Return error so caller can display meaningful error message
return { success: false, error: err };
}
};
export const saveMermaidDataToStorage = (mermaidDefinition: string) => {
EditorLocalStorage.set(
EDITOR_LS_KEYS.MERMAID_TO_EXCALIDRAW,

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