Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6117c46466 | ||
|
|
e69c626ead | ||
|
|
ca5e246074 | ||
|
|
d75889238d | ||
|
|
f21a6b587a | ||
|
|
038714e715 | ||
|
|
8de6516823 | ||
|
|
7f1ef7562c | ||
|
|
d61b3cf83d | ||
|
|
6001f59d38 | ||
|
|
1c66f85ec9 | ||
|
|
a0b968c8e0 | ||
|
|
3a68f0ae7b | ||
|
|
c0e88fbc54 | ||
|
|
99500fc255 | ||
|
|
bc5e5e1ef0 | ||
|
|
50ac3bf855 | ||
|
|
2ea883a05e | ||
|
|
f8b25375a4 | ||
|
|
974745b9e5 | ||
|
|
9dab749dfd | ||
|
|
895f35ae18 | ||
|
|
d2b8f4d2f8 | ||
|
|
f8e65bb77e | ||
|
|
3030e96d62 | ||
|
|
79be25fbc0 | ||
|
|
44453b725d | ||
|
|
1dbc599b88 | ||
|
|
fc80fd15dc | ||
|
|
25bb6738ea | ||
|
|
9e52c30ce8 |
@@ -23,6 +23,11 @@ REACT_APP_DEV_DISABLE_LIVE_RELOAD=
|
|||||||
|
|
||||||
FAST_REFRESH=false
|
FAST_REFRESH=false
|
||||||
|
|
||||||
|
# MATOMO
|
||||||
|
REACT_APP_MATOMO_URL=
|
||||||
|
REACT_APP_CDN_MATOMO_TRACKER_URL=
|
||||||
|
REACT_APP_MATOMO_SITE_ID=
|
||||||
|
|
||||||
#Debug flags
|
#Debug flags
|
||||||
|
|
||||||
# To enable bounding box for text containers
|
# To enable bounding box for text containers
|
||||||
|
|||||||
@@ -12,6 +12,13 @@ REACT_APP_WS_SERVER_URL=
|
|||||||
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
|
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
|
||||||
|
|
||||||
# production-only vars
|
# production-only vars
|
||||||
|
# GOOGLE ANALYTICS
|
||||||
REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13
|
REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13
|
||||||
|
# MATOMO
|
||||||
|
REACT_APP_MATOMO_URL=https://excalidraw.matomo.cloud/
|
||||||
|
REACT_APP_CDN_MATOMO_TRACKER_URL=//cdn.matomo.cloud/excalidraw.matomo.cloud/matomo.js
|
||||||
|
REACT_APP_MATOMO_SITE_ID=1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
REACT_APP_PLUS_APP=https://app.excalidraw.com
|
REACT_APP_PLUS_APP=https://app.excalidraw.com
|
||||||
|
|||||||
@@ -1,6 +1,19 @@
|
|||||||
# ref
|
# ref
|
||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
<a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs">createRef</a> | <a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a> | <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">callbackRef</a> | <br/>{ current: { readyPromise: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/utils.ts#L460">resolvablePromise</a> } }
|
<a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs">
|
||||||
|
createRef
|
||||||
|
</a>{" "}
|
||||||
|
|{" "}
|
||||||
|
<a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a>{" "}
|
||||||
|
|{" "}
|
||||||
|
<a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">
|
||||||
|
callbackRef
|
||||||
|
</a>{" "}
|
||||||
|
| <br />
|
||||||
|
{ current: { readyPromise: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/utils.ts#L460">
|
||||||
|
resolvablePromise
|
||||||
|
</a> } }
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
You can pass a `ref` when you want to access some excalidraw APIs. We expose the below APIs:
|
You can pass a `ref` when you want to access some excalidraw APIs. We expose the below APIs:
|
||||||
@@ -139,7 +152,9 @@ function App() {
|
|||||||
return (
|
return (
|
||||||
<div style={{ height: "500px" }}>
|
<div style={{ height: "500px" }}>
|
||||||
<p style={{ fontSize: "16px" }}> Click to update the scene</p>
|
<p style={{ fontSize: "16px" }}> Click to update the scene</p>
|
||||||
<button className="custom-button" onClick={updateScene}>Update Scene</button>
|
<button className="custom-button" onClick={updateScene}>
|
||||||
|
Update Scene
|
||||||
|
</button>
|
||||||
<Excalidraw ref={(api) => setExcalidrawAPI(api)} />
|
<Excalidraw ref={(api) => setExcalidrawAPI(api)} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -187,7 +202,8 @@ function App() {
|
|||||||
return (
|
return (
|
||||||
<div style={{ height: "500px" }}>
|
<div style={{ height: "500px" }}>
|
||||||
<p style={{ fontSize: "16px" }}> Click to update the library items</p>
|
<p style={{ fontSize: "16px" }}> Click to update the library items</p>
|
||||||
<button className="custom-button"
|
<button
|
||||||
|
className="custom-button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const libraryItems = [
|
const libraryItems = [
|
||||||
{
|
{
|
||||||
@@ -205,10 +221,8 @@ function App() {
|
|||||||
];
|
];
|
||||||
excalidrawAPI.updateLibrary({
|
excalidrawAPI.updateLibrary({
|
||||||
libraryItems,
|
libraryItems,
|
||||||
openLibraryMenu: true
|
openLibraryMenu: true,
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Update Library
|
Update Library
|
||||||
@@ -250,7 +264,7 @@ Resets the scene. If `resetLoadingState` is passed as true then it will also for
|
|||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
() =>{" "}
|
() =>{" "}
|
||||||
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115">
|
||||||
ExcalidrawElement[]
|
ExcalidrawElement[]
|
||||||
</a>
|
</a>
|
||||||
</pre>
|
</pre>
|
||||||
@@ -261,7 +275,7 @@ Returns all the elements including the deleted in the scene.
|
|||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
() => NonDeleted<
|
() => NonDeleted<
|
||||||
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115">
|
||||||
ExcalidrawElement
|
ExcalidrawElement
|
||||||
</a>
|
</a>
|
||||||
[]>
|
[]>
|
||||||
@@ -293,18 +307,31 @@ This is the history API. history.clear() will clear the history.
|
|||||||
## scrollToContent
|
## scrollToContent
|
||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
(target?:{" "}
|
(<br />
|
||||||
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
|
{" "}
|
||||||
|
target?:{" "}
|
||||||
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115">
|
||||||
ExcalidrawElement
|
ExcalidrawElement
|
||||||
</a>{" "}
|
</a>{" "}
|
||||||
|{" "}
|
|{" "}
|
||||||
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115">
|
||||||
ExcalidrawElement
|
ExcalidrawElement
|
||||||
</a>
|
</a>
|
||||||
[]) => void
|
[],
|
||||||
|
<br />
|
||||||
|
{" "}opts?: { fitToContent?: boolean; animate?: boolean; duration?: number
|
||||||
|
}
|
||||||
|
<br />) => void
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
Scroll the nearest element out of the elements supplied to the center. Defaults to the elements on the scene.
|
Scroll the nearest element out of the elements supplied to the center of the viewport. Defaults to the elements on the scene.
|
||||||
|
|
||||||
|
| Attribute | type | default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| target | <code>ExcalidrawElement | ExcalidrawElement[]</code> | All scene elements | The element(s) to scroll to. |
|
||||||
|
| opts.fitToContent | boolean | false | Whether to fit the elements to viewport by automatically changing zoom as needed. |
|
||||||
|
| opts.animate | boolean | false | Whether to animate between starting and ending position. Note that for larger scenes the animation may not be smooth due to performance issues. |
|
||||||
|
| opts.duration | number | 500 | Duration of the animation if `opts.animate` is `true`. |
|
||||||
|
|
||||||
## refresh
|
## refresh
|
||||||
|
|
||||||
@@ -323,7 +350,7 @@ For any other cases if the position of excalidraw is updated (example due to scr
|
|||||||
This API can be used to show the toast with custom message.
|
This API can be used to show the toast with custom message.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
({ message: string, closable?:boolean,duration?:number
|
({ message: string, closable?:boolean,duration?:number
|
||||||
} | null) => void
|
} | null) => void
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -358,15 +385,18 @@ This API can be used to get the files present in the scene. It may contain files
|
|||||||
|
|
||||||
This API has the below signature. It sets the `tool` passed in param as the active tool.
|
This API has the below signature. It sets the `tool` passed in param as the active tool.
|
||||||
|
|
||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
(tool: <br/> { type: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/shapes.tsx#L15">SHAPES</a>[number]["value"]| "eraser" } |<br/> { type: "custom"; customType: string }) => void
|
(tool: <br /> { type:{" "}
|
||||||
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/shapes.tsx#L15">
|
||||||
|
SHAPES
|
||||||
|
</a>
|
||||||
|
[number]["value"]| "eraser" } |
|
||||||
|
<br /> { type: "custom"; customType: string }) => void
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
## setCursor
|
## setCursor
|
||||||
|
|
||||||
This API can be used to customise the mouse cursor on the canvas and has the below signature.
|
This API can be used to customise the mouse cursor on the canvas and has the below signature. It sets the mouse cursor to the cursor passed in param.
|
||||||
It sets the mouse cursor to the cursor passed in param.
|
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
(cursor: string) => void
|
(cursor: string) => void
|
||||||
|
|||||||
+31
-2
@@ -146,8 +146,10 @@
|
|||||||
// setting this so that libraries installation reuses this window tab.
|
// setting this so that libraries installation reuses this window tab.
|
||||||
window.name = "_excalidraw";
|
window.name = "_excalidraw";
|
||||||
</script>
|
</script>
|
||||||
<% if (process.env.REACT_APP_DISABLE_TRACKING !== 'true' &&
|
<% if (process.env.REACT_APP_DISABLE_TRACKING !== 'true') { %>
|
||||||
process.env.REACT_APP_GOOGLE_ANALYTICS_ID) { %>
|
|
||||||
|
<!-- LEGACY GOOGLE ANALYTICS -->
|
||||||
|
<% if (process.env.REACT_APP_GOOGLE_ANALYTICS_ID) { %>
|
||||||
<script
|
<script
|
||||||
async
|
async
|
||||||
src="https://www.googletagmanager.com/gtag/js?id=%REACT_APP_GOOGLE_ANALYTICS_ID%"
|
src="https://www.googletagmanager.com/gtag/js?id=%REACT_APP_GOOGLE_ANALYTICS_ID%"
|
||||||
@@ -160,6 +162,33 @@
|
|||||||
gtag("js", new Date());
|
gtag("js", new Date());
|
||||||
gtag("config", "%REACT_APP_GOOGLE_ANALYTICS_ID%");
|
gtag("config", "%REACT_APP_GOOGLE_ANALYTICS_ID%");
|
||||||
</script>
|
</script>
|
||||||
|
<% } %>
|
||||||
|
<!-- end LEGACY GOOGLE ANALYTICS -->
|
||||||
|
|
||||||
|
<!-- Matomo -->
|
||||||
|
<% if (process.env.REACT_APP_MATOMO_URL &&
|
||||||
|
process.env.REACT_APP_MATOMO_SITE_ID &&
|
||||||
|
process.env.REACT_APP_CDN_MATOMO_TRACKER_URL) { %>
|
||||||
|
<script>
|
||||||
|
var _paq = (window._paq = window._paq || []);
|
||||||
|
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
|
||||||
|
_paq.push(["trackPageView"]);
|
||||||
|
_paq.push(["enableLinkTracking"]);
|
||||||
|
(function () {
|
||||||
|
var u = "%REACT_APP_MATOMO_URL%";
|
||||||
|
_paq.push(["setTrackerUrl", u + "matomo.php"]);
|
||||||
|
_paq.push(["setSiteId", "%REACT_APP_MATOMO_SITE_ID%"]);
|
||||||
|
var d = document,
|
||||||
|
g = d.createElement("script"),
|
||||||
|
s = d.getElementsByTagName("script")[0];
|
||||||
|
g.async = true;
|
||||||
|
g.src = "%REACT_APP_CDN_MATOMO_TRACKER_URL%";
|
||||||
|
s.parentNode.insertBefore(g, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<% } %>
|
||||||
|
<!-- end Matomo analytics -->
|
||||||
|
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
<!-- FIXME: remove this when we update CRA (fix SW caching) -->
|
<!-- FIXME: remove this when we update CRA (fix SW caching) -->
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { mutateElement } from "../element/mutateElement";
|
|||||||
import {
|
import {
|
||||||
computeContainerDimensionForBoundText,
|
computeContainerDimensionForBoundText,
|
||||||
getBoundTextElement,
|
getBoundTextElement,
|
||||||
|
measureText,
|
||||||
redrawTextBoundingBox,
|
redrawTextBoundingBox,
|
||||||
} from "../element/textElement";
|
} from "../element/textElement";
|
||||||
import { measureText } from "../element/textMeasurements";
|
|
||||||
import {
|
import {
|
||||||
getOriginalContainerHeightFromCache,
|
getOriginalContainerHeightFromCache,
|
||||||
resetOriginalContainerCache,
|
resetOriginalContainerCache,
|
||||||
@@ -42,7 +42,7 @@ export const actionUnbindText = register({
|
|||||||
selectedElements.forEach((element) => {
|
selectedElements.forEach((element) => {
|
||||||
const boundTextElement = getBoundTextElement(element);
|
const boundTextElement = getBoundTextElement(element);
|
||||||
if (boundTextElement) {
|
if (boundTextElement) {
|
||||||
const { width, height } = measureText(
|
const { width, height, baseline } = measureText(
|
||||||
boundTextElement.originalText,
|
boundTextElement.originalText,
|
||||||
getFontString(boundTextElement),
|
getFontString(boundTextElement),
|
||||||
boundTextElement.lineHeight,
|
boundTextElement.lineHeight,
|
||||||
@@ -56,6 +56,7 @@ export const actionUnbindText = register({
|
|||||||
containerId: null,
|
containerId: null,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
|
baseline,
|
||||||
text: boundTextElement.originalText,
|
text: boundTextElement.originalText,
|
||||||
});
|
});
|
||||||
mutateElement(element, {
|
mutateElement(element, {
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ const zoomValueToFitBoundsOnViewport = (
|
|||||||
return clampedZoomValueToFitElements as NormalizedZoomValue;
|
return clampedZoomValueToFitElements as NormalizedZoomValue;
|
||||||
};
|
};
|
||||||
|
|
||||||
const zoomToFitElements = (
|
export const zoomToFitElements = (
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
appState: Readonly<AppState>,
|
appState: Readonly<AppState>,
|
||||||
zoomToSelection: boolean,
|
zoomToSelection: boolean,
|
||||||
|
|||||||
@@ -54,8 +54,8 @@ import { mutateElement, newElementWith } from "../element/mutateElement";
|
|||||||
import {
|
import {
|
||||||
getBoundTextElement,
|
getBoundTextElement,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
|
getDefaultLineHeight,
|
||||||
} from "../element/textElement";
|
} from "../element/textElement";
|
||||||
import { getDefaultLineHeight } from "../element/textMeasurements";
|
|
||||||
import {
|
import {
|
||||||
isBoundToContainer,
|
isBoundToContainer,
|
||||||
isLinearElement,
|
isLinearElement,
|
||||||
|
|||||||
@@ -12,14 +12,16 @@ import {
|
|||||||
DEFAULT_FONT_FAMILY,
|
DEFAULT_FONT_FAMILY,
|
||||||
DEFAULT_TEXT_ALIGN,
|
DEFAULT_TEXT_ALIGN,
|
||||||
} from "../constants";
|
} from "../constants";
|
||||||
import { getBoundTextElement } from "../element/textElement";
|
import {
|
||||||
|
getBoundTextElement,
|
||||||
|
getDefaultLineHeight,
|
||||||
|
} from "../element/textElement";
|
||||||
import {
|
import {
|
||||||
hasBoundTextElement,
|
hasBoundTextElement,
|
||||||
canApplyRoundnessTypeToElement,
|
canApplyRoundnessTypeToElement,
|
||||||
getDefaultRoundnessTypeForElement,
|
getDefaultRoundnessTypeForElement,
|
||||||
} from "../element/typeChecks";
|
} from "../element/typeChecks";
|
||||||
import { getSelectedElements } from "../scene";
|
import { getSelectedElements } from "../scene";
|
||||||
import { getDefaultLineHeight } from "../element/textMeasurements";
|
|
||||||
|
|
||||||
// `copiedStyles` is exported only for tests.
|
// `copiedStyles` is exported only for tests.
|
||||||
export let copiedStyles: string = "{}";
|
export let copiedStyles: string = "{}";
|
||||||
|
|||||||
+30
-22
@@ -1,22 +1,30 @@
|
|||||||
export const trackEvent =
|
export const trackEvent = (
|
||||||
typeof process !== "undefined" &&
|
category: string,
|
||||||
process.env?.REACT_APP_GOOGLE_ANALYTICS_ID &&
|
action: string,
|
||||||
typeof window !== "undefined" &&
|
label?: string,
|
||||||
window.gtag
|
value?: number,
|
||||||
? (category: string, action: string, label?: string, value?: number) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
window.gtag("event", action, {
|
// Uncomment the next line to track locally
|
||||||
event_category: category,
|
// console.log("Track Event", { category, action, label, value });
|
||||||
event_label: label,
|
|
||||||
value,
|
if (typeof window === "undefined" || process.env.JEST_WORKER_ID) {
|
||||||
});
|
return;
|
||||||
} catch (error) {
|
}
|
||||||
console.error("error logging to ga", error);
|
|
||||||
}
|
if (process.env.REACT_APP_GOOGLE_ANALYTICS_ID && window.gtag) {
|
||||||
}
|
window.gtag("event", action, {
|
||||||
: typeof process !== "undefined" && process.env?.JEST_WORKER_ID
|
event_category: category,
|
||||||
? (category: string, action: string, label?: string, value?: number) => {}
|
event_label: label,
|
||||||
: (category: string, action: string, label?: string, value?: number) => {
|
value,
|
||||||
// Uncomment the next line to track locally
|
});
|
||||||
// console.log("Track Event", { category, action, label, value });
|
}
|
||||||
};
|
|
||||||
|
// MATOMO event tracking _paq must be same as the one in index.html
|
||||||
|
if (window._paq) {
|
||||||
|
window._paq.push(["trackEvent", category, action, label, value]);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("error during analytics", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
+104
-27
@@ -229,6 +229,7 @@ import {
|
|||||||
updateActiveTool,
|
updateActiveTool,
|
||||||
getShortcutKey,
|
getShortcutKey,
|
||||||
isTransparent,
|
isTransparent,
|
||||||
|
easeToValuesRAF,
|
||||||
} from "../utils";
|
} from "../utils";
|
||||||
import {
|
import {
|
||||||
ContextMenu,
|
ContextMenu,
|
||||||
@@ -260,20 +261,18 @@ import throttle from "lodash.throttle";
|
|||||||
import { fileOpen, FileSystemHandle } from "../data/filesystem";
|
import { fileOpen, FileSystemHandle } from "../data/filesystem";
|
||||||
import {
|
import {
|
||||||
bindTextToShapeAfterDuplication,
|
bindTextToShapeAfterDuplication,
|
||||||
|
getApproxMinLineHeight,
|
||||||
|
getApproxMinLineWidth,
|
||||||
getBoundTextElement,
|
getBoundTextElement,
|
||||||
getContainerCenter,
|
getContainerCenter,
|
||||||
getContainerDims,
|
getContainerDims,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
|
getDefaultLineHeight,
|
||||||
|
getLineHeightInPx,
|
||||||
getTextBindableContainerAtPosition,
|
getTextBindableContainerAtPosition,
|
||||||
|
isMeasureTextSupported,
|
||||||
isValidTextContainer,
|
isValidTextContainer,
|
||||||
} from "../element/textElement";
|
} from "../element/textElement";
|
||||||
import {
|
|
||||||
getApproxMinContainerHeight,
|
|
||||||
getApproxMinContainerWidth,
|
|
||||||
isMeasureTextSupported,
|
|
||||||
getLineHeightInPx,
|
|
||||||
getDefaultLineHeight,
|
|
||||||
} from "../element/textMeasurements";
|
|
||||||
import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
|
import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
|
||||||
import {
|
import {
|
||||||
normalizeLink,
|
normalizeLink,
|
||||||
@@ -286,7 +285,10 @@ import {
|
|||||||
import { shouldShowBoundingBox } from "../element/transformHandles";
|
import { shouldShowBoundingBox } from "../element/transformHandles";
|
||||||
import { Fonts } from "../scene/Fonts";
|
import { Fonts } from "../scene/Fonts";
|
||||||
import { actionPaste } from "../actions/actionClipboard";
|
import { actionPaste } from "../actions/actionClipboard";
|
||||||
import { actionToggleHandTool } from "../actions/actionCanvas";
|
import {
|
||||||
|
actionToggleHandTool,
|
||||||
|
zoomToFitElements,
|
||||||
|
} from "../actions/actionCanvas";
|
||||||
import { jotaiStore } from "../jotai";
|
import { jotaiStore } from "../jotai";
|
||||||
import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
|
import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
|
||||||
import { actionCreateContainerFromText } from "../actions/actionBoundText";
|
import { actionCreateContainerFromText } from "../actions/actionBoundText";
|
||||||
@@ -1845,18 +1847,89 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
this.actionManager.executeAction(actionToggleHandTool);
|
this.actionManager.executeAction(actionToggleHandTool);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zooms on canvas viewport center
|
||||||
|
*/
|
||||||
|
zoomCanvas = (
|
||||||
|
/** decimal fraction between 0.1 (10% zoom) and 30 (3000% zoom) */
|
||||||
|
value: number,
|
||||||
|
) => {
|
||||||
|
this.setState({
|
||||||
|
...getStateForZoom(
|
||||||
|
{
|
||||||
|
viewportX: this.state.width / 2 + this.state.offsetLeft,
|
||||||
|
viewportY: this.state.height / 2 + this.state.offsetTop,
|
||||||
|
nextZoom: getNormalizedZoom(value),
|
||||||
|
},
|
||||||
|
this.state,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
private cancelInProgresAnimation: (() => void) | null = null;
|
||||||
|
|
||||||
scrollToContent = (
|
scrollToContent = (
|
||||||
target:
|
target:
|
||||||
| ExcalidrawElement
|
| ExcalidrawElement
|
||||||
| readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
|
| readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
|
||||||
|
opts?: { fitToContent?: boolean; animate?: boolean; duration?: number },
|
||||||
) => {
|
) => {
|
||||||
this.setState({
|
this.cancelInProgresAnimation?.();
|
||||||
...calculateScrollCenter(
|
|
||||||
Array.isArray(target) ? target : [target],
|
// convert provided target into ExcalidrawElement[] if necessary
|
||||||
this.state,
|
const targets = Array.isArray(target) ? target : [target];
|
||||||
this.canvas,
|
|
||||||
),
|
let zoom = this.state.zoom;
|
||||||
});
|
let scrollX = this.state.scrollX;
|
||||||
|
let scrollY = this.state.scrollY;
|
||||||
|
|
||||||
|
if (opts?.fitToContent) {
|
||||||
|
// compute an appropriate viewport location (scroll X, Y) and zoom level
|
||||||
|
// that fit the target elements on the scene
|
||||||
|
const { appState } = zoomToFitElements(targets, this.state, false);
|
||||||
|
zoom = appState.zoom;
|
||||||
|
scrollX = appState.scrollX;
|
||||||
|
scrollY = appState.scrollY;
|
||||||
|
} else {
|
||||||
|
// compute only the viewport location, without any zoom adjustment
|
||||||
|
const scroll = calculateScrollCenter(targets, this.state, this.canvas);
|
||||||
|
scrollX = scroll.scrollX;
|
||||||
|
scrollY = scroll.scrollY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// when animating, we use RequestAnimationFrame to prevent the animation
|
||||||
|
// from slowing down other processes
|
||||||
|
if (opts?.animate) {
|
||||||
|
const origScrollX = this.state.scrollX;
|
||||||
|
const origScrollY = this.state.scrollY;
|
||||||
|
|
||||||
|
// zoom animation could become problematic on scenes with large number
|
||||||
|
// of elements, setting it to its final value to improve user experience.
|
||||||
|
//
|
||||||
|
// using zoomCanvas() to zoom on current viewport center
|
||||||
|
this.zoomCanvas(zoom.value);
|
||||||
|
|
||||||
|
const cancel = easeToValuesRAF(
|
||||||
|
[origScrollX, origScrollY],
|
||||||
|
[scrollX, scrollY],
|
||||||
|
(scrollX, scrollY) => this.setState({ scrollX, scrollY }),
|
||||||
|
{ duration: opts?.duration ?? 500 },
|
||||||
|
);
|
||||||
|
this.cancelInProgresAnimation = () => {
|
||||||
|
cancel();
|
||||||
|
this.cancelInProgresAnimation = null;
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
this.setState({ scrollX, scrollY, zoom });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** use when changing scrollX/scrollY/zoom based on user interaction */
|
||||||
|
private translateCanvas: React.Component<any, AppState>["setState"] = (
|
||||||
|
state,
|
||||||
|
) => {
|
||||||
|
this.cancelInProgresAnimation?.();
|
||||||
|
this.setState(state);
|
||||||
};
|
};
|
||||||
|
|
||||||
setToast = (
|
setToast = (
|
||||||
@@ -2057,9 +2130,13 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
offset = -offset;
|
offset = -offset;
|
||||||
}
|
}
|
||||||
if (event.shiftKey) {
|
if (event.shiftKey) {
|
||||||
this.setState((state) => ({ scrollX: state.scrollX + offset }));
|
this.translateCanvas((state) => ({
|
||||||
|
scrollX: state.scrollX + offset,
|
||||||
|
}));
|
||||||
} else {
|
} else {
|
||||||
this.setState((state) => ({ scrollY: state.scrollY + offset }));
|
this.translateCanvas((state) => ({
|
||||||
|
scrollY: state.scrollY + offset,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2624,11 +2701,11 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
fontSize,
|
fontSize,
|
||||||
fontFamily,
|
fontFamily,
|
||||||
};
|
};
|
||||||
const minWidth = getApproxMinContainerWidth(
|
const minWidth = getApproxMinLineWidth(
|
||||||
getFontString(fontString),
|
getFontString(fontString),
|
||||||
lineHeight,
|
lineHeight,
|
||||||
);
|
);
|
||||||
const minHeight = getApproxMinContainerHeight(fontSize, lineHeight);
|
const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
|
||||||
const containerDims = getContainerDims(container);
|
const containerDims = getContainerDims(container);
|
||||||
const newHeight = Math.max(containerDims.height, minHeight);
|
const newHeight = Math.max(containerDims.height, minHeight);
|
||||||
const newWidth = Math.max(containerDims.width, minWidth);
|
const newWidth = Math.max(containerDims.width, minWidth);
|
||||||
@@ -2940,12 +3017,12 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
state,
|
state,
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
this.translateCanvas({
|
||||||
zoom: zoomState.zoom,
|
zoom: zoomState.zoom,
|
||||||
scrollX: zoomState.scrollX + deltaX / nextZoom,
|
scrollX: zoomState.scrollX + deltaX / nextZoom,
|
||||||
scrollY: zoomState.scrollY + deltaY / nextZoom,
|
scrollY: zoomState.scrollY + deltaY / nextZoom,
|
||||||
shouldCacheIgnoreZoom: true,
|
shouldCacheIgnoreZoom: true,
|
||||||
};
|
});
|
||||||
});
|
});
|
||||||
this.resetShouldCacheIgnoreZoomDebounced();
|
this.resetShouldCacheIgnoreZoomDebounced();
|
||||||
} else {
|
} else {
|
||||||
@@ -3721,7 +3798,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
|
window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setState({
|
this.translateCanvas({
|
||||||
scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
|
scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
|
||||||
scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
|
scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
|
||||||
});
|
});
|
||||||
@@ -4867,7 +4944,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
if (pointerDownState.scrollbars.isOverHorizontal) {
|
if (pointerDownState.scrollbars.isOverHorizontal) {
|
||||||
const x = event.clientX;
|
const x = event.clientX;
|
||||||
const dx = x - pointerDownState.lastCoords.x;
|
const dx = x - pointerDownState.lastCoords.x;
|
||||||
this.setState({
|
this.translateCanvas({
|
||||||
scrollX: this.state.scrollX - dx / this.state.zoom.value,
|
scrollX: this.state.scrollX - dx / this.state.zoom.value,
|
||||||
});
|
});
|
||||||
pointerDownState.lastCoords.x = x;
|
pointerDownState.lastCoords.x = x;
|
||||||
@@ -4877,7 +4954,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
if (pointerDownState.scrollbars.isOverVertical) {
|
if (pointerDownState.scrollbars.isOverVertical) {
|
||||||
const y = event.clientY;
|
const y = event.clientY;
|
||||||
const dy = y - pointerDownState.lastCoords.y;
|
const dy = y - pointerDownState.lastCoords.y;
|
||||||
this.setState({
|
this.translateCanvas({
|
||||||
scrollY: this.state.scrollY - dy / this.state.zoom.value,
|
scrollY: this.state.scrollY - dy / this.state.zoom.value,
|
||||||
});
|
});
|
||||||
pointerDownState.lastCoords.y = y;
|
pointerDownState.lastCoords.y = y;
|
||||||
@@ -6306,7 +6383,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
// reduced amplification for small deltas (small movements on a trackpad)
|
// reduced amplification for small deltas (small movements on a trackpad)
|
||||||
Math.min(1, absDelta / 20);
|
Math.min(1, absDelta / 20);
|
||||||
|
|
||||||
this.setState((state) => ({
|
this.translateCanvas((state) => ({
|
||||||
...getStateForZoom(
|
...getStateForZoom(
|
||||||
{
|
{
|
||||||
viewportX: cursorX,
|
viewportX: cursorX,
|
||||||
@@ -6323,14 +6400,14 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
|
|
||||||
// scroll horizontally when shift pressed
|
// scroll horizontally when shift pressed
|
||||||
if (event.shiftKey) {
|
if (event.shiftKey) {
|
||||||
this.setState(({ zoom, scrollX }) => ({
|
this.translateCanvas(({ zoom, scrollX }) => ({
|
||||||
// on Mac, shift+wheel tends to result in deltaX
|
// on Mac, shift+wheel tends to result in deltaX
|
||||||
scrollX: scrollX - (deltaY || deltaX) / zoom.value,
|
scrollX: scrollX - (deltaY || deltaX) / zoom.value,
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setState(({ zoom, scrollX, scrollY }) => ({
|
this.translateCanvas(({ zoom, scrollX, scrollY }) => ({
|
||||||
scrollX: scrollX - deltaX / zoom.value,
|
scrollX: scrollX - deltaX / zoom.value,
|
||||||
scrollY: scrollY - deltaY / zoom.value,
|
scrollY: scrollY - deltaY / zoom.value,
|
||||||
}));
|
}));
|
||||||
|
|||||||
+27
-16
@@ -31,14 +31,15 @@ import {
|
|||||||
import { getDefaultAppState } from "../appState";
|
import { getDefaultAppState } from "../appState";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { bumpVersion } from "../element/mutateElement";
|
import { bumpVersion } from "../element/mutateElement";
|
||||||
import { getUpdatedTimestamp, updateActiveTool } from "../utils";
|
import { getFontString, getUpdatedTimestamp, updateActiveTool } from "../utils";
|
||||||
import { arrayToMap } from "../utils";
|
import { arrayToMap } from "../utils";
|
||||||
import oc from "open-color";
|
import oc from "open-color";
|
||||||
import { MarkOptional, Mutable } from "../utility-types";
|
import { MarkOptional, Mutable } from "../utility-types";
|
||||||
import {
|
import {
|
||||||
detectLineHeight,
|
detectLineHeight,
|
||||||
getDefaultLineHeight,
|
getDefaultLineHeight,
|
||||||
} from "../element/textMeasurements";
|
getDOMMetrics,
|
||||||
|
} from "../element/textElement";
|
||||||
|
|
||||||
type RestoredAppState = Omit<
|
type RestoredAppState = Omit<
|
||||||
AppState,
|
AppState,
|
||||||
@@ -174,6 +175,24 @@ const restoreElement = (
|
|||||||
}
|
}
|
||||||
const text = element.text ?? "";
|
const text = element.text ?? "";
|
||||||
|
|
||||||
|
// line-height might not be specified either when creating elements
|
||||||
|
// programmatically, or when importing old diagrams.
|
||||||
|
// For the latter we want to detect the original line height which
|
||||||
|
// will likely differ from our per-font fixed line height we now use,
|
||||||
|
// to maintain backward compatibility.
|
||||||
|
const lineHeight =
|
||||||
|
element.lineHeight ||
|
||||||
|
(element.height
|
||||||
|
? // detect line-height from current element height and font-size
|
||||||
|
detectLineHeight(element)
|
||||||
|
: // no element height likely means programmatic use, so default
|
||||||
|
// to a fixed line height
|
||||||
|
getDefaultLineHeight(element.fontFamily));
|
||||||
|
const { baseline } = getDOMMetrics(
|
||||||
|
element.text,
|
||||||
|
getFontString(element),
|
||||||
|
lineHeight,
|
||||||
|
);
|
||||||
element = restoreElementWithProperties(element, {
|
element = restoreElementWithProperties(element, {
|
||||||
fontSize,
|
fontSize,
|
||||||
fontFamily,
|
fontFamily,
|
||||||
@@ -182,19 +201,9 @@ const restoreElement = (
|
|||||||
verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
|
verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
|
||||||
containerId: element.containerId ?? null,
|
containerId: element.containerId ?? null,
|
||||||
originalText: element.originalText || text,
|
originalText: element.originalText || text,
|
||||||
// line-height might not be specified either when creating elements
|
|
||||||
// programmatically, or when importing old diagrams.
|
lineHeight,
|
||||||
// For the latter we want to detect the original line height which
|
baseline,
|
||||||
// will likely differ from our per-font fixed line height we now use,
|
|
||||||
// to maintain backward compatibility.
|
|
||||||
lineHeight:
|
|
||||||
element.lineHeight ||
|
|
||||||
(element.height
|
|
||||||
? // detect line-height from current element height and font-size
|
|
||||||
detectLineHeight(element)
|
|
||||||
: // no element height likely means programmatic use, so default
|
|
||||||
// to a fixed line height
|
|
||||||
getDefaultLineHeight(element.fontFamily)),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (refreshDimensions) {
|
if (refreshDimensions) {
|
||||||
@@ -498,7 +507,9 @@ export const restoreAppState = (
|
|||||||
? {
|
? {
|
||||||
value: appState.zoom as NormalizedZoomValue,
|
value: appState.zoom as NormalizedZoomValue,
|
||||||
}
|
}
|
||||||
: appState.zoom || defaultAppState.zoom,
|
: appState.zoom?.value
|
||||||
|
? appState.zoom
|
||||||
|
: defaultAppState.zoom,
|
||||||
// when sidebar docked and user left it open in last session,
|
// when sidebar docked and user left it open in last session,
|
||||||
// keep it open. If not docked, keep it closed irrespective of last state.
|
// keep it open. If not docked, keep it closed irrespective of last state.
|
||||||
openSidebar:
|
openSidebar:
|
||||||
|
|||||||
+14
-12
@@ -25,17 +25,15 @@ import {
|
|||||||
getBoundTextElementOffset,
|
getBoundTextElementOffset,
|
||||||
getContainerDims,
|
getContainerDims,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
|
measureText,
|
||||||
normalizeText,
|
normalizeText,
|
||||||
getBoundTextMaxWidth,
|
wrapText,
|
||||||
|
getMaxContainerWidth,
|
||||||
|
getDefaultLineHeight,
|
||||||
} from "./textElement";
|
} from "./textElement";
|
||||||
import { VERTICAL_ALIGN } from "../constants";
|
import { VERTICAL_ALIGN } from "../constants";
|
||||||
import { isArrowElement } from "./typeChecks";
|
import { isArrowElement } from "./typeChecks";
|
||||||
import { MarkOptional, Merge, Mutable } from "../utility-types";
|
import { MarkOptional, Merge, Mutable } from "../utility-types";
|
||||||
import {
|
|
||||||
measureText,
|
|
||||||
wrapText,
|
|
||||||
getDefaultLineHeight,
|
|
||||||
} from "./textMeasurements";
|
|
||||||
|
|
||||||
type ElementConstructorOpts = MarkOptional<
|
type ElementConstructorOpts = MarkOptional<
|
||||||
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">,
|
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">,
|
||||||
@@ -147,6 +145,7 @@ export const newTextElement = (
|
|||||||
const text = normalizeText(opts.text);
|
const text = normalizeText(opts.text);
|
||||||
const metrics = measureText(text, getFontString(opts), lineHeight);
|
const metrics = measureText(text, getFontString(opts), lineHeight);
|
||||||
const offsets = getTextElementPositionOffsets(opts, metrics);
|
const offsets = getTextElementPositionOffsets(opts, metrics);
|
||||||
|
|
||||||
const textElement = newElementWith(
|
const textElement = newElementWith(
|
||||||
{
|
{
|
||||||
..._newElementBase<ExcalidrawTextElement>("text", opts),
|
..._newElementBase<ExcalidrawTextElement>("text", opts),
|
||||||
@@ -159,6 +158,7 @@ export const newTextElement = (
|
|||||||
y: opts.y - offsets.y,
|
y: opts.y - offsets.y,
|
||||||
width: metrics.width,
|
width: metrics.width,
|
||||||
height: metrics.height,
|
height: metrics.height,
|
||||||
|
baseline: metrics.baseline,
|
||||||
containerId: opts.containerId || null,
|
containerId: opts.containerId || null,
|
||||||
originalText: text,
|
originalText: text,
|
||||||
lineHeight,
|
lineHeight,
|
||||||
@@ -176,14 +176,15 @@ const getAdjustedDimensions = (
|
|||||||
y: number;
|
y: number;
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
|
baseline: number;
|
||||||
} => {
|
} => {
|
||||||
const container = getContainerElement(element);
|
const container = getContainerElement(element);
|
||||||
|
|
||||||
const { width: nextWidth, height: nextHeight } = measureText(
|
const {
|
||||||
nextText,
|
width: nextWidth,
|
||||||
getFontString(element),
|
height: nextHeight,
|
||||||
element.lineHeight,
|
baseline: nextBaseline,
|
||||||
);
|
} = measureText(nextText, getFontString(element), element.lineHeight);
|
||||||
const { textAlign, verticalAlign } = element;
|
const { textAlign, verticalAlign } = element;
|
||||||
let x: number;
|
let x: number;
|
||||||
let y: number;
|
let y: number;
|
||||||
@@ -258,6 +259,7 @@ const getAdjustedDimensions = (
|
|||||||
return {
|
return {
|
||||||
width: nextWidth,
|
width: nextWidth,
|
||||||
height: nextHeight,
|
height: nextHeight,
|
||||||
|
baseline: nextBaseline,
|
||||||
x: Number.isFinite(x) ? x : element.x,
|
x: Number.isFinite(x) ? x : element.x,
|
||||||
y: Number.isFinite(y) ? y : element.y,
|
y: Number.isFinite(y) ? y : element.y,
|
||||||
};
|
};
|
||||||
@@ -272,7 +274,7 @@ export const refreshTextDimensions = (
|
|||||||
text = wrapText(
|
text = wrapText(
|
||||||
text,
|
text,
|
||||||
getFontString(textElement),
|
getFontString(textElement),
|
||||||
getBoundTextMaxWidth(container),
|
getMaxContainerWidth(container),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const dimensions = getAdjustedDimensions(textElement, text);
|
const dimensions = getAdjustedDimensions(textElement, text);
|
||||||
|
|||||||
@@ -39,16 +39,17 @@ import {
|
|||||||
import { Point, PointerDownState } from "../types";
|
import { Point, PointerDownState } from "../types";
|
||||||
import Scene from "../scene/Scene";
|
import Scene from "../scene/Scene";
|
||||||
import {
|
import {
|
||||||
|
getApproxMinLineWidth,
|
||||||
getBoundTextElement,
|
getBoundTextElement,
|
||||||
getBoundTextElementId,
|
getBoundTextElementId,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
handleBindTextResize,
|
handleBindTextResize,
|
||||||
getBoundTextMaxWidth,
|
getMaxContainerWidth,
|
||||||
|
getApproxMinLineHeight,
|
||||||
|
measureText,
|
||||||
|
getMaxContainerHeight,
|
||||||
} from "./textElement";
|
} from "./textElement";
|
||||||
import {
|
|
||||||
getApproxMinContainerHeight,
|
|
||||||
getApproxMinContainerWidth,
|
|
||||||
} from "./textMeasurements";
|
|
||||||
export const normalizeAngle = (angle: number): number => {
|
export const normalizeAngle = (angle: number): number => {
|
||||||
if (angle >= 2 * Math.PI) {
|
if (angle >= 2 * Math.PI) {
|
||||||
return angle - 2 * Math.PI;
|
return angle - 2 * Math.PI;
|
||||||
@@ -194,7 +195,8 @@ const MIN_FONT_SIZE = 1;
|
|||||||
const measureFontSizeFromWidth = (
|
const measureFontSizeFromWidth = (
|
||||||
element: NonDeleted<ExcalidrawTextElement>,
|
element: NonDeleted<ExcalidrawTextElement>,
|
||||||
nextWidth: number,
|
nextWidth: number,
|
||||||
): number | null => {
|
nextHeight: number,
|
||||||
|
): { size: number; baseline: number } | null => {
|
||||||
// We only use width to scale font on resize
|
// We only use width to scale font on resize
|
||||||
let width = element.width;
|
let width = element.width;
|
||||||
|
|
||||||
@@ -202,15 +204,22 @@ const measureFontSizeFromWidth = (
|
|||||||
if (hasContainer) {
|
if (hasContainer) {
|
||||||
const container = getContainerElement(element);
|
const container = getContainerElement(element);
|
||||||
if (container) {
|
if (container) {
|
||||||
width = getBoundTextMaxWidth(container);
|
width = getMaxContainerWidth(container);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const nextFontSize = element.fontSize * (nextWidth / width);
|
const nextFontSize = element.fontSize * (nextWidth / width);
|
||||||
if (nextFontSize < MIN_FONT_SIZE) {
|
if (nextFontSize < MIN_FONT_SIZE) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
const metrics = measureText(
|
||||||
return nextFontSize;
|
element.text,
|
||||||
|
getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }),
|
||||||
|
element.lineHeight,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
size: nextFontSize,
|
||||||
|
baseline: metrics.baseline + (nextHeight - metrics.height),
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const getSidesForTransformHandle = (
|
const getSidesForTransformHandle = (
|
||||||
@@ -281,8 +290,8 @@ const resizeSingleTextElement = (
|
|||||||
if (scale > 0) {
|
if (scale > 0) {
|
||||||
const nextWidth = element.width * scale;
|
const nextWidth = element.width * scale;
|
||||||
const nextHeight = element.height * scale;
|
const nextHeight = element.height * scale;
|
||||||
const nextFontSize = measureFontSizeFromWidth(element, nextWidth);
|
const metrics = measureFontSizeFromWidth(element, nextWidth, nextHeight);
|
||||||
if (nextFontSize === null) {
|
if (metrics === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
|
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
|
||||||
@@ -306,9 +315,10 @@ const resizeSingleTextElement = (
|
|||||||
deltaY2,
|
deltaY2,
|
||||||
);
|
);
|
||||||
mutateElement(element, {
|
mutateElement(element, {
|
||||||
fontSize: nextFontSize,
|
fontSize: metrics.size,
|
||||||
width: nextWidth,
|
width: nextWidth,
|
||||||
height: nextHeight,
|
height: nextHeight,
|
||||||
|
baseline: metrics.baseline,
|
||||||
x: nextElementX,
|
x: nextElementX,
|
||||||
y: nextElementY,
|
y: nextElementY,
|
||||||
});
|
});
|
||||||
@@ -361,7 +371,7 @@ export const resizeSingleElement = (
|
|||||||
let scaleX = atStartBoundsWidth / boundsCurrentWidth;
|
let scaleX = atStartBoundsWidth / boundsCurrentWidth;
|
||||||
let scaleY = atStartBoundsHeight / boundsCurrentHeight;
|
let scaleY = atStartBoundsHeight / boundsCurrentHeight;
|
||||||
|
|
||||||
let boundTextFontSize: number | null = null;
|
let boundTextFont: { fontSize?: number; baseline?: number } = {};
|
||||||
const boundTextElement = getBoundTextElement(element);
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
|
||||||
if (transformHandleDirection.includes("e")) {
|
if (transformHandleDirection.includes("e")) {
|
||||||
@@ -411,7 +421,10 @@ export const resizeSingleElement = (
|
|||||||
boundTextElement.id,
|
boundTextElement.id,
|
||||||
) as typeof boundTextElement | undefined;
|
) as typeof boundTextElement | undefined;
|
||||||
if (stateOfBoundTextElementAtResize) {
|
if (stateOfBoundTextElementAtResize) {
|
||||||
boundTextFontSize = stateOfBoundTextElementAtResize.fontSize;
|
boundTextFont = {
|
||||||
|
fontSize: stateOfBoundTextElementAtResize.fontSize,
|
||||||
|
baseline: stateOfBoundTextElementAtResize.baseline,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (shouldMaintainAspectRatio) {
|
if (shouldMaintainAspectRatio) {
|
||||||
const updatedElement = {
|
const updatedElement = {
|
||||||
@@ -420,20 +433,24 @@ export const resizeSingleElement = (
|
|||||||
height: eleNewHeight,
|
height: eleNewHeight,
|
||||||
};
|
};
|
||||||
|
|
||||||
const nextFontSize = measureFontSizeFromWidth(
|
const nextFont = measureFontSizeFromWidth(
|
||||||
boundTextElement,
|
boundTextElement,
|
||||||
getBoundTextMaxWidth(updatedElement),
|
getMaxContainerWidth(updatedElement),
|
||||||
|
getMaxContainerHeight(updatedElement),
|
||||||
);
|
);
|
||||||
if (nextFontSize === null) {
|
if (nextFont === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
boundTextFontSize = nextFontSize;
|
boundTextFont = {
|
||||||
|
fontSize: nextFont.size,
|
||||||
|
baseline: nextFont.baseline,
|
||||||
|
};
|
||||||
} else {
|
} else {
|
||||||
const minWidth = getApproxMinContainerWidth(
|
const minWidth = getApproxMinLineWidth(
|
||||||
getFontString(boundTextElement),
|
getFontString(boundTextElement),
|
||||||
boundTextElement.lineHeight,
|
boundTextElement.lineHeight,
|
||||||
);
|
);
|
||||||
const minHeight = getApproxMinContainerHeight(
|
const minHeight = getApproxMinLineHeight(
|
||||||
boundTextElement.fontSize,
|
boundTextElement.fontSize,
|
||||||
boundTextElement.lineHeight,
|
boundTextElement.lineHeight,
|
||||||
);
|
);
|
||||||
@@ -569,9 +586,10 @@ export const resizeSingleElement = (
|
|||||||
});
|
});
|
||||||
|
|
||||||
mutateElement(element, resizedElement);
|
mutateElement(element, resizedElement);
|
||||||
if (boundTextElement && boundTextFontSize != null) {
|
if (boundTextElement && boundTextFont != null) {
|
||||||
mutateElement(boundTextElement, {
|
mutateElement(boundTextElement, {
|
||||||
fontSize: boundTextFontSize,
|
fontSize: boundTextFont.fontSize,
|
||||||
|
baseline: boundTextFont.baseline,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
handleBindTextResize(element, transformHandleDirection);
|
handleBindTextResize(element, transformHandleDirection);
|
||||||
@@ -678,6 +696,7 @@ const resizeMultipleElements = (
|
|||||||
y: number;
|
y: number;
|
||||||
points?: Point[];
|
points?: Point[];
|
||||||
fontSize?: number;
|
fontSize?: number;
|
||||||
|
baseline?: number;
|
||||||
} = {
|
} = {
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
@@ -686,7 +705,7 @@ const resizeMultipleElements = (
|
|||||||
...rescaledPoints,
|
...rescaledPoints,
|
||||||
};
|
};
|
||||||
|
|
||||||
let boundTextUpdates: { fontSize: number } | null = null;
|
let boundTextUpdates: { fontSize: number; baseline: number } | null = null;
|
||||||
|
|
||||||
const boundTextElement = getBoundTextElement(element.latest);
|
const boundTextElement = getBoundTextElement(element.latest);
|
||||||
|
|
||||||
@@ -696,24 +715,29 @@ const resizeMultipleElements = (
|
|||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
};
|
};
|
||||||
const fontSize = measureFontSizeFromWidth(
|
const metrics = measureFontSizeFromWidth(
|
||||||
boundTextElement ?? (element.orig as ExcalidrawTextElement),
|
boundTextElement ?? (element.orig as ExcalidrawTextElement),
|
||||||
boundTextElement
|
boundTextElement
|
||||||
? getBoundTextMaxWidth(updatedElement)
|
? getMaxContainerWidth(updatedElement)
|
||||||
: updatedElement.width,
|
: updatedElement.width,
|
||||||
|
boundTextElement
|
||||||
|
? getMaxContainerHeight(updatedElement)
|
||||||
|
: updatedElement.height,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!fontSize) {
|
if (!metrics) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isTextElement(element.orig)) {
|
if (isTextElement(element.orig)) {
|
||||||
update.fontSize = fontSize;
|
update.fontSize = metrics.size;
|
||||||
|
update.baseline = metrics.baseline;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (boundTextElement) {
|
if (boundTextElement) {
|
||||||
boundTextUpdates = {
|
boundTextUpdates = {
|
||||||
fontSize,
|
fontSize: metrics.size,
|
||||||
|
baseline: metrics.baseline,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+227
-56
@@ -1,11 +1,189 @@
|
|||||||
|
import { BOUND_TEXT_PADDING, FONT_FAMILY } from "../constants";
|
||||||
import { API } from "../tests/helpers/api";
|
import { API } from "../tests/helpers/api";
|
||||||
import {
|
import {
|
||||||
computeContainerDimensionForBoundText,
|
computeContainerDimensionForBoundText,
|
||||||
getContainerCoords,
|
getContainerCoords,
|
||||||
getBoundTextMaxWidth,
|
getMaxContainerWidth,
|
||||||
getBoundTextMaxHeight,
|
getMaxContainerHeight,
|
||||||
|
wrapText,
|
||||||
|
detectLineHeight,
|
||||||
|
getLineHeightInPx,
|
||||||
|
getDefaultLineHeight,
|
||||||
} from "./textElement";
|
} from "./textElement";
|
||||||
import { ExcalidrawTextElementWithContainer } from "./types";
|
import { FontString } from "./types";
|
||||||
|
|
||||||
|
describe("Test wrapText", () => {
|
||||||
|
const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
|
||||||
|
|
||||||
|
it("shouldn't add new lines for trailing spaces", () => {
|
||||||
|
const text = "Hello whats up ";
|
||||||
|
const maxWidth = 200 - BOUND_TEXT_PADDING * 2;
|
||||||
|
const res = wrapText(text, font, maxWidth);
|
||||||
|
expect(res).toBe(text);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should work with emojis", () => {
|
||||||
|
const text = "😀";
|
||||||
|
const maxWidth = 1;
|
||||||
|
const res = wrapText(text, font, maxWidth);
|
||||||
|
expect(res).toBe("😀");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should show the text correctly when max width reached", () => {
|
||||||
|
const text = "Hello😀";
|
||||||
|
const maxWidth = 10;
|
||||||
|
const res = wrapText(text, font, maxWidth);
|
||||||
|
expect(res).toBe("H\ne\nl\nl\no\n😀");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("When text doesn't contain new lines", () => {
|
||||||
|
const text = "Hello whats up";
|
||||||
|
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "break all words when width of each word is less than container width",
|
||||||
|
width: 80,
|
||||||
|
res: `Hello \nwhats \nup`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break all characters when width of each character is less than container width",
|
||||||
|
width: 25,
|
||||||
|
res: `H
|
||||||
|
e
|
||||||
|
l
|
||||||
|
l
|
||||||
|
o
|
||||||
|
w
|
||||||
|
h
|
||||||
|
a
|
||||||
|
t
|
||||||
|
s
|
||||||
|
u
|
||||||
|
p`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break words as per the width",
|
||||||
|
|
||||||
|
width: 140,
|
||||||
|
res: `Hello whats \nup`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the container",
|
||||||
|
|
||||||
|
width: 250,
|
||||||
|
res: "Hello whats up",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "should push the word if its equal to max width",
|
||||||
|
width: 60,
|
||||||
|
res: `Hello
|
||||||
|
whats
|
||||||
|
up`,
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("When text contain new lines", () => {
|
||||||
|
const text = `Hello
|
||||||
|
whats up`;
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "break all words when width of each word is less than container width",
|
||||||
|
width: 80,
|
||||||
|
res: `Hello\nwhats \nup`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break all characters when width of each character is less than container width",
|
||||||
|
width: 25,
|
||||||
|
res: `H
|
||||||
|
e
|
||||||
|
l
|
||||||
|
l
|
||||||
|
o
|
||||||
|
w
|
||||||
|
h
|
||||||
|
a
|
||||||
|
t
|
||||||
|
s
|
||||||
|
u
|
||||||
|
p`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break words as per the width",
|
||||||
|
|
||||||
|
width: 150,
|
||||||
|
res: `Hello
|
||||||
|
whats up`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the container",
|
||||||
|
|
||||||
|
width: 250,
|
||||||
|
res: `Hello
|
||||||
|
whats up`,
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should respect new lines and ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("When text is long", () => {
|
||||||
|
const text = `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg break it now`;
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "fit characters of long string as per container width",
|
||||||
|
width: 170,
|
||||||
|
res: `hellolongtextth\nisiswhatsupwith\nyouIamtypingggg\ngandtypinggg \nbreak it now`,
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
desc: "fit characters of long string as per container width and break words as per the width",
|
||||||
|
|
||||||
|
width: 130,
|
||||||
|
res: `hellolongte
|
||||||
|
xtthisiswha
|
||||||
|
tsupwithyou
|
||||||
|
Iamtypinggg
|
||||||
|
ggandtyping
|
||||||
|
gg break it
|
||||||
|
now`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the long text when container width is greater than text length and move the rest to next line",
|
||||||
|
|
||||||
|
width: 600,
|
||||||
|
res: `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg \nbreak it now`,
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should wrap the text correctly when word length is exactly equal to max width", () => {
|
||||||
|
const text = "Hello Excalidraw";
|
||||||
|
// Length of "Excalidraw" is 100 and exacty equal to max width
|
||||||
|
const res = wrapText(text, font, 100);
|
||||||
|
expect(res).toEqual(`Hello \nExcalidraw`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return the text as is if max width is invalid", () => {
|
||||||
|
const text = "Hello Excalidraw";
|
||||||
|
expect(wrapText(text, font, NaN)).toEqual(text);
|
||||||
|
expect(wrapText(text, font, -1)).toEqual(text);
|
||||||
|
expect(wrapText(text, font, Infinity)).toEqual(text);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("Test measureText", () => {
|
describe("Test measureText", () => {
|
||||||
describe("Test getContainerCoords", () => {
|
describe("Test getContainerCoords", () => {
|
||||||
@@ -82,7 +260,7 @@ describe("Test measureText", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("Test getBoundTextMaxWidth", () => {
|
describe("Test getMaxContainerWidth", () => {
|
||||||
const params = {
|
const params = {
|
||||||
width: 178,
|
width: 178,
|
||||||
height: 194,
|
height: 194,
|
||||||
@@ -90,84 +268,77 @@ describe("Test measureText", () => {
|
|||||||
|
|
||||||
it("should return max width when container is rectangle", () => {
|
it("should return max width when container is rectangle", () => {
|
||||||
const container = API.createElement({ type: "rectangle", ...params });
|
const container = API.createElement({ type: "rectangle", ...params });
|
||||||
expect(getBoundTextMaxWidth(container)).toBe(168);
|
expect(getMaxContainerWidth(container)).toBe(168);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return max width when container is ellipse", () => {
|
it("should return max width when container is ellipse", () => {
|
||||||
const container = API.createElement({ type: "ellipse", ...params });
|
const container = API.createElement({ type: "ellipse", ...params });
|
||||||
expect(getBoundTextMaxWidth(container)).toBe(116);
|
expect(getMaxContainerWidth(container)).toBe(116);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return max width when container is diamond", () => {
|
it("should return max width when container is diamond", () => {
|
||||||
const container = API.createElement({ type: "diamond", ...params });
|
const container = API.createElement({ type: "diamond", ...params });
|
||||||
expect(getBoundTextMaxWidth(container)).toBe(79);
|
expect(getMaxContainerWidth(container)).toBe(79);
|
||||||
});
|
|
||||||
|
|
||||||
it("should return max width when container is arrow", () => {
|
|
||||||
const container = API.createElement({
|
|
||||||
type: "arrow",
|
|
||||||
...params,
|
|
||||||
});
|
|
||||||
expect(getBoundTextMaxWidth(container)).toBe(220);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("Test getBoundTextMaxHeight", () => {
|
describe("Test getMaxContainerHeight", () => {
|
||||||
const params = {
|
const params = {
|
||||||
width: 178,
|
width: 178,
|
||||||
height: 194,
|
height: 194,
|
||||||
id: "container-id",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const boundTextElement = API.createElement({
|
|
||||||
type: "text",
|
|
||||||
id: "text-id",
|
|
||||||
x: 560.51171875,
|
|
||||||
y: 202.033203125,
|
|
||||||
width: 154,
|
|
||||||
height: 175,
|
|
||||||
fontSize: 20,
|
|
||||||
fontFamily: 1,
|
|
||||||
text: "Excalidraw is a\nvirtual \nopensource \nwhiteboard for \nsketching \nhand-drawn like\ndiagrams",
|
|
||||||
textAlign: "center",
|
|
||||||
verticalAlign: "middle",
|
|
||||||
containerId: params.id,
|
|
||||||
}) as ExcalidrawTextElementWithContainer;
|
|
||||||
|
|
||||||
it("should return max height when container is rectangle", () => {
|
it("should return max height when container is rectangle", () => {
|
||||||
const container = API.createElement({ type: "rectangle", ...params });
|
const container = API.createElement({ type: "rectangle", ...params });
|
||||||
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(184);
|
expect(getMaxContainerHeight(container)).toBe(184);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return max height when container is ellipse", () => {
|
it("should return max height when container is ellipse", () => {
|
||||||
const container = API.createElement({ type: "ellipse", ...params });
|
const container = API.createElement({ type: "ellipse", ...params });
|
||||||
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(127);
|
expect(getMaxContainerHeight(container)).toBe(127);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return max height when container is diamond", () => {
|
it("should return max height when container is diamond", () => {
|
||||||
const container = API.createElement({ type: "diamond", ...params });
|
const container = API.createElement({ type: "diamond", ...params });
|
||||||
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(87);
|
expect(getMaxContainerHeight(container)).toBe(87);
|
||||||
});
|
|
||||||
|
|
||||||
it("should return max height when container is arrow", () => {
|
|
||||||
const container = API.createElement({
|
|
||||||
type: "arrow",
|
|
||||||
...params,
|
|
||||||
});
|
|
||||||
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(194);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return max height when container is arrow and height is less than threshold", () => {
|
|
||||||
const container = API.createElement({
|
|
||||||
type: "arrow",
|
|
||||||
...params,
|
|
||||||
height: 70,
|
|
||||||
boundElements: [{ type: "text", id: "text-id" }],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(
|
|
||||||
boundTextElement.height,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const textElement = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "Excalidraw is a\nvirtual \nopensource \nwhiteboard for \nsketching \nhand-drawn like\ndiagrams",
|
||||||
|
fontSize: 20,
|
||||||
|
fontFamily: 1,
|
||||||
|
height: 175,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Test detectLineHeight", () => {
|
||||||
|
it("should return correct line height", () => {
|
||||||
|
expect(detectLineHeight(textElement)).toBe(1.25);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Test getLineHeightInPx", () => {
|
||||||
|
it("should return correct line height", () => {
|
||||||
|
expect(
|
||||||
|
getLineHeightInPx(textElement.fontSize, textElement.lineHeight),
|
||||||
|
).toBe(25);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Test getDefaultLineHeight", () => {
|
||||||
|
it("should return line height using default font family when not passed", () => {
|
||||||
|
//@ts-ignore
|
||||||
|
expect(getDefaultLineHeight()).toBe(1.25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return line height using default font family for unknown font", () => {
|
||||||
|
const UNKNOWN_FONT = 5;
|
||||||
|
expect(getDefaultLineHeight(UNKNOWN_FONT)).toBe(1.25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return correct line height", () => {
|
||||||
|
expect(getDefaultLineHeight(FONT_FAMILY.Cascadia)).toBe(1.2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+473
-50
@@ -1,13 +1,23 @@
|
|||||||
import { getFontString, arrayToMap } from "../utils";
|
import { getFontString, arrayToMap, isTestEnv } from "../utils";
|
||||||
import {
|
import {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
ExcalidrawTextContainer,
|
ExcalidrawTextContainer,
|
||||||
ExcalidrawTextElement,
|
ExcalidrawTextElement,
|
||||||
ExcalidrawTextElementWithContainer,
|
ExcalidrawTextElementWithContainer,
|
||||||
|
FontFamilyValues,
|
||||||
|
FontString,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import { BOUND_TEXT_PADDING, TEXT_ALIGN, VERTICAL_ALIGN } from "../constants";
|
import {
|
||||||
|
BOUND_TEXT_PADDING,
|
||||||
|
DEFAULT_FONT_FAMILY,
|
||||||
|
DEFAULT_FONT_SIZE,
|
||||||
|
FONT_FAMILY,
|
||||||
|
isSafari,
|
||||||
|
TEXT_ALIGN,
|
||||||
|
VERTICAL_ALIGN,
|
||||||
|
} from "../constants";
|
||||||
import { MaybeTransformHandleType } from "./transformHandles";
|
import { MaybeTransformHandleType } from "./transformHandles";
|
||||||
import Scene from "../scene/Scene";
|
import Scene from "../scene/Scene";
|
||||||
import { isTextElement } from ".";
|
import { isTextElement } from ".";
|
||||||
@@ -23,7 +33,6 @@ import {
|
|||||||
updateOriginalContainerCache,
|
updateOriginalContainerCache,
|
||||||
} from "./textWysiwyg";
|
} from "./textWysiwyg";
|
||||||
import { ExtractSetType } from "../utility-types";
|
import { ExtractSetType } from "../utility-types";
|
||||||
import { measureText, wrapText } from "./textMeasurements";
|
|
||||||
|
|
||||||
export const normalizeText = (text: string) => {
|
export const normalizeText = (text: string) => {
|
||||||
return (
|
return (
|
||||||
@@ -35,6 +44,10 @@ export const normalizeText = (text: string) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const splitIntoLines = (text: string) => {
|
||||||
|
return normalizeText(text).split("\n");
|
||||||
|
};
|
||||||
|
|
||||||
export const redrawTextBoundingBox = (
|
export const redrawTextBoundingBox = (
|
||||||
textElement: ExcalidrawTextElement,
|
textElement: ExcalidrawTextElement,
|
||||||
container: ExcalidrawElement | null,
|
container: ExcalidrawElement | null,
|
||||||
@@ -46,17 +59,19 @@ export const redrawTextBoundingBox = (
|
|||||||
text: textElement.text,
|
text: textElement.text,
|
||||||
width: textElement.width,
|
width: textElement.width,
|
||||||
height: textElement.height,
|
height: textElement.height,
|
||||||
|
baseline: textElement.baseline,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
boundTextUpdates.text = textElement.text;
|
||||||
|
|
||||||
if (container) {
|
if (container) {
|
||||||
maxWidth = getBoundTextMaxWidth(container);
|
maxWidth = getMaxContainerWidth(container);
|
||||||
boundTextUpdates.text = wrapText(
|
boundTextUpdates.text = wrapText(
|
||||||
textElement.originalText,
|
textElement.originalText,
|
||||||
getFontString(textElement),
|
getFontString(textElement),
|
||||||
maxWidth,
|
maxWidth,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const metrics = measureText(
|
const metrics = measureText(
|
||||||
boundTextUpdates.text,
|
boundTextUpdates.text,
|
||||||
getFontString(textElement),
|
getFontString(textElement),
|
||||||
@@ -65,31 +80,38 @@ export const redrawTextBoundingBox = (
|
|||||||
|
|
||||||
boundTextUpdates.width = metrics.width;
|
boundTextUpdates.width = metrics.width;
|
||||||
boundTextUpdates.height = metrics.height;
|
boundTextUpdates.height = metrics.height;
|
||||||
|
boundTextUpdates.baseline = metrics.baseline;
|
||||||
|
|
||||||
if (container) {
|
if (container) {
|
||||||
const containerDims = getContainerDims(container);
|
if (isArrowElement(container)) {
|
||||||
const maxContainerHeight = getBoundTextMaxHeight(
|
const centerX = textElement.x + textElement.width / 2;
|
||||||
container,
|
const centerY = textElement.y + textElement.height / 2;
|
||||||
textElement as ExcalidrawTextElementWithContainer,
|
const diffWidth = metrics.width - textElement.width;
|
||||||
);
|
const diffHeight = metrics.height - textElement.height;
|
||||||
let nextHeight = containerDims.height;
|
boundTextUpdates.x = centerY - (textElement.height + diffHeight) / 2;
|
||||||
|
boundTextUpdates.y = centerX - (textElement.width + diffWidth) / 2;
|
||||||
|
} else {
|
||||||
|
const containerDims = getContainerDims(container);
|
||||||
|
let maxContainerHeight = getMaxContainerHeight(container);
|
||||||
|
|
||||||
if (metrics.height > maxContainerHeight) {
|
let nextHeight = containerDims.height;
|
||||||
nextHeight = computeContainerDimensionForBoundText(
|
if (metrics.height > maxContainerHeight) {
|
||||||
metrics.height,
|
nextHeight = computeContainerDimensionForBoundText(
|
||||||
container.type,
|
metrics.height,
|
||||||
);
|
container.type,
|
||||||
mutateElement(container, { height: nextHeight });
|
);
|
||||||
updateOriginalContainerCache(container.id, nextHeight);
|
mutateElement(container, { height: nextHeight });
|
||||||
|
maxContainerHeight = getMaxContainerHeight(container);
|
||||||
|
updateOriginalContainerCache(container.id, nextHeight);
|
||||||
|
}
|
||||||
|
const updatedTextElement = {
|
||||||
|
...textElement,
|
||||||
|
...boundTextUpdates,
|
||||||
|
} as ExcalidrawTextElementWithContainer;
|
||||||
|
const { x, y } = computeBoundTextPosition(container, updatedTextElement);
|
||||||
|
boundTextUpdates.x = x;
|
||||||
|
boundTextUpdates.y = y;
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatedTextElement = {
|
|
||||||
...textElement,
|
|
||||||
...boundTextUpdates,
|
|
||||||
} as ExcalidrawTextElementWithContainer;
|
|
||||||
const { x, y } = computeBoundTextPosition(container, updatedTextElement);
|
|
||||||
boundTextUpdates.x = x;
|
|
||||||
boundTextUpdates.y = y;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mutateElement(textElement, boundTextUpdates);
|
mutateElement(textElement, boundTextUpdates);
|
||||||
@@ -161,12 +183,10 @@ export const handleBindTextResize = (
|
|||||||
let nextHeight = textElement.height;
|
let nextHeight = textElement.height;
|
||||||
let nextWidth = textElement.width;
|
let nextWidth = textElement.width;
|
||||||
const containerDims = getContainerDims(container);
|
const containerDims = getContainerDims(container);
|
||||||
const maxWidth = getBoundTextMaxWidth(container);
|
const maxWidth = getMaxContainerWidth(container);
|
||||||
const maxHeight = getBoundTextMaxHeight(
|
const maxHeight = getMaxContainerHeight(container);
|
||||||
container,
|
|
||||||
textElement as ExcalidrawTextElementWithContainer,
|
|
||||||
);
|
|
||||||
let containerHeight = containerDims.height;
|
let containerHeight = containerDims.height;
|
||||||
|
let nextBaseLine = textElement.baseline;
|
||||||
if (transformHandleType !== "n" && transformHandleType !== "s") {
|
if (transformHandleType !== "n" && transformHandleType !== "s") {
|
||||||
if (text) {
|
if (text) {
|
||||||
text = wrapText(
|
text = wrapText(
|
||||||
@@ -175,13 +195,14 @@ export const handleBindTextResize = (
|
|||||||
maxWidth,
|
maxWidth,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const dimensions = measureText(
|
const metrics = measureText(
|
||||||
text,
|
text,
|
||||||
getFontString(textElement),
|
getFontString(textElement),
|
||||||
textElement.lineHeight,
|
textElement.lineHeight,
|
||||||
);
|
);
|
||||||
nextHeight = dimensions.height;
|
nextHeight = metrics.height;
|
||||||
nextWidth = dimensions.width;
|
nextWidth = metrics.width;
|
||||||
|
nextBaseLine = metrics.baseline;
|
||||||
}
|
}
|
||||||
// increase height in case text element height exceeds
|
// increase height in case text element height exceeds
|
||||||
if (nextHeight > maxHeight) {
|
if (nextHeight > maxHeight) {
|
||||||
@@ -209,6 +230,7 @@ export const handleBindTextResize = (
|
|||||||
text,
|
text,
|
||||||
width: nextWidth,
|
width: nextWidth,
|
||||||
height: nextHeight,
|
height: nextHeight,
|
||||||
|
baseline: nextBaseLine,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!isArrowElement(container)) {
|
if (!isArrowElement(container)) {
|
||||||
@@ -223,22 +245,16 @@ export const handleBindTextResize = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const computeBoundTextPosition = (
|
const computeBoundTextPosition = (
|
||||||
container: ExcalidrawElement,
|
container: ExcalidrawElement,
|
||||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||||
) => {
|
) => {
|
||||||
const containerCoords = getContainerCoords(container);
|
const containerCoords = getContainerCoords(container);
|
||||||
const maxContainerHeight = getBoundTextMaxHeight(container, boundTextElement);
|
const maxContainerHeight = getMaxContainerHeight(container);
|
||||||
const maxContainerWidth = getBoundTextMaxWidth(container);
|
const maxContainerWidth = getMaxContainerWidth(container);
|
||||||
|
|
||||||
let x;
|
let x;
|
||||||
let y;
|
let y;
|
||||||
if (isArrowElement(container)) {
|
|
||||||
return LinearElementEditor.getBoundTextElementPosition(
|
|
||||||
container,
|
|
||||||
boundTextElement,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (boundTextElement.verticalAlign === VERTICAL_ALIGN.TOP) {
|
if (boundTextElement.verticalAlign === VERTICAL_ALIGN.TOP) {
|
||||||
y = containerCoords.y;
|
y = containerCoords.y;
|
||||||
} else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
} else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
||||||
@@ -259,6 +275,352 @@ export const computeBoundTextPosition = (
|
|||||||
return { x, y };
|
return { x, y };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js
|
||||||
|
|
||||||
|
export const measureText = (
|
||||||
|
text: string,
|
||||||
|
font: FontString,
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
) => {
|
||||||
|
text = text
|
||||||
|
.split("\n")
|
||||||
|
// replace empty lines with single space because leading/trailing empty
|
||||||
|
// lines would be stripped from computation
|
||||||
|
.map((x) => x || " ")
|
||||||
|
.join("\n");
|
||||||
|
const fontSize = parseFloat(font);
|
||||||
|
const height = getTextHeight(text, fontSize, lineHeight);
|
||||||
|
const width = getTextWidth(text, font);
|
||||||
|
const { baseline } = getDOMMetrics(text, font, lineHeight);
|
||||||
|
return { width, height, baseline };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDOMMetrics = (
|
||||||
|
text: string,
|
||||||
|
font: FontString,
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
wrapInContainer?: boolean,
|
||||||
|
) => {
|
||||||
|
const container = document.createElement("div");
|
||||||
|
container.style.position = "absolute";
|
||||||
|
container.style.whiteSpace = "pre";
|
||||||
|
container.style.font = font;
|
||||||
|
container.style.minHeight = "1em";
|
||||||
|
if (wrapInContainer) {
|
||||||
|
container.style.overflow = "hidden";
|
||||||
|
container.style.wordBreak = "break-word";
|
||||||
|
container.style.whiteSpace = "pre-wrap";
|
||||||
|
}
|
||||||
|
|
||||||
|
container.style.lineHeight = String(lineHeight);
|
||||||
|
const canvasHeight = getTextHeight(text, parseFloat(font), lineHeight);
|
||||||
|
|
||||||
|
container.innerText = text;
|
||||||
|
|
||||||
|
// Baseline is important for positioning text on canvas
|
||||||
|
document.body.appendChild(container);
|
||||||
|
|
||||||
|
const span = document.createElement("span");
|
||||||
|
span.style.display = "inline-block";
|
||||||
|
span.style.overflow = "hidden";
|
||||||
|
span.style.width = "1px";
|
||||||
|
span.style.height = "1px";
|
||||||
|
container.appendChild(span);
|
||||||
|
let baseline = span.offsetTop + span.offsetHeight;
|
||||||
|
const height = container.offsetHeight;
|
||||||
|
|
||||||
|
if (isSafari) {
|
||||||
|
// In Safari sometimes DOM height could be less than canvas height due to
|
||||||
|
// which text could go out of the bounding box hence shifting the baseline
|
||||||
|
// to make sure text is rendered correctly
|
||||||
|
if (canvasHeight > height) {
|
||||||
|
baseline += canvasHeight - height;
|
||||||
|
}
|
||||||
|
// In Safari sometimes DOM height could be more than canvas height due to
|
||||||
|
// which text could go out of the bounding box hence shifting the baseline
|
||||||
|
// to make sure text is rendered correctly
|
||||||
|
if (height > canvasHeight) {
|
||||||
|
baseline -= height - canvasHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.body.removeChild(container);
|
||||||
|
return { baseline, height };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* To get unitless line-height (if unknown) we can calculate it by dividing
|
||||||
|
* height-per-line by fontSize.
|
||||||
|
*/
|
||||||
|
export const detectLineHeight = (textElement: ExcalidrawTextElement) => {
|
||||||
|
const lineCount = splitIntoLines(textElement.text).length;
|
||||||
|
return (textElement.height /
|
||||||
|
lineCount /
|
||||||
|
textElement.fontSize) as ExcalidrawTextElement["lineHeight"];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We calculate the line height from the font size and the unitless line height,
|
||||||
|
* aligning with the W3C spec.
|
||||||
|
*/
|
||||||
|
export const getLineHeightInPx = (
|
||||||
|
fontSize: ExcalidrawTextElement["fontSize"],
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
) => {
|
||||||
|
const res = fontSize * lineHeight;
|
||||||
|
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// FIXME rename to getApproxMinContainerHeight
|
||||||
|
export const getApproxMinLineHeight = (
|
||||||
|
fontSize: ExcalidrawTextElement["fontSize"],
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
) => {
|
||||||
|
return getLineHeightInPx(fontSize, lineHeight) + BOUND_TEXT_PADDING * 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
let canvas: HTMLCanvasElement | undefined;
|
||||||
|
|
||||||
|
const getLineWidth = (text: string, font: FontString) => {
|
||||||
|
if (!canvas) {
|
||||||
|
canvas = document.createElement("canvas");
|
||||||
|
}
|
||||||
|
const canvas2dContext = canvas.getContext("2d")!;
|
||||||
|
canvas2dContext.font = font;
|
||||||
|
const width = canvas2dContext.measureText(text).width;
|
||||||
|
|
||||||
|
// since in test env the canvas measureText algo
|
||||||
|
// doesn't measure text and instead just returns number of
|
||||||
|
// characters hence we assume that each letteris 10px
|
||||||
|
if (isTestEnv()) {
|
||||||
|
return width * 10;
|
||||||
|
}
|
||||||
|
return width;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getTextWidth = (text: string, font: FontString) => {
|
||||||
|
const lines = splitIntoLines(text);
|
||||||
|
let width = 0;
|
||||||
|
lines.forEach((line) => {
|
||||||
|
width = Math.max(width, getLineWidth(line, font));
|
||||||
|
});
|
||||||
|
return width;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getTextHeight = (
|
||||||
|
text: string,
|
||||||
|
fontSize: number,
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
) => {
|
||||||
|
const lineCount = splitIntoLines(text).length;
|
||||||
|
return getLineHeightInPx(fontSize, lineHeight) * lineCount;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const wrapText = (text: string, font: FontString, maxWidth: number) => {
|
||||||
|
// if maxWidth is not finite or NaN which can happen in case of bugs in
|
||||||
|
// computation, we need to make sure we don't continue as we'll end up
|
||||||
|
// in an infinite loop
|
||||||
|
if (!Number.isFinite(maxWidth) || maxWidth < 0) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines: Array<string> = [];
|
||||||
|
const originalLines = text.split("\n");
|
||||||
|
const spaceWidth = getLineWidth(" ", font);
|
||||||
|
|
||||||
|
let currentLine = "";
|
||||||
|
let currentLineWidthTillNow = 0;
|
||||||
|
|
||||||
|
const push = (str: string) => {
|
||||||
|
if (str.trim()) {
|
||||||
|
lines.push(str);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetParams = () => {
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
originalLines.forEach((originalLine) => {
|
||||||
|
const currentLineWidth = getTextWidth(originalLine, font);
|
||||||
|
|
||||||
|
//Push the line if its <= maxWidth
|
||||||
|
if (currentLineWidth <= maxWidth) {
|
||||||
|
lines.push(originalLine);
|
||||||
|
return; // continue
|
||||||
|
}
|
||||||
|
const words = originalLine.split(" ");
|
||||||
|
|
||||||
|
resetParams();
|
||||||
|
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
while (index < words.length) {
|
||||||
|
const currentWordWidth = getLineWidth(words[index], font);
|
||||||
|
|
||||||
|
// This will only happen when single word takes entire width
|
||||||
|
if (currentWordWidth === maxWidth) {
|
||||||
|
push(words[index]);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start breaking longer words exceeding max width
|
||||||
|
else if (currentWordWidth > maxWidth) {
|
||||||
|
// push current line since the current word exceeds the max width
|
||||||
|
// so will be appended in next line
|
||||||
|
push(currentLine);
|
||||||
|
|
||||||
|
resetParams();
|
||||||
|
|
||||||
|
while (words[index].length > 0) {
|
||||||
|
const currentChar = String.fromCodePoint(
|
||||||
|
words[index].codePointAt(0)!,
|
||||||
|
);
|
||||||
|
const width = charWidth.calculate(currentChar, font);
|
||||||
|
currentLineWidthTillNow += width;
|
||||||
|
words[index] = words[index].slice(currentChar.length);
|
||||||
|
|
||||||
|
if (currentLineWidthTillNow >= maxWidth) {
|
||||||
|
push(currentLine);
|
||||||
|
currentLine = currentChar;
|
||||||
|
currentLineWidthTillNow = width;
|
||||||
|
} else {
|
||||||
|
currentLine += currentChar;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// push current line if appending space exceeds max width
|
||||||
|
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
||||||
|
push(currentLine);
|
||||||
|
resetParams();
|
||||||
|
} else {
|
||||||
|
// space needs to be appended before next word
|
||||||
|
// as currentLine contains chars which couldn't be appended
|
||||||
|
// to previous line
|
||||||
|
currentLine += " ";
|
||||||
|
currentLineWidthTillNow += spaceWidth;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
} else {
|
||||||
|
// Start appending words in a line till max width reached
|
||||||
|
while (currentLineWidthTillNow < maxWidth && index < words.length) {
|
||||||
|
const word = words[index];
|
||||||
|
currentLineWidthTillNow = getLineWidth(currentLine + word, font);
|
||||||
|
|
||||||
|
if (currentLineWidthTillNow > maxWidth) {
|
||||||
|
push(currentLine);
|
||||||
|
resetParams();
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
currentLine += `${word} `;
|
||||||
|
|
||||||
|
// Push the word if appending space exceeds max width
|
||||||
|
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
||||||
|
const word = currentLine.slice(0, -1);
|
||||||
|
push(word);
|
||||||
|
resetParams();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentLine.slice(-1) === " ") {
|
||||||
|
// only remove last trailing space which we have added when joining words
|
||||||
|
currentLine = currentLine.slice(0, -1);
|
||||||
|
push(currentLine);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return lines.join("\n");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const charWidth = (() => {
|
||||||
|
const cachedCharWidth: { [key: FontString]: Array<number> } = {};
|
||||||
|
|
||||||
|
const calculate = (char: string, font: FontString) => {
|
||||||
|
const ascii = char.charCodeAt(0);
|
||||||
|
if (!cachedCharWidth[font]) {
|
||||||
|
cachedCharWidth[font] = [];
|
||||||
|
}
|
||||||
|
if (!cachedCharWidth[font][ascii]) {
|
||||||
|
const width = getLineWidth(char, font);
|
||||||
|
cachedCharWidth[font][ascii] = width;
|
||||||
|
}
|
||||||
|
|
||||||
|
return cachedCharWidth[font][ascii];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCache = (font: FontString) => {
|
||||||
|
return cachedCharWidth[font];
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
calculate,
|
||||||
|
getCache,
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
|
||||||
|
|
||||||
|
// FIXME rename to getApproxMinContainerWidth
|
||||||
|
export const getApproxMinLineWidth = (
|
||||||
|
font: FontString,
|
||||||
|
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||||
|
) => {
|
||||||
|
const maxCharWidth = getMaxCharWidth(font);
|
||||||
|
if (maxCharWidth === 0) {
|
||||||
|
return (
|
||||||
|
measureText(DUMMY_TEXT.split("").join("\n"), font, lineHeight).width +
|
||||||
|
BOUND_TEXT_PADDING * 2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return maxCharWidth + BOUND_TEXT_PADDING * 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMinCharWidth = (font: FontString) => {
|
||||||
|
const cache = charWidth.getCache(font);
|
||||||
|
if (!cache) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const cacheWithOutEmpty = cache.filter((val) => val !== undefined);
|
||||||
|
|
||||||
|
return Math.min(...cacheWithOutEmpty);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMaxCharWidth = (font: FontString) => {
|
||||||
|
const cache = charWidth.getCache(font);
|
||||||
|
if (!cache) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const cacheWithOutEmpty = cache.filter((val) => val !== undefined);
|
||||||
|
return Math.max(...cacheWithOutEmpty);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getApproxCharsToFitInWidth = (font: FontString, width: number) => {
|
||||||
|
// Generally lower case is used so converting to lower case
|
||||||
|
const dummyText = DUMMY_TEXT.toLocaleLowerCase();
|
||||||
|
const batchLength = 6;
|
||||||
|
let index = 0;
|
||||||
|
let widthTillNow = 0;
|
||||||
|
let str = "";
|
||||||
|
while (widthTillNow <= width) {
|
||||||
|
const batch = dummyText.substr(index, index + batchLength);
|
||||||
|
str += batch;
|
||||||
|
widthTillNow += getLineWidth(str, font);
|
||||||
|
if (index === dummyText.length - 1) {
|
||||||
|
index = 0;
|
||||||
|
}
|
||||||
|
index = index + batchLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (widthTillNow > width) {
|
||||||
|
str = str.substr(0, str.length - 1);
|
||||||
|
widthTillNow = getLineWidth(str, font);
|
||||||
|
}
|
||||||
|
return str.length;
|
||||||
|
};
|
||||||
|
|
||||||
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||||
return container?.boundElements?.length
|
return container?.boundElements?.length
|
||||||
? container?.boundElements?.filter((ele) => ele.type === "text")[0]?.id ||
|
? container?.boundElements?.filter((ele) => ele.type === "text")[0]?.id ||
|
||||||
@@ -384,6 +746,18 @@ export const getBoundTextElementOffset = (
|
|||||||
return BOUND_TEXT_PADDING;
|
return BOUND_TEXT_PADDING;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getBoundTextElementPosition = (
|
||||||
|
container: ExcalidrawElement,
|
||||||
|
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||||
|
) => {
|
||||||
|
if (isArrowElement(container)) {
|
||||||
|
return LinearElementEditor.getBoundTextElementPosition(
|
||||||
|
container,
|
||||||
|
boundTextElement,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const shouldAllowVerticalAlign = (
|
export const shouldAllowVerticalAlign = (
|
||||||
selectedElements: NonDeletedExcalidrawElement[],
|
selectedElements: NonDeletedExcalidrawElement[],
|
||||||
) => {
|
) => {
|
||||||
@@ -484,10 +858,18 @@ export const computeContainerDimensionForBoundText = (
|
|||||||
return dimension + padding;
|
return dimension + padding;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getBoundTextMaxWidth = (container: ExcalidrawElement) => {
|
export const getMaxContainerWidth = (container: ExcalidrawElement) => {
|
||||||
const width = getContainerDims(container).width;
|
const width = getContainerDims(container).width;
|
||||||
if (isArrowElement(container)) {
|
if (isArrowElement(container)) {
|
||||||
return width - BOUND_TEXT_PADDING * 8 * 2;
|
const containerWidth = width - BOUND_TEXT_PADDING * 8 * 2;
|
||||||
|
if (containerWidth <= 0) {
|
||||||
|
const boundText = getBoundTextElement(container);
|
||||||
|
if (boundText) {
|
||||||
|
return boundText.width;
|
||||||
|
}
|
||||||
|
return BOUND_TEXT_PADDING * 8 * 2;
|
||||||
|
}
|
||||||
|
return containerWidth;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (container.type === "ellipse") {
|
if (container.type === "ellipse") {
|
||||||
@@ -504,15 +886,16 @@ export const getBoundTextMaxWidth = (container: ExcalidrawElement) => {
|
|||||||
return width - BOUND_TEXT_PADDING * 2;
|
return width - BOUND_TEXT_PADDING * 2;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getBoundTextMaxHeight = (
|
export const getMaxContainerHeight = (container: ExcalidrawElement) => {
|
||||||
container: ExcalidrawElement,
|
|
||||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
|
||||||
) => {
|
|
||||||
const height = getContainerDims(container).height;
|
const height = getContainerDims(container).height;
|
||||||
if (isArrowElement(container)) {
|
if (isArrowElement(container)) {
|
||||||
const containerHeight = height - BOUND_TEXT_PADDING * 8 * 2;
|
const containerHeight = height - BOUND_TEXT_PADDING * 8 * 2;
|
||||||
if (containerHeight <= 0) {
|
if (containerHeight <= 0) {
|
||||||
return boundTextElement.height;
|
const boundText = getBoundTextElement(container);
|
||||||
|
if (boundText) {
|
||||||
|
return boundText.height;
|
||||||
|
}
|
||||||
|
return BOUND_TEXT_PADDING * 8 * 2;
|
||||||
}
|
}
|
||||||
return height;
|
return height;
|
||||||
}
|
}
|
||||||
@@ -529,3 +912,43 @@ export const getBoundTextMaxHeight = (
|
|||||||
}
|
}
|
||||||
return height - BOUND_TEXT_PADDING * 2;
|
return height - BOUND_TEXT_PADDING * 2;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const isMeasureTextSupported = () => {
|
||||||
|
const width = getTextWidth(
|
||||||
|
DUMMY_TEXT,
|
||||||
|
getFontString({
|
||||||
|
fontSize: DEFAULT_FONT_SIZE,
|
||||||
|
fontFamily: DEFAULT_FONT_FAMILY,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return width > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unitless line height
|
||||||
|
*
|
||||||
|
* In previous versions we used `normal` line height, which browsers interpret
|
||||||
|
* differently, and based on font-family and font-size.
|
||||||
|
*
|
||||||
|
* To make line heights consistent across browsers we hardcode the values for
|
||||||
|
* each of our fonts based on most common average line-heights.
|
||||||
|
* See https://github.com/excalidraw/excalidraw/pull/6360#issuecomment-1477635971
|
||||||
|
* where the values come from.
|
||||||
|
*/
|
||||||
|
const DEFAULT_LINE_HEIGHT = {
|
||||||
|
// ~1.25 is the average for Virgil in WebKit and Blink.
|
||||||
|
// Gecko (FF) uses ~1.28.
|
||||||
|
[FONT_FAMILY.Virgil]: 1.25 as ExcalidrawTextElement["lineHeight"],
|
||||||
|
// ~1.15 is the average for Virgil in WebKit and Blink.
|
||||||
|
// Gecko if all over the place.
|
||||||
|
[FONT_FAMILY.Helvetica]: 1.15 as ExcalidrawTextElement["lineHeight"],
|
||||||
|
// ~1.2 is the average for Virgil in WebKit and Blink, and kinda Gecko too
|
||||||
|
[FONT_FAMILY.Cascadia]: 1.2 as ExcalidrawTextElement["lineHeight"],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDefaultLineHeight = (fontFamily: FontFamilyValues) => {
|
||||||
|
if (fontFamily in DEFAULT_LINE_HEIGHT) {
|
||||||
|
return DEFAULT_LINE_HEIGHT[fontFamily];
|
||||||
|
}
|
||||||
|
return DEFAULT_LINE_HEIGHT[DEFAULT_FONT_FAMILY];
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,213 +0,0 @@
|
|||||||
import { BOUND_TEXT_PADDING, FONT_FAMILY } from "../constants";
|
|
||||||
import { API } from "../tests/helpers/api";
|
|
||||||
import {
|
|
||||||
detectLineHeight,
|
|
||||||
getDefaultLineHeight,
|
|
||||||
getLineHeightInPx,
|
|
||||||
wrapText,
|
|
||||||
} from "./textMeasurements";
|
|
||||||
import { FontString } from "./types";
|
|
||||||
|
|
||||||
describe("Test wrapText", () => {
|
|
||||||
const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
|
|
||||||
|
|
||||||
it("shouldn't add new lines for trailing spaces", () => {
|
|
||||||
const text = "Hello whats up ";
|
|
||||||
const maxWidth = 200 - BOUND_TEXT_PADDING * 2;
|
|
||||||
const res = wrapText(text, font, maxWidth);
|
|
||||||
expect(res).toBe(text);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should work with emojis", () => {
|
|
||||||
const text = "😀";
|
|
||||||
const maxWidth = 1;
|
|
||||||
const res = wrapText(text, font, maxWidth);
|
|
||||||
expect(res).toBe("😀");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should show the text correctly when max width reached", () => {
|
|
||||||
const text = "Hello😀";
|
|
||||||
const maxWidth = 10;
|
|
||||||
const res = wrapText(text, font, maxWidth);
|
|
||||||
expect(res).toBe("H\ne\nl\nl\no\n😀");
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("When text doesn't contain new lines", () => {
|
|
||||||
const text = "Hello whats up";
|
|
||||||
|
|
||||||
[
|
|
||||||
{
|
|
||||||
desc: "break all words when width of each word is less than container width",
|
|
||||||
width: 80,
|
|
||||||
res: `Hello \nwhats \nup`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "break all characters when width of each character is less than container width",
|
|
||||||
width: 25,
|
|
||||||
res: `H
|
|
||||||
e
|
|
||||||
l
|
|
||||||
l
|
|
||||||
o
|
|
||||||
w
|
|
||||||
h
|
|
||||||
a
|
|
||||||
t
|
|
||||||
s
|
|
||||||
u
|
|
||||||
p`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "break words as per the width",
|
|
||||||
|
|
||||||
width: 140,
|
|
||||||
res: `Hello whats \nup`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "fit the container",
|
|
||||||
|
|
||||||
width: 250,
|
|
||||||
res: "Hello whats up",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "should push the word if its equal to max width",
|
|
||||||
width: 60,
|
|
||||||
res: `Hello
|
|
||||||
whats
|
|
||||||
up`,
|
|
||||||
},
|
|
||||||
].forEach((data) => {
|
|
||||||
it(`should ${data.desc}`, () => {
|
|
||||||
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
|
||||||
expect(res).toEqual(data.res);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("When text contain new lines", () => {
|
|
||||||
const text = `Hello
|
|
||||||
whats up`;
|
|
||||||
[
|
|
||||||
{
|
|
||||||
desc: "break all words when width of each word is less than container width",
|
|
||||||
width: 80,
|
|
||||||
res: `Hello\nwhats \nup`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "break all characters when width of each character is less than container width",
|
|
||||||
width: 25,
|
|
||||||
res: `H
|
|
||||||
e
|
|
||||||
l
|
|
||||||
l
|
|
||||||
o
|
|
||||||
w
|
|
||||||
h
|
|
||||||
a
|
|
||||||
t
|
|
||||||
s
|
|
||||||
u
|
|
||||||
p`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "break words as per the width",
|
|
||||||
|
|
||||||
width: 150,
|
|
||||||
res: `Hello
|
|
||||||
whats up`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "fit the container",
|
|
||||||
|
|
||||||
width: 250,
|
|
||||||
res: `Hello
|
|
||||||
whats up`,
|
|
||||||
},
|
|
||||||
].forEach((data) => {
|
|
||||||
it(`should respect new lines and ${data.desc}`, () => {
|
|
||||||
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
|
||||||
expect(res).toEqual(data.res);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("When text is long", () => {
|
|
||||||
const text = `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg break it now`;
|
|
||||||
[
|
|
||||||
{
|
|
||||||
desc: "fit characters of long string as per container width",
|
|
||||||
width: 170,
|
|
||||||
res: `hellolongtextth\nisiswhatsupwith\nyouIamtypingggg\ngandtypinggg \nbreak it now`,
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
desc: "fit characters of long string as per container width and break words as per the width",
|
|
||||||
|
|
||||||
width: 130,
|
|
||||||
res: `hellolongte
|
|
||||||
xtthisiswha
|
|
||||||
tsupwithyou
|
|
||||||
Iamtypinggg
|
|
||||||
ggandtyping
|
|
||||||
gg break it
|
|
||||||
now`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
desc: "fit the long text when container width is greater than text length and move the rest to next line",
|
|
||||||
|
|
||||||
width: 600,
|
|
||||||
res: `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg \nbreak it now`,
|
|
||||||
},
|
|
||||||
].forEach((data) => {
|
|
||||||
it(`should ${data.desc}`, () => {
|
|
||||||
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
|
|
||||||
expect(res).toEqual(data.res);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should wrap the text correctly when word length is exactly equal to max width", () => {
|
|
||||||
const text = "Hello Excalidraw";
|
|
||||||
// Length of "Excalidraw" is 100 and exacty equal to max width
|
|
||||||
const res = wrapText(text, font, 100);
|
|
||||||
expect(res).toEqual(`Hello \nExcalidraw`);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return the text as is if max width is invalid", () => {
|
|
||||||
const text = "Hello Excalidraw";
|
|
||||||
expect(wrapText(text, font, NaN)).toEqual(text);
|
|
||||||
expect(wrapText(text, font, -1)).toEqual(text);
|
|
||||||
expect(wrapText(text, font, Infinity)).toEqual(text);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
const textElement = API.createElement({
|
|
||||||
type: "text",
|
|
||||||
text: "Excalidraw is a\nvirtual \nopensource \nwhiteboard for \nsketching \nhand-drawn like\ndiagrams",
|
|
||||||
fontSize: 20,
|
|
||||||
fontFamily: 1,
|
|
||||||
height: 175,
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Test detectLineHeight", () => {
|
|
||||||
it("should return correct line height", () => {
|
|
||||||
expect(detectLineHeight(textElement)).toBe(1.25);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Test getLineHeightInPx", () => {
|
|
||||||
it("should return correct line height", () => {
|
|
||||||
expect(
|
|
||||||
getLineHeightInPx(textElement.fontSize, textElement.lineHeight),
|
|
||||||
).toBe(25);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Test getDefaultLineHeight", () => {
|
|
||||||
it("should return line height using default font family when not passed", () => {
|
|
||||||
//@ts-ignore
|
|
||||||
expect(getDefaultLineHeight()).toBe(1.25);
|
|
||||||
});
|
|
||||||
it("should return correct line height", () => {
|
|
||||||
expect(getDefaultLineHeight(FONT_FAMILY.Cascadia)).toBe(1.2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
import {
|
|
||||||
BOUND_TEXT_PADDING,
|
|
||||||
DEFAULT_FONT_FAMILY,
|
|
||||||
DEFAULT_FONT_SIZE,
|
|
||||||
FONT_FAMILY,
|
|
||||||
} from "../constants";
|
|
||||||
import { getFontString, isTestEnv } from "../utils";
|
|
||||||
import { normalizeText } from "./textElement";
|
|
||||||
import { ExcalidrawTextElement, FontFamilyValues, FontString } from "./types";
|
|
||||||
|
|
||||||
const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
|
|
||||||
|
|
||||||
let canvas: HTMLCanvasElement | undefined;
|
|
||||||
|
|
||||||
// since in test env the canvas measureText algo
|
|
||||||
// doesn't measure text and instead just returns number of
|
|
||||||
// characters hence we assume that each letter is 10px
|
|
||||||
const DUMMY_CHAR_WIDTH = 10;
|
|
||||||
|
|
||||||
const getLineWidth = (text: string, font: FontString) => {
|
|
||||||
if (!canvas) {
|
|
||||||
canvas = document.createElement("canvas");
|
|
||||||
}
|
|
||||||
const canvas2dContext = canvas.getContext("2d")!;
|
|
||||||
canvas2dContext.font = font;
|
|
||||||
const width = canvas2dContext.measureText(text).width;
|
|
||||||
|
|
||||||
/* istanbul ignore else */
|
|
||||||
if (isTestEnv()) {
|
|
||||||
return width * DUMMY_CHAR_WIDTH;
|
|
||||||
}
|
|
||||||
/* istanbul ignore next */
|
|
||||||
return width;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getTextWidth = (text: string, font: FontString) => {
|
|
||||||
const lines = splitIntoLines(text);
|
|
||||||
let width = 0;
|
|
||||||
lines.forEach((line) => {
|
|
||||||
width = Math.max(width, getLineWidth(line, font));
|
|
||||||
});
|
|
||||||
return width;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getTextHeight = (
|
|
||||||
text: string,
|
|
||||||
fontSize: number,
|
|
||||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
|
||||||
) => {
|
|
||||||
const lineCount = splitIntoLines(text).length;
|
|
||||||
return getLineHeightInPx(fontSize, lineHeight) * lineCount;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const splitIntoLines = (text: string) => {
|
|
||||||
return normalizeText(text).split("\n");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const measureText = (
|
|
||||||
text: string,
|
|
||||||
font: FontString,
|
|
||||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
|
||||||
) => {
|
|
||||||
text = text
|
|
||||||
.split("\n")
|
|
||||||
// replace empty lines with single space because leading/trailing empty
|
|
||||||
// lines would be stripped from computation
|
|
||||||
.map((x) => x || " ")
|
|
||||||
.join("\n");
|
|
||||||
const fontSize = parseFloat(font);
|
|
||||||
const height = getTextHeight(text, fontSize, lineHeight);
|
|
||||||
const width = getTextWidth(text, font);
|
|
||||||
|
|
||||||
return { width, height };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getApproxMinContainerWidth = (
|
|
||||||
font: FontString,
|
|
||||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
|
||||||
) => {
|
|
||||||
const maxCharWidth = getMaxCharWidth(font);
|
|
||||||
if (maxCharWidth === 0) {
|
|
||||||
return (
|
|
||||||
measureText(DUMMY_TEXT.split("").join("\n"), font, lineHeight).width +
|
|
||||||
BOUND_TEXT_PADDING * 2
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return maxCharWidth + BOUND_TEXT_PADDING * 2;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getApproxMinContainerHeight = (
|
|
||||||
fontSize: ExcalidrawTextElement["fontSize"],
|
|
||||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
|
||||||
) => {
|
|
||||||
return getLineHeightInPx(fontSize, lineHeight) + BOUND_TEXT_PADDING * 2;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const charWidth = (() => {
|
|
||||||
const cachedCharWidth: { [key: FontString]: Array<number> } = {};
|
|
||||||
|
|
||||||
const calculate = (char: string, font: FontString) => {
|
|
||||||
const ascii = char.charCodeAt(0);
|
|
||||||
if (!cachedCharWidth[font]) {
|
|
||||||
cachedCharWidth[font] = [];
|
|
||||||
}
|
|
||||||
if (!cachedCharWidth[font][ascii]) {
|
|
||||||
const width = getLineWidth(char, font);
|
|
||||||
cachedCharWidth[font][ascii] = width;
|
|
||||||
}
|
|
||||||
|
|
||||||
return cachedCharWidth[font][ascii];
|
|
||||||
};
|
|
||||||
|
|
||||||
const getCache = (font: FontString) => {
|
|
||||||
return cachedCharWidth[font];
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
calculate,
|
|
||||||
getCache,
|
|
||||||
};
|
|
||||||
})();
|
|
||||||
|
|
||||||
export const getMaxCharWidth = (font: FontString) => {
|
|
||||||
const cache = charWidth.getCache(font);
|
|
||||||
if (!cache) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
const cacheWithOutEmpty = cache.filter((val) => val !== undefined);
|
|
||||||
return Math.max(...cacheWithOutEmpty);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** this is not used currently but might be useful
|
|
||||||
* in future hence keeping it
|
|
||||||
*/
|
|
||||||
/* istanbul ignore next */
|
|
||||||
export const getApproxCharsToFitInWidth = (font: FontString, width: number) => {
|
|
||||||
// Generally lower case is used so converting to lower case
|
|
||||||
const dummyText = DUMMY_TEXT.toLocaleLowerCase();
|
|
||||||
const batchLength = 6;
|
|
||||||
let index = 0;
|
|
||||||
let widthTillNow = 0;
|
|
||||||
let str = "";
|
|
||||||
while (widthTillNow <= width) {
|
|
||||||
const batch = dummyText.substr(index, index + batchLength);
|
|
||||||
str += batch;
|
|
||||||
widthTillNow += getLineWidth(str, font);
|
|
||||||
if (index === dummyText.length - 1) {
|
|
||||||
index = 0;
|
|
||||||
}
|
|
||||||
index = index + batchLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (widthTillNow > width) {
|
|
||||||
str = str.substr(0, str.length - 1);
|
|
||||||
widthTillNow = getLineWidth(str, font);
|
|
||||||
}
|
|
||||||
return str.length;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const wrapText = (text: string, font: FontString, maxWidth: number) => {
|
|
||||||
// if maxWidth is not finite or NaN which can happen in case of bugs in
|
|
||||||
// computation, we need to make sure we don't continue as we'll end up
|
|
||||||
// in an infinite loop
|
|
||||||
if (!Number.isFinite(maxWidth) || maxWidth < 0) {
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lines: Array<string> = [];
|
|
||||||
const originalLines = text.split("\n");
|
|
||||||
const spaceWidth = getLineWidth(" ", font);
|
|
||||||
|
|
||||||
let currentLine = "";
|
|
||||||
let currentLineWidthTillNow = 0;
|
|
||||||
|
|
||||||
const push = (str: string) => {
|
|
||||||
if (str.trim()) {
|
|
||||||
lines.push(str);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetParams = () => {
|
|
||||||
currentLine = "";
|
|
||||||
currentLineWidthTillNow = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
originalLines.forEach((originalLine) => {
|
|
||||||
const currentLineWidth = getTextWidth(originalLine, font);
|
|
||||||
|
|
||||||
//Push the line if its <= maxWidth
|
|
||||||
if (currentLineWidth <= maxWidth) {
|
|
||||||
lines.push(originalLine);
|
|
||||||
return; // continue
|
|
||||||
}
|
|
||||||
const words = originalLine.split(" ");
|
|
||||||
|
|
||||||
resetParams();
|
|
||||||
|
|
||||||
let index = 0;
|
|
||||||
|
|
||||||
while (index < words.length) {
|
|
||||||
const currentWordWidth = getLineWidth(words[index], font);
|
|
||||||
|
|
||||||
// This will only happen when single word takes entire width
|
|
||||||
if (currentWordWidth === maxWidth) {
|
|
||||||
push(words[index]);
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start breaking longer words exceeding max width
|
|
||||||
else if (currentWordWidth > maxWidth) {
|
|
||||||
// push current line since the current word exceeds the max width
|
|
||||||
// so will be appended in next line
|
|
||||||
push(currentLine);
|
|
||||||
|
|
||||||
resetParams();
|
|
||||||
|
|
||||||
while (words[index].length > 0) {
|
|
||||||
const currentChar = String.fromCodePoint(
|
|
||||||
words[index].codePointAt(0)!,
|
|
||||||
);
|
|
||||||
const width = charWidth.calculate(currentChar, font);
|
|
||||||
currentLineWidthTillNow += width;
|
|
||||||
words[index] = words[index].slice(currentChar.length);
|
|
||||||
|
|
||||||
if (currentLineWidthTillNow >= maxWidth) {
|
|
||||||
push(currentLine);
|
|
||||||
currentLine = currentChar;
|
|
||||||
currentLineWidthTillNow = width;
|
|
||||||
} else {
|
|
||||||
currentLine += currentChar;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// push current line if appending space exceeds max width
|
|
||||||
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
|
||||||
push(currentLine);
|
|
||||||
resetParams();
|
|
||||||
} else {
|
|
||||||
// space needs to be appended before next word
|
|
||||||
// as currentLine contains chars which couldn't be appended
|
|
||||||
// to previous line
|
|
||||||
currentLine += " ";
|
|
||||||
currentLineWidthTillNow += spaceWidth;
|
|
||||||
}
|
|
||||||
index++;
|
|
||||||
} else {
|
|
||||||
// Start appending words in a line till max width reached
|
|
||||||
while (currentLineWidthTillNow < maxWidth && index < words.length) {
|
|
||||||
const word = words[index];
|
|
||||||
currentLineWidthTillNow = getLineWidth(currentLine + word, font);
|
|
||||||
|
|
||||||
if (currentLineWidthTillNow > maxWidth) {
|
|
||||||
push(currentLine);
|
|
||||||
resetParams();
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
index++;
|
|
||||||
currentLine += `${word} `;
|
|
||||||
|
|
||||||
// Push the word if appending space exceeds max width
|
|
||||||
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
|
||||||
const word = currentLine.slice(0, -1);
|
|
||||||
push(word);
|
|
||||||
resetParams();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (currentLine.slice(-1) === " ") {
|
|
||||||
// only remove last trailing space which we have added when joining words
|
|
||||||
currentLine = currentLine.slice(0, -1);
|
|
||||||
push(currentLine);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return lines.join("\n");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isMeasureTextSupported = () => {
|
|
||||||
const width = getTextWidth(
|
|
||||||
DUMMY_TEXT,
|
|
||||||
getFontString({
|
|
||||||
fontSize: DEFAULT_FONT_SIZE,
|
|
||||||
fontFamily: DEFAULT_FONT_FAMILY,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
return width > 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* We calculate the line height from the font size and the unitless line height,
|
|
||||||
* aligning with the W3C spec.
|
|
||||||
*/
|
|
||||||
export const getLineHeightInPx = (
|
|
||||||
fontSize: ExcalidrawTextElement["fontSize"],
|
|
||||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
|
||||||
) => {
|
|
||||||
return fontSize * lineHeight;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* To get unitless line-height (if unknown) we can calculate it by dividing
|
|
||||||
* height-per-line by fontSize.
|
|
||||||
*/
|
|
||||||
export const detectLineHeight = (textElement: ExcalidrawTextElement) => {
|
|
||||||
const lineCount = splitIntoLines(textElement.text).length;
|
|
||||||
return (textElement.height /
|
|
||||||
lineCount /
|
|
||||||
textElement.fontSize) as ExcalidrawTextElement["lineHeight"];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unitless line height
|
|
||||||
*
|
|
||||||
* In previous versions we used `normal` line height, which browsers interpret
|
|
||||||
* differently, and based on font-family and font-size.
|
|
||||||
*
|
|
||||||
* To make line heights consistent across browsers we hardcode the values for
|
|
||||||
* each of our fonts based on most common average line-heights.
|
|
||||||
* See https://github.com/excalidraw/excalidraw/pull/6360#issuecomment-1477635971
|
|
||||||
* where the values come from.
|
|
||||||
*/
|
|
||||||
const DEFAULT_LINE_HEIGHT = {
|
|
||||||
// ~1.25 is the average for Virgil in WebKit and Blink.
|
|
||||||
// Gecko (FF) uses ~1.28.
|
|
||||||
[FONT_FAMILY.Virgil]: 1.25 as ExcalidrawTextElement["lineHeight"],
|
|
||||||
// ~1.15 is the average for Helvetica in WebKit and Blink.
|
|
||||||
// Gecko if all over the place.
|
|
||||||
[FONT_FAMILY.Helvetica]: 1.15 as ExcalidrawTextElement["lineHeight"],
|
|
||||||
// ~1.2 is the average for Cascadia in WebKit and Blink, and kinda Gecko too
|
|
||||||
[FONT_FAMILY.Cascadia]: 1.2 as ExcalidrawTextElement["lineHeight"],
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getDefaultLineHeight = (fontFamily: FontFamilyValues) => {
|
|
||||||
if (fontFamily) {
|
|
||||||
return DEFAULT_LINE_HEIGHT[fontFamily];
|
|
||||||
}
|
|
||||||
return DEFAULT_LINE_HEIGHT[DEFAULT_FONT_FAMILY];
|
|
||||||
};
|
|
||||||
@@ -526,6 +526,44 @@ describe("textWysiwyg", () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should compute the container height correctly and not throw error when height is updated while editing the text", async () => {
|
||||||
|
const diamond = API.createElement({
|
||||||
|
type: "diamond",
|
||||||
|
x: 10,
|
||||||
|
y: 20,
|
||||||
|
width: 90,
|
||||||
|
height: 75,
|
||||||
|
});
|
||||||
|
h.elements = [diamond];
|
||||||
|
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
expect(h.elements[0].id).toBe(diamond.id);
|
||||||
|
|
||||||
|
API.setSelectedElements([diamond]);
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
const value = new Array(1000).fill("1").join("\n");
|
||||||
|
|
||||||
|
// Pasting large text to simulate height increase
|
||||||
|
expect(() =>
|
||||||
|
fireEvent.input(editor, { target: { value } }),
|
||||||
|
).not.toThrow();
|
||||||
|
|
||||||
|
expect(diamond.height).toBe(50020);
|
||||||
|
|
||||||
|
// Clearing text to simulate height decrease
|
||||||
|
expect(() =>
|
||||||
|
fireEvent.input(editor, { target: { value: "" } }),
|
||||||
|
).not.toThrow();
|
||||||
|
|
||||||
|
expect(diamond.height).toBe(70);
|
||||||
|
});
|
||||||
|
|
||||||
it("should bind text to container when double clicked on center of transparent container", async () => {
|
it("should bind text to container when double clicked on center of transparent container", async () => {
|
||||||
const rectangle = API.createElement({
|
const rectangle = API.createElement({
|
||||||
type: "rectangle",
|
type: "rectangle",
|
||||||
@@ -1181,9 +1219,7 @@ describe("textWysiwyg", () => {
|
|||||||
expect(
|
expect(
|
||||||
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
|
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
|
||||||
).toEqual(36);
|
).toEqual(36);
|
||||||
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
|
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(97);
|
||||||
96.39999999999999,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should update line height when font family updated", async () => {
|
it("should update line height when font family updated", async () => {
|
||||||
|
|||||||
+73
-47
@@ -11,7 +11,7 @@ import {
|
|||||||
isBoundToContainer,
|
isBoundToContainer,
|
||||||
isTextElement,
|
isTextElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
import { CLASSES } from "../constants";
|
import { CLASSES, isSafari, VERTICAL_ALIGN } from "../constants";
|
||||||
import {
|
import {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
ExcalidrawLinearElement,
|
ExcalidrawLinearElement,
|
||||||
@@ -23,14 +23,21 @@ import { AppState } from "../types";
|
|||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import {
|
import {
|
||||||
getBoundTextElementId,
|
getBoundTextElementId,
|
||||||
|
getContainerCoords,
|
||||||
getContainerDims,
|
getContainerDims,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
getTextElementAngle,
|
getTextElementAngle,
|
||||||
|
getTextWidth,
|
||||||
|
measureText,
|
||||||
normalizeText,
|
normalizeText,
|
||||||
redrawTextBoundingBox,
|
redrawTextBoundingBox,
|
||||||
getBoundTextMaxHeight,
|
wrapText,
|
||||||
getBoundTextMaxWidth,
|
getMaxContainerHeight,
|
||||||
computeBoundTextPosition,
|
getMaxContainerWidth,
|
||||||
|
computeContainerDimensionForBoundText,
|
||||||
|
getDOMMetrics,
|
||||||
|
splitIntoLines,
|
||||||
|
detectLineHeight,
|
||||||
} from "./textElement";
|
} from "./textElement";
|
||||||
import {
|
import {
|
||||||
actionDecreaseFontSize,
|
actionDecreaseFontSize,
|
||||||
@@ -40,12 +47,6 @@ import { actionZoomIn, actionZoomOut } from "../actions/actionCanvas";
|
|||||||
import App from "../components/App";
|
import App from "../components/App";
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
import { LinearElementEditor } from "./linearElementEditor";
|
||||||
import { parseClipboard } from "../clipboard";
|
import { parseClipboard } from "../clipboard";
|
||||||
import {
|
|
||||||
getTextWidth,
|
|
||||||
measureText,
|
|
||||||
wrapText,
|
|
||||||
getTextHeight,
|
|
||||||
} from "./textMeasurements";
|
|
||||||
|
|
||||||
const getTransform = (
|
const getTransform = (
|
||||||
width: number,
|
width: number,
|
||||||
@@ -180,12 +181,15 @@ export const textWysiwyg = ({
|
|||||||
editable,
|
editable,
|
||||||
);
|
);
|
||||||
const containerDims = getContainerDims(container);
|
const containerDims = getContainerDims(container);
|
||||||
|
// using editor.style.height to get the accurate height of text editor
|
||||||
textElementHeight = getTextHeight(
|
const editorHeight = Number(editable.style.height.slice(0, -2));
|
||||||
updatedTextElement.text,
|
if (editorHeight > 0) {
|
||||||
updatedTextElement.fontSize,
|
textElementHeight = editorHeight;
|
||||||
updatedTextElement.lineHeight,
|
}
|
||||||
);
|
if (propertiesUpdated) {
|
||||||
|
// update height of the editor after properties updated
|
||||||
|
textElementHeight = updatedTextElement.height;
|
||||||
|
}
|
||||||
|
|
||||||
let originalContainerData;
|
let originalContainerData;
|
||||||
if (propertiesUpdated) {
|
if (propertiesUpdated) {
|
||||||
@@ -203,19 +207,17 @@ export const textWysiwyg = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
maxWidth = getBoundTextMaxWidth(container);
|
maxWidth = getMaxContainerWidth(container);
|
||||||
maxHeight = getBoundTextMaxHeight(
|
maxHeight = getMaxContainerHeight(container);
|
||||||
container,
|
|
||||||
updatedTextElement as ExcalidrawTextElementWithContainer,
|
|
||||||
);
|
|
||||||
|
|
||||||
// autogrow container height if text exceeds
|
// autogrow container height if text exceeds
|
||||||
if (!isArrowElement(container) && textElementHeight > maxHeight) {
|
if (!isArrowElement(container) && textElementHeight > maxHeight) {
|
||||||
const diff = Math.min(
|
const targetContainerHeight = computeContainerDimensionForBoundText(
|
||||||
textElementHeight - maxHeight,
|
textElementHeight,
|
||||||
element.lineHeight,
|
container.type,
|
||||||
);
|
);
|
||||||
mutateElement(container, { height: containerDims.height + diff });
|
|
||||||
|
mutateElement(container, { height: targetContainerHeight });
|
||||||
return;
|
return;
|
||||||
} else if (
|
} else if (
|
||||||
// autoshrink container height until original container height
|
// autoshrink container height until original container height
|
||||||
@@ -224,17 +226,27 @@ export const textWysiwyg = ({
|
|||||||
containerDims.height > originalContainerData.height &&
|
containerDims.height > originalContainerData.height &&
|
||||||
textElementHeight < maxHeight
|
textElementHeight < maxHeight
|
||||||
) {
|
) {
|
||||||
const diff = Math.min(
|
const targetContainerHeight = computeContainerDimensionForBoundText(
|
||||||
maxHeight - textElementHeight,
|
textElementHeight,
|
||||||
element.lineHeight,
|
container.type,
|
||||||
);
|
);
|
||||||
mutateElement(container, { height: containerDims.height - diff });
|
mutateElement(container, { height: targetContainerHeight });
|
||||||
} else {
|
}
|
||||||
const { y } = computeBoundTextPosition(
|
// Start pushing text upward until a diff of 30px (padding)
|
||||||
container,
|
// is reached
|
||||||
updatedTextElement as ExcalidrawTextElementWithContainer,
|
else {
|
||||||
);
|
const containerCoords = getContainerCoords(container);
|
||||||
coordY = y;
|
|
||||||
|
// vertically center align the text
|
||||||
|
if (verticalAlign === VERTICAL_ALIGN.MIDDLE) {
|
||||||
|
if (!isArrowElement(container)) {
|
||||||
|
coordY =
|
||||||
|
containerCoords.y + maxHeight / 2 - textElementHeight / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
||||||
|
coordY = containerCoords.y + (maxHeight - textElementHeight);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const [viewportX, viewportY] = getViewportCoords(coordX, coordY);
|
const [viewportX, viewportY] = getViewportCoords(coordX, coordY);
|
||||||
@@ -262,25 +274,38 @@ export const textWysiwyg = ({
|
|||||||
} else {
|
} else {
|
||||||
textElementWidth += 0.5;
|
textElementWidth += 0.5;
|
||||||
}
|
}
|
||||||
|
const { height: domHeight } = getDOMMetrics(
|
||||||
|
updatedTextElement.text,
|
||||||
|
getFontString(updatedTextElement),
|
||||||
|
updatedTextElement.lineHeight,
|
||||||
|
);
|
||||||
|
|
||||||
|
let lineHeight = element.lineHeight;
|
||||||
|
const fontSize = Math.floor(updatedTextElement.fontSize);
|
||||||
|
|
||||||
|
if (isSafari) {
|
||||||
|
//@ts-ignore
|
||||||
|
lineHeight =
|
||||||
|
updatedTextElement.height /
|
||||||
|
splitIntoLines(updatedTextElement.text).length /
|
||||||
|
fontSize;
|
||||||
|
}
|
||||||
|
|
||||||
// Make sure text editor height doesn't go beyond viewport
|
// Make sure text editor height doesn't go beyond viewport
|
||||||
const editorMaxHeight =
|
const editorMaxHeight =
|
||||||
(appState.height - viewportY) / appState.zoom.value;
|
(appState.height - viewportY) / appState.zoom.value;
|
||||||
Object.assign(editable.style, {
|
Object.assign(editable.style, {
|
||||||
font: getFontString(updatedTextElement),
|
font: getFontString({
|
||||||
|
fontSize,
|
||||||
|
fontFamily: updatedTextElement.fontFamily,
|
||||||
|
}),
|
||||||
// must be defined *after* font ¯\_(ツ)_/¯
|
// must be defined *after* font ¯\_(ツ)_/¯
|
||||||
lineHeight: element.lineHeight,
|
lineHeight,
|
||||||
width: `${textElementWidth}px`,
|
width: `${textElementWidth}px`,
|
||||||
height: `${textElementHeight}px`,
|
height: `${textElementHeight}px`,
|
||||||
left: `${viewportX}px`,
|
left: `${viewportX}px`,
|
||||||
top: `${viewportY}px`,
|
top: `${viewportY}px`,
|
||||||
transform: getTransform(
|
transform: `scale(${updatedTextElement.fontSize / fontSize})`,
|
||||||
textElementWidth,
|
|
||||||
textElementHeight,
|
|
||||||
getTextElementAngle(updatedTextElement),
|
|
||||||
appState,
|
|
||||||
maxWidth,
|
|
||||||
editorMaxHeight,
|
|
||||||
),
|
|
||||||
textAlign,
|
textAlign,
|
||||||
verticalAlign,
|
verticalAlign,
|
||||||
color: updatedTextElement.strokeColor,
|
color: updatedTextElement.strokeColor,
|
||||||
@@ -288,6 +313,7 @@ export const textWysiwyg = ({
|
|||||||
filter: "var(--theme-filter)",
|
filter: "var(--theme-filter)",
|
||||||
maxHeight: `${editorMaxHeight}px`,
|
maxHeight: `${editorMaxHeight}px`,
|
||||||
});
|
});
|
||||||
|
editable.scrollTop = 0;
|
||||||
// For some reason updating font attribute doesn't set font family
|
// For some reason updating font attribute doesn't set font family
|
||||||
// hence updating font family explicitly for test environment
|
// hence updating font family explicitly for test environment
|
||||||
if (isTestEnv()) {
|
if (isTestEnv()) {
|
||||||
@@ -355,7 +381,7 @@ export const textWysiwyg = ({
|
|||||||
const wrappedText = wrapText(
|
const wrappedText = wrapText(
|
||||||
`${editable.value}${data}`,
|
`${editable.value}${data}`,
|
||||||
font,
|
font,
|
||||||
getBoundTextMaxWidth(container),
|
getMaxContainerWidth(container),
|
||||||
);
|
);
|
||||||
const width = getTextWidth(wrappedText, font);
|
const width = getTextWidth(wrappedText, font);
|
||||||
editable.style.width = `${width}px`;
|
editable.style.width = `${width}px`;
|
||||||
@@ -372,7 +398,7 @@ export const textWysiwyg = ({
|
|||||||
const wrappedText = wrapText(
|
const wrappedText = wrapText(
|
||||||
normalizeText(editable.value),
|
normalizeText(editable.value),
|
||||||
font,
|
font,
|
||||||
getBoundTextMaxWidth(container!),
|
getMaxContainerWidth(container!),
|
||||||
);
|
);
|
||||||
const { width, height } = measureText(
|
const { width, height } = measureText(
|
||||||
wrappedText,
|
wrappedText,
|
||||||
|
|||||||
@@ -131,6 +131,7 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
|
|||||||
fontSize: number;
|
fontSize: number;
|
||||||
fontFamily: FontFamilyValues;
|
fontFamily: FontFamilyValues;
|
||||||
text: string;
|
text: string;
|
||||||
|
baseline: number;
|
||||||
textAlign: TextAlign;
|
textAlign: TextAlign;
|
||||||
verticalAlign: VerticalAlign;
|
verticalAlign: VerticalAlign;
|
||||||
containerId: ExcalidrawGenericElement["id"] | null;
|
containerId: ExcalidrawGenericElement["id"] | null;
|
||||||
|
|||||||
Vendored
+2
@@ -18,6 +18,8 @@ interface Window {
|
|||||||
EXCALIDRAW_EXPORT_SOURCE: string;
|
EXCALIDRAW_EXPORT_SOURCE: string;
|
||||||
EXCALIDRAW_THROTTLE_RENDER: boolean | undefined;
|
EXCALIDRAW_THROTTLE_RENDER: boolean | undefined;
|
||||||
gtag: Function;
|
gtag: Function;
|
||||||
|
_paq: any[];
|
||||||
|
_mtm: any[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CanvasRenderingContext2D {
|
interface CanvasRenderingContext2D {
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ Please add the latest change on the top under the correct section.
|
|||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|
||||||
|
- [`ExcalidrawAPI.scrolToContent`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props/ref#scrolltocontent) has new opts object allowing you to fit viewport to content, and animate the scrolling. [#6319](https://github.com/excalidraw/excalidraw/pull/6319)
|
||||||
|
|
||||||
- Expose `useI18n()` hook return an object containing `t()` i18n helper and current `langCode`. You can use this in components you render as `<Excalidraw>` children to render any of our i18n locale strings. [#6224](https://github.com/excalidraw/excalidraw/pull/6224)
|
- Expose `useI18n()` hook return an object containing `t()` i18n helper and current `langCode`. You can use this in components you render as `<Excalidraw>` children to render any of our i18n locale strings. [#6224](https://github.com/excalidraw/excalidraw/pull/6224)
|
||||||
|
|
||||||
- [`restoreElements`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/utils/restore#restoreelements) API now takes an optional parameter `opts` which currently supports the below attributes
|
- [`restoreElements`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/utils/restore#restoreelements) API now takes an optional parameter `opts` which currently supports the below attributes
|
||||||
|
|||||||
@@ -43,11 +43,11 @@ import {
|
|||||||
getBoundTextElement,
|
getBoundTextElement,
|
||||||
getContainerCoords,
|
getContainerCoords,
|
||||||
getContainerElement,
|
getContainerElement,
|
||||||
getBoundTextMaxHeight,
|
getLineHeightInPx,
|
||||||
getBoundTextMaxWidth,
|
getMaxContainerHeight,
|
||||||
|
getMaxContainerWidth,
|
||||||
} from "../element/textElement";
|
} from "../element/textElement";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { getLineHeightInPx } from "../element/textMeasurements";
|
|
||||||
|
|
||||||
// using a stronger invert (100% vs our regular 93%) and saturate
|
// using a stronger invert (100% vs our regular 93%) and saturate
|
||||||
// as a temp hack to make images in dark theme look closer to original
|
// as a temp hack to make images in dark theme look closer to original
|
||||||
@@ -200,7 +200,6 @@ const drawImagePlaceholder = (
|
|||||||
size,
|
size,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const drawElementOnCanvas = (
|
const drawElementOnCanvas = (
|
||||||
element: NonDeletedExcalidrawElement,
|
element: NonDeletedExcalidrawElement,
|
||||||
rc: RoughCanvas,
|
rc: RoughCanvas,
|
||||||
@@ -273,30 +272,32 @@ const drawElementOnCanvas = (
|
|||||||
}
|
}
|
||||||
context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
|
context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
|
||||||
context.save();
|
context.save();
|
||||||
context.font = getFontString(element);
|
context.font = getFontString({
|
||||||
|
...element,
|
||||||
|
fontSize: Math.floor(element.fontSize),
|
||||||
|
});
|
||||||
context.fillStyle = element.strokeColor;
|
context.fillStyle = element.strokeColor;
|
||||||
context.textAlign = element.textAlign as CanvasTextAlign;
|
context.textAlign = element.textAlign as CanvasTextAlign;
|
||||||
|
|
||||||
// Canvas does not support multiline text by default
|
// Canvas does not support multiline text by default
|
||||||
const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
|
const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
|
||||||
|
|
||||||
const horizontalOffset =
|
const horizontalOffset =
|
||||||
element.textAlign === "center"
|
element.textAlign === "center"
|
||||||
? element.width / 2
|
? element.width / 2
|
||||||
: element.textAlign === "right"
|
: element.textAlign === "right"
|
||||||
? element.width
|
? element.width
|
||||||
: 0;
|
: 0;
|
||||||
context.textBaseline = "bottom";
|
|
||||||
|
|
||||||
const lineHeightPx = getLineHeightInPx(
|
const lineHeightPx = getLineHeightInPx(
|
||||||
element.fontSize,
|
element.fontSize,
|
||||||
element.lineHeight,
|
element.lineHeight,
|
||||||
);
|
);
|
||||||
|
const verticalOffset = element.height - element.baseline;
|
||||||
for (let index = 0; index < lines.length; index++) {
|
for (let index = 0; index < lines.length; index++) {
|
||||||
context.fillText(
|
context.fillText(
|
||||||
lines[index],
|
lines[index],
|
||||||
horizontalOffset,
|
horizontalOffset,
|
||||||
(index + 1) * lineHeightPx,
|
(index + 1) * lineHeightPx - verticalOffset,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
context.restore();
|
context.restore();
|
||||||
@@ -822,17 +823,14 @@ const drawElementFromCanvas = (
|
|||||||
process.env.REACT_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX &&
|
process.env.REACT_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX &&
|
||||||
hasBoundTextElement(element)
|
hasBoundTextElement(element)
|
||||||
) {
|
) {
|
||||||
const textElement = getBoundTextElement(
|
|
||||||
element,
|
|
||||||
) as ExcalidrawTextElementWithContainer;
|
|
||||||
const coords = getContainerCoords(element);
|
const coords = getContainerCoords(element);
|
||||||
context.strokeStyle = "#c92a2a";
|
context.strokeStyle = "#c92a2a";
|
||||||
context.lineWidth = 3;
|
context.lineWidth = 3;
|
||||||
context.strokeRect(
|
context.strokeRect(
|
||||||
(coords.x + renderConfig.scrollX) * window.devicePixelRatio,
|
(coords.x + renderConfig.scrollX) * window.devicePixelRatio,
|
||||||
(coords.y + renderConfig.scrollY) * window.devicePixelRatio,
|
(coords.y + renderConfig.scrollY) * window.devicePixelRatio,
|
||||||
getBoundTextMaxWidth(element) * window.devicePixelRatio,
|
getMaxContainerWidth(element) * window.devicePixelRatio,
|
||||||
getBoundTextMaxHeight(element, textElement) * window.devicePixelRatio,
|
getMaxContainerHeight(element) * window.devicePixelRatio,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,12 @@ import { render, waitFor, GlobalTestState } from "./test-utils";
|
|||||||
import { Pointer, Keyboard } from "./helpers/ui";
|
import { Pointer, Keyboard } from "./helpers/ui";
|
||||||
import ExcalidrawApp from "../excalidraw-app";
|
import ExcalidrawApp from "../excalidraw-app";
|
||||||
import { KEYS } from "../keys";
|
import { KEYS } from "../keys";
|
||||||
|
|
||||||
import { getElementBounds } from "../element";
|
|
||||||
import { NormalizedZoomValue } from "../types";
|
|
||||||
import {
|
import {
|
||||||
getDefaultLineHeight,
|
getDefaultLineHeight,
|
||||||
getLineHeightInPx,
|
getLineHeightInPx,
|
||||||
} from "../element/textMeasurements";
|
} from "../element/textElement";
|
||||||
|
import { getElementBounds } from "../element";
|
||||||
|
import { NormalizedZoomValue } from "../types";
|
||||||
|
|
||||||
const { h } = window;
|
const { h } = window;
|
||||||
|
|
||||||
|
|||||||
@@ -282,6 +282,7 @@ exports[`restoreElements should restore text element correctly passing value for
|
|||||||
Object {
|
Object {
|
||||||
"angle": 0,
|
"angle": 0,
|
||||||
"backgroundColor": "transparent",
|
"backgroundColor": "transparent",
|
||||||
|
"baseline": 0,
|
||||||
"boundElements": Array [],
|
"boundElements": Array [],
|
||||||
"containerId": null,
|
"containerId": null,
|
||||||
"fillStyle": "hachure",
|
"fillStyle": "hachure",
|
||||||
@@ -321,6 +322,7 @@ exports[`restoreElements should restore text element correctly with unknown font
|
|||||||
Object {
|
Object {
|
||||||
"angle": 0,
|
"angle": 0,
|
||||||
"backgroundColor": "transparent",
|
"backgroundColor": "transparent",
|
||||||
|
"baseline": 0,
|
||||||
"boundElements": Array [],
|
"boundElements": Array [],
|
||||||
"containerId": null,
|
"containerId": null,
|
||||||
"fillStyle": "hachure",
|
"fillStyle": "hachure",
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import { render } from "./test-utils";
|
||||||
|
import { API } from "./helpers/api";
|
||||||
|
|
||||||
|
import ExcalidrawApp from "../excalidraw-app";
|
||||||
|
|
||||||
|
const { h } = window;
|
||||||
|
|
||||||
|
describe("fitToContent", () => {
|
||||||
|
it("should zoom to fit the selected element", async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
h.state.width = 10;
|
||||||
|
h.state.height = 10;
|
||||||
|
|
||||||
|
const rectElement = API.createElement({
|
||||||
|
width: 50,
|
||||||
|
height: 100,
|
||||||
|
x: 50,
|
||||||
|
y: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
|
||||||
|
h.app.scrollToContent(rectElement, { fitToContent: true });
|
||||||
|
|
||||||
|
// element is 10x taller than the viewport size,
|
||||||
|
// zoom should be at least 1/10
|
||||||
|
expect(h.state.zoom.value).toBeLessThanOrEqual(0.1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should zoom to fit multiple elements", async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
const topLeft = API.createElement({
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const bottomRight = API.createElement({
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
x: 80,
|
||||||
|
y: 80,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.state.width = 10;
|
||||||
|
h.state.height = 10;
|
||||||
|
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
|
||||||
|
h.app.scrollToContent([topLeft, bottomRight], {
|
||||||
|
fitToContent: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// elements take 100x100, which is 10x bigger than the viewport size,
|
||||||
|
// zoom should be at least 1/10
|
||||||
|
expect(h.state.zoom.value).toBeLessThanOrEqual(0.1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should scroll the viewport to the selected element", async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
h.state.width = 10;
|
||||||
|
h.state.height = 10;
|
||||||
|
|
||||||
|
const rectElement = API.createElement({
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
x: 100,
|
||||||
|
y: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
expect(h.state.scrollX).toBe(0);
|
||||||
|
expect(h.state.scrollY).toBe(0);
|
||||||
|
|
||||||
|
h.app.scrollToContent(rectElement);
|
||||||
|
|
||||||
|
// zoom level should stay the same
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
|
||||||
|
// state should reflect some scrolling
|
||||||
|
expect(h.state.scrollX).not.toBe(0);
|
||||||
|
expect(h.state.scrollY).not.toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const waitForNextAnimationFrame = () => {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(resolve);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("fitToContent animated", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.spyOn(window, "requestAnimationFrame");
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should ease scroll the viewport to the selected element", async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
h.state.width = 10;
|
||||||
|
h.state.height = 10;
|
||||||
|
|
||||||
|
const rectElement = API.createElement({
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
x: -100,
|
||||||
|
y: -100,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.app.scrollToContent(rectElement, { animate: true });
|
||||||
|
|
||||||
|
expect(window.requestAnimationFrame).toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Since this is an animation, we expect values to change through time.
|
||||||
|
// We'll verify that the scroll values change at 50ms and 100ms
|
||||||
|
expect(h.state.scrollX).toBe(0);
|
||||||
|
expect(h.state.scrollY).toBe(0);
|
||||||
|
|
||||||
|
await waitForNextAnimationFrame();
|
||||||
|
|
||||||
|
const prevScrollX = h.state.scrollX;
|
||||||
|
const prevScrollY = h.state.scrollY;
|
||||||
|
|
||||||
|
expect(h.state.scrollX).not.toBe(0);
|
||||||
|
expect(h.state.scrollY).not.toBe(0);
|
||||||
|
|
||||||
|
await waitForNextAnimationFrame();
|
||||||
|
|
||||||
|
expect(h.state.scrollX).not.toBe(prevScrollX);
|
||||||
|
expect(h.state.scrollY).not.toBe(prevScrollY);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should animate the scroll but not the zoom", async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
h.state.width = 50;
|
||||||
|
h.state.height = 50;
|
||||||
|
|
||||||
|
const rectElement = API.createElement({
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
x: 100,
|
||||||
|
y: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(h.state.scrollX).toBe(0);
|
||||||
|
expect(h.state.scrollY).toBe(0);
|
||||||
|
|
||||||
|
h.app.scrollToContent(rectElement, { animate: true, fitToContent: true });
|
||||||
|
|
||||||
|
expect(window.requestAnimationFrame).toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Since this is an animation, we expect values to change through time.
|
||||||
|
// We'll verify that the zoom/scroll values change in each animation frame
|
||||||
|
|
||||||
|
// zoom is not animated, it should be set to its final value, which in our
|
||||||
|
// case zooms out to 50% so that th element is fully visible (it's 2x large
|
||||||
|
// as the canvas)
|
||||||
|
expect(h.state.zoom.value).toBeLessThanOrEqual(0.5);
|
||||||
|
|
||||||
|
// FIXME I think this should be [-100, -100] so we may have a bug in our zoom
|
||||||
|
// hadnling, alas
|
||||||
|
expect(h.state.scrollX).toBe(25);
|
||||||
|
expect(h.state.scrollY).toBe(25);
|
||||||
|
|
||||||
|
await waitForNextAnimationFrame();
|
||||||
|
|
||||||
|
const prevScrollX = h.state.scrollX;
|
||||||
|
const prevScrollY = h.state.scrollY;
|
||||||
|
|
||||||
|
expect(h.state.scrollX).not.toBe(0);
|
||||||
|
expect(h.state.scrollY).not.toBe(0);
|
||||||
|
|
||||||
|
await waitForNextAnimationFrame();
|
||||||
|
|
||||||
|
expect(h.state.scrollX).not.toBe(prevScrollX);
|
||||||
|
expect(h.state.scrollY).not.toBe(prevScrollY);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -17,8 +17,11 @@ import { KEYS } from "../keys";
|
|||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { queryByTestId, queryByText } from "@testing-library/react";
|
import { queryByTestId, queryByText } from "@testing-library/react";
|
||||||
import { resize, rotate } from "./utils";
|
import { resize, rotate } from "./utils";
|
||||||
import { getBoundTextMaxWidth } from "../element/textElement";
|
import {
|
||||||
import { wrapText } from "../element/textMeasurements";
|
getBoundTextElementPosition,
|
||||||
|
wrapText,
|
||||||
|
getMaxContainerWidth,
|
||||||
|
} from "../element/textElement";
|
||||||
import * as textElementUtils from "../element/textElement";
|
import * as textElementUtils from "../element/textElement";
|
||||||
import { ROUNDNESS } from "../constants";
|
import { ROUNDNESS } from "../constants";
|
||||||
|
|
||||||
@@ -726,7 +729,7 @@ describe("Test Linear Elements", () => {
|
|||||||
type: "text",
|
type: "text",
|
||||||
x: 0,
|
x: 0,
|
||||||
y: 0,
|
y: 0,
|
||||||
text: wrapText(text, font, getBoundTextMaxWidth(container)),
|
text: wrapText(text, font, getMaxContainerWidth(container)),
|
||||||
containerId: container.id,
|
containerId: container.id,
|
||||||
width: 30,
|
width: 30,
|
||||||
height: 20,
|
height: 20,
|
||||||
@@ -934,9 +937,8 @@ describe("Test Linear Elements", () => {
|
|||||||
|
|
||||||
expect(container.angle).toBe(0);
|
expect(container.angle).toBe(0);
|
||||||
expect(textElement.angle).toBe(0);
|
expect(textElement.angle).toBe(0);
|
||||||
expect(
|
expect(getBoundTextElementPosition(arrow, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(arrow, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 75,
|
"x": 75,
|
||||||
"y": 60,
|
"y": 60,
|
||||||
@@ -962,9 +964,8 @@ describe("Test Linear Elements", () => {
|
|||||||
rotate(container, -35, 55);
|
rotate(container, -35, 55);
|
||||||
expect(container.angle).toMatchInlineSnapshot(`1.3988061968364685`);
|
expect(container.angle).toMatchInlineSnapshot(`1.3988061968364685`);
|
||||||
expect(textElement.angle).toBe(0);
|
expect(textElement.angle).toBe(0);
|
||||||
expect(
|
expect(getBoundTextElementPosition(container, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(container, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 21.73926141863671,
|
"x": 21.73926141863671,
|
||||||
"y": 73.31003398390868,
|
"y": 73.31003398390868,
|
||||||
@@ -1001,9 +1002,8 @@ describe("Test Linear Elements", () => {
|
|||||||
);
|
);
|
||||||
expect(container.width).toBe(70);
|
expect(container.width).toBe(70);
|
||||||
expect(container.height).toBe(50);
|
expect(container.height).toBe(50);
|
||||||
expect(
|
expect(getBoundTextElementPosition(container, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(container, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 75,
|
"x": 75,
|
||||||
"y": 60,
|
"y": 60,
|
||||||
@@ -1036,9 +1036,8 @@ describe("Test Linear Elements", () => {
|
|||||||
}
|
}
|
||||||
`);
|
`);
|
||||||
|
|
||||||
expect(
|
expect(getBoundTextElementPosition(container, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(container, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 272,
|
"x": 272,
|
||||||
"y": 45,
|
"y": 45,
|
||||||
@@ -1071,9 +1070,8 @@ describe("Test Linear Elements", () => {
|
|||||||
arrow,
|
arrow,
|
||||||
);
|
);
|
||||||
expect(container.width).toBe(40);
|
expect(container.width).toBe(40);
|
||||||
expect(
|
expect(getBoundTextElementPosition(container, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(container, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 25,
|
"x": 25,
|
||||||
"y": 10,
|
"y": 10,
|
||||||
@@ -1097,9 +1095,8 @@ describe("Test Linear Elements", () => {
|
|||||||
}
|
}
|
||||||
`);
|
`);
|
||||||
|
|
||||||
expect(
|
expect(getBoundTextElementPosition(container, textElement))
|
||||||
LinearElementEditor.getBoundTextElementPosition(container, textElement),
|
.toMatchInlineSnapshot(`
|
||||||
).toMatchInlineSnapshot(`
|
|
||||||
Object {
|
Object {
|
||||||
"x": 75,
|
"x": 75,
|
||||||
"y": -5,
|
"y": -5,
|
||||||
@@ -1152,7 +1149,7 @@ describe("Test Linear Elements", () => {
|
|||||||
expect(rect.x).toBe(400);
|
expect(rect.x).toBe(400);
|
||||||
expect(rect.y).toBe(0);
|
expect(rect.y).toBe(0);
|
||||||
expect(
|
expect(
|
||||||
wrapText(textElement.originalText, font, getBoundTextMaxWidth(arrow)),
|
wrapText(textElement.originalText, font, getMaxContainerWidth(arrow)),
|
||||||
).toMatchInlineSnapshot(`
|
).toMatchInlineSnapshot(`
|
||||||
"Online whiteboard collaboration
|
"Online whiteboard collaboration
|
||||||
made easy"
|
made easy"
|
||||||
@@ -1175,7 +1172,7 @@ describe("Test Linear Elements", () => {
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
wrapText(textElement.originalText, font, getBoundTextMaxWidth(arrow)),
|
wrapText(textElement.originalText, font, getMaxContainerWidth(arrow)),
|
||||||
).toMatchInlineSnapshot(`
|
).toMatchInlineSnapshot(`
|
||||||
"Online whiteboard
|
"Online whiteboard
|
||||||
collaboration made
|
collaboration made
|
||||||
|
|||||||
+74
-5
@@ -181,6 +181,79 @@ export const throttleRAF = <T extends any[]>(
|
|||||||
return ret;
|
return ret;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exponential ease-out method
|
||||||
|
*
|
||||||
|
* @param {number} k - The value to be tweened.
|
||||||
|
* @returns {number} The tweened value.
|
||||||
|
*/
|
||||||
|
function easeOut(k: number): number {
|
||||||
|
return 1 - Math.pow(1 - k, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute new values based on the same ease function and trigger the
|
||||||
|
* callback through a requestAnimationFrame call
|
||||||
|
*
|
||||||
|
* use `opts` to define a duration and/or an easeFn
|
||||||
|
*
|
||||||
|
* for example:
|
||||||
|
* ```ts
|
||||||
|
* easeToValuesRAF([10, 20, 10], [0, 0, 0], (a, b, c) => setState(a,b, c))
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param fromValues The initial values, must be numeric
|
||||||
|
* @param toValues The destination values, must also be numeric
|
||||||
|
* @param callback The callback receiving the values
|
||||||
|
* @param opts default to 250ms duration and the easeOut function
|
||||||
|
*/
|
||||||
|
export const easeToValuesRAF = (
|
||||||
|
fromValues: number[],
|
||||||
|
toValues: number[],
|
||||||
|
callback: (...values: number[]) => void,
|
||||||
|
opts?: { duration?: number; easeFn?: (value: number) => number },
|
||||||
|
) => {
|
||||||
|
let canceled = false;
|
||||||
|
let frameId = 0;
|
||||||
|
let startTime: number;
|
||||||
|
|
||||||
|
const duration = opts?.duration || 250; // default animation to 0.25 seconds
|
||||||
|
const easeFn = opts?.easeFn || easeOut; // default the easeFn to easeOut
|
||||||
|
|
||||||
|
function step(timestamp: number) {
|
||||||
|
if (canceled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (startTime === undefined) {
|
||||||
|
startTime = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsed = timestamp - startTime;
|
||||||
|
|
||||||
|
if (elapsed < duration) {
|
||||||
|
// console.log(elapsed, duration, elapsed / duration);
|
||||||
|
const factor = easeFn(elapsed / duration);
|
||||||
|
const newValues = fromValues.map(
|
||||||
|
(fromValue, index) =>
|
||||||
|
(toValues[index] - fromValue) * factor + fromValue,
|
||||||
|
);
|
||||||
|
|
||||||
|
callback(...newValues);
|
||||||
|
frameId = window.requestAnimationFrame(step);
|
||||||
|
} else {
|
||||||
|
// ensure final values are reached at the end of the transition
|
||||||
|
callback(...toValues);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
frameId = window.requestAnimationFrame(step);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
canceled = true;
|
||||||
|
window.cancelAnimationFrame(frameId);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
// https://github.com/lodash/lodash/blob/es/chunk.js
|
// https://github.com/lodash/lodash/blob/es/chunk.js
|
||||||
export const chunk = <T extends any>(
|
export const chunk = <T extends any>(
|
||||||
array: readonly T[],
|
array: readonly T[],
|
||||||
@@ -616,11 +689,7 @@ export const arrayToMapWithIndex = <T extends { id: string }>(
|
|||||||
return acc;
|
return acc;
|
||||||
}, new Map<string, [element: T, index: number]>());
|
}, new Map<string, [element: T, index: number]>());
|
||||||
|
|
||||||
export const isTestEnv = () =>
|
export const isTestEnv = () => process.env.NODE_ENV === "test";
|
||||||
typeof process !== "undefined" && process.env?.NODE_ENV === "test";
|
|
||||||
|
|
||||||
export const isProdEnv = () =>
|
|
||||||
typeof process !== "undefined" && process.env?.NODE_ENV === "production";
|
|
||||||
|
|
||||||
export const wrapEvent = <T extends Event>(name: EVENT, nativeEvent: T) => {
|
export const wrapEvent = <T extends Event>(name: EVENT, nativeEvent: T) => {
|
||||||
return new CustomEvent(name, {
|
return new CustomEvent(name, {
|
||||||
|
|||||||
Reference in New Issue
Block a user