Compare commits

..

1 Commits

Author SHA1 Message Date
dwelle 28cbe82a86 wip 2026-03-19 10:30:55 +01:00
34 changed files with 266 additions and 919 deletions
+2 -11
View File
@@ -465,12 +465,7 @@ export const intersectElementWithLineSegment = (
case "line":
case "freedraw":
case "arrow":
return intersectLinearOrFreeDrawWithLineSegment(
element,
line,
elementsMap,
onlyFirst,
);
return intersectLinearOrFreeDrawWithLineSegment(element, line, onlyFirst);
}
};
@@ -537,15 +532,11 @@ const lineIntersections = (
const intersectLinearOrFreeDrawWithLineSegment = (
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
segment: LineSegment<GlobalPoint>,
elementsMap: ElementsMap,
onlyFirst = false,
): GlobalPoint[] => {
// NOTE: This is the only one which return the decomposed elements
// rotated! This is due to taking advantage of roughjs definitions.
const [lines, curves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
const intersections: GlobalPoint[] = [];
for (const l of lines) {
+2 -6
View File
@@ -48,7 +48,7 @@ export const distanceToElement = (
case "line":
case "arrow":
case "freedraw":
return distanceToLinearOrFreeDraElement(element, elementsMap, p);
return distanceToLinearOrFreeDraElement(element, p);
}
};
@@ -133,13 +133,9 @@ const distanceToEllipseElement = (
const distanceToLinearOrFreeDraElement = (
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
p: GlobalPoint,
) => {
const [lines, curves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
return Math.min(
...lines.map((s) => distanceToLineSegment(p, s)),
...curves.map((a) => curvePointDistance(a, p)),
+14 -31
View File
@@ -476,22 +476,16 @@ export class LinearElementEditor {
});
}
if (
lastClickedPoint < 0 ||
!selectedPointsIndices.includes(lastClickedPoint) ||
!element.points[lastClickedPoint]
) {
console.error(
`There must be a valid lastClickedPoint in order to drag it. selectedPointsIndices(${JSON.stringify(
selectedPointsIndices,
)}) points(0..${
element.points.length - 1
}) lastClickedPoint(${lastClickedPoint})`,
);
// Fall back to the actual last point as a last resort.
lastClickedPoint = element.points.length - 1;
}
invariant(
lastClickedPoint > -1 &&
selectedPointsIndices.includes(lastClickedPoint) &&
element.points[lastClickedPoint],
`There must be a valid lastClickedPoint in order to drag it. selectedPointsIndices(${JSON.stringify(
selectedPointsIndices,
)}) points(0..${
element.points.length - 1
}) lastClickedPoint(${lastClickedPoint})`,
);
// point that's being dragged (out of all selected points)
const draggingPoint = element.points[lastClickedPoint];
@@ -800,7 +794,6 @@ export class LinearElementEditor {
element.points[index + 1],
index,
appState.zoom,
elementsMap,
)
) {
midpoints.push(null);
@@ -810,7 +803,6 @@ export class LinearElementEditor {
const segmentMidPoint = LinearElementEditor.getSegmentMidPoint(
element,
index + 1,
elementsMap,
);
midpoints.push(segmentMidPoint);
index++;
@@ -898,7 +890,6 @@ export class LinearElementEditor {
endPoint: P,
index: number,
zoom: Zoom,
elementsMap: ElementsMap,
) {
if (isElbowArrow(element)) {
if (index >= 0 && index < element.points.length) {
@@ -913,10 +904,7 @@ export class LinearElementEditor {
let distance = pointDistance(startPoint, endPoint);
if (element.points.length > 2 && element.roundness) {
const [lines, curves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
invariant(
lines.length === 0 && curves.length > 0,
@@ -936,7 +924,6 @@ export class LinearElementEditor {
static getSegmentMidPoint(
element: NonDeleted<ExcalidrawLinearElement>,
index: number,
elementsMap: ElementsMap,
): GlobalPoint {
if (isElbowArrow(element)) {
invariant(
@@ -949,10 +936,7 @@ export class LinearElementEditor {
return pointFrom<GlobalPoint>(element.x + p[0], element.y + p[1]);
}
const [lines, curves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
invariant(
(lines.length === 0 && curves.length > 0) ||
@@ -1867,7 +1851,6 @@ export class LinearElementEditor {
const midSegmentMidpoint = LinearElementEditor.getSegmentMidPoint(
element,
index + 1,
elementsMap,
);
x = midSegmentMidpoint[0] - boundTextElement.width / 2;
@@ -2417,7 +2400,7 @@ const pointDraggingUpdates = (
? nextArrow.points[0]
: endBindable
? updateBoundPoint(
nextArrow,
element,
"endBinding",
nextArrow.endBinding,
endBindable,
@@ -2448,7 +2431,7 @@ const pointDraggingUpdates = (
? endLocalPoint
: startBindable
? updateBoundPoint(
nextArrow,
element,
"startBinding",
nextArrow.startBinding,
startBindable,
-18
View File
@@ -11,7 +11,6 @@ import {
isBoundToContainer,
isFrameLikeElement,
isLinearElement,
isTextElement,
} from "./typeChecks";
import {
elementOverlapsWithFrame,
@@ -26,7 +25,6 @@ import type {
ElementsMap,
ElementsMapOrArray,
ExcalidrawElement,
NonDeleted,
NonDeletedExcalidrawElement,
} from "./types";
@@ -290,19 +288,3 @@ export const getSelectionStateForElements = (
),
};
};
/**
* Returns editing or single-selected text element, if any.
*/
export const getActiveTextElement = (
selectedElements: readonly NonDeleted<ExcalidrawElement>[],
appState: Pick<AppState, "editingTextElement">,
) => {
const activeTextElement =
appState.editingTextElement ||
(selectedElements.length === 1 &&
isTextElement(selectedElements[0]) &&
selectedElements[0]);
return activeTextElement || null;
};
+16 -7
View File
@@ -57,8 +57,8 @@ import { headingForPointIsHorizontal } from "./heading";
import { canChangeRoundness } from "./comparisons";
import {
elementCenterPoint,
getArrowheadPoints,
getCenterForBounds,
getDiamondPoints,
getElementAbsoluteCoords,
} from "./bounds";
@@ -583,11 +583,7 @@ const getArrowheadShapes = (
export const generateLinearCollisionShape = (
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
): {
op: string;
data: number[];
}[] => {
) => {
const generator = new RoughGenerator();
const options: Options = {
seed: element.seed,
@@ -596,7 +592,20 @@ export const generateLinearCollisionShape = (
roughness: 0,
preserveVertices: true,
};
const center = elementCenterPoint(element, elementsMap);
const center = getCenterForBounds(
// Need a non-rotated center point
element.points.reduce(
(acc, point) => {
return [
Math.min(element.x + point[0], acc[0]),
Math.min(element.y + point[1], acc[1]),
Math.max(element.x + point[0], acc[2]),
Math.max(element.y + point[1], acc[3]),
];
},
[Infinity, Infinity, -Infinity, -Infinity],
),
);
switch (element.type) {
case "line":
-1
View File
@@ -347,7 +347,6 @@ export const getContainerCenter = (
midSegmentMidpoint = LinearElementEditor.getSegmentMidPoint(
container,
index + 1,
elementsMap,
);
}
return { x: midSegmentMidpoint[0], y: midSegmentMidpoint[1] };
+4 -2
View File
@@ -124,7 +124,6 @@ const setElementShapesCacheEntry = <T extends ExcalidrawElement>(
*/
export function deconstructLinearOrFreeDrawElement(
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
const cachedShape = getElementShapesCacheEntry(element, 0);
@@ -132,7 +131,10 @@ export function deconstructLinearOrFreeDrawElement(
return cachedShape;
}
const ops = generateLinearCollisionShape(element, elementsMap);
const ops = generateLinearCollisionShape(element) as {
op: string;
data: number[];
}[];
const lines = [];
const curves = [];
@@ -191,7 +191,7 @@ export const getFormValue = function <T extends Primitive>(
elements: readonly ExcalidrawElement[],
app: AppClassProperties,
getAttribute: (element: ExcalidrawElement) => T,
elementPredicate: true | ((element: ExcalidrawElement) => boolean),
isRelevantElement: true | ((element: ExcalidrawElement) => boolean),
defaultValue: T | ((isSomeElementSelected: boolean) => T),
): T {
const editingTextElement = app.state.editingTextElement;
@@ -209,9 +209,9 @@ export const getFormValue = function <T extends Primitive>(
if (hasSelection) {
const selectedElements = app.scene.getSelectedElements(app.state);
const targetElements =
elementPredicate === true
isRelevantElement === true
? selectedElements
: selectedElements.filter((el) => elementPredicate(el));
: selectedElements.filter((el) => isRelevantElement(el));
ret =
reduceToCommonValue(targetElements, getAttribute) ??
@@ -730,28 +730,9 @@ export const actionChangeOpacity = register<ExcalidrawElement["opacity"]>({
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, app, updateData }) => {
const opacity = getFormValue(
elements,
app,
(element) => element.opacity,
true,
(hasSelection) => (hasSelection ? null : appState.currentItemOpacity),
);
return (
<Range
label={t("labels.opacity")}
value={opacity ?? appState.currentItemOpacity}
hasCommonValue={opacity !== null}
onChange={updateData}
min={0}
max={100}
step={10}
testId="opacity"
/>
);
},
PanelComponent: ({ app, updateData }) => (
<Range updateData={updateData} app={app} testId="opacity" />
),
});
export const actionChangeFontSize = register<ExcalidrawTextElement["fontSize"]>(
@@ -1,24 +1,24 @@
import { getFontString } from "@excalidraw/common";
import { isExcalidrawElement, newElementWith } from "@excalidraw/element";
import { newElementWith } from "@excalidraw/element";
import { measureText } from "@excalidraw/element";
import { isTextElement } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import type { ExcalidrawElement } from "@excalidraw/element/types";
import { getSelectedElements } from "../scene";
import { register } from "./register";
import type { AppClassProperties } from "../types";
export const actionTextAutoResize = register({
name: "autoResize",
label: "labels.autoResize",
icon: null,
trackEvent: { category: "element" },
predicate: (elements, appState, _: unknown) => {
predicate: (elements, appState, _: unknown, app: AppClassProperties) => {
const selectedElements = getSelectedElements(elements, appState);
return (
selectedElements.length === 1 &&
@@ -26,18 +26,13 @@ export const actionTextAutoResize = register({
!selectedElements[0].autoResize
);
},
perform: (elements, appState, targetElement) => {
perform: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(elements, appState);
const targetTextElement =
isExcalidrawElement(targetElement) && isTextElement(targetElement)
? targetElement
: (selectedElements[0] as ExcalidrawElement | undefined);
return {
appState,
elements: elements.map((element) => {
if (element.id === targetTextElement?.id && isTextElement(element)) {
if (element.id === selectedElements[0].id && isTextElement(element)) {
const metrics = measureText(
element.originalText,
getFontString(element),
+18 -128
View File
@@ -257,7 +257,6 @@ import {
handleFocusPointPointerUp,
maybeHandleArrowPointlikeDrag,
getUncroppedWidthAndHeight,
getActiveTextElement,
} from "@excalidraw/element";
import type { GlobalPoint, LocalPoint, Radians } from "@excalidraw/math";
@@ -417,7 +416,6 @@ import {
import { ElementCanvasButtons } from "../components/ElementCanvasButtons";
import { LaserTrails } from "../laser-trails";
import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
import { isPointHittingTextAutoResizeHandle } from "../textAutoResizeHandle";
import { textWysiwyg } from "../wysiwyg/textWysiwyg";
import { isOverScrollBars } from "../scene/scrollbars";
@@ -1256,26 +1254,6 @@ class App extends React.Component<AppProps, AppState> {
) as NullableGridSize;
};
private getTextCreationGridPoint = (x: number, y: number) => {
const effectiveGridSize = this.getEffectiveGridSize();
if (effectiveGridSize === null) {
return null;
}
const getTextCreationGridCoordinate = (coordinate: number) => {
const topLeftGridPoint =
Math.floor(coordinate / effectiveGridSize) * effectiveGridSize;
return topLeftGridPoint;
};
return {
x: getTextCreationGridCoordinate(x),
y: getTextCreationGridCoordinate(y),
};
};
private getHTMLIFrameElement(
element: ExcalidrawIframeLikeElement,
): HTMLIFrameElement | undefined {
@@ -5874,58 +5852,6 @@ class App extends React.Component<AppProps, AppState> {
return null;
}
private isHittingTextAutoResizeHandle = (
selectedElements: NonDeleted<ExcalidrawElement>[],
point: Readonly<{ x: number; y: number }>,
): boolean => {
const activeTextElement = getActiveTextElement(
selectedElements,
this.state,
);
if (
activeTextElement &&
!activeTextElement.isDeleted &&
!activeTextElement.autoResize &&
isPointHittingTextAutoResizeHandle(
point,
activeTextElement,
this.state.zoom.value,
this.editorInterface.formFactor,
)
) {
return true;
}
return false;
};
private handleTextAutoResizeHandlePointerDown = (
selectedElements: NonDeleted<ExcalidrawElement>[],
point: Readonly<{ x: number; y: number }>,
) => {
const activeTextElement = getActiveTextElement(
selectedElements,
this.state,
);
if (
!activeTextElement ||
!this.isHittingTextAutoResizeHandle(selectedElements, point)
) {
return false;
}
this.actionManager.executeAction(
actionTextAutoResize,
"ui",
// we need to pass down the element since it may already be deselected
// due to the pointerdown
activeTextElement,
);
this.resetCursor();
return true;
};
// NOTE: Hot path for hit testing, so avoid unnecessary computations
private getElementAtPosition(
x: number,
@@ -6218,32 +6144,11 @@ class App extends React.Component<AppProps, AppState> {
y: sceneY,
});
const textCreationGridPoint = this.getTextCreationGridPoint(sceneX, sceneY);
const newTextElementPosition = parentCenterPosition
? {
x: parentCenterPosition.elementCenterX,
y: parentCenterPosition.elementCenterY,
}
: !existingTextElement
? {
x: textCreationGridPoint?.x ?? sceneX,
y:
textCreationGridPoint === null
? // Free text starts from a point cursor, so center the first line box on it.
sceneY - getLineHeightInPx(fontSize, lineHeight) / 2
: textCreationGridPoint.y,
}
: {
x: sceneX,
y: sceneY,
};
const element =
existingTextElement ||
newTextElement({
x: newTextElementPosition.x,
y: newTextElementPosition.y,
x: parentCenterPosition ? parentCenterPosition.elementCenterX : sceneX,
y: parentCenterPosition ? parentCenterPosition.elementCenterY : sceneY,
strokeColor: this.state.currentItemStrokeColor,
backgroundColor: this.state.currentItemBackgroundColor,
fillStyle: this.state.currentItemFillStyle,
@@ -6995,23 +6900,27 @@ class App extends React.Component<AppProps, AppState> {
},
{ informMutation: false, isDragging: false },
);
const newLastIdx = multiElement.points.length - 1;
this.setState({
selectedLinearElement: {
...selectedLinearElement,
selectedPointsIndices: selectedLinearElement.selectedPointsIndices
? [
...new Set(
selectedLinearElement.selectedPointsIndices.map((idx) =>
Math.min(idx, newLastIdx),
selectedPointsIndices:
selectedLinearElement.selectedPointsIndices?.includes(
multiElement.points.length,
)
? [
...selectedLinearElement.selectedPointsIndices.filter(
(idx) =>
idx !== multiElement.points.length &&
idx !== multiElement.points.length - 1,
),
),
]
: selectedLinearElement.selectedPointsIndices,
lastCommittedPoint: multiElement.points[newLastIdx],
multiElement.points.length - 1,
]
: selectedLinearElement.selectedPointsIndices,
lastCommittedPoint:
multiElement.points[multiElement.points.length - 1],
initialState: {
...selectedLinearElement.initialState,
lastClickedPoint: newLastIdx,
lastClickedPoint: multiElement.points.length - 1,
},
},
});
@@ -7097,12 +7006,6 @@ class App extends React.Component<AppProps, AppState> {
const elements = this.scene.getNonDeletedElements();
const selectedElements = this.scene.getSelectedElements(this.state);
if (this.isHittingTextAutoResizeHandle(selectedElements, scenePointer)) {
setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
return;
}
if (
selectedElements.length === 1 &&
!isOverScrollBar &&
@@ -7247,9 +7150,7 @@ class App extends React.Component<AppProps, AppState> {
setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
} else if (
// if using cmd/ctrl, we're not dragging
!event[KEYS.CTRL_OR_CMD] &&
// editing text -> don't show move cursor when hovering over its bbox
hitElement?.id !== this.state.editingTextElement?.id
!event[KEYS.CTRL_OR_CMD]
) {
if (
(hitElement ||
@@ -7470,8 +7371,6 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerDown = (
event: React.PointerEvent<HTMLElement>,
) => {
const selectedElements = this.scene.getSelectedElements(this.state);
// If Ctrl is not held, ensure isBindingEnabled reflects the user preference.
if (!event.ctrlKey) {
const preferenceEnabled = this.state.bindingPreference === "enabled";
@@ -7695,15 +7594,6 @@ class App extends React.Component<AppProps, AppState> {
selectedElementsAreBeingDragged: false,
});
if (
this.handleTextAutoResizeHandlePointerDown(
selectedElements,
pointerDownState.origin,
)
) {
return;
}
if (this.handleDraggingScrollBar(event, pointerDownState)) {
return;
}
+33 -37
View File
@@ -1,78 +1,74 @@
import React, { useEffect } from "react";
import { t } from "../i18n";
import "./Range.scss";
import type { AppClassProperties } from "../types";
export type RangeProps = {
label: React.ReactNode;
value: number;
onChange: (value: number) => void;
min?: number;
max?: number;
step?: number;
minLabel?: React.ReactNode;
hasCommonValue?: boolean;
updateData: (value: number) => void;
app: AppClassProperties;
testId?: string;
};
export const Range = ({
label,
value,
onChange,
min = 0,
max = 100,
step = 10,
minLabel = min,
hasCommonValue = true,
testId,
}: RangeProps) => {
export const Range = ({ updateData, app, testId }: RangeProps) => {
const rangeRef = React.useRef<HTMLInputElement>(null);
const valueRef = React.useRef<HTMLDivElement>(null);
const selectedElements = app.scene.getSelectedElements(app.state);
let hasCommonOpacity = true;
const firstElement = selectedElements.at(0);
const leastCommonOpacity = selectedElements.reduce((acc, element) => {
if (acc != null && acc !== element.opacity) {
hasCommonOpacity = false;
}
if (acc == null || acc > element.opacity) {
return element.opacity;
}
return acc;
}, firstElement?.opacity ?? null);
const value = leastCommonOpacity ?? app.state.currentItemOpacity;
useEffect(() => {
if (rangeRef.current && valueRef.current) {
const rangeElement = rangeRef.current;
const valueElement = valueRef.current;
const inputWidth = rangeElement.offsetWidth;
const thumbWidth =
parseFloat(
getComputedStyle(rangeElement).getPropertyValue(
"--slider-thumb-size",
),
) || 16;
const progress = ((value - min) / (max - min || 1)) * 100;
const thumbWidth = 15; // 15 is the width of the thumb
const position =
(progress / 100) * (inputWidth - thumbWidth) + thumbWidth / 2;
(value / 100) * (inputWidth - thumbWidth) + thumbWidth / 2;
valueElement.style.left = `${position}px`;
rangeElement.style.background = `linear-gradient(to right, var(--color-slider-track) 0%, var(--color-slider-track) ${progress}%, var(--button-bg) ${progress}%, var(--button-bg) 100%)`;
rangeElement.style.background = `linear-gradient(to right, var(--color-slider-track) 0%, var(--color-slider-track) ${value}%, var(--button-bg) ${value}%, var(--button-bg) 100%)`;
}
}, [max, min, value]);
}, [value]);
return (
<label className="control-label">
{label}
{t("labels.opacity")}
<div className="range-wrapper">
<input
style={{
["--color-slider-track" as string]: hasCommonValue
["--color-slider-track" as string]: hasCommonOpacity
? undefined
: "var(--button-bg)",
}}
ref={rangeRef}
type="range"
min={min}
max={max}
step={step}
min="0"
max="100"
step="10"
onChange={(event) => {
onChange(+event.target.value);
updateData(+event.target.value);
}}
value={value}
className="range-input"
data-testid={testId}
/>
<div className="value-bubble" ref={valueRef}>
{value !== min ? value : null}
{value !== 0 ? value : null}
</div>
<div className="zero-label">{minLabel}</div>
<div className="zero-label">0</div>
</div>
</label>
);
@@ -3,25 +3,7 @@
$verticalBreakpoint: 861px;
.excalidraw {
--ttd-mermaid-token-keyword: #0000ff;
--ttd-mermaid-token-string: #a31515;
--ttd-mermaid-token-comment: #008000;
--ttd-mermaid-token-number: #098658;
--ttd-mermaid-token-operator: #1e1e1e;
--ttd-mermaid-token-punctuation: #1e1e1e;
--ttd-mermaid-token-variable-name: #001080;
--ttd-mermaid-token-bracket: #af00db;
&.theme--dark {
--ttd-mermaid-token-keyword: #569cd6;
--ttd-mermaid-token-string: #ce9178;
--ttd-mermaid-token-comment: #6a9955;
--ttd-mermaid-token-number: #b5cea8;
--ttd-mermaid-token-operator: #d4d4d4;
--ttd-mermaid-token-punctuation: #d4d4d4;
--ttd-mermaid-token-variable-name: #9cdcfe;
--ttd-mermaid-token-bracket: #ffd700;
.chat-message {
&--assistant {
.chat-message__content {
@@ -212,7 +194,7 @@ $verticalBreakpoint: 861px;
align-items: flex-start;
.chat-message__content {
background: #f7f7f7;
background: var(--color-surface-low);
color: var(--color-on-surface);
border-radius: var(--border-radius-md);
min-width: 6rem;
@@ -310,51 +292,6 @@ $verticalBreakpoint: 861px;
word-wrap: break-word;
}
&__text--error {
color: inherit;
}
&__text--mermaid {
overflow-x: auto;
font-weight: 400;
}
&__token {
white-space: inherit;
}
&__token--keyword {
color: var(--ttd-mermaid-token-keyword);
}
&__token--string {
color: var(--ttd-mermaid-token-string);
}
&__token--comment {
color: var(--ttd-mermaid-token-comment);
}
&__token--number {
color: var(--ttd-mermaid-token-number);
}
&__token--operator {
color: var(--ttd-mermaid-token-operator);
}
&__token--punctuation {
color: var(--ttd-mermaid-token-punctuation);
}
&__token--variableName {
color: var(--ttd-mermaid-token-variable-name);
}
&__token--bracket {
color: var(--ttd-mermaid-token-bracket);
}
&__cursor {
display: inline-block;
margin-left: 2px;
@@ -395,13 +332,11 @@ $verticalBreakpoint: 861px;
&__error {
color: var(--color-danger);
font-weight: 500;
white-space: pre-wrap;
word-wrap: break-word;
display: flex;
flex-direction: column;
gap: 0.5rem;
.chat-message__text--mermaid {
color: var(--color-on-surface);
}
}
&__error_message {
@@ -5,49 +5,8 @@ import { t } from "../../../i18n";
import { FilledButton } from "../../FilledButton";
import { TrashIcon, codeIcon, stackPushIcon, RetryIcon } from "../../icons";
import { tokenizeMermaid } from "../mermaid-highlighting";
import type { TChat, TTTDDialog } from "../types";
const isMermaidMessage = (message: TChat.ChatMessage) =>
message.contentFormat === "mermaid";
const renderMessageContent = (
message: TChat.ChatMessage,
className: string,
) => {
const content = message.content ?? "";
console.log("@", message);
if (!isMermaidMessage(message)) {
return (
<div className={className}>
{content}
{message.isGenerating && (
<span className="chat-message__cursor"></span>
)}
</div>
);
}
return (
<div className={clsx(className, "chat-message__text--mermaid")}>
{tokenizeMermaid(content).map((token, index) => (
<span
key={`${index}-${token.type ?? "text"}-${token.value}`}
className={clsx("chat-message__token", {
[`chat-message__token--${token.type}`]: token.type,
})}
>
{token.value}
</span>
))}
{message.isGenerating && <span className="chat-message__cursor"></span>}
</div>
);
};
export const ChatMessage: React.FC<{
message: TChat.ChatMessage;
onMermaidTabClick?: (message: TChat.ChatMessage) => void;
@@ -163,14 +122,7 @@ export const ChatMessage: React.FC<{
<div className="chat-message__body">
{message.error ? (
<>
<div className="chat-message__error">
{renderMessageContent(
message,
clsx("chat-message__text", {
"chat-message__text--error": !isMermaidMessage(message),
}),
)}
</div>
<div className="chat-message__error">{message.content}</div>
{message.errorType !== "parse" && (
<div className="chat-message__error_message">
Error: {message.error || t("chat.errors.generationFailed")}
@@ -180,7 +132,7 @@ export const ChatMessage: React.FC<{
<div className="chat-message__error_message">
<p>{t("chat.errors.invalidDiagram")}</p>
<div className="chat-message__error-actions">
{onMermaidTabClick && isMermaidMessage(message) && (
{onMermaidTabClick && (
<button
className="chat-message__error-link"
onClick={() => onMermaidTabClick(message)}
@@ -204,13 +156,18 @@ export const ChatMessage: React.FC<{
)}
</>
) : (
renderMessageContent(message, "chat-message__text")
<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 && isMermaidMessage(message) && (
{!message.error && onInsertMessage && (
<button
className="chat-message__action"
onClick={() => onInsertMessage(message)}
@@ -221,7 +178,7 @@ export const ChatMessage: React.FC<{
{stackPushIcon}
</button>
)}
{onMermaidTabClick && isMermaidMessage(message) && message.content && (
{onMermaidTabClick && message.content && (
<button
className="chat-message__action"
onClick={() => onMermaidTabClick(message)}
@@ -25,7 +25,6 @@ export const TTDChatPanel = ({
onGenerate,
isGenerating,
generatedResponse,
generatedResponseFormat,
isMenuOpen,
onMenuToggle,
onMenuClose,
@@ -51,7 +50,6 @@ export const TTDChatPanel = ({
onGenerate: TTTDDialog.OnGenerate;
isGenerating: boolean;
generatedResponse: string | null | undefined;
generatedResponseFormat?: TChat.ChatMessage["contentFormat"];
isMenuOpen: boolean;
onMenuToggle: () => void;
@@ -91,7 +89,7 @@ export const TTDChatPanel = ({
});
}
if (generatedResponse && generatedResponseFormat === "mermaid") {
if (generatedResponse) {
actions.push({
action: onViewAsMermaid,
label: t("chat.viewAsMermaid"),
@@ -25,7 +25,6 @@ export const useChatAgent = () => {
{
type: "assistant",
content: "",
contentFormat: "mermaid",
isGenerating: true,
},
]),
@@ -1,21 +1,13 @@
import { useEffect, useRef } from "react";
import {
Decoration,
type DecorationSet,
EditorView,
ViewPlugin,
type ViewUpdate,
keymap,
lineNumbers,
placeholder as cmPlaceholder,
drawSelection,
} from "@codemirror/view";
import {
Compartment,
EditorState,
type Extension,
type Range,
} from "@codemirror/state";
import { Compartment, EditorState, type Extension } from "@codemirror/state";
import {
defaultKeymap,
history,
@@ -48,13 +40,6 @@ const darkTheme = EditorView.theme(
},
".cm-content": { caretColor: "#fff" },
".cm-cursor": { borderLeftColor: "#fff" },
".cm-selectionBackground": {
backgroundColor: "rgba(86, 156, 214, 0.3)",
},
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":
{
backgroundColor: "rgba(86, 156, 214, 0.42)",
},
".cm-gutters": {
backgroundColor: "#1e1e1e",
color: "#858585",
@@ -63,10 +48,6 @@ const darkTheme = EditorView.theme(
".cm-activeLineGutter": { backgroundColor: "#2a2a2a" },
".cm-activeLine": { backgroundColor: "#2a2a2a" },
".cm-errorLine": { backgroundColor: "rgba(255, 0, 0, 0.15)" },
".cm-selectedWordMatch": {
backgroundColor: "rgba(255, 209, 102, 0.22)",
borderRadius: "2px",
},
},
{ dark: true },
);
@@ -99,10 +80,6 @@ const lightTheme = EditorView.theme({
".cm-activeLineGutter": { backgroundColor: "#e8e8e8" },
".cm-activeLine": { backgroundColor: "#e8e8e8" },
".cm-errorLine": { backgroundColor: "rgba(255, 0, 0, 0.1)" },
".cm-selectedWordMatch": {
backgroundColor: "rgba(255, 209, 102, 0.35)",
borderRadius: "2px",
},
});
const lightHighlight = HighlightStyle.define([
@@ -119,79 +96,6 @@ const lightHighlight = HighlightStyle.define([
// ---- Error line decoration ----
const errorLineDeco = Decoration.line({ class: "cm-errorLine" });
const selectedWordMatchDeco = Decoration.mark({
class: "cm-selectedWordMatch",
});
const getSelectedWordMatchText = (state: EditorState) => {
const mainSelection = state.selection.main;
if (state.selection.ranges.length !== 1 || mainSelection.empty) {
return null;
}
const selectedWord = state.wordAt(mainSelection.from);
if (
!selectedWord ||
selectedWord.from !== mainSelection.from ||
selectedWord.to !== mainSelection.to
) {
return null;
}
return state.sliceDoc(mainSelection.from, mainSelection.to);
};
const getSelectedWordMatchDecorations = (view: EditorView): DecorationSet => {
const selectedWord = getSelectedWordMatchText(view.state);
if (!selectedWord) {
return Decoration.none;
}
const selection = view.state.selection.main;
const ranges: Range<Decoration>[] = [];
const doc = view.state.doc.toString();
let searchFrom = 0;
while (searchFrom <= doc.length - selectedWord.length) {
const matchFrom = doc.indexOf(selectedWord, searchFrom);
if (matchFrom === -1) {
break;
}
const matchTo = matchFrom + selectedWord.length;
const matchWord = view.state.wordAt(matchFrom);
if (
matchWord?.from === matchFrom &&
matchWord.to === matchTo &&
(matchFrom !== selection.from || matchTo !== selection.to)
) {
ranges.push(selectedWordMatchDeco.range(matchFrom, matchTo));
}
searchFrom = matchTo;
}
return ranges.length ? Decoration.set(ranges) : Decoration.none;
};
const selectedWordMatchExtension = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = getSelectedWordMatchDecorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.selectionSet) {
this.decorations = getSelectedWordMatchDecorations(update.view);
}
}
},
{
decorations: (value) => value.decorations,
},
);
const getErrorLineExtension = (
errorLine: number | null | undefined,
@@ -268,7 +172,6 @@ const CodeMirrorEditor = ({
errorLineCompartmentRef.current.of([]),
mermaidLite(),
drawSelection({ drawRangeCursor: true }),
selectedWordMatchExtension,
...(placeholder ? [cmPlaceholder(placeholder)] : []),
],
}),
@@ -80,10 +80,7 @@ const TextToDiagramContent = ({
} = useChatManagement({ persistenceAdapter });
const onViewAsMermaid = () => {
if (
lastAssistantMessage?.contentFormat === "mermaid" &&
typeof lastAssistantMessage.content === "string"
) {
if (typeof lastAssistantMessage?.content === "string") {
saveMermaidDataToStorage(lastAssistantMessage.content);
setAppState({
openDialog: { name: "ttd", tab: "mermaid" },
@@ -209,7 +206,6 @@ const TextToDiagramContent = ({
onGenerate={onGenerate}
isGenerating={lastAssistantMessage?.isGenerating ?? false}
generatedResponse={lastAssistantMessage?.content}
generatedResponseFormat={lastAssistantMessage?.contentFormat}
isMenuOpen={isMenuOpen}
onMenuToggle={handleMenuToggle}
onMenuClose={handleMenuClose}
@@ -88,7 +88,6 @@ export const useTextGeneration = ({
updateAssistantContent(prev, {
isGenerating: true,
content: "",
contentFormat: "mermaid",
error: undefined,
errorType: undefined,
errorDetails: undefined,
@@ -1,40 +0,0 @@
import {
getMermaidHighlightToken,
tokenizeMermaid,
} from "./mermaid-highlighting";
describe("mermaid highlighting", () => {
it("tokenizes mermaid syntax with shared token types", () => {
const tokens = tokenizeMermaid('flowchart LR\nA["Hello"] --> B');
expect(tokens).toEqual([
{ type: "keyword", value: "flowchart" },
{ type: null, value: " " },
{ type: "keyword", value: "LR" },
{ type: null, value: "\n" },
{ type: "variableName", value: "A" },
{ type: "bracket", value: "[" },
{ type: "string", value: '"Hello"' },
{ type: "bracket", value: "]" },
{ type: null, value: " " },
{ type: "operator", value: "-->" },
{ type: null, value: " " },
{ type: "variableName", value: "B" },
]);
});
it("limits comment tokens to a single line", () => {
const tokens = tokenizeMermaid("%% comment\nflowchart TD");
expect(tokens[0]).toEqual({ type: "comment", value: "%% comment" });
expect(tokens[1]).toEqual({ type: null, value: "\n" });
expect(tokens[2]).toEqual({ type: "keyword", value: "flowchart" });
});
it("falls back to plain text for unsupported characters", () => {
expect(getMermaidHighlightToken("@node")).toEqual({
type: null,
value: "@",
});
});
});
@@ -1,79 +0,0 @@
export type MermaidHighlightTokenType =
| "bracket"
| "comment"
| "keyword"
| "number"
| "operator"
| "punctuation"
| "string"
| "variableName";
export type MermaidHighlightToken = {
type: MermaidHighlightTokenType | null;
value: string;
};
const DIAGRAM_TYPE_PATTERN =
/^(flowchart|graph|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|mindmap|journey|gitGraph|timeline|quadrantChart|sankey|xychart)\b/i;
const DIRECTION_PATTERN = /^(TB|TD|BT|RL|LR)\b/;
const KEYWORD_PATTERN =
/^(subgraph|end|participant|actor|loop|alt|else|opt|par|critical|break|rect|note|over|activate|deactivate|title|section|class|style|linkStyle|classDef|click)\b/i;
const MERMAID_TOKEN_RULES: ReadonlyArray<{
pattern: RegExp;
type: MermaidHighlightTokenType | null;
}> = [
{ pattern: /^%%[^\n]*/, type: "comment" },
{ pattern: /^"(?:[^"\\]|\\.)*"/, type: "string" },
{ pattern: DIAGRAM_TYPE_PATTERN, type: "keyword" },
{ pattern: DIRECTION_PATTERN, type: "keyword" },
{ pattern: KEYWORD_PATTERN, type: "keyword" },
{ pattern: /^[-.=<>|ox]+>/, type: "operator" },
{ pattern: /^<[-.=<>|ox]+/, type: "operator" },
{ pattern: /^(--+|\.\.+|==+)/, type: "operator" },
{ pattern: /^[[\](){}|<>]/, type: "bracket" },
{ pattern: /^[A-Za-z_][A-Za-z0-9_]*/, type: "variableName" },
{ pattern: /^\d+(\.\d+)?/, type: "number" },
{ pattern: /^[,:;]/, type: "punctuation" },
{ pattern: /^\s+/, type: null },
];
export const getMermaidHighlightToken = (
input: string,
): MermaidHighlightToken | null => {
if (!input) {
return null;
}
for (const rule of MERMAID_TOKEN_RULES) {
const match = input.match(rule.pattern);
if (match) {
return {
type: rule.type,
value: match[0],
};
}
}
return {
type: null,
value: input[0],
};
};
export const tokenizeMermaid = (input: string): MermaidHighlightToken[] => {
const tokens: MermaidHighlightToken[] = [];
let remaining = input;
while (remaining) {
const token = getMermaidHighlightToken(remaining);
if (!token) {
break;
}
tokens.push(token);
remaining = remaining.slice(token.value.length);
}
return tokens;
};
@@ -1,17 +1,79 @@
import { StreamLanguage } from "@codemirror/language";
import { getMermaidHighlightToken } from "./mermaid-highlighting";
const mermaidStreamParser = StreamLanguage.define({
token(stream) {
const token = getMermaidHighlightToken(stream.string.slice(stream.pos));
if (!token) {
stream.skipToEnd();
// Comments: %%...
if (stream.match(/^%%.*$/)) {
return "comment";
}
// Strings
if (stream.match(/^"(?:[^"\\]|\\.)*"/)) {
return "string";
}
// Diagram type keywords (at start of line or after whitespace)
if (
stream.match(
/^(flowchart|graph|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|mindmap|journey|gitGraph|timeline|quadrantChart|sankey|xychart)\b/i,
)
) {
return "keyword";
}
// Direction keywords
if (stream.match(/^(TB|TD|BT|RL|LR)\b/)) {
return "keyword";
}
// Keywords
if (
stream.match(
/^(subgraph|end|participant|actor|loop|alt|else|opt|par|critical|break|rect|note|over|activate|deactivate|title|section|class|style|linkStyle|classDef|click)\b/i,
)
) {
return "keyword";
}
// Arrows: -->, ---, -.->, ===>, etc.
if (stream.match(/^[-.=<>|ox]+>/)) {
return "operator";
}
if (stream.match(/^<[-.=<>|ox]+/)) {
return "operator";
}
if (stream.match(/^--+|\.\.+|==+/)) {
return "operator";
}
// Labels in brackets/parens: [text], (text), {text}, ((text)), etc.
if (stream.match(/^[[\](){}|<>]/)) {
return "bracket";
}
// Node IDs (alphanumeric)
if (stream.match(/^[A-Za-z_][A-Za-z0-9_]*/)) {
return "variableName";
}
// Numbers
if (stream.match(/^\d+(\.\d+)?/)) {
return "number";
}
// Punctuation
if (stream.match(/^[,:;]/)) {
return "punctuation";
}
// Skip whitespace
if (stream.eatSpace()) {
return null;
}
stream.pos += token.value.length;
return token.type;
// Skip any other character
stream.next();
return null;
},
});
@@ -18,8 +18,6 @@ export type MermaidData = {
files: BinaryFiles | null;
};
export type ChatMessageContentFormat = "text" | "mermaid";
export interface RateLimits {
rateLimit: number;
rateLimitRemaining: number;
@@ -35,7 +33,6 @@ export namespace TChat {
errorType?: "parse" | "network" | "other";
lastAttemptAt?: number;
type: "user" | "assistant" | "warning";
contentFormat?: ChatMessageContentFormat;
warningType?: /* daily rate limit */
"messageLimitExceeded" | /* general 429 */ "rateLimitExceeded";
content?: string;
@@ -7,17 +7,6 @@ import { chatHistoryAtom } from "./TTDContext";
import type { SavedChat, SavedChats, TTDPersistenceAdapter } from "./types";
const normalizePersistedChat = (chat: SavedChat): SavedChat => ({
...chat,
messages: chat.messages.map((message) => ({
...message,
// Legacy TTD chats predate explicit content format metadata.
contentFormat:
message.contentFormat ??
(message.type === "assistant" ? "mermaid" : undefined),
})),
});
interface UseTTDChatStorageProps {
persistenceAdapter: TTDPersistenceAdapter;
}
@@ -67,7 +56,7 @@ export const useTTDChatStorage = ({
setIsLoading(true);
try {
const chats = await persistenceAdapter.loadChats();
setSavedChats(chats.map(normalizePersistedChat));
setSavedChats(chats);
setChatsLoaded(true);
} catch (error) {
console.warn("Failed to load chats:", error);
@@ -117,28 +117,6 @@ describe("chat utils", () => {
expect(result.messages[0].errorType).toBe("network");
});
it("should update content format when provided", () => {
const chatHistory: TChat.ChatHistory = {
id: "chat-1",
currentPrompt: "",
messages: [
{
id: "1",
type: "assistant",
content: "graph TD",
timestamp: new Date("2024-01-01"),
contentFormat: "text",
},
],
};
const result = updateAssistantContent(chatHistory, {
contentFormat: "mermaid",
});
expect(result.messages[0].contentFormat).toBe("mermaid");
});
it("should return unchanged chatHistory if no assistant message exists", () => {
const chatHistory: TChat.ChatHistory = {
id: "chat-1",
@@ -379,7 +357,6 @@ describe("chat utils", () => {
{
type: "assistant",
content: "Message",
contentFormat: "mermaid",
isGenerating: true,
error: "Error text",
errorType: "parse",
@@ -387,7 +364,6 @@ describe("chat utils", () => {
]);
expect(result.messages[0].isGenerating).toBe(true);
expect(result.messages[0].contentFormat).toBe("mermaid");
expect(result.messages[0].error).toBe("Error text");
expect(result.messages[0].errorType).toBe("parse");
});
+1 -3
View File
@@ -251,9 +251,7 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
};
}
console.error(
`Could not repair binding for element "${boundElement?.id}" out of (${elementsMap?.size}) elements`,
);
console.error(`could not repair binding for element`);
} catch (error) {
console.error("Error repairing binding:", error);
}
-2
View File
@@ -382,8 +382,6 @@ export { DiagramToCodePlugin } from "./components/DiagramToCodePlugin/DiagramToC
export { getDataURL } from "./data/blob";
export { isElementLink } from "@excalidraw/element";
export { Fonts } from "./fonts/Fonts";
export { setCustomTextMetricsProvider } from "@excalidraw/element";
export { CommandPalette } from "./components/CommandPalette/CommandPalette";
@@ -41,7 +41,6 @@ import {
maxBindingDistance_simple,
isTextElement,
LinearElementEditor,
getActiveTextElement,
} from "@excalidraw/element";
import { renderSelectionElement } from "@excalidraw/element";
@@ -59,8 +58,6 @@ import {
isFocusPointVisible,
} from "@excalidraw/element";
import type { EditorInterface } from "@excalidraw/common";
import type {
TransformHandles,
TransformHandleType,
@@ -89,10 +86,6 @@ import {
} from "../scene/scrollbars";
import { getClientColor, renderRemoteCursors } from "../clients";
import {
getTextAutoResizeHandle,
getTextBoxPadding,
} from "../textAutoResizeHandle";
import {
bootstrapCanvas,
@@ -1156,7 +1149,6 @@ const renderLinearPointHandles = (
points[idx],
idx,
appState.zoom,
elementsMap,
)
) {
renderSingleLinearPoint(
@@ -1497,58 +1489,21 @@ const renderTextBox = (
selectionColor: InteractiveCanvasRenderConfig["selectionColor"],
) => {
context.save();
const padding = getTextBoxPadding(appState.zoom.value);
const padding = (DEFAULT_TRANSFORM_HANDLE_SPACING * 2) / appState.zoom.value;
const width = text.width + padding * 2;
const height = text.height + padding * 2;
const cx = text.x + text.width / 2;
const cy = text.y + text.height / 2;
const shiftX = -(text.width / 2 + padding);
const shiftY = -(text.height / 2 + padding);
const cx = text.x + width / 2;
const cy = text.y + height / 2;
const shiftX = -(width / 2 + padding);
const shiftY = -(height / 2 + padding);
context.translate(cx + appState.scrollX, cy + appState.scrollY);
context.rotate(text.angle);
context.lineWidth = 1 / appState.zoom.value;
context.strokeStyle = selectionColor;
context.globalAlpha = 0.5;
context.setLineDash([6 / appState.zoom.value, 4 / appState.zoom.value]);
context.strokeRect(shiftX, shiftY, width, height);
context.restore();
};
const renderResetAutoResizeHandle = (
text: NonDeleted<ExcalidrawTextElement>,
context: CanvasRenderingContext2D,
appState: InteractiveCanvasAppState,
selectionColor: InteractiveCanvasRenderConfig["selectionColor"],
formFactor: EditorInterface["formFactor"],
) => {
const autoResizeHandle = getTextAutoResizeHandle(
text,
appState.zoom.value,
formFactor,
);
if (!autoResizeHandle) {
return;
}
context.save();
context.globalAlpha = 0.5;
context.lineWidth = 1.5 / appState.zoom.value;
context.lineCap = "round";
context.strokeStyle = selectionColor;
context.beginPath();
context.moveTo(
autoResizeHandle.start[0] + appState.scrollX,
autoResizeHandle.start[1] + appState.scrollY,
);
context.lineTo(
autoResizeHandle.end[0] + appState.scrollX,
autoResizeHandle.end[1] + appState.scrollY,
);
context.stroke();
context.restore();
};
const _renderInteractiveScene = ({
app,
canvas,
@@ -1629,19 +1584,10 @@ const _renderInteractiveScene = ({
}
}
const activeTextElement = getActiveTextElement(selectedElements, appState);
if (activeTextElement && !activeTextElement.autoResize) {
renderResetAutoResizeHandle(
activeTextElement,
context,
appState,
renderConfig.selectionColor,
editorInterface.formFactor,
);
}
if (appState.editingTextElement) {
if (
appState.editingTextElement &&
isTextElement(appState.editingTextElement)
) {
const textElement = allElementsMap.get(appState.editingTextElement.id) as
| ExcalidrawTextElement
| undefined;
@@ -224,7 +224,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"strokeWidth": 2,
"type": "arrow",
"updated": 1,
"version": 22,
"version": 29,
"width": "94.00000",
"x": 0,
"y": 0,
@@ -350,9 +350,8 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
],
"mode": "orbit",
},
"version": 21,
"version": 28,
"width": "88.00000",
"y": "7.20923",
},
"inserted": {
"endBinding": {
@@ -382,9 +381,8 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
],
"mode": "orbit",
},
"version": 20,
"version": 25,
"width": "88.00000",
"y": "0.01000",
},
},
},
@@ -439,7 +437,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
],
],
"startBinding": null,
"version": 22,
"version": 29,
"width": "94.00000",
"x": 0,
"y": 0,
@@ -464,7 +462,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
],
"mode": "orbit",
},
"version": 21,
"version": 28,
"width": "88.00000",
"x": 6,
"y": "7.20923",
@@ -1362,9 +1360,9 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"strokeWidth": 2,
"type": "arrow",
"updated": 1,
"version": 7,
"version": 8,
"width": 88,
"x": "6.00000",
"x": 6,
"y": "2.00947",
}
`;
@@ -1539,12 +1537,12 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
],
"mode": "orbit",
},
"version": 7,
"version": 8,
},
"inserted": {
"endBinding": null,
"startBinding": null,
"version": 6,
"version": 7,
},
},
},
@@ -1724,7 +1722,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"updated": 1,
"version": 8,
"width": 88,
"x": "6.00000",
"x": 6,
"y": "38.80379",
}
`;
@@ -1869,7 +1867,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"type": "arrow",
"version": 8,
"width": 88,
"x": "6.00000",
"x": 6,
"y": "38.80379",
},
"inserted": {
@@ -2418,7 +2416,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"strokeWidth": 2,
"type": "arrow",
"updated": 1,
"version": 11,
"version": 12,
"width": 488,
"x": 6,
"y": "-5.39000",
@@ -2583,7 +2581,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "arrow",
"version": 11,
"version": 12,
"width": 488,
"x": 6,
"y": "-5.39000",
@@ -16638,7 +16636,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": 0,
"height": "0.00120",
"index": "a3",
"isDeleted": false,
"link": null,
@@ -16651,7 +16649,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
],
[
"88.00000",
0,
"0.00120",
],
],
"roughness": 1,
@@ -16674,7 +16672,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"version": 7,
"width": "88.00000",
"x": 6,
"y": "0.01000",
"y": "0.00880",
},
"inserted": {
"isDeleted": true,
@@ -18652,7 +18650,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": 0,
"height": "0.00120",
"index": "a3",
"isDeleted": false,
"link": null,
@@ -18665,7 +18663,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
],
[
"88.00000",
0,
"0.00120",
],
],
"roughness": 1,
@@ -18688,7 +18686,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"version": 7,
"width": "88.00000",
"x": 6,
"y": "0.01000",
"y": "0.00880",
},
"inserted": {
"isDeleted": true,
@@ -19400,7 +19398,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": 0,
"height": "0.00120",
"index": "a3",
"isDeleted": false,
"link": null,
@@ -19413,7 +19411,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
],
[
"88.00000",
0,
"0.00120",
],
],
"roughness": 1,
@@ -19436,7 +19434,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"version": 7,
"width": "88.00000",
"x": 6,
"y": "0.01000",
"y": "0.00880",
},
"inserted": {
"isDeleted": true,
+2 -12
View File
@@ -4,7 +4,6 @@ import {
elementCenterPoint,
getCommonBounds,
getElementPointsCoords,
getLineHeightInPx,
} from "@excalidraw/element";
import { cropElement } from "@excalidraw/element";
import {
@@ -21,7 +20,7 @@ import {
isTextElement,
isFrameLikeElement,
} from "@excalidraw/element";
import { KEYS, arrayToMap, getLineHeight } from "@excalidraw/common";
import { KEYS, arrayToMap } from "@excalidraw/common";
import type { GlobalPoint, LocalPoint, Radians } from "@excalidraw/math";
@@ -517,17 +516,8 @@ export class UI {
UI.clickTool(type);
if (type === "text") {
const clickY = h.state.gridModeEnabled
? y
: y +
getLineHeightInPx(
h.state.currentItemFontSize,
getLineHeight(h.state.currentItemFontFamily),
) /
2;
mouse.reset();
mouse.click(x, clickY);
mouse.click(x, y);
} else if ((type === "line" || type === "arrow") && points.length > 2) {
points.forEach((point) => {
mouse.reset();
@@ -1,88 +0,0 @@
import { DEFAULT_TRANSFORM_HANDLE_SPACING } from "@excalidraw/common";
import {
pointFrom,
pointRotateRads,
type GlobalPoint,
type Radians,
} from "@excalidraw/math";
import type { EditorInterface } from "@excalidraw/common";
import type { ExcalidrawTextElement } from "@excalidraw/element/types";
const TEXT_AUTO_RESIZE_HANDLE_GAP = 12;
const TEXT_AUTO_RESIZE_HANDLE_LENGTH = 16;
const TEXT_AUTO_RESIZE_HANDLE_HITBOX_WIDTH = 10;
const TEXT_AUTO_RESIZE_HANDLE_HITBOX_HEIGHT =
TEXT_AUTO_RESIZE_HANDLE_LENGTH + 2;
const MAX_HANDLE_HEIGHT_RATIO = 0.8;
export const getTextBoxPadding = (zoomValue: number) =>
(DEFAULT_TRANSFORM_HANDLE_SPACING * 2) / zoomValue;
export const getTextAutoResizeHandle = (
textElement: ExcalidrawTextElement,
zoomValue: number,
formFactor: EditorInterface["formFactor"],
) => {
if (
formFactor !== "desktop" ||
TEXT_AUTO_RESIZE_HANDLE_LENGTH >
textElement.height * zoomValue * MAX_HANDLE_HEIGHT_RATIO
) {
return null;
}
const padding = getTextBoxPadding(zoomValue);
const gap = TEXT_AUTO_RESIZE_HANDLE_GAP / zoomValue;
const length = TEXT_AUTO_RESIZE_HANDLE_LENGTH / zoomValue;
const center = pointFrom(
textElement.x + textElement.width / 2,
textElement.y + textElement.height / 2,
);
const handleCenter = pointRotateRads(
pointFrom(center[0] + textElement.width / 2 + padding + gap, center[1]),
center,
textElement.angle,
);
return {
center: handleCenter,
start: pointRotateRads(
pointFrom(handleCenter[0], handleCenter[1] - length / 2),
handleCenter,
textElement.angle,
) as GlobalPoint,
end: pointRotateRads(
pointFrom(handleCenter[0], handleCenter[1] + length / 2),
handleCenter,
textElement.angle,
) as GlobalPoint,
hitboxWidth: TEXT_AUTO_RESIZE_HANDLE_HITBOX_WIDTH / zoomValue,
hitboxHeight: TEXT_AUTO_RESIZE_HANDLE_HITBOX_HEIGHT / zoomValue,
};
};
export const isPointHittingTextAutoResizeHandle = (
point: Readonly<{ x: number; y: number }>,
textElement: ExcalidrawTextElement,
zoomValue: number,
formFactor: EditorInterface["formFactor"],
) => {
const handle = getTextAutoResizeHandle(textElement, zoomValue, formFactor);
if (!handle) {
return false;
}
const unrotatedPoint = pointRotateRads(
pointFrom(point.x, point.y),
handle.center,
-textElement.angle as Radians,
);
return (
Math.abs(unrotatedPoint[0] - handle.center[0]) <= handle.hitboxWidth / 2 &&
Math.abs(unrotatedPoint[1] - handle.center[1]) <= handle.hitboxHeight / 2
);
};
+4 -4
View File
@@ -32,7 +32,6 @@ import type {
OrderedExcalidrawElement,
ExcalidrawNonSelectionElement,
BindMode,
ExcalidrawTextElement,
} from "@excalidraw/element/types";
import type {
@@ -328,7 +327,7 @@ export interface AppState {
/**
* set when a new text is created or when an existing text is being edited
*/
editingTextElement: ExcalidrawTextElement | null;
editingTextElement: NonDeletedExcalidrawElement | null;
activeTool: {
/**
* indicates a previous tool we should revert back to if we deselect the
@@ -877,8 +876,9 @@ export type PointerDownState = Readonly<{
// by default same as PointerDownState.origin. On alt-duplication, reset
// to current pointer position at time of duplication.
origin: { x: number; y: number };
// explicit flag for specific scenarios such as:
// - after lasso selection until the next pointer down
// Whether to block drag after lasso selection
// this is meant to be used to block dragging after lasso selection on PCs
// until the next pointer down
blockDragging: boolean;
};
// We need to have these in the state so that we can unsubscribe them
@@ -1,10 +1,7 @@
import { queryByText } from "@testing-library/react";
import { pointFrom } from "@excalidraw/math";
import {
getLineHeightInPx,
getOriginalContainerHeightFromCache,
} from "@excalidraw/element";
import { getOriginalContainerHeightFromCache } from "@excalidraw/element";
import {
CODES,
@@ -213,42 +210,6 @@ describe("textWysiwyg", () => {
expect(h.elements.length).toBe(1);
});
it("should vertically center newly created text on the cursor when clicked with text tool", async () => {
API.setAppState({
currentItemFontFamily: FONT_FAMILY.Cascadia,
currentItemFontSize: 40,
});
UI.clickTool("text");
mouse.clickAt(120, 80);
const editor = await getTextEditor();
const text = h.elements[0] as ExcalidrawTextElement;
const lineHeightPx = getLineHeightInPx(text.fontSize, text.lineHeight);
expect(editor).not.toBe(null);
expect(text.y + lineHeightPx / 2).toBe(80);
});
it("should snap newly created text top-left to the current grid cell when clicked with text tool in grid mode", async () => {
API.setAppState({
currentItemFontFamily: FONT_FAMILY.Cascadia,
currentItemFontSize: 40,
gridModeEnabled: true,
gridSize: 24,
});
UI.clickTool("text");
mouse.clickAt(113, 86);
const editor = await getTextEditor();
const text = h.elements[0] as ExcalidrawTextElement;
expect(editor).not.toBe(null);
expect(text.x).toBe(96);
expect(text.y).toBe(72);
});
it("should edit text under cursor when double-clicked with selection tool", async () => {
const text = API.createElement({
type: "text",
@@ -332,6 +293,39 @@ describe("textWysiwyg", () => {
expect(await getTextEditor({ waitForEditor: false })).toBe(null);
});
it("should ignore double-click when the second click ends away from where it started", async () => {
UI.clickTool("selection");
mouse.downAt(40, 40);
mouse.upAt(40, 40);
fireEvent.click(GlobalTestState.interactiveCanvas, {
button: 0,
clientX: 40,
clientY: 40,
});
mouse.downAt(40, 40);
mouse.moveTo(200, 200);
mouse.upAt(200, 200);
fireEvent.click(GlobalTestState.interactiveCanvas, {
button: 0,
clientX: 200,
clientY: 200,
});
fireEvent.doubleClick(GlobalTestState.interactiveCanvas, {
button: 0,
clientX: 200,
clientY: 200,
});
const editor = await getTextEditor({ waitForEditor: false });
expect(editor).toBe(null);
expect(h.state.editingTextElement).toBe(null);
expect(h.elements.length).toBe(0);
});
// FIXME too flaky. No one knows why.
it.skip("should bump the version of a labeled arrow when the label is updated", async () => {
const arrow = UI.createElement("arrow", {
@@ -1611,7 +1605,7 @@ describe("textWysiwyg", () => {
version: 2,
width: 610,
x: 15,
y: 12.5,
y: 25,
}),
);
expect(h.elements[2] as ExcalidrawTextElement).toEqual(
+2 -7
View File
@@ -123,15 +123,10 @@ export function pointsEqual<Point extends GlobalPoint | LocalPoint>(
* @returns The rotated point
*/
export function pointRotateRads<Point extends GlobalPoint | LocalPoint>(
point: Point,
center: Point,
[x, y]: Point,
[cx, cy]: Point,
angle: Radians,
): Point {
if (!angle) {
return point;
}
const [x, y] = point;
const [cx, cy] = center;
return pointFrom(
(x - cx) * Math.cos(angle) - (y - cy) * Math.sin(angle) + cx,
(x - cx) * Math.sin(angle) + (y - cy) * Math.cos(angle) + cy,
+4 -4
View File
@@ -1531,10 +1531,10 @@
resolved "https://registry.yarnpkg.com/@excalidraw/markdown-to-text/-/markdown-to-text-0.1.2.tgz#1703705e7da608cf478f17bfe96fb295f55a23eb"
integrity sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==
"@excalidraw/mermaid-to-excalidraw@2.1.1":
version "2.1.1"
resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-2.1.1.tgz#659c934a607dd2cf57f2a69282588ee2b0722959"
integrity sha512-jU+frqcxazsY+t5yOBf2mgrQy+WUrbrzA36if3SQB/Vwaf2qOJjnWxucNafgZZk/3+9xGmRotUeOviSOJG+wYA==
"@excalidraw/mermaid-to-excalidraw@2.1.0":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-2.1.0.tgz#a5b9cf87c3185558cda7f9687d87b9937f452358"
integrity sha512-RMd+c2b7WzzUjhERMpKwp8PhF2/XlHDjr/zK+Gxfp8K9sVlafPYJ5OEa/GkN6edi2rBUXRfW+41WdO6L56b6Kw==
dependencies:
"@excalidraw/markdown-to-text" "0.1.2"
"@mermaid-js/parser" "^0.6.3"